mirror of
https://github.com/backnotprop/plannotator.git
synced 2026-09-14 14:17:26 +08:00
bb404f8d14
* feat(shared): add isSameProject, PR stack types, and PR list provider Extends PRRef/PRMetadata with defaultBranch, PRStackInfo, PRStackTree, PRStackNode, PRDiffScope, and PRListItem types. Adds isSameProject() for owner/repo validation on PR switching. Adds fetchPRStack() and fetchPRList() dispatch functions (GitHub-only for now, GitLab stubs). Includes 9 new tests for isSameProject covering GitHub, GitLab, and cross-platform scenarios. For provenance purposes, this commit was AI assisted. * feat(shared): add GitHub PR stack tree walking and PR list fetching Implements fetchGhPRStack() which walks up/down the PR stack via GraphQL, resolving numbers and titles for each node in the chain. Collapses queryPRsByHead/queryPRsByBase into a single queryPRsByRef helper. Adds fetchGhPRList() using gh pr list. Fixes GHE support by removing hostnameArgs from fetchGhPRList (--repo already handles GHE). Filters jq "null" string from defaultBranch detection. For provenance purposes, this commit was AI assisted. * feat(shared): fetch defaultBranch for GitLab MRs Queries the project's default_branch via glab API so getPRStackInfo can detect stacked MRs on GitLab. Best-effort — caught errors fall back to undefined. For provenance purposes, this commit was AI assisted. * feat(shared): add PR stack detection and full-stack diff module New pr-stack module with: - getPRStackInfo(): detects stacked PRs from baseBranch vs defaultBranch - getPRDiffScopeOptions(): generates layer/full-stack scope options - runPRFullStackDiff(): computes diff from default branch to HEAD - resolvePRFullStackBaseRef(): resolves origin/main or local main - checkoutPRHead(): fetches and checks out a PR head in a worktree - buildMinimalStackTree(): builds UI tree from stack info Includes 13 tests covering ref resolution, branch fallbacks, and GitLab ref formats. For provenance purposes, this commit was AI assisted. * feat(shared): add worktree pool for per-PR agent isolation Creates a session-scoped pool of git worktrees — each PR visited during a stacked review gets its own isolated checkout. Agents run in their PR's worktree undisturbed by PR switches. Handles deduplication of concurrent ensure() calls for the same PR. Includes 11 tests covering caching, cross-repo restrictions, GitLab ref formats, and cleanup. For provenance purposes, this commit was AI assisted. * feat(shared): add diffScope/prUrl to agent jobs, branch diff type Adds prUrl and diffScope optional fields to AgentJobInfo so agent findings carry the PR and scope context they were launched under. Exports new pr-stack and worktree-pool modules from package.json. Adds 'branch' to DefaultDiffType union for branch diff as default. For provenance purposes, this commit was AI assisted. * feat(ui): add PR annotation fields, Popover, and SearchableSelect Extends CodeAnnotation with prUrl, prNumber, prTitle, prRepo, and diffScope fields for stacked PR attribution. Adds shared Popover wrapper around radix-ui. Adds SearchableSelect for filterable dropdown lists (used by PR selector). For provenance purposes, this commit was AI assisted. * feat(ui): add branch diff as default option, new Git settings tab Adds 'Branch' as a fourth default diff type option in both the first-run dialog and settings panel. Moves the default diff type setting from the Display tab to a new Git tab in review mode. Updates config store validators to accept 'branch'. For provenance purposes, this commit was AI assisted. * feat(server): add prUrl/diffScope plumbing to agent jobs and prompts Threads prUrl and diffScope through the agent job lifecycle so findings carry the PR and scope they were generated under. Adds full-stack prompt branch to codex-review and tour-review — when in full-stack mode, the diff is inlined in the prompt instead of telling the agent to run git diff. Re-exports isSameProject and new PR provider functions from server/pr.ts. For provenance purposes, this commit was AI assisted. * feat(server): add stacked PR support to Bun review server Adds PR switching, layer/full-stack scope toggling, PR list caching, worktree pool integration, and multi-PR platform posting to the Bun review server. Key additions: - /api/pr-diff-scope: switch between layer and full-stack diffs - /api/pr-list: cached PR list for the current repo - /api/pr-switch: in-place navigation between PRs in a stack - /api/pr-action: targetPrUrl support for multi-PR posting - /api/file-content: full-stack branch for hunk expansion - prSwitchCache/prStackTreeCache for session-scoped caching - diffScope tagging on agent job completion - Scope guard: returns 400 on full-stack diff failure instead of overwriting the working diff with empty content For provenance purposes, this commit was AI assisted. * feat(ai): pass cwd to Claude agent SDK for worktree support Forwards the working directory to the Claude agent provider so agents run in the correct worktree when reviewing stacked PRs. For provenance purposes, this commit was AI assisted. * feat(pi): add stacked PR support to Pi server (Bun parity) Mirrors all stacked PR features from the Bun server: - PR switching, scope toggling, PR list, multi-PR posting - prSwitchCache/prStackTreeCache with initial PR seeding - diffScope/prUrl plumbing in agent jobs - Worktree pool creation and lifecycle - Full-stack file-content resolution matching Bun's guard structure - targetPrUrl support on /api/pr-action Hoists worktreePool declaration to outer scope in plannotator-browser to fix TS18004 scoping error. Updates vendor.sh for new shared modules. For provenance purposes, this commit was AI assisted. * feat(hook): create worktree pool for PR review sessions Creates a worktree pool when opening a PR review with --local, seeding it with the initial PR's checkout. Integrates pool cleanup into server shutdown. Passes the pool to startReviewServer for agent isolation during PR switching. For provenance purposes, this commit was AI assisted. * feat(review-editor): add hooks for PR stack, context, and annotations - useAnnotationFactory: stamps prUrl/prNumber/prTitle/prRepo/diffScope onto annotations, only when viewing a stacked PR - usePRStack: handles scope selection and PR switching with loading state - usePRContext: adds URL-change detection to prevent stale-fetch race when switching PRs (discards in-flight responses for previous PR) For provenance purposes, this commit was AI assisted. * feat(review-editor): add stacked PR UI components - PRSelector: searchable dropdown for switching between PRs in a repo - PRSwitchOverlay: loading animation during PR switch - StackedPRLabel: stack tree popover with scope selector and PR navigation - ReviewSubmissionDialog: multi-PR submission dialog with per-target status, orphaned findings section with copy-as-markdown, and partial failure retry For provenance purposes, this commit was AI assisted. * feat(review-editor): multi-PR export with heading hierarchy Updates exportReviewFeedback for multi-PR sessions: - Groups annotations by prUrl, then by file within each PR - Uses proper heading hierarchy (## for files, ### for annotations in multi-PR mode) - Detects single-PR mismatch (annotations from a different PR than the current view) and uses annotation-level PR context - Adds diffScope labels per PR group when present Includes 5 new tests: multi-PR headings, single-PR mismatch, diffScope labels, and non-stacked annotation handling. For provenance purposes, this commit was AI assisted. * feat(review-editor): integrate stacked PR into sidebar, diff panel, and agents - ReviewSidebar: groups annotations by PR in multi-PR sessions, shows PR headers with annotation counts - ReviewDiffPanel: filters annotations by prUrl and diffScope so only matching annotations appear in the diff gutter - ReviewStateContext: adds prDiffScope to shared review state - ReviewAgentJobDetailPanel: shows diffScope in job detail - PRSummaryTab: shows stack info in PR summary - index.css: PR switch shimmer and overlay animations For provenance purposes, this commit was AI assisted. * feat(review-editor): wire stacked PR into main review app Integrates all stacked PR features into the review editor: - PR stack state management (prStackInfo, prStackTree, prDiffScope) - applyPRResponse: shared handler for PR switch and scope toggle, preserves active file index on scope changes - Multi-PR platform posting via Promise.allSettled with parallel requests, partial failure retry, and per-target status tracking - ReviewSubmissionDialog replaces inline dialog JSX - useAnnotationFactory stamps PR context onto annotations - keepalive on /api/feedback to survive tab closure - Proper try/catch/finally on handlePlatformAction For provenance purposes, this commit was AI assisted. * docs: add stacked PR review documentation Updates AGENTS.md, code-review command docs, and AI code review guide with stacked PR review capabilities. For provenance purposes, this commit was AI assisted. * fix(server): stamp prNumber/prTitle/prRepo on agent findings Agent annotations only had prUrl and diffScope, missing prNumber, prTitle, and prRepo. When agent findings were the only annotations for a PR target in the submission dialog, the target rendered as #0 with no title. Now resolves full PR context from prSwitchCache at job completion and stamps all five fields. Both Bun and Pi. For provenance purposes, this commit was AI assisted. * feat(ui): rename diff options — "Committed" replaces "Branch" / "Current PR Diff" Consolidates two confusing committed-diff options into one: - Settings/first-run: "Committed" — "Everything you've committed on this branch" - Mid-session switcher: "Committed changes" (replaces both "vs main" and "Current PR Diff") Uses merge-base under the hood (matches GitHub PR behavior). Removes the two-dot branch diff from the UI — it stays in the runtime DiffType union for backwards compat. Old "branch" values in config/cookies are silently upgraded to merge-base. Git settings tab now uses radio cards with descriptions instead of a cramped segmented control. First-run dialog descriptions rewritten in plain language — no git commands. For provenance purposes, this commit was AI assisted. * fix(review-editor): rename client-side "PR Diff" labels to "Committed changes" DiffTypePicker.tsx had a hardcoded "PR Diff" override for merge-base when the base picker is present. exportFeedback.ts also used "PR Diff" in export labels. Both now say "Committed changes" to match the server-side label and settings UI. For provenance purposes, this commit was AI assisted. * fix(server): discover stack UI for root PRs targeting the default branch Root PRs (baseBranch === defaultBranch) were excluded from stack detection because getPRStackInfo returned null. Now the server always fetches the stack tree in PR mode. If the tree reveals descendant PRs, prStackInfo is retroactively set with source "tree-discovered", enabling the stack UI, scope selector, and PR navigation from the root of a stack. Both Bun and Pi servers updated. Adds "tree-discovered" to the PRStackInfo source union. For provenance purposes, this commit was AI assisted. * fix(review-editor): derive diff scope from annotations, not UI state The export function now reads diffScope from annotations instead of the prReviewScope parameter. Fixes two issues: 1. Agent job "Copy All" showed the wrong scope when the user switched between layer/full-stack after launching the agent 2. Mixed-scope annotations produced a confusing "layer, full-stack" comma-joined label instead of grouping by scope Extracts renderScopedGroups helper for scope-aware grouping — used by both single-PR and multi-PR export paths. When annotations share one scope, it appears in the header. When mixed, annotations are grouped under ## Layer / ## Full-stack headings. Includes 4 new tests: uniform scope derivation, mixed scope grouping, single scope header, and prReviewScope override prevention. For provenance purposes, this commit was AI assisted. * fix(server): add tree-discovered stack fallback to pr-switch handler The initial-load path upgrades prStackInfo for root PRs when the stack tree reveals descendants, but the pr-switch handler was missing this logic. The server now sends correct prStackInfo after switching to a root-of-stack PR. Both Bun and Pi. Also removes stale prReviewScope dependency from agent job panel's copyAllText useMemo. For provenance purposes, this commit was AI assisted. * fix: extract resolveStackInfo helper, fix stack UI on non-stacked PRs Extracts the tree-discovered stack fallback into resolveStackInfo() in pr-stack.ts — eliminates 4 copies of the same logic across Bun startup, Bun pr-switch, Pi startup, and Pi pr-switch. Fixes StackedPRLabel showing on every PR: the check now counts non-default-branch nodes (> 1) instead of all nodes (> 1). Without this, every PR showed a "Stack (1 PR)" popover because the tree always has at least [defaultBranch, currentPR]. For provenance purposes, this commit was AI assisted. * fix(review-editor): don't re-open already-succeeded PR tabs on retry On partial failure retry, openUrls was pre-seeded with URLs from previously succeeded targets, causing those PR pages to re-open in the browser alongside newly succeeded ones. Now starts empty — only URLs from the current attempt are opened. For provenance purposes, this commit was AI assisted. * refactor(review-editor): extract PR session state into usePRSession hook Consolidates 5 independent useState calls (prMetadata, prStackInfo, prStackTree, prDiffScope, prDiffScopeOptions) into a single usePRSession hook with atomic updatePRSession callback. Replaces two identical 5-line setter blocks (initial load and applyPRResponse) with single updatePRSession calls. All ~60 consumer sites unchanged — same variable names via destructuring. For provenance purposes, this commit was AI assisted.
521 lines
17 KiB
TypeScript
521 lines
17 KiB
TypeScript
/**
|
|
* GitLab-specific MR provider implementation.
|
|
*
|
|
* All functions use the `glab` CLI via the PRRuntime abstraction.
|
|
* Self-hosted instances are supported via the --hostname flag.
|
|
*/
|
|
|
|
import type { PRRuntime, PRMetadata, PRContext, PRReviewFileComment, CommandResult } from "./pr-provider";
|
|
import { encodeApiFilePath } from "./pr-provider";
|
|
|
|
// GitLab-specific MRRef shape (used internally)
|
|
interface GlMRRef {
|
|
platform: "gitlab";
|
|
host: string;
|
|
projectPath: string;
|
|
iid: number;
|
|
}
|
|
|
|
/** URL-encode the project path for GitLab API (group/project → group%2Fproject) */
|
|
function encodeProject(projectPath: string): string {
|
|
return encodeURIComponent(projectPath);
|
|
}
|
|
|
|
/** Build glab API args with optional --hostname for self-hosted */
|
|
function apiArgs(host: string, endpoint: string, extra: string[] = []): string[] {
|
|
const args = ["api", endpoint, ...extra];
|
|
if (host !== "gitlab.com") {
|
|
args.push("--hostname", host);
|
|
}
|
|
return args;
|
|
}
|
|
|
|
/** Shape of each entry from the GitLab merge_request diffs API */
|
|
interface GitLabDiffEntry {
|
|
diff: string;
|
|
old_path: string;
|
|
new_path: string;
|
|
new_file: boolean;
|
|
deleted_file: boolean;
|
|
renamed_file: boolean;
|
|
}
|
|
|
|
/** Parse JSON array from glab api --paginate output (already merged by glab) */
|
|
function parsePaginatedArray<T>(stdout: string): T[] {
|
|
return JSON.parse(stdout) as T[];
|
|
}
|
|
|
|
/**
|
|
* Reconstruct a unified patch from GitLab's merge_request diffs API response.
|
|
*
|
|
* Each entry has: { diff, old_path, new_path, new_file, deleted_file, renamed_file }
|
|
* We construct proper `diff --git` headers that the UI parser expects.
|
|
*/
|
|
function reconstructPatch(diffs: GitLabDiffEntry[]): string {
|
|
const parts: string[] = [];
|
|
|
|
for (const d of diffs) {
|
|
const aPath = d.new_file ? "/dev/null" : `a/${d.old_path}`;
|
|
const bPath = d.deleted_file ? "/dev/null" : `b/${d.new_path}`;
|
|
const displayOld = d.new_file ? d.new_path : d.old_path;
|
|
const displayNew = d.deleted_file ? d.old_path : d.new_path;
|
|
|
|
let header = `diff --git a/${displayOld} b/${displayNew}`;
|
|
if (d.renamed_file) {
|
|
header += `\nrename from ${d.old_path}\nrename to ${d.new_path}`;
|
|
}
|
|
if (d.new_file) {
|
|
header += "\nnew file mode 100644";
|
|
}
|
|
if (d.deleted_file) {
|
|
header += "\ndeleted file mode 100644";
|
|
}
|
|
|
|
parts.push(`${header}\n--- ${aPath}\n+++ ${bPath}\n${d.diff}`);
|
|
}
|
|
|
|
return parts.join("");
|
|
}
|
|
|
|
// --- Auth ---
|
|
|
|
export async function checkGlAuth(runtime: PRRuntime, host: string): Promise<void> {
|
|
const args = ["auth", "status"];
|
|
if (host !== "gitlab.com") {
|
|
args.push("--hostname", host);
|
|
}
|
|
const result = await runtime.runCommand("glab", args);
|
|
if (result.exitCode !== 0) {
|
|
const stderr = result.stderr.trim();
|
|
const hostHint = host !== "gitlab.com" ? ` --hostname ${host}` : "";
|
|
throw new Error(
|
|
`GitLab CLI not authenticated. Run \`glab auth login${hostHint}\` first.\n${stderr}`,
|
|
);
|
|
}
|
|
}
|
|
|
|
export async function getGlUser(runtime: PRRuntime, host: string): Promise<string | null> {
|
|
try {
|
|
const result = await runtime.runCommand("glab", apiArgs(host, "/user"));
|
|
if (result.exitCode === 0 && result.stdout.trim()) {
|
|
const user = JSON.parse(result.stdout) as { username?: string };
|
|
return user.username ?? null;
|
|
}
|
|
return null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
// --- Fetch MR ---
|
|
|
|
export async function fetchGlMR(
|
|
runtime: PRRuntime,
|
|
ref: GlMRRef,
|
|
): Promise<{ metadata: PRMetadata; rawPatch: string }> {
|
|
const encoded = encodeProject(ref.projectPath);
|
|
|
|
// Fetch diff and metadata in parallel via glab api (supports --hostname for self-hosted)
|
|
const [diffResult, viewResult] = await Promise.all([
|
|
runtime.runCommand("glab", apiArgs(ref.host, `projects/${encoded}/merge_requests/${ref.iid}/diffs?per_page=100`, ["--paginate"])),
|
|
runtime.runCommand("glab", apiArgs(ref.host, `projects/${encoded}/merge_requests/${ref.iid}`)),
|
|
]);
|
|
|
|
if (diffResult.exitCode !== 0) {
|
|
throw new Error(
|
|
`Failed to fetch MR diff: ${diffResult.stderr.trim() || `exit code ${diffResult.exitCode}`}`,
|
|
);
|
|
}
|
|
|
|
if (viewResult.exitCode !== 0) {
|
|
throw new Error(
|
|
`Failed to fetch MR metadata: ${viewResult.stderr.trim() || `exit code ${viewResult.exitCode}`}`,
|
|
);
|
|
}
|
|
|
|
// Reconstruct unified patch from structured API response
|
|
const diffs = parsePaginatedArray<GitLabDiffEntry>(diffResult.stdout);
|
|
const rawPatch = reconstructPatch(diffs);
|
|
|
|
const raw = JSON.parse(viewResult.stdout) as {
|
|
title: string;
|
|
author: { username: string };
|
|
source_branch: string;
|
|
target_branch: string;
|
|
target_project_id?: number;
|
|
diff_refs: { base_sha: string; head_sha: string; start_sha: string } | null;
|
|
web_url: string;
|
|
};
|
|
|
|
if (!raw.diff_refs) {
|
|
throw new Error("MR has no diff refs — it may have been merged or the source branch deleted.");
|
|
}
|
|
|
|
let defaultBranch: string | undefined;
|
|
const projectEndpoint = typeof raw.target_project_id === "number"
|
|
? `projects/${raw.target_project_id}`
|
|
: `projects/${encoded}`;
|
|
try {
|
|
const projectResult = await runtime.runCommand("glab", apiArgs(ref.host, projectEndpoint));
|
|
if (projectResult.exitCode === 0 && projectResult.stdout.trim()) {
|
|
const project = JSON.parse(projectResult.stdout) as { default_branch?: string };
|
|
defaultBranch = project.default_branch;
|
|
}
|
|
} catch { /* default branch is best-effort metadata */ }
|
|
|
|
const metadata: PRMetadata = {
|
|
platform: "gitlab",
|
|
host: ref.host,
|
|
projectPath: ref.projectPath,
|
|
iid: ref.iid,
|
|
title: raw.title,
|
|
author: raw.author.username,
|
|
baseBranch: raw.target_branch,
|
|
headBranch: raw.source_branch,
|
|
defaultBranch,
|
|
baseSha: raw.diff_refs.base_sha,
|
|
headSha: raw.diff_refs.head_sha,
|
|
url: raw.web_url,
|
|
};
|
|
|
|
return { metadata, rawPatch };
|
|
}
|
|
|
|
// --- MR Context ---
|
|
|
|
export async function fetchGlMRContext(
|
|
runtime: PRRuntime,
|
|
ref: GlMRRef,
|
|
): Promise<PRContext> {
|
|
const encoded = encodeProject(ref.projectPath);
|
|
const mrEndpoint = `projects/${encoded}/merge_requests/${ref.iid}`;
|
|
|
|
// Fetch all context in parallel
|
|
const [mrResult, notesResult, approvalsResult, pipelinesResult, issuesResult] = await Promise.all([
|
|
runtime.runCommand("glab", apiArgs(ref.host, mrEndpoint)),
|
|
runtime.runCommand("glab", apiArgs(ref.host, `${mrEndpoint}/notes?sort=asc&per_page=100`)),
|
|
runtime.runCommand("glab", apiArgs(ref.host, `${mrEndpoint}/approvals`)),
|
|
runtime.runCommand("glab", apiArgs(ref.host, `${mrEndpoint}/pipelines?per_page=5`)),
|
|
runtime.runCommand("glab", apiArgs(ref.host, `${mrEndpoint}/closes_issues`)),
|
|
]);
|
|
|
|
const str = (v: unknown): string => (typeof v === "string" ? v : "");
|
|
const arr = (v: unknown): unknown[] => (Array.isArray(v) ? v : []);
|
|
|
|
// --- MR details ---
|
|
let mr: Record<string, unknown> = {};
|
|
if (mrResult.exitCode === 0) {
|
|
try { mr = JSON.parse(mrResult.stdout); } catch { /* non-JSON response */ }
|
|
}
|
|
|
|
// Normalize state: GitLab uses "opened"/"closed"/"merged" → uppercase
|
|
const glState = str(mr.state);
|
|
const state = glState === "opened" ? "OPEN" : glState.toUpperCase();
|
|
|
|
const isDraft = mr.draft === true
|
|
|| (typeof mr.title === "string" && /^(Draft:|WIP:)/i.test(mr.title));
|
|
|
|
const labels = arr(mr.labels).map((l: any) => {
|
|
if (typeof l === "string") return { name: l, color: "" };
|
|
return { name: str(l?.name), color: str(l?.color) };
|
|
});
|
|
|
|
// GitLab merge_status values
|
|
const mergeStatus = str(mr.merge_status);
|
|
const detailedStatus = str(mr.detailed_merge_status);
|
|
const mergeable = mergeStatus === "can_be_merged" ? "MERGEABLE"
|
|
: mergeStatus === "cannot_be_merged" ? "CONFLICTING"
|
|
: mergeStatus === "unchecked" ? "UNKNOWN"
|
|
: mergeStatus.toUpperCase();
|
|
|
|
// Map GitLab detailed_merge_status to GitHub-compatible merge state enums
|
|
const mergeStateMap: Record<string, string> = {
|
|
mergeable: "CLEAN",
|
|
broken_status: "DIRTY",
|
|
checking: "UNKNOWN",
|
|
unchecked: "UNKNOWN",
|
|
ci_must_pass: "BLOCKED",
|
|
ci_still_running: "BLOCKED",
|
|
discussions_not_resolved: "BLOCKED",
|
|
draft_status: "BLOCKED",
|
|
blocked_status: "BLOCKED",
|
|
not_approved: "BLOCKED",
|
|
not_open: "DIRTY",
|
|
need_rebase: "BEHIND",
|
|
conflict: "DIRTY",
|
|
jira_association_missing: "BLOCKED",
|
|
};
|
|
const mergeStateStatus = detailedStatus
|
|
? (mergeStateMap[detailedStatus] ?? detailedStatus.toUpperCase())
|
|
: mergeable;
|
|
|
|
// --- Notes (comments) ---
|
|
const notes: PRContext["comments"] = [];
|
|
if (notesResult.exitCode === 0) {
|
|
try {
|
|
const rawNotes = JSON.parse(notesResult.stdout) as any[];
|
|
for (const n of rawNotes) {
|
|
if (n.system) continue;
|
|
notes.push({
|
|
id: String(n.id ?? ""),
|
|
author: str(n.author?.username),
|
|
body: str(n.body),
|
|
createdAt: str(n.created_at),
|
|
url: str(n.web_url) || "",
|
|
});
|
|
}
|
|
} catch { /* non-JSON response */ }
|
|
}
|
|
|
|
// --- Approvals ---
|
|
let reviewDecision = "";
|
|
const reviews: PRContext["reviews"] = [];
|
|
if (approvalsResult.exitCode === 0) {
|
|
try {
|
|
const approvals = JSON.parse(approvalsResult.stdout) as Record<string, unknown>;
|
|
const approvedBy = arr(approvals.approved_by);
|
|
const approved = approvals.approved === true || approvedBy.length > 0;
|
|
reviewDecision = approved ? "APPROVED" : "";
|
|
|
|
for (const a of approvedBy) {
|
|
const user = (a as any)?.user;
|
|
if (!user) continue;
|
|
reviews.push({
|
|
id: String(user.id ?? ""),
|
|
author: str(user.username),
|
|
state: "APPROVED",
|
|
body: "",
|
|
submittedAt: "",
|
|
});
|
|
}
|
|
} catch { /* non-JSON response */ }
|
|
}
|
|
|
|
// --- Pipelines → Checks ---
|
|
const checks: PRContext["checks"] = [];
|
|
if (pipelinesResult.exitCode === 0) {
|
|
try {
|
|
const pipelines = JSON.parse(pipelinesResult.stdout) as any[];
|
|
if (pipelines.length > 0) {
|
|
const latest = pipelines[0];
|
|
const jobsResult = await runtime.runCommand(
|
|
"glab",
|
|
apiArgs(ref.host, `projects/${encoded}/pipelines/${latest.id}/jobs?per_page=100`),
|
|
);
|
|
if (jobsResult.exitCode === 0) {
|
|
try {
|
|
const jobs = JSON.parse(jobsResult.stdout) as any[];
|
|
for (const job of jobs) {
|
|
const jobStatus = str(job.status);
|
|
const isComplete = ["success", "failed", "canceled", "skipped"].includes(jobStatus);
|
|
// Map GitLab job statuses to GitHub-compatible conclusion enums
|
|
const conclusionMap: Record<string, string> = {
|
|
success: "SUCCESS",
|
|
failed: "FAILURE",
|
|
canceled: "NEUTRAL",
|
|
skipped: "SKIPPED",
|
|
};
|
|
checks.push({
|
|
name: str(job.name),
|
|
status: isComplete ? "COMPLETED" : "IN_PROGRESS",
|
|
conclusion: isComplete ? (conclusionMap[jobStatus] ?? jobStatus.toUpperCase()) : null,
|
|
workflowName: str(latest.ref),
|
|
detailsUrl: str(job.web_url),
|
|
});
|
|
}
|
|
} catch { /* non-JSON jobs response */ }
|
|
}
|
|
}
|
|
} catch { /* non-JSON pipelines response */ }
|
|
}
|
|
|
|
// --- Linked Issues ---
|
|
const linkedIssues: PRContext["linkedIssues"] = [];
|
|
if (issuesResult.exitCode === 0) {
|
|
try {
|
|
const issues = JSON.parse(issuesResult.stdout) as any[];
|
|
for (const i of issues) {
|
|
linkedIssues.push({
|
|
number: typeof i.iid === "number" ? i.iid : 0,
|
|
url: str(i.web_url),
|
|
repo: ref.projectPath,
|
|
});
|
|
}
|
|
} catch {
|
|
// Non-critical — some GitLab versions may not support this endpoint
|
|
}
|
|
}
|
|
|
|
return {
|
|
body: str(mr.description),
|
|
state,
|
|
isDraft,
|
|
labels,
|
|
reviewDecision,
|
|
mergeable,
|
|
mergeStateStatus,
|
|
comments: notes,
|
|
reviews,
|
|
reviewThreads: [], // TODO: parse DiffNote positions from notes for thread support
|
|
checks,
|
|
linkedIssues,
|
|
};
|
|
}
|
|
|
|
// --- File Content ---
|
|
|
|
export async function fetchGlFileContent(
|
|
runtime: PRRuntime,
|
|
ref: GlMRRef,
|
|
sha: string,
|
|
filePath: string,
|
|
): Promise<string | null> {
|
|
const encoded = encodeProject(ref.projectPath);
|
|
const encodedPath = encodeApiFilePath(filePath);
|
|
|
|
const result = await runtime.runCommand(
|
|
"glab",
|
|
apiArgs(ref.host, `projects/${encoded}/repository/files/${encodedPath}/raw?ref=${sha}`),
|
|
);
|
|
|
|
if (result.exitCode !== 0) return null;
|
|
|
|
// GitLab returns raw file content (no base64 encoding)
|
|
return result.stdout;
|
|
}
|
|
|
|
// --- Submit MR Review ---
|
|
|
|
export async function submitGlMRReview(
|
|
runtime: PRRuntime,
|
|
ref: GlMRRef,
|
|
headSha: string,
|
|
action: "approve" | "comment",
|
|
body: string,
|
|
fileComments: PRReviewFileComment[],
|
|
): Promise<void> {
|
|
if (!runtime.runCommandWithInput) {
|
|
throw new Error("Runtime does not support stdin input; cannot submit MR review");
|
|
}
|
|
|
|
const encoded = encodeProject(ref.projectPath);
|
|
const mrEndpoint = `projects/${encoded}/merge_requests/${ref.iid}`;
|
|
|
|
// Fetch base SHA for position context (needed for line comments)
|
|
// We use the headSha passed in and derive baseSha from MR metadata
|
|
// The caller already has this info, but GitLab's discussion API needs start_sha too
|
|
|
|
// 1. Post general body as a note (if non-empty)
|
|
if (body && body.trim()) {
|
|
const notePayload = JSON.stringify({ body: body.trim() });
|
|
const noteResult = await runtime.runCommandWithInput(
|
|
"glab",
|
|
apiArgs(ref.host, `${mrEndpoint}/notes`, ["--method", "POST", "--input", "-", "-H", "Content-Type:application/json"]),
|
|
notePayload,
|
|
);
|
|
if (noteResult.exitCode !== 0) {
|
|
const msg = noteResult.stderr.trim() || noteResult.stdout.trim() || `exit code ${noteResult.exitCode}`;
|
|
throw new Error(`Failed to post MR note: ${msg}`);
|
|
}
|
|
}
|
|
|
|
// 2. Post inline file comments as discussions with position
|
|
if (fileComments.length > 0) {
|
|
// We need the MR's diff_refs for the position SHAs.
|
|
const mrResult = await runtime.runCommand(
|
|
"glab",
|
|
apiArgs(ref.host, mrEndpoint),
|
|
);
|
|
let baseSha = headSha; // fallback
|
|
let startSha = headSha;
|
|
if (mrResult.exitCode === 0 && mrResult.stdout.trim()) {
|
|
try {
|
|
const mrData = JSON.parse(mrResult.stdout) as { diff_refs?: { base_sha: string; start_sha: string; head_sha: string } };
|
|
if (mrData.diff_refs) {
|
|
baseSha = mrData.diff_refs.base_sha;
|
|
startSha = mrData.diff_refs.start_sha;
|
|
}
|
|
} catch {
|
|
// Use fallbacks
|
|
}
|
|
}
|
|
|
|
const errors: string[] = [];
|
|
|
|
// Submit comments in parallel
|
|
const results = await Promise.allSettled(
|
|
fileComments.map(async (comment) => {
|
|
const isOldSide = comment.side === "LEFT";
|
|
const position: Record<string, unknown> = {
|
|
position_type: "text",
|
|
base_sha: baseSha,
|
|
head_sha: headSha,
|
|
start_sha: startSha,
|
|
new_path: comment.path,
|
|
old_path: comment.path,
|
|
};
|
|
|
|
if (isOldSide) {
|
|
position.old_line = comment.line;
|
|
} else {
|
|
position.new_line = comment.line;
|
|
}
|
|
|
|
// Multi-line range support
|
|
if (comment.start_line != null && comment.start_line !== comment.line) {
|
|
const startIsOld = (comment.start_side ?? comment.side) === "LEFT";
|
|
const startEntry: Record<string, unknown> = { type: startIsOld ? "old" : "new" };
|
|
if (startIsOld) startEntry.old_line = comment.start_line;
|
|
else startEntry.new_line = comment.start_line;
|
|
|
|
const endEntry: Record<string, unknown> = { type: isOldSide ? "old" : "new" };
|
|
if (isOldSide) endEntry.old_line = comment.line;
|
|
else endEntry.new_line = comment.line;
|
|
|
|
position.line_range = { start: startEntry, end: endEntry };
|
|
}
|
|
|
|
const payload = JSON.stringify({ body: comment.body, position });
|
|
const res = await runtime.runCommandWithInput!(
|
|
"glab",
|
|
apiArgs(ref.host, `${mrEndpoint}/discussions`, ["--method", "POST", "--input", "-", "-H", "Content-Type:application/json"]),
|
|
payload,
|
|
);
|
|
|
|
if (res.exitCode !== 0) {
|
|
const msg = res.stderr.trim() || res.stdout.trim() || `exit code ${res.exitCode}`;
|
|
throw new Error(`${comment.path}:${comment.line}: ${msg}`);
|
|
}
|
|
}),
|
|
);
|
|
|
|
for (const r of results) {
|
|
if (r.status === "rejected") {
|
|
errors.push(r.reason instanceof Error ? r.reason.message : String(r.reason));
|
|
}
|
|
}
|
|
|
|
if (errors.length > 0 && errors.length === fileComments.length) {
|
|
// All failed — throw
|
|
throw new Error(`Failed to post inline comments:\n${errors.join("\n")}`);
|
|
}
|
|
// Partial failures: some comments posted, some didn't — log but don't throw
|
|
if (errors.length > 0) {
|
|
console.error(`Warning: ${errors.length}/${fileComments.length} inline comments failed:\n${errors.join("\n")}`);
|
|
}
|
|
}
|
|
|
|
// 3. Approve if requested
|
|
if (action === "approve") {
|
|
const approveResult = await runtime.runCommandWithInput(
|
|
"glab",
|
|
apiArgs(ref.host, `${mrEndpoint}/approve`, ["--method", "POST", "--input", "-", "-H", "Content-Type:application/json"]),
|
|
"{}",
|
|
);
|
|
if (approveResult.exitCode !== 0) {
|
|
const msg = approveResult.stderr.trim() || approveResult.stdout.trim() || `exit code ${approveResult.exitCode}`;
|
|
throw new Error(`Failed to approve MR: ${msg}`);
|
|
}
|
|
}
|
|
}
|