@g-abhishek/gitx 0.1.4 → 0.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +82 -13
- package/dist/ai/claudeAi.d.ts.map +1 -1
- package/dist/ai/claudeAi.js +4 -30
- package/dist/ai/claudeAi.js.map +1 -1
- package/dist/ai/claudeCliAi.d.ts.map +1 -1
- package/dist/ai/claudeCliAi.js +4 -21
- package/dist/ai/claudeCliAi.js.map +1 -1
- package/dist/ai/openAiAi.d.ts.map +1 -1
- package/dist/ai/openAiAi.js +4 -30
- package/dist/ai/openAiAi.js.map +1 -1
- package/dist/ai/reviewHelpers.d.ts +24 -0
- package/dist/ai/reviewHelpers.d.ts.map +1 -1
- package/dist/ai/reviewHelpers.js +123 -39
- package/dist/ai/reviewHelpers.js.map +1 -1
- package/dist/cli/commands/pr/cherryPick.d.ts +25 -0
- package/dist/cli/commands/pr/cherryPick.d.ts.map +1 -0
- package/dist/cli/commands/pr/cherryPick.js +317 -0
- package/dist/cli/commands/pr/cherryPick.js.map +1 -0
- package/dist/cli/commands/pr/fixComments.d.ts +5 -2
- package/dist/cli/commands/pr/fixComments.d.ts.map +1 -1
- package/dist/cli/commands/pr/fixComments.js +5 -82
- package/dist/cli/commands/pr/fixComments.js.map +1 -1
- package/dist/cli/commands/pr/index.d.ts.map +1 -1
- package/dist/cli/commands/pr/index.js +6 -2
- package/dist/cli/commands/pr/index.js.map +1 -1
- package/dist/cli/commands/pr/port.d.ts +34 -0
- package/dist/cli/commands/pr/port.d.ts.map +1 -0
- package/dist/cli/commands/pr/port.js +453 -0
- package/dist/cli/commands/pr/port.js.map +1 -0
- package/dist/cli/commands/pr/resolve.d.ts +3 -0
- package/dist/cli/commands/pr/resolve.d.ts.map +1 -0
- package/dist/cli/commands/pr/resolve.js +92 -0
- package/dist/cli/commands/pr/resolve.js.map +1 -0
- package/dist/cli/commands/pr/review.js +1 -1
- package/dist/cli/commands/pr/review.js.map +1 -1
- package/dist/cli/commands/sync.d.ts +12 -11
- package/dist/cli/commands/sync.d.ts.map +1 -1
- package/dist/cli/commands/sync.js +13 -101
- package/dist/cli/commands/sync.js.map +1 -1
- package/dist/utils/gitOps.d.ts +11 -4
- package/dist/utils/gitOps.d.ts.map +1 -1
- package/dist/utils/gitOps.js +53 -37
- package/dist/utils/gitOps.js.map +1 -1
- package/dist/workflows/pr.d.ts +1 -1
- package/dist/workflows/pr.d.ts.map +1 -1
- package/dist/workflows/pr.js +82 -19
- package/dist/workflows/pr.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reviewHelpers.js","sourceRoot":"","sources":["../../src/ai/reviewHelpers.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAIH,iFAAiF;AAEjF,MAAM,UAAU,uBAAuB;IACrC,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAsCP,CAAC;AACH,CAAC;AAED,iFAAiF;AAEjF;;;;;;GAMG;AACH,SAAS,eAAe,CAAC,IAAY;IACnC,MAAM,MAAM,GAAG,IAAI,GAAG,EAAiD,CAAC;IACxE,IAAI,WAAW,GAAG,EAAE,CAAC;IAErB,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;QACpC,MAAM,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAC;QAChD,IAAI,SAAS,EAAE,CAAC,CAAC,CAAC,IAAI,SAAS,CAAC,CAAC,CAAC,KAAK,WAAW,EAAE,CAAC;YACnD,WAAW,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;YAClC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,WAAW,CAAC;gBAAE,MAAM,CAAC,GAAG,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC;YAC1D,SAAS;QACX,CAAC;QAED,8BAA8B;QAC9B,MAAM,SAAS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aAAa,CAAC,CAAC;YAC1B,GAAG,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,EAAE,EAAE,EAAE,CACzB,KAAK,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC,MAAM,KAAK,EAAE,CAAC,KAAK,MAAM,EAAE,CAAC,KAAK,cAAc,EAAE,CAAC,MAAM,GAAG,CAAC,CACnF,CAAC;QACJ,CAAC;IACH,CAAC;IAED,6EAA6E;IAC7E,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACf,KAAK,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;IAC1B,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IAErB,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC1B,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,gBAAgB,CAAC,GAAW;IAC1C,IAAI,CAAC;QACH,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAA2B,CAAC;QACzD,OAAO;YACL,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,GAAG,CAAC,IAAI,EAAE;YAC3C,iBAAiB,EAAE,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,iBAAiB,CAAC;gBACxD,CAAC,CAAC,MAAM,CAAC,iBAAiB,CAAC,MAAM,CAAC,CAAC,CAAC,EAAe,EAAE,CAAC,OAAO,CAAC,KAAK,QAAQ,CAAC;gBAC5E,CAAC,CAAC,EAAE;SACP,CAAC;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,iEAAiE;QACjE,OAAO,EAAE,MAAM,EAAE,GAAG,CAAC,IAAI,EAAE,EAAE,iBAAiB,EAAE,EAAE,EAAE,CAAC;IACvD,CAAC;AACH,CAAC","sourcesContent":["/**\n * Shared helpers for the senior-developer PR review.\n *\n * buildSeniorReviewSystem() — the AI system prompt\n * buildSeniorReviewPrompt() — formats the user-facing context block\n * parseSeniorReview() — safely parses the AI JSON response\n */\n\nimport type { AiAskContext, AiAskResponse, AiDetailedReviewResponse, AiFixResponse } from \"./types.js\";\n\n// ─── System prompt ────────────────────────────────────────────────────────────\n\nexport function buildSeniorReviewSystem(): string {\n return `You are a principal software engineer and tech lead doing a thorough pull request review.\nYou have access to the CHANGED SECTIONS of each file (extracted around the exact lines that changed),\nplus supporting context files and the full unified diff.\n\nYour review MUST cover every one of these dimensions:\n 1. Correctness — logic errors, off-by-one, wrong conditions, silent failures\n 2. Security — injection, auth bypass, secret leakage, unvalidated input\n 3. Robustness — missing error handling, null/undefined guard, edge cases\n 4. Performance — unnecessary loops, N+1 queries, missing caching\n 5. Breaking changes — does this break existing API contracts, interfaces, or callers?\n 6. Best practices — naming, DRY, SOLID, idiomatic language usage\n 7. Test coverage — are critical paths tested? are tests meaningful?\n 8. Documentation — are public APIs documented? are complex sections explained?\n\nFor EVERY issue that maps to a specific line, add an inline comment.\nLine numbers shown in the excerpts are the REAL line numbers in the new file — use them exactly.\nOnly reference lines that appear in the excerpts you were given.\n\nVerdict rules:\n - \"approve\" → no critical or warning issues\n - \"request_changes\" → one or more critical/warning issues found\n - \"comment\" → only suggestions / minor observations\n\nRespond with ONLY valid JSON (no markdown fences, no prose outside JSON):\n{\n \"summary\": \"<3-5 sentence executive summary>\",\n \"verdict\": \"approve|request_changes|comment\",\n \"issues\": [\n { \"severity\": \"critical|warning|suggestion\", \"description\": \"<issue>\", \"file\": \"<path or null>\", \"line\": <number or null> }\n ],\n \"inlineComments\": [\n { \"path\": \"<relative file path>\", \"line\": <line number>, \"body\": \"<markdown comment>\", \"severity\": \"critical|warning|suggestion\", \"suggestion\": \"<replacement code or null>\" }\n ],\n \"positives\": [\"<good thing>\"],\n \"testingNotes\": \"<how to manually test>\",\n \"checklist\": [\n { \"area\": \"<Correctness|Security|Robustness|Performance|Breaking changes|Best practices|Tests|Documentation>\", \"status\": \"pass|warn|fail\", \"note\": \"<one sentence>\" }\n ]\n}`;\n}\n\n// ─── Diff parsing ─────────────────────────────────────────────────────────────\n\n/**\n * Parse a unified diff and return the NEW-file line ranges that were touched,\n * grouped by file path.\n *\n * A diff hunk header looks like: @@ -10,7 +12,8 @@\n * +12,8 → new file starts at line 12, hunk spans 8 lines\n */\nfunction parseHunkRanges(diff: string): Map<string, Array<{ start: number; end: number }>> {\n const result = new Map<string, Array<{ start: number; end: number }>>();\n let currentFile = \"\";\n\n for (const line of diff.split(\"\\n\")) {\n const fileMatch = line.match(/^\\+\\+\\+ b\\/(.+)/);\n if (fileMatch?.[1] && fileMatch[1] !== \"/dev/null\") {\n currentFile = fileMatch[1].trim();\n if (!result.has(currentFile)) result.set(currentFile, []);\n continue;\n }\n\n // @@ -old,count +new,count @@\n const hunkMatch = line.match(/^@@ -\\d+(?:,\\d+)? \\+(\\d+)(?:,(\\d+))? @@/);\n if (hunkMatch && currentFile) {\n const start = parseInt(hunkMatch[1]!, 10);\n const count = parseInt(hunkMatch[2] ?? \"1\", 10);\n result.get(currentFile)!.push({ start, end: start + Math.max(count - 1, 0) });\n }\n }\n\n return result;\n}\n\n/**\n * Scan BACKWARD from `fromLine` (1-based) to find where the containing\n * function / class / method starts.\n *\n * Recognises common declaration patterns for TypeScript, JavaScript, Python,\n * Go, Rust, Java, and C#. Falls back to `fromLine - fallback` if nothing\n * is found within `maxScan` lines.\n */\nfunction findContainerStart(\n lines: string[],\n fromLine: number,\n maxScan = 80,\n fallback = 30\n): number {\n // fromLine is 1-based; lines[] is 0-based\n const startIdx = Math.min(lines.length - 1, Math.max(0, fromLine - 2));\n\n for (let i = startIdx; i >= Math.max(0, startIdx - maxScan); i--) {\n const line = lines[i] ?? \"\";\n if (\n // TS/JS: export [default] [abstract] [async] function foo(\n /^\\s*(export\\s+)?(default\\s+)?(abstract\\s+)?(async\\s+)?function[\\s*]/.test(line) ||\n // TS/JS: export [abstract] class Foo\n /^\\s*(export\\s+)?(abstract\\s+)?class\\s+\\w/.test(line) ||\n // TS/JS class methods: [public|private|protected|static|override|async] methodName(\n /^\\s*(public|private|protected|static|override|async)(\\s+(public|private|protected|static|override|async))*\\s+\\w+\\s*[(<]/.test(line) ||\n // TS/JS arrow function assigned to const/let/var\n /^\\s*(export\\s+)?(const|let|var)\\s+\\w+\\s*=\\s*(async\\s+)?\\(/.test(line) ||\n // TS/JS shorthand method (no keyword): methodName(args) {\n /^\\s*\\w+\\s*\\([^)]*\\)\\s*(?::\\s*\\S+\\s*)?\\{/.test(line) ||\n // Python: def foo(\n /^\\s*def\\s+\\w+\\s*\\(/.test(line) ||\n // Go: func (recv) Foo(\n /^\\s*func\\s+/.test(line) ||\n // Rust: fn foo(\n /^\\s*(pub\\s+)?(async\\s+)?fn\\s+\\w+/.test(line) ||\n // Java/C#: returnType methodName(\n /^\\s*(public|private|protected|internal|static|virtual|override)\\s+\\S+\\s+\\w+\\s*\\(/.test(line)\n ) {\n return i + 1; // convert back to 1-based\n }\n }\n\n // Nothing found — fall back to a fixed number of lines above\n return Math.max(1, fromLine - fallback);\n}\n\n/**\n * Extract the sections of a file that were changed, always starting each\n * window at the nearest enclosing function/class boundary (or 30 lines up,\n * whichever is closer).\n *\n * Overlapping windows are merged so the same lines aren't shown twice.\n * The first HEADER_LINES of the file are always prepended (imports, class\n * declarations) so the AI understands module structure.\n *\n * Returns a line-numbered string ready to paste into the prompt.\n */\nfunction extractChangedSections(\n fileContent: string,\n hunks: Array<{ start: number; end: number }>,\n contextLinesBelow = 20 // lines below the hunk (above uses function-boundary scan)\n): string {\n const lines = fileContent.split(\"\\n\");\n const total = lines.length;\n\n // Always include file header (imports / module preamble) for structural context\n const HEADER_LINES = 20;\n\n // Build windows: above = scan to function start, below = fixed context\n const windows: Array<{ start: number; end: number }> = [];\n for (const hunk of hunks) {\n const windowStart = findContainerStart(lines, hunk.start);\n windows.push({\n start: windowStart,\n end: Math.min(total, hunk.end + contextLinesBelow),\n });\n }\n // Sort then merge\n windows.sort((a, b) => a.start - b.start);\n const merged: Array<{ start: number; end: number }> = [];\n for (const w of windows) {\n if (merged.length > 0 && w.start <= merged[merged.length - 1]!.end + 1) {\n merged[merged.length - 1]!.end = Math.max(merged[merged.length - 1]!.end, w.end);\n } else {\n merged.push({ ...w });\n }\n }\n\n const formatRange = (start: number, end: number): string =>\n lines\n .slice(start - 1, end)\n .map((l, i) => `${String(start + i).padStart(5, \" \")} | ${l}`)\n .join(\"\\n\");\n\n const sections: string[] = [];\n\n // File header (always included, unless the first window already covers it)\n const firstWindowStart = merged[0]?.start ?? 1;\n if (firstWindowStart > HEADER_LINES + 1) {\n sections.push(formatRange(1, Math.min(HEADER_LINES, total)));\n sections.push(\" … (lines omitted) …\");\n }\n\n for (let i = 0; i < merged.length; i++) {\n const { start, end } = merged[i]!;\n if (i > 0 && start > (merged[i - 1]!.end + 1)) {\n sections.push(\" … (lines omitted) …\");\n }\n sections.push(formatRange(start, end));\n }\n\n return sections.join(\"\\n\");\n}\n\n// ─── User prompt builder ──────────────────────────────────────────────────────\n\nexport function buildSeniorReviewPrompt(\n context: {\n prTitle: string;\n prBody: string;\n author: string;\n headBranch: string;\n baseBranch: string;\n diff: string;\n changedFiles: Record<string, string>;\n contextFiles: Record<string, string>;\n repoFileList: string[];\n existingComments: Array<{ author: string; body: string; path?: string; line?: number }>;\n }\n): string {\n const parts: string[] = [];\n\n parts.push(`## PR: ${context.prTitle}`);\n parts.push(`Author: ${context.author} | ${context.headBranch} → ${context.baseBranch}`);\n if (context.prBody.trim()) {\n parts.push(`\\n### Description\\n${context.prBody.slice(0, 1000)}`);\n }\n\n // ── Parse which lines actually changed per file ───────────────────────────\n const hunkRanges = parseHunkRanges(context.diff);\n\n // ── Changed file sections — only the relevant areas + function context ──────\n // Hard per-file cap: if a single function is genuinely 500+ lines we still\n // need to stop somewhere, but we ALWAYS stop on a complete line boundary so\n // the AI never sees half a statement.\n // The per-file cap is generous (300 lines) to handle large but realistic functions.\n const PER_FILE_LINE_CAP = 300;\n const DIFF_BUDGET = 5_000;\n const CTX_FILE_MAX = 1_500;\n\n const changedEntries = Object.entries(context.changedFiles);\n if (changedEntries.length > 0) {\n parts.push(`\\n### Changed sections (line numbers are exact positions in the new file)`);\n\n for (const [path, content] of changedEntries) {\n const hunks = hunkRanges.get(path) ?? [];\n\n let excerpt: string;\n if (hunks.length === 0) {\n // No hunk data (binary / rename-only) — show first 60 lines as fallback\n const lines = content.split(\"\\n\");\n excerpt = lines\n .slice(0, 60)\n .map((l, i) => `${String(i + 1).padStart(5, \" \")} | ${l}`)\n .join(\"\\n\");\n if (lines.length > 60) excerpt += \"\\n … (file continues — only first 60 lines shown as fallback)\";\n } else {\n excerpt = extractChangedSections(content, hunks);\n }\n\n // Cap at PER_FILE_LINE_CAP complete lines — never mid-line\n const excerptLines = excerpt.split(\"\\n\");\n let finalExcerpt: string;\n if (excerptLines.length > PER_FILE_LINE_CAP) {\n finalExcerpt =\n excerptLines.slice(0, PER_FILE_LINE_CAP).join(\"\\n\") +\n `\\n … (${excerptLines.length - PER_FILE_LINE_CAP} more lines not shown` +\n ` — this function is unusually large; review the diff for remaining changes)`;\n } else {\n finalExcerpt = excerpt;\n }\n\n const hunkDesc = hunks.length > 0\n ? ` (${hunks.length} change hunk${hunks.length > 1 ? \"s\" : \"\"})`\n : \"\";\n parts.push(`\\n#### ${path}${hunkDesc}\\n\\`\\`\\`\\n${finalExcerpt}\\n\\`\\`\\``);\n }\n }\n\n // ── Diff (compact view of what changed, used for overall change understanding)\n if (context.diff.trim()) {\n const diffSlice = context.diff.slice(0, DIFF_BUDGET);\n const diffTrunc = diffSlice.length < context.diff.length;\n parts.push(\n `\\n### Unified diff${diffTrunc ? \" (truncated)\" : \"\"}\\n\\`\\`\\`diff\\n${diffSlice}\\n\\`\\`\\``\n );\n }\n\n // ── Supporting context files (unchanged files the changes depend on) ──────\n const ctxEntries = Object.entries(context.contextFiles);\n if (ctxEntries.length > 0) {\n parts.push(`\\n### Supporting context files (unchanged — imported by changed files)`);\n for (const [path, content] of ctxEntries) {\n parts.push(`\\n#### ${path}\\n\\`\\`\\`\\n${content.slice(0, CTX_FILE_MAX)}\\n\\`\\`\\``);\n }\n }\n\n // ── Existing PR comments ──────────────────────────────────────────────────\n if (context.existingComments.length > 0) {\n parts.push(`\\n### Existing review comments`);\n for (const c of context.existingComments.slice(0, 6)) {\n const loc = c.path ? ` (${c.path}${c.line ? `:${c.line}` : \"\"})` : \"\";\n parts.push(`- **${c.author}**${loc}: ${c.body.slice(0, 150)}`);\n }\n }\n\n // ── Repo file tree (structural awareness) ────────────────────────────────\n if (context.repoFileList.length > 0) {\n parts.push(`\\n### Repository file tree (top 60 files)\\n${context.repoFileList.slice(0, 60).join(\"\\n\")}`);\n }\n\n return parts.join(\"\\n\");\n}\n\n// ─── Response parser ──────────────────────────────────────────────────────────\n\nexport function parseSeniorReview(text: string): AiDetailedReviewResponse {\n let parsed: Partial<AiDetailedReviewResponse> = {};\n try {\n const fenced = text.match(/```(?:json)?\\s*([\\s\\S]*?)```/);\n const raw = fenced?.[1]?.trim() ?? text.trim();\n const start = raw.search(/\\{/);\n const end = raw.lastIndexOf(\"}\");\n const jsonStr = start !== -1 && end > start ? raw.slice(start, end + 1) : raw;\n parsed = JSON.parse(jsonStr) as Partial<AiDetailedReviewResponse>;\n } catch {\n return {\n summary: \"AI review could not be parsed. Please inspect the diff manually.\",\n verdict: \"comment\",\n issues: [],\n inlineComments: [],\n positives: [],\n testingNotes: \"Test the changed functionality manually.\",\n checklist: [],\n };\n }\n\n return {\n summary: parsed.summary ?? \"Review generated.\",\n verdict: ([\"approve\", \"request_changes\", \"comment\"].includes(parsed.verdict ?? \"\"))\n ? (parsed.verdict as AiDetailedReviewResponse[\"verdict\"])\n : \"comment\",\n issues: Array.isArray(parsed.issues) ? parsed.issues : [],\n inlineComments: Array.isArray(parsed.inlineComments)\n ? parsed.inlineComments.filter((c) => c.path && c.line > 0)\n : [],\n positives: Array.isArray(parsed.positives) ? parsed.positives : [],\n testingNotes: parsed.testingNotes ?? \"\",\n checklist: Array.isArray(parsed.checklist) ? parsed.checklist : [],\n };\n}\n\n// ─── Fix generation helpers ───────────────────────────────────────────────────\n\n/**\n * System prompt for the AI fix generator.\n * Instructs the model to produce a minimal, targeted line-range replacement.\n */\nexport function buildFixSystem(): string {\n return `You are a senior developer addressing a pull request review comment.\nYour job is to generate the MINIMAL code change that addresses the reviewer's concern.\n\nRules:\n- Change as few lines as possible — do not refactor surrounding code\n- Preserve the existing indentation style exactly\n- If the comment is a question or discussion (no code change needed), set isDiscussion: true\n- If you are unsure of the correct fix, set confidence: \"low\"\n- startLine and endLine are 1-based, inclusive line numbers in the CURRENT file\n\nRespond with ONLY valid JSON (no markdown fences, no prose outside JSON):\n{\n \"file\": \"<relative file path>\",\n \"startLine\": <1-based line where replacement starts>,\n \"endLine\": <1-based line where replacement ends, inclusive>,\n \"replacement\": \"<new code lines, newline-separated, preserving indentation>\",\n \"explanation\": \"<one sentence: what you changed and why>\",\n \"confidence\": \"high|low\",\n \"resolves\": true|false,\n \"isDiscussion\": true|false\n}`;\n}\n\n/**\n * Build the user prompt for a single fix request.\n * Includes the comment, file content with line numbers, and the relevant diff.\n */\nexport function buildFixPrompt(ctx: {\n comment: string;\n commentAuthor: string;\n filePath: string;\n line: number;\n fileContent: string;\n fileDiff: string;\n}): string {\n const lines = ctx.fileContent.split(\"\\n\");\n\n // Show a window of ±30 lines around the commented line (with real line numbers)\n const windowStart = Math.max(1, ctx.line - 30);\n const windowEnd = Math.min(lines.length, ctx.line + 30);\n const excerpt = lines\n .slice(windowStart - 1, windowEnd)\n .map((l, i) => `${String(windowStart + i).padStart(4, \" \")} | ${l}`)\n .join(\"\\n\");\n\n const diffSection = ctx.fileDiff.length > 3000\n ? ctx.fileDiff.slice(0, 3000) + \"\\n... (diff truncated)\"\n : ctx.fileDiff;\n\n return `## Review Comment\nAuthor: ${ctx.commentAuthor}\nFile: ${ctx.filePath} · Line: ${ctx.line}\n\n> ${ctx.comment.replace(/\\n/g, \"\\n> \")}\n\n## File Context (lines ${windowStart}–${windowEnd} of ${lines.length})\n\\`\\`\\`\n${excerpt}\n\\`\\`\\`\n\n## Diff for this file\n\\`\\`\\`diff\n${diffSection}\n\\`\\`\\`\n\nGenerate the fix JSON now.`;\n}\n\n/**\n * Safely parse the AI response for a fix request.\n * Returns a safe fallback (isDiscussion + low confidence) on parse failure.\n */\nexport function parseFixResponse(text: string, filePath: string, line: number): AiFixResponse {\n try {\n const jsonMatch = text.match(/\\{[\\s\\S]*\\}/);\n if (!jsonMatch) throw new Error(\"no JSON found\");\n const parsed = JSON.parse(jsonMatch[0]) as Partial<AiFixResponse>;\n\n if (parsed.isDiscussion) {\n return {\n file: parsed.file ?? filePath,\n startLine: line,\n endLine: line,\n replacement: \"\",\n explanation: parsed.explanation ?? \"This comment is a discussion — no code change needed.\",\n confidence: \"low\",\n resolves: parsed.resolves ?? false,\n isDiscussion: true,\n };\n }\n\n // Validate required fields; fall back to low confidence if anything is off\n const hasReplacement = typeof parsed.replacement === \"string\";\n const hasLines = typeof parsed.startLine === \"number\" && typeof parsed.endLine === \"number\";\n if (!hasReplacement || !hasLines) {\n throw new Error(\"missing required fields\");\n }\n\n return {\n file: parsed.file ?? filePath,\n startLine: parsed.startLine!,\n endLine: parsed.endLine!,\n replacement: parsed.replacement!,\n explanation: parsed.explanation ?? \"AI-generated fix.\",\n confidence: parsed.confidence === \"high\" ? \"high\" : \"low\",\n resolves: parsed.resolves ?? false,\n isDiscussion: false,\n };\n } catch {\n return {\n file: filePath,\n startLine: line,\n endLine: line,\n replacement: \"\",\n explanation: \"AI could not generate a fix for this comment.\",\n confidence: \"low\",\n resolves: false,\n isDiscussion: true, // treat parse failure as discussion → no code change\n };\n }\n}\n\n// ─── Ask command helpers ───────────────────────────────────────────────────────\n\n/** Command reference embedded into the ask system prompt. */\nconst GITX_COMMAND_REFERENCE = `\n## gitx Command Reference\n\n| Command | Description |\n|---------|-------------|\n| gitx init / gitx config setup | Interactive setup wizard — configure git & AI providers |\n| gitx config show | Display current configuration (secrets redacted) |\n| gitx config set <key> [value] | Set a single config value (provider, token, model, etc.) |\n| gitx commit [-m msg] [--push] [--dry-run] | AI-generate commit message → commit (optionally push) |\n| gitx push [-b branch] [--dry-run] | Stage → AI-commit → push in one step |\n| gitx sync [--base branch] [--strategy merge|rebase] [--continue] [--abort] | Sync current branch with base; AI resolves conflicts |\n| gitx implement \"<task>\" [--mode plan|guided|semi-auto|auto] [--dry-run] | AI-plan and implement a task end-to-end |\n| gitx pr list [--state open|closed|all] | List pull requests |\n| gitx pr create [--title T] [--body B] [--draft] [--dry-run] | AI-generate PR title/body → open PR |\n| gitx pr review <number> [--no-comment] [--address] [--no-push] | Senior-dev AI review with inline comments |\n| gitx pr fix-comments <number> [--dry-run] [--no-push] | AI-fix review comments and push |\n| gitx pr merge <number> [--strategy squash|merge|rebase] [--delete-branch] | Merge a PR |\n| gitx pr close <number> [-f] | Close a PR |\n| gitx ask \"<question>\" [--pr] | Ask a question about the repo using AI + live git context |\n\n## Supported Providers\n- Git hosts: GitHub, GitLab, Azure DevOps\n- AI backends: Anthropic Claude (API), OpenAI, Local Claude CLI\n\n## Environment Variables\n- ANTHROPIC_API_KEY — Anthropic API key (auto-selects Claude as AI provider)\n- OPENAI_API_KEY — OpenAI API key\n- GITX_AI_MODEL — Override the AI model name\n- GITX_DEBUG=1 — Print full stack traces on errors\n`.trim();\n\n/**\n * Builds the system prompt for `gitx ask`.\n * Includes the full command reference and setup guidance so the AI can answer\n * both \"how do I…\" questions and \"is X configured?\" diagnostics.\n */\nexport function buildAskSystem(): string {\n return `You are gitx-assistant, a smart support assistant embedded in the gitx CLI.\nYou help users with three types of questions:\n\n1. SETUP / DIAGNOSTIC — \"is my AI provider set up?\", \"why isn't gitx working?\", \"what provider am I using?\"\n → Use the GITX SETUP STATUS section in the context. Give a clear yes/no diagnostic and actionable fix steps.\n\n2. REPO STATE — \"what did I last commit?\", \"do I have unstaged changes?\", \"show me open PRs\"\n → Use the LIVE REPO CONTEXT section in the context.\n\n3. HOW-TO — \"how do I sync with main?\", \"how do I undo a commit?\", \"how do I create a PR?\"\n → Use the GITX COMMAND REFERENCE below. Show the exact command.\n\n${GITX_COMMAND_REFERENCE}\n\n## Setup Fix Guide (use when AI or provider is not configured)\n- No AI provider → Run: gitx config setup (or set ANTHROPIC_API_KEY / OPENAI_API_KEY env var)\n- AI provider configured in config but not working → Run: gitx config show to inspect; re-run gitx config set <provider>\n- No git provider token → Run: gitx config set github (or gitlab / azure)\n- Not inside a git repo → cd into your project folder first\n\nRules:\n- Answer concisely and accurately. Get to the point immediately.\n- For setup/diagnostic questions: state clearly whether it IS or IS NOT configured, then explain WHY and how to fix it.\n- Never fabricate details — only use what is in the provided context.\n- Format your answer in plain text. Use a code block only for commands or file paths.\n- When suggesting commands, put them in suggestedCommands so they render highlighted.\n\nRespond with ONLY valid JSON (no markdown fences):\n{\"answer\":\"<answer text>\",\"suggestedCommands\":[\"<cmd1>\",\"<cmd2>\"]}\n\nThe suggestedCommands array may be empty [] if no command applies.`;\n}\n\n/**\n * Builds the user-turn prompt for `gitx ask`, injecting live repo context\n * and the full gitx setup status so the AI can answer diagnostic questions accurately.\n */\nexport function buildAskPrompt(question: string, ctx: AiAskContext): string {\n const lines: string[] = [];\n\n // ── Section 1: gitx setup status ──────────────────────────────────────────\n lines.push(`## gitx Setup Status`);\n\n // AI provider\n const ai = ctx.aiSetup;\n lines.push(`- AI provider: ${ai.provider}`);\n lines.push(`- AI configured: ${ai.isConfigured ? \"YES\" : \"NO — not configured\"}`);\n if (ai.model) lines.push(`- AI model: ${ai.model}`);\n lines.push(`- AI key source: ${ai.keySource}`);\n\n // Git providers\n if (ctx.gitProviders.length > 0) {\n lines.push(`- Git providers configured:`);\n ctx.gitProviders.forEach((p) => {\n const tokenStatus = p.hasToken ? \"token ✓\" : \"token MISSING\";\n lines.push(` ${p.name}: ${tokenStatus}`);\n });\n } else {\n lines.push(`- Git providers configured: none`);\n }\n\n if (ctx.defaultBranch) {\n lines.push(`- Default base branch: ${ctx.defaultBranch}`);\n }\n\n // ── Section 2: live repo context ──────────────────────────────────────────\n lines.push(``);\n lines.push(`## Live Repo Context`);\n lines.push(`- Inside git repo: ${ctx.isInsideGitRepo ? \"YES\" : \"NO\"}`);\n\n if (ctx.isInsideGitRepo) {\n lines.push(`- Current branch: ${ctx.currentBranch}`);\n\n if (ctx.recentCommits.length > 0) {\n lines.push(`- Recent commits (newest first):`);\n ctx.recentCommits.forEach((c) => lines.push(` ${c}`));\n } else {\n lines.push(`- Recent commits: (none yet)`);\n }\n\n if (ctx.gitStatus.trim()) {\n lines.push(`- Working tree status:\\n${ctx.gitStatus}`);\n } else {\n lines.push(`- Working tree status: clean`);\n }\n\n if (ctx.stashes && ctx.stashes.length > 0) {\n lines.push(`- Stashes:`);\n ctx.stashes.forEach((s) => lines.push(` ${s}`));\n }\n\n if (ctx.openPRs && ctx.openPRs.length > 0) {\n lines.push(`- Open PRs:`);\n ctx.openPRs.forEach((pr) =>\n lines.push(` #${pr.number} [${pr.state}] \"${pr.title}\" (branch: ${pr.branch})`)\n );\n }\n }\n\n // ── Section 3: question ───────────────────────────────────────────────────\n lines.push(``);\n lines.push(`## Question`);\n lines.push(question);\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Safely parses the AI JSON response for `gitx ask`.\n * Falls back to using the raw text as the answer if JSON parsing fails.\n */\nexport function parseAskResponse(raw: string): AiAskResponse {\n try {\n const parsed = JSON.parse(raw) as Partial<AiAskResponse>;\n return {\n answer: parsed.answer?.trim() ?? raw.trim(),\n suggestedCommands: Array.isArray(parsed.suggestedCommands)\n ? parsed.suggestedCommands.filter((c): c is string => typeof c === \"string\")\n : [],\n };\n } catch {\n // If the AI returned plain text instead of JSON, use it directly\n return { answer: raw.trim(), suggestedCommands: [] };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"reviewHelpers.js","sourceRoot":"","sources":["../../src/ai/reviewHelpers.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAIH,iFAAiF;AAEjF,MAAM,UAAU,uBAAuB;I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t\n * buildSeniorReviewPrompt() — formats the user-facing context block\n * parseSeniorReview() — safely parses the AI JSON response\n */\n\nimport type { AiAskContext, AiAskResponse, AiDetailedReviewResponse, AiFixResponse } from \"./types.js\";\n\n// ─── System prompt ────────────────────────────────────────────────────────────\n\nexport function buildSeniorReviewSystem(): string {\n return `You are a principal software engineer and tech lead doing a thorough pull request review.\nYou have access to the CHANGED SECTIONS of each file (extracted around the exact lines that changed),\nplus supporting context files and the full unified diff.\n\nYour review MUST cover every one of these dimensions:\n 1. Correctness — logic errors, off-by-one, wrong conditions, silent failures\n 2. Security — injection, auth bypass, secret leakage, unvalidated input\n 3. Robustness — missing error handling, null/undefined guard, edge cases\n 4. Performance — unnecessary loops, N+1 queries, missing caching\n 5. Breaking changes — does this break existing API contracts, interfaces, or callers?\n 6. Best practices — naming, DRY, SOLID, idiomatic language usage\n 7. Test coverage — are critical paths tested? are tests meaningful?\n 8. Documentation — are public APIs documented? are complex sections explained?\n\nFor EVERY issue that maps to a specific line, add an inline comment.\nLine numbers shown in the excerpts are the REAL line numbers in the new file — use them exactly.\nOnly reference lines that appear in the excerpts you were given.\n\nVerdict rules:\n - \"approve\" → no critical or warning issues\n - \"request_changes\" → one or more critical/warning issues found\n - \"comment\" → only suggestions / minor observations\n\nRespond with ONLY valid JSON (no markdown fences, no prose outside JSON):\n{\n \"summary\": \"<3-5 sentence executive summary>\",\n \"verdict\": \"approve|request_changes|comment\",\n \"issues\": [\n { \"severity\": \"critical|warning|suggestion\", \"description\": \"<issue>\", \"file\": \"<path or null>\", \"line\": <number or null> }\n ],\n \"inlineComments\": [\n { \"path\": \"<relative file path>\", \"line\": <line number>, \"body\": \"<markdown comment>\", \"severity\": \"critical|warning|suggestion\", \"suggestion\": \"<replacement code or null>\" }\n ],\n \"positives\": [\"<good thing>\"],\n \"testingNotes\": \"<how to manually test>\",\n \"checklist\": [\n { \"area\": \"<Correctness|Security|Robustness|Performance|Breaking changes|Best practices|Tests|Documentation>\", \"status\": \"pass|warn|fail\", \"note\": \"<one sentence>\" }\n ]\n}`;\n}\n\n// ─── Diff parsing ─────────────────────────────────────────────────────────────\n\n/**\n * Parse a unified diff and return the NEW-file line ranges that were touched,\n * grouped by file path.\n *\n * A diff hunk header looks like: @@ -10,7 +12,8 @@\n * +12,8 → new file starts at line 12, hunk spans 8 lines\n */\nfunction parseHunkRanges(diff: string): Map<string, Array<{ start: number; end: number }>> {\n const result = new Map<string, Array<{ start: number; end: number }>>();\n let currentFile = \"\";\n\n for (const line of diff.split(\"\\n\")) {\n const fileMatch = line.match(/^\\+\\+\\+ b\\/(.+)/);\n if (fileMatch?.[1] && fileMatch[1] !== \"/dev/null\") {\n currentFile = fileMatch[1].trim();\n if (!result.has(currentFile)) result.set(currentFile, []);\n continue;\n }\n\n // @@ -old,count +new,count @@\n const hunkMatch = line.match(/^@@ -\\d+(?:,\\d+)? \\+(\\d+)(?:,(\\d+))? @@/);\n if (hunkMatch && currentFile) {\n const start = parseInt(hunkMatch[1]!, 10);\n const count = parseInt(hunkMatch[2] ?? \"1\", 10);\n result.get(currentFile)!.push({ start, end: start + Math.max(count - 1, 0) });\n }\n }\n\n return result;\n}\n\n/**\n * Scan BACKWARD from `fromLine` (1-based) to find where the containing\n * function / class / method starts.\n *\n * Recognises common declaration patterns for TypeScript, JavaScript, Python,\n * Go, Rust, Java, and C#. Falls back to `fromLine - fallback` if nothing\n * is found within `maxScan` lines.\n */\nfunction findContainerStart(\n lines: string[],\n fromLine: number,\n maxScan = 80,\n fallback = 30\n): number {\n // fromLine is 1-based; lines[] is 0-based\n const startIdx = Math.min(lines.length - 1, Math.max(0, fromLine - 2));\n\n for (let i = startIdx; i >= Math.max(0, startIdx - maxScan); i--) {\n const line = lines[i] ?? \"\";\n if (\n // TS/JS: export [default] [abstract] [async] function foo(\n /^\\s*(export\\s+)?(default\\s+)?(abstract\\s+)?(async\\s+)?function[\\s*]/.test(line) ||\n // TS/JS: export [abstract] class Foo\n /^\\s*(export\\s+)?(abstract\\s+)?class\\s+\\w/.test(line) ||\n // TS/JS class methods: [public|private|protected|static|override|async] methodName(\n /^\\s*(public|private|protected|static|override|async)(\\s+(public|private|protected|static|override|async))*\\s+\\w+\\s*[(<]/.test(line) ||\n // TS/JS arrow function assigned to const/let/var\n /^\\s*(export\\s+)?(const|let|var)\\s+\\w+\\s*=\\s*(async\\s+)?\\(/.test(line) ||\n // TS/JS shorthand method (no keyword): methodName(args) {\n /^\\s*\\w+\\s*\\([^)]*\\)\\s*(?::\\s*\\S+\\s*)?\\{/.test(line) ||\n // Python: def foo(\n /^\\s*def\\s+\\w+\\s*\\(/.test(line) ||\n // Go: func (recv) Foo(\n /^\\s*func\\s+/.test(line) ||\n // Rust: fn foo(\n /^\\s*(pub\\s+)?(async\\s+)?fn\\s+\\w+/.test(line) ||\n // Java/C#: returnType methodName(\n /^\\s*(public|private|protected|internal|static|virtual|override)\\s+\\S+\\s+\\w+\\s*\\(/.test(line)\n ) {\n return i + 1; // convert back to 1-based\n }\n }\n\n // Nothing found — fall back to a fixed number of lines above\n return Math.max(1, fromLine - fallback);\n}\n\n/**\n * Extract the sections of a file that were changed, always starting each\n * window at the nearest enclosing function/class boundary (or 30 lines up,\n * whichever is closer).\n *\n * Overlapping windows are merged so the same lines aren't shown twice.\n * The first HEADER_LINES of the file are always prepended (imports, class\n * declarations) so the AI understands module structure.\n *\n * Returns a line-numbered string ready to paste into the prompt.\n */\nfunction extractChangedSections(\n fileContent: string,\n hunks: Array<{ start: number; end: number }>,\n contextLinesBelow = 20 // lines below the hunk (above uses function-boundary scan)\n): string {\n const lines = fileContent.split(\"\\n\");\n const total = lines.length;\n\n // Always include file header (imports / module preamble) for structural context\n const HEADER_LINES = 20;\n\n // Build windows: above = scan to function start, below = fixed context\n const windows: Array<{ start: number; end: number }> = [];\n for (const hunk of hunks) {\n const windowStart = findContainerStart(lines, hunk.start);\n windows.push({\n start: windowStart,\n end: Math.min(total, hunk.end + contextLinesBelow),\n });\n }\n // Sort then merge\n windows.sort((a, b) => a.start - b.start);\n const merged: Array<{ start: number; end: number }> = [];\n for (const w of windows) {\n if (merged.length > 0 && w.start <= merged[merged.length - 1]!.end + 1) {\n merged[merged.length - 1]!.end = Math.max(merged[merged.length - 1]!.end, w.end);\n } else {\n merged.push({ ...w });\n }\n }\n\n const formatRange = (start: number, end: number): string =>\n lines\n .slice(start - 1, end)\n .map((l, i) => `${String(start + i).padStart(5, \" \")} | ${l}`)\n .join(\"\\n\");\n\n const sections: string[] = [];\n\n // File header (always included, unless the first window already covers it)\n const firstWindowStart = merged[0]?.start ?? 1;\n if (firstWindowStart > HEADER_LINES + 1) {\n sections.push(formatRange(1, Math.min(HEADER_LINES, total)));\n sections.push(\" … (lines omitted) …\");\n }\n\n for (let i = 0; i < merged.length; i++) {\n const { start, end } = merged[i]!;\n if (i > 0 && start > (merged[i - 1]!.end + 1)) {\n sections.push(\" … (lines omitted) …\");\n }\n sections.push(formatRange(start, end));\n }\n\n return sections.join(\"\\n\");\n}\n\n// ─── User prompt builder ──────────────────────────────────────────────────────\n\nexport function buildSeniorReviewPrompt(\n context: {\n prTitle: string;\n prBody: string;\n author: string;\n headBranch: string;\n baseBranch: string;\n diff: string;\n changedFiles: Record<string, string>;\n contextFiles: Record<string, string>;\n repoFileList: string[];\n existingComments: Array<{ author: string; body: string; path?: string; line?: number }>;\n }\n): string {\n const parts: string[] = [];\n\n parts.push(`## PR: ${context.prTitle}`);\n parts.push(`Author: ${context.author} | ${context.headBranch} → ${context.baseBranch}`);\n if (context.prBody.trim()) {\n parts.push(`\\n### Description\\n${context.prBody.slice(0, 1000)}`);\n }\n\n // ── Parse which lines actually changed per file ───────────────────────────\n const hunkRanges = parseHunkRanges(context.diff);\n\n // ── Budget constants ──────────────────────────────────────────────────────\n // Claude has a 200k-token context window. We stay well within that while\n // sending enough code for a thorough review.\n //\n // Strategy:\n // • Files ≤ FULL_FILE_THRESHOLD lines → send the ENTIRE file (best context)\n // • Larger files → smart section extraction around hunks\n // with generous context above (function boundary) and below (CONTEXT_LINES_BELOW)\n // • Hard per-file cap for huge files → PER_FILE_LINE_CAP lines of excerpts\n const FULL_FILE_THRESHOLD = 400; // files ≤ this many lines are sent whole\n const CONTEXT_LINES_BELOW = 60; // lines below each hunk in extraction mode\n const PER_FILE_LINE_CAP = 800; // hard cap on excerpt lines for very large files\n const DIFF_BUDGET = 30_000; // unified diff character budget (was 5k — way too small)\n const CTX_FILE_MAX = 4_000; // max chars per supporting context file (was 1.5k)\n\n const changedEntries = Object.entries(context.changedFiles);\n if (changedEntries.length > 0) {\n parts.push(`\\n### Changed files (line numbers are exact positions in the new file)`);\n\n for (const [path, content] of changedEntries) {\n const fileLines = content.split(\"\\n\");\n const hunks = hunkRanges.get(path) ?? [];\n\n let excerpt: string;\n let deliveryNote: string;\n\n if (fileLines.length <= FULL_FILE_THRESHOLD) {\n // Small file — send the whole thing. The AI gets complete context with no gaps.\n excerpt = fileLines\n .map((l, i) => `${String(i + 1).padStart(5, \" \")} | ${l}`)\n .join(\"\\n\");\n deliveryNote = `full file, ${fileLines.length} lines`;\n } else if (hunks.length === 0) {\n // No hunk data (binary / rename-only) — show first 100 lines as fallback\n excerpt = fileLines\n .slice(0, 100)\n .map((l, i) => `${String(i + 1).padStart(5, \" \")} | ${l}`)\n .join(\"\\n\");\n if (fileLines.length > 100)\n excerpt += `\\n … (file continues — only first 100 lines shown; no hunk data available)`;\n deliveryNote = `first 100 of ${fileLines.length} lines (no hunk data)`;\n } else {\n // Large file — extract sections around changed hunks with generous context\n excerpt = extractChangedSections(content, hunks, CONTEXT_LINES_BELOW);\n\n // Cap at PER_FILE_LINE_CAP complete lines — never mid-line\n const excerptLines = excerpt.split(\"\\n\");\n if (excerptLines.length > PER_FILE_LINE_CAP) {\n excerpt =\n excerptLines.slice(0, PER_FILE_LINE_CAP).join(\"\\n\") +\n `\\n … (${excerptLines.length - PER_FILE_LINE_CAP} more excerpt lines omitted` +\n ` — file has ${fileLines.length} total lines; see the diff below for full change)`;\n }\n deliveryNote = `${hunks.length} hunk${hunks.length > 1 ? \"s\" : \"\"}, ${fileLines.length} total lines`;\n }\n\n parts.push(`\\n#### ${path} (${deliveryNote})\\n\\`\\`\\`\\n${excerpt}\\n\\`\\`\\``);\n }\n }\n\n // ── Unified diff (the raw patch — gives the AI the exact before/after for every line)\n if (context.diff.trim()) {\n const diffSlice = context.diff.slice(0, DIFF_BUDGET);\n const diffTrunc = diffSlice.length < context.diff.length;\n parts.push(\n `\\n### Unified diff${diffTrunc ? ` (truncated to ${DIFF_BUDGET} chars — see file sections above for full content)` : \"\"}\\n\\`\\`\\`diff\\n${diffSlice}\\n\\`\\`\\``\n );\n }\n\n // ── Supporting context files (unchanged files the changes depend on) ──────\n const ctxEntries = Object.entries(context.contextFiles);\n if (ctxEntries.length > 0) {\n parts.push(`\\n### Supporting context files (unchanged — imported by changed files)`);\n for (const [path, content] of ctxEntries) {\n const ctxLines = content.split(\"\\n\");\n const ctxExcerpt = content.length <= CTX_FILE_MAX\n ? content\n : content.slice(0, CTX_FILE_MAX) + `\\n… (truncated — ${ctxLines.length} total lines)`;\n parts.push(`\\n#### ${path}\\n\\`\\`\\`\\n${ctxExcerpt}\\n\\`\\`\\``);\n }\n }\n\n // ── Existing PR comments ──────────────────────────────────────────────────\n if (context.existingComments.length > 0) {\n parts.push(`\\n### Existing review comments`);\n for (const c of context.existingComments.slice(0, 6)) {\n const loc = c.path ? ` (${c.path}${c.line ? `:${c.line}` : \"\"})` : \"\";\n parts.push(`- **${c.author}**${loc}: ${c.body.slice(0, 150)}`);\n }\n }\n\n // ── Repo file tree (structural awareness) ────────────────────────────────\n if (context.repoFileList.length > 0) {\n parts.push(`\\n### Repository file tree (top 60 files)\\n${context.repoFileList.slice(0, 60).join(\"\\n\")}`);\n }\n\n return parts.join(\"\\n\");\n}\n\n// ─── Response parser ──────────────────────────────────────────────────────────\n\nexport function parseSeniorReview(text: string): AiDetailedReviewResponse {\n let parsed: Partial<AiDetailedReviewResponse> = {};\n try {\n const fenced = text.match(/```(?:json)?\\s*([\\s\\S]*?)```/);\n const raw = fenced?.[1]?.trim() ?? text.trim();\n const start = raw.search(/\\{/);\n const end = raw.lastIndexOf(\"}\");\n const jsonStr = start !== -1 && end > start ? raw.slice(start, end + 1) : raw;\n parsed = JSON.parse(jsonStr) as Partial<AiDetailedReviewResponse>;\n } catch {\n return {\n summary: \"AI review could not be parsed. Please inspect the diff manually.\",\n verdict: \"comment\",\n issues: [],\n inlineComments: [],\n positives: [],\n testingNotes: \"Test the changed functionality manually.\",\n checklist: [],\n };\n }\n\n return {\n summary: parsed.summary ?? \"Review generated.\",\n verdict: ([\"approve\", \"request_changes\", \"comment\"].includes(parsed.verdict ?? \"\"))\n ? (parsed.verdict as AiDetailedReviewResponse[\"verdict\"])\n : \"comment\",\n issues: Array.isArray(parsed.issues) ? parsed.issues : [],\n inlineComments: Array.isArray(parsed.inlineComments)\n ? parsed.inlineComments.filter((c) => c.path && c.line > 0)\n : [],\n positives: Array.isArray(parsed.positives) ? parsed.positives : [],\n testingNotes: parsed.testingNotes ?? \"\",\n checklist: Array.isArray(parsed.checklist) ? parsed.checklist : [],\n };\n}\n\n// ─── Fix generation helpers ───────────────────────────────────────────────────\n\n/**\n * System prompt for the AI fix generator.\n * Instructs the model to produce a minimal, targeted line-range replacement.\n */\nexport function buildFixSystem(): string {\n return `You are a senior developer addressing a pull request review comment.\nYour job is to generate the MINIMAL code change that addresses the reviewer's concern.\n\nRules:\n- Change as few lines as possible — do not refactor surrounding code\n- Preserve the existing indentation style exactly\n- If the comment is a question or discussion (no code change needed), set isDiscussion: true\n- If you are unsure of the correct fix, set confidence: \"low\"\n- startLine and endLine are 1-based, inclusive line numbers in the CURRENT file\n\nRespond with ONLY valid JSON (no markdown fences, no prose outside JSON):\n{\n \"file\": \"<relative file path>\",\n \"startLine\": <1-based line where replacement starts>,\n \"endLine\": <1-based line where replacement ends, inclusive>,\n \"replacement\": \"<new code lines, newline-separated, preserving indentation>\",\n \"explanation\": \"<one sentence: what you changed and why>\",\n \"confidence\": \"high|low\",\n \"resolves\": true|false,\n \"isDiscussion\": true|false\n}`;\n}\n\n/**\n * Build the user prompt for a single fix request.\n * Includes the comment, file content with line numbers, and the relevant diff.\n */\nexport function buildFixPrompt(ctx: {\n comment: string;\n commentAuthor: string;\n filePath: string;\n line: number;\n fileContent: string;\n fileDiff: string;\n}): string {\n const lines = ctx.fileContent.split(\"\\n\");\n\n // Show a window of ±30 lines around the commented line (with real line numbers)\n const windowStart = Math.max(1, ctx.line - 30);\n const windowEnd = Math.min(lines.length, ctx.line + 30);\n const excerpt = lines\n .slice(windowStart - 1, windowEnd)\n .map((l, i) => `${String(windowStart + i).padStart(4, \" \")} | ${l}`)\n .join(\"\\n\");\n\n const diffSection = ctx.fileDiff.length > 3000\n ? ctx.fileDiff.slice(0, 3000) + \"\\n... (diff truncated)\"\n : ctx.fileDiff;\n\n return `## Review Comment\nAuthor: ${ctx.commentAuthor}\nFile: ${ctx.filePath} · Line: ${ctx.line}\n\n> ${ctx.comment.replace(/\\n/g, \"\\n> \")}\n\n## File Context (lines ${windowStart}–${windowEnd} of ${lines.length})\n\\`\\`\\`\n${excerpt}\n\\`\\`\\`\n\n## Diff for this file\n\\`\\`\\`diff\n${diffSection}\n\\`\\`\\`\n\nGenerate the fix JSON now.`;\n}\n\n/**\n * Safely parse the AI response for a fix request.\n * Returns a safe fallback (isDiscussion + low confidence) on parse failure.\n */\nexport function parseFixResponse(text: string, filePath: string, line: number): AiFixResponse {\n try {\n const jsonMatch = text.match(/\\{[\\s\\S]*\\}/);\n if (!jsonMatch) throw new Error(\"no JSON found\");\n const parsed = JSON.parse(jsonMatch[0]) as Partial<AiFixResponse>;\n\n if (parsed.isDiscussion) {\n return {\n file: parsed.file ?? filePath,\n startLine: line,\n endLine: line,\n replacement: \"\",\n explanation: parsed.explanation ?? \"This comment is a discussion — no code change needed.\",\n confidence: \"low\",\n resolves: parsed.resolves ?? false,\n isDiscussion: true,\n };\n }\n\n // Validate required fields; fall back to low confidence if anything is off\n const hasReplacement = typeof parsed.replacement === \"string\";\n const hasLines = typeof parsed.startLine === \"number\" && typeof parsed.endLine === \"number\";\n if (!hasReplacement || !hasLines) {\n throw new Error(\"missing required fields\");\n }\n\n return {\n file: parsed.file ?? filePath,\n startLine: parsed.startLine!,\n endLine: parsed.endLine!,\n replacement: parsed.replacement!,\n explanation: parsed.explanation ?? \"AI-generated fix.\",\n confidence: parsed.confidence === \"high\" ? \"high\" : \"low\",\n resolves: parsed.resolves ?? false,\n isDiscussion: false,\n };\n } catch {\n return {\n file: filePath,\n startLine: line,\n endLine: line,\n replacement: \"\",\n explanation: \"AI could not generate a fix for this comment.\",\n confidence: \"low\",\n resolves: false,\n isDiscussion: true, // treat parse failure as discussion → no code change\n };\n }\n}\n\n// ─── Ask command helpers ───────────────────────────────────────────────────────\n\n/** Command reference embedded into the ask system prompt. */\nconst GITX_COMMAND_REFERENCE = `\n## gitx Command Reference\n\n| Command | Description |\n|---------|-------------|\n| gitx init / gitx config setup | Interactive setup wizard — configure git & AI providers |\n| gitx config show | Display current configuration (secrets redacted) |\n| gitx config set <key> [value] | Set a single config value (provider, token, model, etc.) |\n| gitx commit [-m msg] [--push] [--dry-run] | AI-generate commit message → commit (optionally push) |\n| gitx push [-b branch] [--staged] [--dry-run] | Stage → AI-commit → push in one step; --staged uses already-staged files only |\n| gitx sync [--base branch] [--strategy merge|rebase] [--continue] [--abort] | Fetch + merge/rebase base into current branch; AI auto-resolves conflicts. Run \"gitx pr resolve\" first if you have open review comments. |\n| gitx port <target…> [--base branch] [--no-pr] [--draft] [--continue] [--abort] | Cherry-pick commits onto other branches with incremental detection |\n| gitx implement \"<task>\" [--mode plan|guided|semi-auto|auto] [--dry-run] | AI-plan and implement a task end-to-end |\n| gitx pr list [--state open|closed|all] | List pull requests |\n| gitx pr create [--title T] [--body B] [--draft] [--dry-run] | AI-generate PR title/body → open PR |\n| gitx pr review <number> [--no-comment] [--inline] | Senior-dev AI review — posts inline comments to the PR |\n| gitx pr resolve <number> [--no-commit] [--no-push] [--dry-run] | AI-fix review comments in code; --no-commit applies fixes without committing |\n| gitx pr merge <number> [--strategy squash|merge|rebase] [--delete-branch] | Merge a PR |\n| gitx pr close <number> [-f] | Close a PR |\n| gitx pr cherry-pick <number> [--dry-run] [--no-confirm] | Cherry-pick all commits from a PR into the current branch |\n| gitx pr port <number> <target1> [target2...] [--no-pr] [--draft] [--dry-run] [--no-confirm] | Port a PR's commits onto one or more target branches and open PRs (current branch untouched) |\n| gitx ask \"<question>\" [--pr] | Ask a question about the repo using AI + live git context |\n\n## Supported Providers\n- Git hosts: GitHub, GitLab, Azure DevOps\n- AI backends: Anthropic Claude (API), OpenAI, Local Claude CLI\n\n## Environment Variables\n- ANTHROPIC_API_KEY — Anthropic API key (auto-selects Claude as AI provider)\n- OPENAI_API_KEY — OpenAI API key\n- GITX_AI_MODEL — Override the AI model name\n- GITX_DEBUG=1 — Print full stack traces on errors\n`.trim();\n\n/**\n * Builds the system prompt for `gitx ask`.\n * Includes the full command reference and setup guidance so the AI can answer\n * both \"how do I…\" questions and \"is X configured?\" diagnostics.\n */\nexport function buildAskSystem(): string {\n return `You are gitx-assistant, a smart support assistant embedded in the gitx CLI.\nYou help users with three types of questions:\n\n1. SETUP / DIAGNOSTIC — \"is my AI provider set up?\", \"why isn't gitx working?\", \"what provider am I using?\"\n → Use the GITX SETUP STATUS section in the context. Give a clear yes/no diagnostic and actionable fix steps.\n\n2. REPO STATE — \"what did I last commit?\", \"do I have unstaged changes?\", \"show me open PRs\"\n → Use the LIVE REPO CONTEXT section in the context.\n\n3. HOW-TO — \"how do I sync with main?\", \"how do I undo a commit?\", \"how do I create a PR?\"\n → Use the GITX COMMAND REFERENCE below. Show the exact command.\n\n${GITX_COMMAND_REFERENCE}\n\n## Setup Fix Guide (use when AI or provider is not configured)\n- No AI provider → Run: gitx config setup (or set ANTHROPIC_API_KEY / OPENAI_API_KEY env var)\n- AI provider configured in config but not working → Run: gitx config show to inspect; re-run gitx config set <provider>\n- No git provider token → Run: gitx config set github (or gitlab / azure)\n- Not inside a git repo → cd into your project folder first\n\nRules:\n- Answer concisely and accurately. Get to the point immediately.\n- For setup/diagnostic questions: state clearly whether it IS or IS NOT configured, then explain WHY and how to fix it.\n- Never fabricate details — only use what is in the provided context.\n- Format your answer in plain text. Use a code block only for commands or file paths.\n- When suggesting commands, put them in suggestedCommands so they render highlighted.\n\nRespond with ONLY valid JSON (no markdown fences):\n{\"answer\":\"<answer text>\",\"suggestedCommands\":[\"<cmd1>\",\"<cmd2>\"]}\n\nThe suggestedCommands array may be empty [] if no command applies.`;\n}\n\n/**\n * Builds the user-turn prompt for `gitx ask`, injecting live repo context\n * and the full gitx setup status so the AI can answer diagnostic questions accurately.\n */\nexport function buildAskPrompt(question: string, ctx: AiAskContext): string {\n const lines: string[] = [];\n\n // ── Section 1: gitx setup status ──────────────────────────────────────────\n lines.push(`## gitx Setup Status`);\n\n // AI provider\n const ai = ctx.aiSetup;\n lines.push(`- AI provider: ${ai.provider}`);\n lines.push(`- AI configured: ${ai.isConfigured ? \"YES\" : \"NO — not configured\"}`);\n if (ai.model) lines.push(`- AI model: ${ai.model}`);\n lines.push(`- AI key source: ${ai.keySource}`);\n\n // Git providers\n if (ctx.gitProviders.length > 0) {\n lines.push(`- Git providers configured:`);\n ctx.gitProviders.forEach((p) => {\n const tokenStatus = p.hasToken ? \"token ✓\" : \"token MISSING\";\n lines.push(` ${p.name}: ${tokenStatus}`);\n });\n } else {\n lines.push(`- Git providers configured: none`);\n }\n\n if (ctx.defaultBranch) {\n lines.push(`- Default base branch: ${ctx.defaultBranch}`);\n }\n\n // ── Section 2: live repo context ──────────────────────────────────────────\n lines.push(``);\n lines.push(`## Live Repo Context`);\n lines.push(`- Inside git repo: ${ctx.isInsideGitRepo ? \"YES\" : \"NO\"}`);\n\n if (ctx.isInsideGitRepo) {\n lines.push(`- Current branch: ${ctx.currentBranch}`);\n\n if (ctx.recentCommits.length > 0) {\n lines.push(`- Recent commits (newest first):`);\n ctx.recentCommits.forEach((c) => lines.push(` ${c}`));\n } else {\n lines.push(`- Recent commits: (none yet)`);\n }\n\n if (ctx.gitStatus.trim()) {\n lines.push(`- Working tree status:\\n${ctx.gitStatus}`);\n } else {\n lines.push(`- Working tree status: clean`);\n }\n\n if (ctx.stashes && ctx.stashes.length > 0) {\n lines.push(`- Stashes:`);\n ctx.stashes.forEach((s) => lines.push(` ${s}`));\n }\n\n if (ctx.openPRs && ctx.openPRs.length > 0) {\n lines.push(`- Open PRs:`);\n ctx.openPRs.forEach((pr) =>\n lines.push(` #${pr.number} [${pr.state}] \"${pr.title}\" (branch: ${pr.branch})`)\n );\n }\n }\n\n // ── Section 3: question ───────────────────────────────────────────────────\n lines.push(``);\n lines.push(`## Question`);\n lines.push(question);\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Safely parses the AI JSON response for `gitx ask`.\n * Falls back to using the raw text as the answer if JSON parsing fails.\n */\nexport function parseAskResponse(raw: string): AiAskResponse {\n try {\n const parsed = JSON.parse(raw) as Partial<AiAskResponse>;\n return {\n answer: parsed.answer?.trim() ?? raw.trim(),\n suggestedCommands: Array.isArray(parsed.suggestedCommands)\n ? parsed.suggestedCommands.filter((c): c is string => typeof c === \"string\")\n : [],\n };\n } catch {\n // If the AI returned plain text instead of JSON, use it directly\n return { answer: raw.trim(), suggestedCommands: [] };\n }\n}\n\n// ─── suggestFixes helpers (used by gitx pr resolve) ──────────────────────────\n\nexport interface SuggestFixesContext {\n comments: Array<{ body: string; path?: string; line?: number; author?: string }>;\n prTitle?: string;\n prBody?: string;\n /** Full unified diff of the PR — tells the AI what changed vs. the base */\n diff?: string;\n /** File contents keyed by relative path (with line numbers prefixed) */\n fileContents?: Record<string, string>;\n}\n\nexport interface SuggestFixesResponse {\n suggestedEdits: Array<{ path: string; rationale: string; unifiedDiff: string }>;\n}\n\nexport function buildSuggestFixesSystem(): string {\n return `You are a senior software engineer resolving pull request review comments by making precise code fixes.\n\nYou are given:\n 1. The PR title and description (for context)\n 2. The unified diff of the PR (shows exactly what changed vs. the base branch)\n 3. The current file contents of every file that has comments (with line numbers)\n 4. The review comments, each tagged with the file and line they target\n\nYour job:\n - For each comment that requires a code change, produce a minimal, correct unified diff that fixes it\n - The diff MUST apply cleanly to the CURRENT file content shown (not the base)\n - Preserve the existing code style, indentation, and patterns\n - If a comment is a question or praise (no code change needed), omit it from suggestedEdits\n - Do NOT fix things not mentioned in the comments — minimal targeted changes only\n\nRespond with ONLY valid JSON (no markdown fences):\n{\n \"suggestedEdits\": [\n {\n \"path\": \"<relative file path>\",\n \"rationale\": \"<one sentence: which comment this fixes and how>\",\n \"unifiedDiff\": \"<valid unified diff that applies to the current file content>\"\n }\n ]\n}`;\n}\n\nexport function buildSuggestFixesPrompt(ctx: SuggestFixesContext): string {\n const parts: string[] = [];\n\n parts.push(`PR Title: ${ctx.prTitle ?? \"(none)\"}`);\n if (ctx.prBody?.trim()) {\n parts.push(`\\nPR Description:\\n${ctx.prBody.trim()}`);\n }\n\n // Unified diff — gives the AI the before/after context for every changed line\n const DIFF_BUDGET = 30_000;\n if (ctx.diff?.trim()) {\n const diffSlice = ctx.diff.slice(0, DIFF_BUDGET);\n const truncated = diffSlice.length < ctx.diff.length;\n parts.push(\n `\\n### PR Unified Diff${truncated ? \" (truncated)\" : \"\"}\\n\\`\\`\\`diff\\n${diffSlice}\\n\\`\\`\\``\n );\n }\n\n // Review comments\n const commentsText = ctx.comments\n .map((c) =>\n `[${c.author ?? \"reviewer\"}${c.path ? ` on ${c.path}:${c.line ?? \"?\"}` : \"\"}]:\\n${c.body}`\n )\n .join(\"\\n\\n---\\n\\n\");\n parts.push(`\\n### Review Comments\\n${commentsText}`);\n\n // Current file contents (with line numbers so the diff is anchored correctly)\n if (ctx.fileContents && Object.keys(ctx.fileContents).length > 0) {\n parts.push(`\\n### Current File Contents (line numbers are exact — use them for your diffs)`);\n for (const [path, content] of Object.entries(ctx.fileContents)) {\n parts.push(`\\n#### ${path}\\n\\`\\`\\`\\n${content}\\n\\`\\`\\``);\n }\n }\n\n return parts.join(\"\\n\");\n}\n\nexport function parseSuggestFixesResponse(raw: string): SuggestFixesResponse {\n try {\n const parsed = JSON.parse(raw) as Partial<SuggestFixesResponse>;\n return {\n suggestedEdits: Array.isArray(parsed.suggestedEdits)\n ? parsed.suggestedEdits.filter(\n (e) => typeof e?.path === \"string\" && typeof e?.unifiedDiff === \"string\"\n )\n : [],\n };\n } catch {\n return { suggestedEdits: [] };\n }\n}\n"]}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* gitx pr cherry-pick <number>
|
|
3
|
+
*
|
|
4
|
+
* Fetch all commits from a PR and cherry-pick them into the current branch.
|
|
5
|
+
*
|
|
6
|
+
* Use this when you want to pull someone else's PR work (or a PR targeting
|
|
7
|
+
* a different branch) directly onto your own branch — without merging or
|
|
8
|
+
* waiting for the PR to land.
|
|
9
|
+
*
|
|
10
|
+
* Flow:
|
|
11
|
+
* 1. Fetch PR metadata → get head branch + base branch
|
|
12
|
+
* 2. git fetch origin <head> — ensure commits exist locally
|
|
13
|
+
* 3. List commits between base and head (oldest → newest)
|
|
14
|
+
* 4. Show commits + ask for confirmation (skipped with --no-confirm)
|
|
15
|
+
* 5. Cherry-pick each commit with -x flag (records source SHA)
|
|
16
|
+
* 6. On conflict → AI attempts resolution; unresolvable ones pause for manual fix
|
|
17
|
+
*
|
|
18
|
+
* Usage:
|
|
19
|
+
* gitx pr cherry-pick 42 # cherry-pick all commits of PR #42
|
|
20
|
+
* gitx pr cherry-pick 42 --dry-run # list commits without applying
|
|
21
|
+
* gitx pr cherry-pick 42 --no-confirm # skip confirmation prompt
|
|
22
|
+
*/
|
|
23
|
+
import type { Command } from "commander";
|
|
24
|
+
export declare function registerPrCherryPickCommand(pr: Command): void;
|
|
25
|
+
//# sourceMappingURL=cherryPick.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cherryPick.d.ts","sourceRoot":"","sources":["../../../../src/cli/commands/pr/cherryPick.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAqMzC,wBAAgB,2BAA2B,CAAC,EAAE,EAAE,OAAO,GAAG,IAAI,CAqK7D"}
|
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* gitx pr cherry-pick <number>
|
|
3
|
+
*
|
|
4
|
+
* Fetch all commits from a PR and cherry-pick them into the current branch.
|
|
5
|
+
*
|
|
6
|
+
* Use this when you want to pull someone else's PR work (or a PR targeting
|
|
7
|
+
* a different branch) directly onto your own branch — without merging or
|
|
8
|
+
* waiting for the PR to land.
|
|
9
|
+
*
|
|
10
|
+
* Flow:
|
|
11
|
+
* 1. Fetch PR metadata → get head branch + base branch
|
|
12
|
+
* 2. git fetch origin <head> — ensure commits exist locally
|
|
13
|
+
* 3. List commits between base and head (oldest → newest)
|
|
14
|
+
* 4. Show commits + ask for confirmation (skipped with --no-confirm)
|
|
15
|
+
* 5. Cherry-pick each commit with -x flag (records source SHA)
|
|
16
|
+
* 6. On conflict → AI attempts resolution; unresolvable ones pause for manual fix
|
|
17
|
+
*
|
|
18
|
+
* Usage:
|
|
19
|
+
* gitx pr cherry-pick 42 # cherry-pick all commits of PR #42
|
|
20
|
+
* gitx pr cherry-pick 42 --dry-run # list commits without applying
|
|
21
|
+
* gitx pr cherry-pick 42 --no-confirm # skip confirmation prompt
|
|
22
|
+
*/
|
|
23
|
+
import ora from "ora";
|
|
24
|
+
import { execFile } from "node:child_process";
|
|
25
|
+
import { promisify } from "node:util";
|
|
26
|
+
import { readFile, writeFile } from "node:fs/promises";
|
|
27
|
+
import { resolve as resolvePath } from "node:path";
|
|
28
|
+
import { confirm } from "@inquirer/prompts";
|
|
29
|
+
import { logger } from "../../../logger/logger.js";
|
|
30
|
+
import { isInsideGitRepo } from "../../../utils/git.js";
|
|
31
|
+
import { getCurrentBranch } from "../../../utils/gitOps.js";
|
|
32
|
+
import { GitxError } from "../../../utils/errors.js";
|
|
33
|
+
import { Gitx } from "../../../core/gitx.js";
|
|
34
|
+
import { createProvider } from "../../../providers/factory.js";
|
|
35
|
+
const execFileAsync = promisify(execFile);
|
|
36
|
+
// ─── Git helper ───────────────────────────────────────────────────────────────
|
|
37
|
+
async function git(args, cwd) {
|
|
38
|
+
try {
|
|
39
|
+
const result = await execFileAsync("git", args, { cwd });
|
|
40
|
+
return { stdout: result.stdout.trim(), stderr: "", exitCode: 0 };
|
|
41
|
+
}
|
|
42
|
+
catch (err) {
|
|
43
|
+
const e = err;
|
|
44
|
+
return {
|
|
45
|
+
stdout: e.stdout?.trim() ?? "",
|
|
46
|
+
stderr: e.stderr?.trim() ?? "",
|
|
47
|
+
exitCode: e.code ?? 1,
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
// ─── Conflict detection ───────────────────────────────────────────────────────
|
|
52
|
+
async function getConflictingFiles(cwd) {
|
|
53
|
+
const { stdout } = await git(["diff", "--name-only", "--diff-filter=U"], cwd);
|
|
54
|
+
return stdout.split("\n").map((l) => l.trim()).filter(Boolean);
|
|
55
|
+
}
|
|
56
|
+
// ─── AI conflict resolution ───────────────────────────────────────────────────
|
|
57
|
+
async function resolveConflictsWithAi(conflictFiles, cwd, gitx) {
|
|
58
|
+
const resolved = [];
|
|
59
|
+
const needsManual = [];
|
|
60
|
+
for (const filePath of conflictFiles) {
|
|
61
|
+
const absPath = resolvePath(cwd, filePath);
|
|
62
|
+
let content;
|
|
63
|
+
try {
|
|
64
|
+
content = await readFile(absPath, "utf8");
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
needsManual.push(filePath);
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
if (!content.includes("<<<<<<<")) {
|
|
71
|
+
needsManual.push(filePath);
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
const spinner = ora(` 🤖 AI resolving: ${filePath}`).start();
|
|
75
|
+
try {
|
|
76
|
+
const result = await gitx.ai.resolveConflict(filePath, content);
|
|
77
|
+
if (result.confidence === "high") {
|
|
78
|
+
await writeFile(absPath, result.resolved, "utf8");
|
|
79
|
+
spinner.succeed(` ✅ Auto-resolved: ${filePath} — ${result.explanation}`);
|
|
80
|
+
resolved.push(filePath);
|
|
81
|
+
}
|
|
82
|
+
else {
|
|
83
|
+
spinner.warn(` ⚠️ Low confidence: ${filePath} — ${result.explanation}`);
|
|
84
|
+
logger.info(`\n AI proposed resolution (low confidence). Preview:\n`);
|
|
85
|
+
const preview = result.resolved.split("\n").slice(0, 30).join("\n");
|
|
86
|
+
logger.info(preview);
|
|
87
|
+
if (result.resolved.split("\n").length > 30) {
|
|
88
|
+
logger.info(` … (${result.resolved.split("\n").length - 30} more lines)`);
|
|
89
|
+
}
|
|
90
|
+
logger.info("");
|
|
91
|
+
let apply = false;
|
|
92
|
+
try {
|
|
93
|
+
apply = await confirm({
|
|
94
|
+
message: `Apply AI resolution for ${filePath}?`,
|
|
95
|
+
default: true,
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
catch {
|
|
99
|
+
apply = false;
|
|
100
|
+
}
|
|
101
|
+
if (apply) {
|
|
102
|
+
await writeFile(absPath, result.resolved, "utf8");
|
|
103
|
+
logger.success(` ✅ Applied: ${filePath}`);
|
|
104
|
+
resolved.push(filePath);
|
|
105
|
+
}
|
|
106
|
+
else {
|
|
107
|
+
logger.info(` ⏭️ Skipped: ${filePath} — resolve manually`);
|
|
108
|
+
needsManual.push(filePath);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
spinner.fail(` ❌ AI resolution failed for: ${filePath}`);
|
|
114
|
+
needsManual.push(filePath);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return { resolved, needsManual };
|
|
118
|
+
}
|
|
119
|
+
// ─── Cherry-pick a list of commits ───────────────────────────────────────────
|
|
120
|
+
async function cherryPickCommits(commits, cwd, gitx, aiAvailable) {
|
|
121
|
+
for (let i = 0; i < commits.length; i++) {
|
|
122
|
+
const { sha, subject } = commits[i];
|
|
123
|
+
const shortSha = sha.slice(0, 7);
|
|
124
|
+
logger.info(`\n 🍒 [${i + 1}/${commits.length}] ${shortSha} — ${subject}`);
|
|
125
|
+
// -x appends "(cherry picked from commit <sha>)" to the commit message
|
|
126
|
+
const result = await git(["cherry-pick", "-x", sha], cwd);
|
|
127
|
+
if (result.exitCode === 0) {
|
|
128
|
+
logger.success(` ✓ Applied cleanly`);
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
// Cherry-pick failed — check for conflicts
|
|
132
|
+
const conflictFiles = await getConflictingFiles(cwd);
|
|
133
|
+
if (conflictFiles.length === 0) {
|
|
134
|
+
// Empty or already-applied commit
|
|
135
|
+
logger.warn(` ⚠️ Skipping (empty or already applied): ${shortSha}`);
|
|
136
|
+
await git(["cherry-pick", "--skip"], cwd);
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
logger.warn(`\n ⚡ Conflicts in ${conflictFiles.length} file(s):`);
|
|
140
|
+
conflictFiles.forEach((f) => logger.info(` • ${f}`));
|
|
141
|
+
if (!aiAvailable) {
|
|
142
|
+
// No AI — print manual instructions and pause
|
|
143
|
+
logger.error(`\n ⛔ Manual conflict resolution needed:`);
|
|
144
|
+
conflictFiles.forEach((f) => logger.warn(` • ${f}`));
|
|
145
|
+
logger.info(`\n Steps to resolve:`);
|
|
146
|
+
logger.info(` 1. Fix the conflict markers (<<<<, ====, >>>>) in each file`);
|
|
147
|
+
logger.info(` 2. Stage resolved files: git add <file>`);
|
|
148
|
+
logger.info(` 3. Continue: git cherry-pick --continue`);
|
|
149
|
+
logger.info(` 4. Or abort: git cherry-pick --abort`);
|
|
150
|
+
return { status: "paused", remainingIndex: i };
|
|
151
|
+
}
|
|
152
|
+
const { resolved, needsManual } = await resolveConflictsWithAi(conflictFiles, cwd, gitx);
|
|
153
|
+
if (needsManual.length > 0) {
|
|
154
|
+
// Stage auto-resolved files first
|
|
155
|
+
if (resolved.length > 0) {
|
|
156
|
+
await git(["add", ...resolved], cwd);
|
|
157
|
+
logger.info(`\n ✅ Auto-resolved ${resolved.length} file(s) — staged.`);
|
|
158
|
+
}
|
|
159
|
+
logger.warn(`\n ⛔ ${needsManual.length} file(s) need manual resolution:`);
|
|
160
|
+
needsManual.forEach((f) => logger.warn(` • ${f}`));
|
|
161
|
+
logger.info(`\n Steps to finish:`);
|
|
162
|
+
logger.info(` 1. Fix the conflict markers (<<<<, ====, >>>>) in each file above`);
|
|
163
|
+
logger.info(` 2. Stage resolved files: git add <file>`);
|
|
164
|
+
logger.info(` 3. Continue: git cherry-pick --continue`);
|
|
165
|
+
logger.info(` 4. Resume remaining: gitx pr cherry-pick ${commits.slice(i + 1).map((c) => c.sha.slice(0, 7)).join(", ")}`);
|
|
166
|
+
logger.info(` Or abort: git cherry-pick --abort`);
|
|
167
|
+
return { status: "paused", remainingIndex: i };
|
|
168
|
+
}
|
|
169
|
+
// All conflicts resolved — stage and continue
|
|
170
|
+
await git(["add", ...resolved], cwd);
|
|
171
|
+
const continueResult = await git(["cherry-pick", "--continue", "--no-edit"], cwd);
|
|
172
|
+
if (continueResult.exitCode !== 0) {
|
|
173
|
+
logger.error(` ❌ Could not continue cherry-pick: ${continueResult.stderr}`);
|
|
174
|
+
return { status: "paused", remainingIndex: i };
|
|
175
|
+
}
|
|
176
|
+
logger.success(` ✅ Conflict resolved and applied`);
|
|
177
|
+
}
|
|
178
|
+
return { status: "success", remainingIndex: -1 };
|
|
179
|
+
}
|
|
180
|
+
// ─── Register command ─────────────────────────────────────────────────────────
|
|
181
|
+
export function registerPrCherryPickCommand(pr) {
|
|
182
|
+
pr
|
|
183
|
+
.command("cherry-pick")
|
|
184
|
+
.description("🍒 Cherry-pick all commits from a PR into the current branch")
|
|
185
|
+
.argument("<number>", "PR number whose commits to cherry-pick")
|
|
186
|
+
.option("--dry-run", "List the commits that would be cherry-picked without applying them")
|
|
187
|
+
.option("--no-confirm", "Skip the confirmation prompt")
|
|
188
|
+
.action(async (prArg, opts) => {
|
|
189
|
+
const cwd = process.cwd();
|
|
190
|
+
if (!(await isInsideGitRepo(cwd))) {
|
|
191
|
+
throw new GitxError("Not inside a git repository. cd into your project folder first.", { exitCode: 2 });
|
|
192
|
+
}
|
|
193
|
+
const prNumber = parseInt(prArg, 10);
|
|
194
|
+
if (isNaN(prNumber) || prNumber <= 0) {
|
|
195
|
+
throw new GitxError(`Invalid PR number: "${prArg}"`, { exitCode: 2 });
|
|
196
|
+
}
|
|
197
|
+
const gitx = await Gitx.fromCwd(cwd);
|
|
198
|
+
// ── Fetch PR metadata ────────────────────────────────────────────────────
|
|
199
|
+
let ctx;
|
|
200
|
+
try {
|
|
201
|
+
ctx = await gitx.getRepoContext();
|
|
202
|
+
}
|
|
203
|
+
catch (err) {
|
|
204
|
+
throw new GitxError(`Could not determine repo context: ${err instanceof Error ? err.message : String(err)}`, { exitCode: 2 });
|
|
205
|
+
}
|
|
206
|
+
const provider = createProvider(ctx);
|
|
207
|
+
const prSpinner = ora(`Fetching PR #${prNumber}…`).start();
|
|
208
|
+
let pr;
|
|
209
|
+
try {
|
|
210
|
+
pr = await provider.getPR(ctx.repoSlug, prNumber);
|
|
211
|
+
prSpinner.succeed(`PR #${prNumber}: "${pr.title}" (${pr.head} → ${pr.base})`);
|
|
212
|
+
}
|
|
213
|
+
catch (err) {
|
|
214
|
+
prSpinner.fail(`Could not fetch PR #${prNumber}: ${err instanceof Error ? err.message : String(err)}`);
|
|
215
|
+
process.exitCode = 1;
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
// ── Guard: don't cherry-pick onto the same branch ────────────────────────
|
|
219
|
+
const currentBranch = await getCurrentBranch(cwd);
|
|
220
|
+
if (currentBranch === pr.head) {
|
|
221
|
+
logger.error(`❌ You are already on the PR source branch "${pr.head}". Nothing to cherry-pick.`);
|
|
222
|
+
process.exitCode = 1;
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
// ── Fetch the PR head branch from origin ─────────────────────────────────
|
|
226
|
+
const fetchSpinner = ora(`Fetching origin/${pr.head}…`).start();
|
|
227
|
+
const fetchResult = await git(["fetch", "origin", pr.head], cwd);
|
|
228
|
+
if (fetchResult.exitCode !== 0 && !fetchResult.stderr.includes("->")) {
|
|
229
|
+
// If the head branch no longer exists (merged/deleted), try fetching by ref
|
|
230
|
+
// For GitHub PRs: refs/pull/<number>/head
|
|
231
|
+
const refResult = await git(["fetch", "origin", `refs/pull/${prNumber}/head:refs/remotes/origin/pr/${prNumber}`], cwd);
|
|
232
|
+
if (refResult.exitCode !== 0) {
|
|
233
|
+
fetchSpinner.warn(`Could not fetch branch "${pr.head}" — it may have been deleted after merge.`);
|
|
234
|
+
// Continue with whatever we have locally
|
|
235
|
+
}
|
|
236
|
+
else {
|
|
237
|
+
fetchSpinner.succeed(`Fetched PR #${prNumber} via refs/pull/${prNumber}/head`);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
else {
|
|
241
|
+
fetchSpinner.succeed(`Fetched origin/${pr.head}`);
|
|
242
|
+
}
|
|
243
|
+
// ── Collect commits: base..head (oldest first) ────────────────────────────
|
|
244
|
+
// Try origin/<head> first; fall back to the special PR ref we fetched above
|
|
245
|
+
const headRef = (await git(["rev-parse", "--verify", `origin/${pr.head}`], cwd)).exitCode === 0
|
|
246
|
+
? `origin/${pr.head}`
|
|
247
|
+
: `origin/pr/${prNumber}`;
|
|
248
|
+
// Base ref — what the PR targets
|
|
249
|
+
const baseRef = `origin/${pr.base}`;
|
|
250
|
+
const logResult = await git(["log", "--format=%H %s", `${baseRef}..${headRef}`], cwd);
|
|
251
|
+
if (logResult.exitCode !== 0 || !logResult.stdout) {
|
|
252
|
+
logger.error(`❌ No commits found between ${baseRef} and ${headRef}.`);
|
|
253
|
+
logger.info(` Make sure the base branch (${pr.base}) exists on origin.`);
|
|
254
|
+
process.exitCode = 1;
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
// git log returns newest-first; reverse to oldest-first for cherry-pick
|
|
258
|
+
const commits = logResult.stdout
|
|
259
|
+
.split("\n")
|
|
260
|
+
.map((l) => l.trim())
|
|
261
|
+
.filter(Boolean)
|
|
262
|
+
.map((line) => {
|
|
263
|
+
const spaceIdx = line.indexOf(" ");
|
|
264
|
+
return {
|
|
265
|
+
sha: line.slice(0, spaceIdx),
|
|
266
|
+
subject: line.slice(spaceIdx + 1),
|
|
267
|
+
};
|
|
268
|
+
})
|
|
269
|
+
.reverse();
|
|
270
|
+
if (commits.length === 0) {
|
|
271
|
+
logger.info(`✅ No commits to cherry-pick — PR #${prNumber} has no new commits relative to ${pr.base}.`);
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
// ── Show commit list ──────────────────────────────────────────────────────
|
|
275
|
+
logger.info(`\n📋 ${commits.length} commit(s) from PR #${prNumber} to cherry-pick into ${currentBranch}:\n`);
|
|
276
|
+
for (const { sha, subject } of commits) {
|
|
277
|
+
logger.info(` + ${sha.slice(0, 7)} — ${subject}`);
|
|
278
|
+
}
|
|
279
|
+
if (opts.dryRun) {
|
|
280
|
+
logger.info(`\n⏸ Dry run — no commits applied.`);
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
// ── Confirmation ──────────────────────────────────────────────────────────
|
|
284
|
+
if (opts.confirm !== false) {
|
|
285
|
+
let proceed = false;
|
|
286
|
+
try {
|
|
287
|
+
proceed = await confirm({
|
|
288
|
+
message: `Cherry-pick ${commits.length} commit(s) onto "${currentBranch}"?`,
|
|
289
|
+
default: true,
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
catch {
|
|
293
|
+
proceed = false;
|
|
294
|
+
}
|
|
295
|
+
if (!proceed) {
|
|
296
|
+
logger.info("Cancelled.");
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
// ── Cherry-pick ───────────────────────────────────────────────────────────
|
|
301
|
+
logger.info(`\n🍒 Cherry-picking ${commits.length} commit(s)…`);
|
|
302
|
+
const aiAvailable = await Gitx.isAiAvailable(gitx.config);
|
|
303
|
+
if (!aiAvailable) {
|
|
304
|
+
logger.warn("⚠️ No AI configured — conflicts will require manual resolution.");
|
|
305
|
+
}
|
|
306
|
+
const result = await cherryPickCommits(commits, cwd, gitx, aiAvailable);
|
|
307
|
+
if (result.status === "paused") {
|
|
308
|
+
logger.warn(`\n⚠️ Cherry-pick paused at commit ${commits[result.remainingIndex]?.sha.slice(0, 7) ?? "?"}. Resolve conflicts manually then run:`);
|
|
309
|
+
logger.info(` git cherry-pick --continue`);
|
|
310
|
+
process.exitCode = 1;
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
logger.success(`\n✅ All ${commits.length} commit(s) from PR #${prNumber} cherry-picked into "${currentBranch}".`);
|
|
314
|
+
logger.info(` Review the changes, then push when ready: gitx push`);
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
//# sourceMappingURL=cherryPick.js.map
|