@g-abhishek/gitx 0.1.5 → 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 +58 -1
- 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 +70 -1
- 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/index.d.ts.map +1 -1
- package/dist/cli/commands/pr/index.js +4 -0
- 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/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/workflows/pr.d.ts.map +1 -1
- package/dist/workflows/pr.js +71 -14
- package/dist/workflows/pr.js.map +1 -1
- package/package.json +1 -1
package/dist/ai/openAiAi.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openAiAi.js","sourceRoot":"","sources":["../../src/ai/openAiAi.ts"],"names":[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E,GAAG,MAAM,MAAM,CAAC,oBAAoB,CAAC,CAAC;QAChG,MAAM,IAAI,GAAG,MAAM,UAAU,CAAC,cAAc,EAAE,EAAE,cAAc,CAAC,QAAQ,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC;QAC5G,OAAO,gBAAgB,CAAC,IAAI,CAAC,CAAC;IAChC,CAAC;CACF","sourcesContent":["/**\n * OpenAiAi — OpenAI Chat Completions API integration.\n *\n * Authentication: OPENAI_API_KEY env var or stored config key.\n * Model: defaults to gpt-4o. Override via GITX_AI_MODEL env var.\n *\n * All methods use the same structured JSON prompt pattern as ClaudeAi.\n */\n\nimport axios, { isAxiosError } from \"axios\";\nimport { GitxError } from \"../utils/errors.js\";\nimport type {\n AiAnalyzeTaskResponse,\n AiClient,\n AiGenerateDiffsResponse,\n AiGeneratePlanResponse,\n AiReviewPRResponse,\n AiSuggestFixesResponse,\n AiSummarizeChangesResponse,\n} from \"./types.js\";\n\nconst OPENAI_API = \"https://api.openai.com/v1/chat/completions\";\nconst DEFAULT_MODEL = \"gpt-4o\";\nconst MAX_TOKENS = 4096;\n\n// ─── Helpers ──────────────────────────────────────────────────────────────────\n\nfunction getModel(override?: string): string {\n return process.env[\"GITX_AI_MODEL\"] ?? override ?? DEFAULT_MODEL;\n}\n\ninterface ChatMessage {\n role: \"system\" | \"user\" | \"assistant\";\n content: string;\n}\n\ninterface OpenAiRequestBody {\n model: string;\n max_tokens: number;\n messages: ChatMessage[];\n}\n\ninterface OpenAiResponseBody {\n choices: Array<{\n message: { role: string; content: string };\n finish_reason: string;\n }>;\n}\n\nasync function callOpenAi(\n system: string,\n userPrompt: string,\n apiKey: string,\n model: string\n): Promise<string> {\n const body: OpenAiRequestBody = {\n model,\n max_tokens: MAX_TOKENS,\n messages: [\n { role: \"system\", content: system },\n { role: \"user\", content: userPrompt },\n ],\n };\n\n try {\n const { data } = await axios.post<OpenAiResponseBody>(OPENAI_API, body, {\n headers: {\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n timeout: 60_000,\n });\n\n return data.choices[0]?.message?.content?.trim() ?? \"\";\n } catch (err) {\n if (isAxiosError(err)) {\n const status = err.response?.status;\n const msg =\n (err.response?.data as Record<string, unknown> | undefined)?.error ??\n err.message;\n if (status === 401) {\n throw new GitxError(\n \"OpenAI API authentication failed. Check OPENAI_API_KEY.\",\n { exitCode: 1, cause: err }\n );\n }\n if (status === 429) {\n throw new GitxError(\n \"OpenAI rate limit exceeded. Wait a moment and retry.\",\n { exitCode: 1, cause: err }\n );\n }\n throw new GitxError(\n `OpenAI API error (${status ?? \"network\"}): ${String(msg)}`,\n { exitCode: 1, cause: err }\n );\n }\n throw new GitxError(`Unexpected OpenAI error: ${String(err)}`, {\n exitCode: 1,\n cause: err,\n });\n }\n}\n\nfunction extractJson(text: string): string {\n const fenced = text.match(/```(?:json)?\\s*([\\s\\S]*?)```/);\n if (fenced?.[1]) return fenced[1].trim();\n const start = text.search(/[{[]/);\n const endBrace = text.lastIndexOf(\"}\");\n const endBracket = text.lastIndexOf(\"]\");\n const end = Math.max(endBrace, endBracket);\n if (start !== -1 && end !== -1 && end > start) return text.slice(start, end + 1);\n return text.trim();\n}\n\nfunction parseJson<T>(text: string, fallback: T): T {\n try {\n return JSON.parse(extractJson(text)) as T;\n } catch {\n return fallback;\n }\n}\n\n// ─── OpenAiAi ─────────────────────────────────────────────────────────────────\n\nexport class OpenAiAi implements AiClient {\n private readonly apiKey: string;\n private readonly model: string;\n\n /**\n * @param apiKey OpenAI API key. Falls back to OPENAI_API_KEY env var.\n * @param model Model override. Falls back to GITX_AI_MODEL then gpt-4o.\n */\n constructor(apiKey?: string, model?: string) {\n const key = apiKey ?? process.env[\"OPENAI_API_KEY\"];\n if (!key) {\n throw new GitxError(\n \"No OpenAI API key available. Run `gitx config set openai` or set OPENAI_API_KEY.\",\n { exitCode: 2 }\n );\n }\n this.apiKey = key;\n this.model = getModel(model);\n }\n\n /** Check whether an OpenAI API key is available without instantiating. */\n static isAvailable(key?: string): boolean {\n return Boolean(key ?? process.env[\"OPENAI_API_KEY\"]);\n }\n\n async analyzeTask(input: string): Promise<AiAnalyzeTaskResponse> {\n const system = `You are an expert software engineer. Analyze the given development task and respond with ONLY valid JSON matching this exact structure (no prose, no markdown):\n{\n \"task\": \"<the original task string>\",\n \"intent\": \"<one of: refactor | bugfix | feature | chore | unknown>\",\n \"summary\": \"<one sentence explaining what needs to be done>\",\n \"assumptions\": [\"<assumption 1>\", \"<assumption 2>\"],\n \"risks\": [\"<risk 1>\", \"<risk 2>\"]\n}`;\n\n const text = await callOpenAi(system, `Task: ${input}`, this.apiKey, this.model);\n const parsed = parseJson<Partial<AiAnalyzeTaskResponse>>(text, {});\n return {\n task: input,\n intent: (parsed.intent as AiAnalyzeTaskResponse[\"intent\"]) ?? \"unknown\",\n summary: parsed.summary ?? \"Unable to analyze task.\",\n assumptions: Array.isArray(parsed.assumptions) ? parsed.assumptions : [],\n risks: Array.isArray(parsed.risks) ? parsed.risks : [],\n };\n }\n\n async generatePlan(context: unknown): Promise<AiGeneratePlanResponse> {\n const ctx = context as {\n task?: string;\n analysis?: AiAnalyzeTaskResponse;\n repoFiles?: string[];\n fileContents?: Record<string, string>;\n };\n\n const taskDesc = ctx.task ?? \"Unknown task\";\n const analysisSummary = ctx.analysis?.summary ?? \"\";\n const fileList = ctx.repoFiles?.slice(0, 50).join(\"\\n\") ?? \"(not provided)\";\n const fileContentsSection =\n ctx.fileContents && Object.keys(ctx.fileContents).length > 0\n ? `\\n\\nRelevant file contents:\\n${Object.entries(ctx.fileContents)\n .map(([p, c]) => `--- ${p} ---\\n${c}`)\n .join(\"\\n\\n\")}`\n : \"\";\n\n const system = `You are an expert software engineer creating a step-by-step implementation plan. Respond with ONLY valid JSON:\n{\n \"steps\": [\n { \"id\": \"step-1\", \"title\": \"<short title>\", \"description\": \"<detailed description>\" }\n ]\n}\nKeep steps atomic and ordered. Each step should touch one logical concern.`;\n\n const userPrompt = `Task: ${taskDesc}\nAnalysis: ${analysisSummary}\nRepo files (top 50):\n${fileList}${fileContentsSection}`;\n\n const text = await callOpenAi(system, userPrompt, this.apiKey, this.model);\n const parsed = parseJson<Partial<AiGeneratePlanResponse>>(text, { steps: [] });\n const steps = Array.isArray(parsed.steps) ? parsed.steps : [];\n\n if (steps.length === 0) {\n return { steps: [{ id: \"step-1\", title: \"Analyze & implement\", description: taskDesc }] };\n }\n return { steps };\n }\n\n async generateDiffs(step: unknown): Promise<AiGenerateDiffsResponse> {\n const s = step as {\n id?: string;\n title?: string;\n description?: string;\n task?: string;\n fileContents?: Record<string, string>;\n };\n\n const stepId = s.id ?? \"step-1\";\n const fileContentsSection =\n s.fileContents && Object.keys(s.fileContents).length > 0\n ? `\\n\\nCurrent file contents:\\n${Object.entries(s.fileContents)\n .map(([p, c]) => `--- ${p} ---\\n${c}`)\n .join(\"\\n\\n\")}`\n : \"\\n\\n(No existing file contents — create new files as needed.)\";\n\n const system = `You are an expert software engineer. Generate unified diffs for the given implementation step.\nRespond with ONLY valid JSON:\n{\n \"stepId\": \"<step id>\",\n \"diffs\": [\n {\n \"path\": \"<relative file path>\",\n \"unifiedDiff\": \"<valid unified diff starting with --- a/path and +++ b/path>\"\n }\n ]\n}\n\nRules for unified diffs:\n- Start with: --- a/<path>\\\\n+++ b/<path>\n- Use @@ -<start>,<count> +<start>,<count> @@ context headers\n- Lines starting with ' ' are context (unchanged)\n- Lines starting with '-' are removed\n- Lines starting with '+' are added\n- For new files use: --- /dev/null\\\\n+++ b/<path>\n- Always include 3 lines of context around changes`;\n\n const userPrompt = `Task: ${s.task ?? \"\"}\nStep ID: ${stepId}\nStep Title: ${s.title ?? \"\"}\nStep Description: ${s.description ?? \"\"}${fileContentsSection}`;\n\n const text = await callOpenAi(system, userPrompt, this.apiKey, this.model);\n const parsed = parseJson<Partial<AiGenerateDiffsResponse>>(text, { stepId, diffs: [] });\n return {\n stepId,\n diffs: Array.isArray(parsed.diffs) ? parsed.diffs : [],\n };\n }\n\n async summarizeChanges(diff: unknown): Promise<AiSummarizeChangesResponse> {\n const d = diff as { diffs?: AiGenerateDiffsResponse[]; rawDiff?: string };\n const diffContent =\n d.rawDiff ??\n (d.diffs ?? [])\n .flatMap((dr) => dr.diffs.map((f) => `File: ${f.path}\\n${f.unifiedDiff}`))\n .join(\"\\n\\n\") ??\n \"(no diffs)\";\n\n const system = `You are a technical writer. Summarize code changes for a pull request. Respond with ONLY valid JSON:\n{\n \"summary\": \"<2-3 sentence plain-English summary of what changed and why>\",\n \"filesChanged\": [\n { \"path\": \"<file path>\", \"changeType\": \"<add | modify | delete>\" }\n ]\n}`;\n\n const text = await callOpenAi(system, `Changes:\\n${diffContent}`, this.apiKey, this.model);\n const parsed = parseJson<Partial<AiSummarizeChangesResponse>>(text, {\n summary: \"\",\n filesChanged: [],\n });\n return {\n summary: parsed.summary ?? \"Code changes applied.\",\n filesChanged: Array.isArray(parsed.filesChanged) ? parsed.filesChanged : [],\n };\n }\n\n async suggestFixes(comment: unknown): Promise<AiSuggestFixesResponse> {\n const c = comment as {\n comments?: Array<{ body: string; path?: string; line?: number; author?: string }>;\n prTitle?: string;\n prBody?: string;\n fileContents?: Record<string, string>;\n };\n\n const commentsText = (c.comments ?? [])\n .map(\n (co) =>\n `[${co.author ?? \"reviewer\"}${co.path ? ` on ${co.path}:${co.line ?? \"\"}` : \"\"}]: ${co.body}`\n )\n .join(\"\\n\\n\");\n\n const fileContentsSection =\n c.fileContents && Object.keys(c.fileContents).length > 0\n ? `\\n\\nCurrent file contents:\\n${Object.entries(c.fileContents)\n .map(([p, content]) => `--- ${p} ---\\n${content}`)\n .join(\"\\n\\n\")}`\n : \"\";\n\n const system = `You are an expert code reviewer suggesting fixes for pull request review comments. Respond with ONLY valid JSON:\n{\n \"suggestedEdits\": [\n {\n \"path\": \"<file path>\",\n \"rationale\": \"<why this change addresses the comment>\",\n \"unifiedDiff\": \"<valid unified diff>\"\n }\n ]\n}\nIf a comment doesn't require a code change, omit it from suggestedEdits.`;\n\n const userPrompt = `PR Title: ${c.prTitle ?? \"\"}\nPR Body: ${c.prBody ?? \"\"}\n\nReview Comments:\n${commentsText}${fileContentsSection}`;\n\n const text = await callOpenAi(system, userPrompt, this.apiKey, this.model);\n const parsed = parseJson<Partial<AiSuggestFixesResponse>>(text, { suggestedEdits: [] });\n return {\n suggestedEdits: Array.isArray(parsed.suggestedEdits) ? parsed.suggestedEdits : [],\n };\n }\n\n async reviewPR(context: unknown): Promise<AiReviewPRResponse> {\n const ctx = context as {\n prTitle?: string;\n prBody?: string;\n diff?: string;\n comments?: Array<{ body: string; author: string; path?: string }>;\n };\n\n const diffSection = ctx.diff\n ? `\\n\\nDiff (unified):\\n${ctx.diff.slice(0, 8000)}`\n : \"\";\n const commentsSection =\n ctx.comments && ctx.comments.length > 0\n ? `\\n\\nExisting review comments:\\n${ctx.comments\n .map((c) => `[${c.author}${c.path ? ` @ ${c.path}` : \"\"}]: ${c.body}`)\n .join(\"\\n\")}`\n : \"\";\n\n const system = `You are an expert code reviewer. Review the given pull request thoroughly and respond with ONLY valid JSON:\n{\n \"summary\": \"<2-4 sentence overall assessment>\",\n \"issues\": [\n { \"severity\": \"<critical|warning|suggestion>\", \"description\": \"<specific issue>\", \"file\": \"<optional file>\", \"line\": null }\n ],\n \"positives\": [\"<good thing 1>\", \"<good thing 2>\"],\n \"verdict\": \"<approve|request_changes|comment>\"\n}\n\nSeverity guide:\n- critical: bugs, security issues, data loss risk\n- warning: code quality, performance, missing error handling\n- suggestion: style, naming, minor improvements`;\n\n const userPrompt = `PR Title: ${ctx.prTitle ?? \"\"}\nPR Description: ${ctx.prBody ?? \"\"}${diffSection}${commentsSection}`;\n\n const text = await callOpenAi(system, userPrompt, this.apiKey, this.model);\n const parsed = parseJson<Partial<AiReviewPRResponse>>(text, {\n summary: \"\",\n issues: [],\n positives: [],\n verdict: \"comment\",\n });\n\n return {\n summary: parsed.summary ?? \"Review could not be generated.\",\n issues: Array.isArray(parsed.issues) ? parsed.issues : [],\n positives: Array.isArray(parsed.positives) ? parsed.positives : [],\n verdict: ([\"approve\", \"request_changes\", \"comment\"].includes(parsed.verdict ?? \"\"))\n ? (parsed.verdict as AiReviewPRResponse[\"verdict\"])\n : \"comment\",\n };\n }\n\n async generatePrContent(commits: string[], diff: string, stat?: string): Promise<import(\"./types.js\").AiPrContentResponse> {\n const system = `You are an expert software engineer writing pull request descriptions.\nYou are given a list of commits on the branch and the unified diff of all changes.\n\nThe input may contain:\n - \"=== Changed files (complete list) ===\" — the full --stat summary of every file touched\n - \"=== Detailed diff ===\" — the actual patch (may be truncated for large changesets)\n\nWhen a file list is present, use it as the authoritative source of ALL changed files.\nDo not ignore files that appear in the list but are absent from the truncated diff.\n\nProduce a clear, informative PR title and description:\n\nRules:\n- title: short, human-readable, present-tense. No conventional-commit prefix. Max 72 chars.\n- body: 2-4 sentences describing WHAT changed and WHY. Cover ALL files from the list.\n Plain English, no bullet points.\n\nRespond with ONLY valid JSON (no markdown fences):\n{\"title\":\"<PR title>\",\"body\":\"<PR description>\"}`;\n\n const commitList = commits.slice(0, 20).join(\"\\n\");\n const diffSection = stat\n ? `=== Changed files (complete list) ===\\n${stat}\\n\\n=== Detailed diff ===\\n${diff.slice(0, 16000)}`\n : `Diff:\\n${diff.slice(0, 16000)}`;\n const userPrompt = `Commits on this branch:\\n${commitList}\\n\\n${diffSection}`;\n const text = await callOpenAi(system, userPrompt, this.apiKey, this.model);\n const parsed = parseJson<Partial<import(\"./types.js\").AiPrContentResponse>>(text, {});\n return {\n title: parsed.title?.trim() ?? \"Update branch\",\n body: parsed.body?.trim() ?? \"\",\n };\n }\n\n async resolveConflict(filePath: string, conflictContent: string): Promise<import(\"./types.js\").AiConflictResolutionResponse> {\n const system = `You are an expert software engineer resolving git merge conflicts.\n\nThe file contains standard git conflict markers:\n <<<<<<< HEAD — changes on the current branch\n ======= — separator\n >>>>>>> theirs — incoming changes\n\nYour task:\n1. Understand BOTH sides of every conflict.\n2. Produce a single correct version preserving the intent of BOTH changes where possible.\n3. If the sides are genuinely contradictory, set confidence to \"low\".\n\nRules:\n- Remove ALL conflict markers from the output.\n- Do NOT add explanatory comments.\n- Keep all non-conflicting code exactly as-is.\n- Output must be syntactically valid.\n\nRespond with ONLY valid JSON (no markdown fences):\n{\"resolved\":\"<full resolved file content>\",\"confidence\":\"high|low\",\"explanation\":\"<one sentence>\"}`;\n\n const userPrompt = `File: ${filePath}\\n\\n${conflictContent.slice(0, 20000)}`;\n const text = await callOpenAi(system, userPrompt, this.apiKey, this.model);\n const parsed = parseJson<Partial<import(\"./types.js\").AiConflictResolutionResponse>>(text, {});\n return {\n resolved: parsed.resolved ?? conflictContent,\n confidence: parsed.confidence === \"low\" ? \"low\" : \"high\",\n explanation: parsed.explanation?.trim() ?? \"Conflict resolved.\",\n };\n }\n async generateCommitMessage(diff: string): Promise<import(\"./types.js\").AiCommitMessageResponse> {\n const system = `You are an expert software engineer writing git commit messages.\nYou receive either a plain unified diff OR a structured input with:\n - \"=== Changed files (complete list) ===\" — the full --stat summary of every file touched\n - \"=== Detailed diff ===\" — the actual patch (may be truncated for large changesets)\n\nWhen a file list is present, use it as the authoritative source of ALL changes.\nDo not ignore files that appear in the list but are missing from the truncated diff.\n\nProduce ONE CONVENTIONAL COMMIT covering all the changes:\n\nRules:\n- subject: \"<type>(<scope>): <imperative description>\"\n - type: feat | fix | refactor | chore | docs | test | perf | ci | style | build\n - scope: the primary area affected; omit if changes span many unrelated areas\n - description: imperative mood, no period, 72 chars max for the whole subject line\n - if several distinct features or fixes are present, pick the most impactful for the subject\n- body: cover EVERY significant change visible in the file list. For each distinct change,\n one sentence on what was done and why. Plain English, no bullet lists, no repetition of the subject.\n\nRespond with ONLY valid JSON (no markdown fences):\n{\"subject\":\"<subject line>\",\"body\":\"<body covering all changes, or empty string>\"}`;\n\n const text = await callOpenAi(system, `Diff:\\n${diff.slice(0, 20000)}`, this.apiKey, this.model);\n const parsed = parseJson<Partial<import(\"./types.js\").AiCommitMessageResponse>>(text, {});\n return {\n subject: parsed.subject?.trim() ?? \"chore: update files\",\n body: parsed.body?.trim() || undefined,\n };\n }\n\n async reviewPRDetailed(\n context: Parameters<import(\"./types.js\").AiClient[\"reviewPRDetailed\"]>[0]\n ): Promise<import(\"./types.js\").AiDetailedReviewResponse> {\n const { buildSeniorReviewSystem, buildSeniorReviewPrompt, parseSeniorReview } = await import(\"./reviewHelpers.js\");\n const text = await callOpenAi(\n buildSeniorReviewSystem(),\n buildSeniorReviewPrompt(context),\n this.apiKey,\n this.model\n );\n return parseSeniorReview(text);\n }\n\n async generateFix(\n context: Parameters<import(\"./types.js\").AiClient[\"generateFix\"]>[0]\n ): Promise<import(\"./types.js\").AiFixResponse> {\n const { buildFixSystem, buildFixPrompt, parseFixResponse } = await import(\"./reviewHelpers.js\");\n const text = await callOpenAi(\n buildFixSystem(),\n buildFixPrompt(context),\n this.apiKey,\n this.model\n );\n return parseFixResponse(text, context.filePath, context.line);\n }\n\n async ask(\n question: string,\n context: import(\"./types.js\").AiAskContext\n ): Promise<import(\"./types.js\").AiAskResponse> {\n const { buildAskSystem, buildAskPrompt, parseAskResponse } = await import(\"./reviewHelpers.js\");\n const text = await callOpenAi(buildAskSystem(), buildAskPrompt(question, context), this.apiKey, this.model);\n return parseAskResponse(text);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"openAiAi.js","sourceRoot":"","sources":["../../src/ai/openAiAi.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,EAAE,YAAY,EAAE,MAAM,OAAO,CAAC;AAC5C,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAW/C,MAAM,UAAU,GAAG,4CAA4C,CAAC;AAChE,MAAM,aAAa,GAAG,QAAQ,CAAC;AAC/B,MAAM,UAAU,GAAG,IAAI,CAAC;AAExB,iFAAiF;AAEjF,SAAS,QAAQ,CAAC,QAAiB;IACjC,OAAO,O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,GAAG,MAAM,UAAU,CAAC,cAAc,EAAE,EAAE,cAAc,CAAC,QAAQ,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC;QAC5G,OAAO,gBAAgB,CAAC,IAAI,CAAC,CAAC;IAChC,CAAC;CACF","sourcesContent":["/**\n * OpenAiAi — OpenAI Chat Completions API integration.\n *\n * Authentication: OPENAI_API_KEY env var or stored config key.\n * Model: defaults to gpt-4o. Override via GITX_AI_MODEL env var.\n *\n * All methods use the same structured JSON prompt pattern as ClaudeAi.\n */\n\nimport axios, { isAxiosError } from \"axios\";\nimport { GitxError } from \"../utils/errors.js\";\nimport type {\n AiAnalyzeTaskResponse,\n AiClient,\n AiGenerateDiffsResponse,\n AiGeneratePlanResponse,\n AiReviewPRResponse,\n AiSuggestFixesResponse,\n AiSummarizeChangesResponse,\n} from \"./types.js\";\n\nconst OPENAI_API = \"https://api.openai.com/v1/chat/completions\";\nconst DEFAULT_MODEL = \"gpt-4o\";\nconst MAX_TOKENS = 4096;\n\n// ─── Helpers ──────────────────────────────────────────────────────────────────\n\nfunction getModel(override?: string): string {\n return process.env[\"GITX_AI_MODEL\"] ?? override ?? DEFAULT_MODEL;\n}\n\ninterface ChatMessage {\n role: \"system\" | \"user\" | \"assistant\";\n content: string;\n}\n\ninterface OpenAiRequestBody {\n model: string;\n max_tokens: number;\n messages: ChatMessage[];\n}\n\ninterface OpenAiResponseBody {\n choices: Array<{\n message: { role: string; content: string };\n finish_reason: string;\n }>;\n}\n\nasync function callOpenAi(\n system: string,\n userPrompt: string,\n apiKey: string,\n model: string\n): Promise<string> {\n const body: OpenAiRequestBody = {\n model,\n max_tokens: MAX_TOKENS,\n messages: [\n { role: \"system\", content: system },\n { role: \"user\", content: userPrompt },\n ],\n };\n\n try {\n const { data } = await axios.post<OpenAiResponseBody>(OPENAI_API, body, {\n headers: {\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n timeout: 60_000,\n });\n\n return data.choices[0]?.message?.content?.trim() ?? \"\";\n } catch (err) {\n if (isAxiosError(err)) {\n const status = err.response?.status;\n const msg =\n (err.response?.data as Record<string, unknown> | undefined)?.error ??\n err.message;\n if (status === 401) {\n throw new GitxError(\n \"OpenAI API authentication failed. Check OPENAI_API_KEY.\",\n { exitCode: 1, cause: err }\n );\n }\n if (status === 429) {\n throw new GitxError(\n \"OpenAI rate limit exceeded. Wait a moment and retry.\",\n { exitCode: 1, cause: err }\n );\n }\n throw new GitxError(\n `OpenAI API error (${status ?? \"network\"}): ${String(msg)}`,\n { exitCode: 1, cause: err }\n );\n }\n throw new GitxError(`Unexpected OpenAI error: ${String(err)}`, {\n exitCode: 1,\n cause: err,\n });\n }\n}\n\nfunction extractJson(text: string): string {\n const fenced = text.match(/```(?:json)?\\s*([\\s\\S]*?)```/);\n if (fenced?.[1]) return fenced[1].trim();\n const start = text.search(/[{[]/);\n const endBrace = text.lastIndexOf(\"}\");\n const endBracket = text.lastIndexOf(\"]\");\n const end = Math.max(endBrace, endBracket);\n if (start !== -1 && end !== -1 && end > start) return text.slice(start, end + 1);\n return text.trim();\n}\n\nfunction parseJson<T>(text: string, fallback: T): T {\n try {\n return JSON.parse(extractJson(text)) as T;\n } catch {\n return fallback;\n }\n}\n\n// ─── OpenAiAi ─────────────────────────────────────────────────────────────────\n\nexport class OpenAiAi implements AiClient {\n private readonly apiKey: string;\n private readonly model: string;\n\n /**\n * @param apiKey OpenAI API key. Falls back to OPENAI_API_KEY env var.\n * @param model Model override. Falls back to GITX_AI_MODEL then gpt-4o.\n */\n constructor(apiKey?: string, model?: string) {\n const key = apiKey ?? process.env[\"OPENAI_API_KEY\"];\n if (!key) {\n throw new GitxError(\n \"No OpenAI API key available. Run `gitx config set openai` or set OPENAI_API_KEY.\",\n { exitCode: 2 }\n );\n }\n this.apiKey = key;\n this.model = getModel(model);\n }\n\n /** Check whether an OpenAI API key is available without instantiating. */\n static isAvailable(key?: string): boolean {\n return Boolean(key ?? process.env[\"OPENAI_API_KEY\"]);\n }\n\n async analyzeTask(input: string): Promise<AiAnalyzeTaskResponse> {\n const system = `You are an expert software engineer. Analyze the given development task and respond with ONLY valid JSON matching this exact structure (no prose, no markdown):\n{\n \"task\": \"<the original task string>\",\n \"intent\": \"<one of: refactor | bugfix | feature | chore | unknown>\",\n \"summary\": \"<one sentence explaining what needs to be done>\",\n \"assumptions\": [\"<assumption 1>\", \"<assumption 2>\"],\n \"risks\": [\"<risk 1>\", \"<risk 2>\"]\n}`;\n\n const text = await callOpenAi(system, `Task: ${input}`, this.apiKey, this.model);\n const parsed = parseJson<Partial<AiAnalyzeTaskResponse>>(text, {});\n return {\n task: input,\n intent: (parsed.intent as AiAnalyzeTaskResponse[\"intent\"]) ?? \"unknown\",\n summary: parsed.summary ?? \"Unable to analyze task.\",\n assumptions: Array.isArray(parsed.assumptions) ? parsed.assumptions : [],\n risks: Array.isArray(parsed.risks) ? parsed.risks : [],\n };\n }\n\n async generatePlan(context: unknown): Promise<AiGeneratePlanResponse> {\n const ctx = context as {\n task?: string;\n analysis?: AiAnalyzeTaskResponse;\n repoFiles?: string[];\n fileContents?: Record<string, string>;\n };\n\n const taskDesc = ctx.task ?? \"Unknown task\";\n const analysisSummary = ctx.analysis?.summary ?? \"\";\n const fileList = ctx.repoFiles?.slice(0, 50).join(\"\\n\") ?? \"(not provided)\";\n const fileContentsSection =\n ctx.fileContents && Object.keys(ctx.fileContents).length > 0\n ? `\\n\\nRelevant file contents:\\n${Object.entries(ctx.fileContents)\n .map(([p, c]) => `--- ${p} ---\\n${c}`)\n .join(\"\\n\\n\")}`\n : \"\";\n\n const system = `You are an expert software engineer creating a step-by-step implementation plan. Respond with ONLY valid JSON:\n{\n \"steps\": [\n { \"id\": \"step-1\", \"title\": \"<short title>\", \"description\": \"<detailed description>\" }\n ]\n}\nKeep steps atomic and ordered. Each step should touch one logical concern.`;\n\n const userPrompt = `Task: ${taskDesc}\nAnalysis: ${analysisSummary}\nRepo files (top 50):\n${fileList}${fileContentsSection}`;\n\n const text = await callOpenAi(system, userPrompt, this.apiKey, this.model);\n const parsed = parseJson<Partial<AiGeneratePlanResponse>>(text, { steps: [] });\n const steps = Array.isArray(parsed.steps) ? parsed.steps : [];\n\n if (steps.length === 0) {\n return { steps: [{ id: \"step-1\", title: \"Analyze & implement\", description: taskDesc }] };\n }\n return { steps };\n }\n\n async generateDiffs(step: unknown): Promise<AiGenerateDiffsResponse> {\n const s = step as {\n id?: string;\n title?: string;\n description?: string;\n task?: string;\n fileContents?: Record<string, string>;\n };\n\n const stepId = s.id ?? \"step-1\";\n const fileContentsSection =\n s.fileContents && Object.keys(s.fileContents).length > 0\n ? `\\n\\nCurrent file contents:\\n${Object.entries(s.fileContents)\n .map(([p, c]) => `--- ${p} ---\\n${c}`)\n .join(\"\\n\\n\")}`\n : \"\\n\\n(No existing file contents — create new files as needed.)\";\n\n const system = `You are an expert software engineer. Generate unified diffs for the given implementation step.\nRespond with ONLY valid JSON:\n{\n \"stepId\": \"<step id>\",\n \"diffs\": [\n {\n \"path\": \"<relative file path>\",\n \"unifiedDiff\": \"<valid unified diff starting with --- a/path and +++ b/path>\"\n }\n ]\n}\n\nRules for unified diffs:\n- Start with: --- a/<path>\\\\n+++ b/<path>\n- Use @@ -<start>,<count> +<start>,<count> @@ context headers\n- Lines starting with ' ' are context (unchanged)\n- Lines starting with '-' are removed\n- Lines starting with '+' are added\n- For new files use: --- /dev/null\\\\n+++ b/<path>\n- Always include 3 lines of context around changes`;\n\n const userPrompt = `Task: ${s.task ?? \"\"}\nStep ID: ${stepId}\nStep Title: ${s.title ?? \"\"}\nStep Description: ${s.description ?? \"\"}${fileContentsSection}`;\n\n const text = await callOpenAi(system, userPrompt, this.apiKey, this.model);\n const parsed = parseJson<Partial<AiGenerateDiffsResponse>>(text, { stepId, diffs: [] });\n return {\n stepId,\n diffs: Array.isArray(parsed.diffs) ? parsed.diffs : [],\n };\n }\n\n async summarizeChanges(diff: unknown): Promise<AiSummarizeChangesResponse> {\n const d = diff as { diffs?: AiGenerateDiffsResponse[]; rawDiff?: string };\n const diffContent =\n d.rawDiff ??\n (d.diffs ?? [])\n .flatMap((dr) => dr.diffs.map((f) => `File: ${f.path}\\n${f.unifiedDiff}`))\n .join(\"\\n\\n\") ??\n \"(no diffs)\";\n\n const system = `You are a technical writer. Summarize code changes for a pull request. Respond with ONLY valid JSON:\n{\n \"summary\": \"<2-3 sentence plain-English summary of what changed and why>\",\n \"filesChanged\": [\n { \"path\": \"<file path>\", \"changeType\": \"<add | modify | delete>\" }\n ]\n}`;\n\n const text = await callOpenAi(system, `Changes:\\n${diffContent}`, this.apiKey, this.model);\n const parsed = parseJson<Partial<AiSummarizeChangesResponse>>(text, {\n summary: \"\",\n filesChanged: [],\n });\n return {\n summary: parsed.summary ?? \"Code changes applied.\",\n filesChanged: Array.isArray(parsed.filesChanged) ? parsed.filesChanged : [],\n };\n }\n\n async suggestFixes(comment: unknown): Promise<AiSuggestFixesResponse> {\n const { buildSuggestFixesSystem, buildSuggestFixesPrompt, parseSuggestFixesResponse } =\n await import(\"./reviewHelpers.js\");\n const ctx = comment as Parameters<typeof buildSuggestFixesPrompt>[0];\n const text = await callOpenAi(\n buildSuggestFixesSystem(),\n buildSuggestFixesPrompt(ctx),\n this.apiKey,\n this.model\n );\n return parseSuggestFixesResponse(text);\n }\n\n async reviewPR(context: unknown): Promise<AiReviewPRResponse> {\n const ctx = context as {\n prTitle?: string;\n prBody?: string;\n diff?: string;\n comments?: Array<{ body: string; author: string; path?: string }>;\n };\n\n const diffSection = ctx.diff\n ? `\\n\\nDiff (unified):\\n${ctx.diff.slice(0, 8000)}`\n : \"\";\n const commentsSection =\n ctx.comments && ctx.comments.length > 0\n ? `\\n\\nExisting review comments:\\n${ctx.comments\n .map((c) => `[${c.author}${c.path ? ` @ ${c.path}` : \"\"}]: ${c.body}`)\n .join(\"\\n\")}`\n : \"\";\n\n const system = `You are an expert code reviewer. Review the given pull request thoroughly and respond with ONLY valid JSON:\n{\n \"summary\": \"<2-4 sentence overall assessment>\",\n \"issues\": [\n { \"severity\": \"<critical|warning|suggestion>\", \"description\": \"<specific issue>\", \"file\": \"<optional file>\", \"line\": null }\n ],\n \"positives\": [\"<good thing 1>\", \"<good thing 2>\"],\n \"verdict\": \"<approve|request_changes|comment>\"\n}\n\nSeverity guide:\n- critical: bugs, security issues, data loss risk\n- warning: code quality, performance, missing error handling\n- suggestion: style, naming, minor improvements`;\n\n const userPrompt = `PR Title: ${ctx.prTitle ?? \"\"}\nPR Description: ${ctx.prBody ?? \"\"}${diffSection}${commentsSection}`;\n\n const text = await callOpenAi(system, userPrompt, this.apiKey, this.model);\n const parsed = parseJson<Partial<AiReviewPRResponse>>(text, {\n summary: \"\",\n issues: [],\n positives: [],\n verdict: \"comment\",\n });\n\n return {\n summary: parsed.summary ?? \"Review could not be generated.\",\n issues: Array.isArray(parsed.issues) ? parsed.issues : [],\n positives: Array.isArray(parsed.positives) ? parsed.positives : [],\n verdict: ([\"approve\", \"request_changes\", \"comment\"].includes(parsed.verdict ?? \"\"))\n ? (parsed.verdict as AiReviewPRResponse[\"verdict\"])\n : \"comment\",\n };\n }\n\n async generatePrContent(commits: string[], diff: string, stat?: string): Promise<import(\"./types.js\").AiPrContentResponse> {\n const system = `You are an expert software engineer writing pull request descriptions.\nYou are given a list of commits on the branch and the unified diff of all changes.\n\nThe input may contain:\n - \"=== Changed files (complete list) ===\" — the full --stat summary of every file touched\n - \"=== Detailed diff ===\" — the actual patch (may be truncated for large changesets)\n\nWhen a file list is present, use it as the authoritative source of ALL changed files.\nDo not ignore files that appear in the list but are absent from the truncated diff.\n\nProduce a clear, informative PR title and description:\n\nRules:\n- title: short, human-readable, present-tense. No conventional-commit prefix. Max 72 chars.\n- body: 2-4 sentences describing WHAT changed and WHY. Cover ALL files from the list.\n Plain English, no bullet points.\n\nRespond with ONLY valid JSON (no markdown fences):\n{\"title\":\"<PR title>\",\"body\":\"<PR description>\"}`;\n\n const commitList = commits.slice(0, 20).join(\"\\n\");\n const diffSection = stat\n ? `=== Changed files (complete list) ===\\n${stat}\\n\\n=== Detailed diff ===\\n${diff.slice(0, 16000)}`\n : `Diff:\\n${diff.slice(0, 16000)}`;\n const userPrompt = `Commits on this branch:\\n${commitList}\\n\\n${diffSection}`;\n const text = await callOpenAi(system, userPrompt, this.apiKey, this.model);\n const parsed = parseJson<Partial<import(\"./types.js\").AiPrContentResponse>>(text, {});\n return {\n title: parsed.title?.trim() ?? \"Update branch\",\n body: parsed.body?.trim() ?? \"\",\n };\n }\n\n async resolveConflict(filePath: string, conflictContent: string): Promise<import(\"./types.js\").AiConflictResolutionResponse> {\n const system = `You are an expert software engineer resolving git merge conflicts.\n\nThe file contains standard git conflict markers:\n <<<<<<< HEAD — changes on the current branch\n ======= — separator\n >>>>>>> theirs — incoming changes\n\nYour task:\n1. Understand BOTH sides of every conflict.\n2. Produce a single correct version preserving the intent of BOTH changes where possible.\n3. If the sides are genuinely contradictory, set confidence to \"low\".\n\nRules:\n- Remove ALL conflict markers from the output.\n- Do NOT add explanatory comments.\n- Keep all non-conflicting code exactly as-is.\n- Output must be syntactically valid.\n\nRespond with ONLY valid JSON (no markdown fences):\n{\"resolved\":\"<full resolved file content>\",\"confidence\":\"high|low\",\"explanation\":\"<one sentence>\"}`;\n\n const userPrompt = `File: ${filePath}\\n\\n${conflictContent.slice(0, 20000)}`;\n const text = await callOpenAi(system, userPrompt, this.apiKey, this.model);\n const parsed = parseJson<Partial<import(\"./types.js\").AiConflictResolutionResponse>>(text, {});\n return {\n resolved: parsed.resolved ?? conflictContent,\n confidence: parsed.confidence === \"low\" ? \"low\" : \"high\",\n explanation: parsed.explanation?.trim() ?? \"Conflict resolved.\",\n };\n }\n async generateCommitMessage(diff: string): Promise<import(\"./types.js\").AiCommitMessageResponse> {\n const system = `You are an expert software engineer writing git commit messages.\nYou receive either a plain unified diff OR a structured input with:\n - \"=== Changed files (complete list) ===\" — the full --stat summary of every file touched\n - \"=== Detailed diff ===\" — the actual patch (may be truncated for large changesets)\n\nWhen a file list is present, use it as the authoritative source of ALL changes.\nDo not ignore files that appear in the list but are missing from the truncated diff.\n\nProduce ONE CONVENTIONAL COMMIT covering all the changes:\n\nRules:\n- subject: \"<type>(<scope>): <imperative description>\"\n - type: feat | fix | refactor | chore | docs | test | perf | ci | style | build\n - scope: the primary area affected; omit if changes span many unrelated areas\n - description: imperative mood, no period, 72 chars max for the whole subject line\n - if several distinct features or fixes are present, pick the most impactful for the subject\n- body: cover EVERY significant change visible in the file list. For each distinct change,\n one sentence on what was done and why. Plain English, no bullet lists, no repetition of the subject.\n\nRespond with ONLY valid JSON (no markdown fences):\n{\"subject\":\"<subject line>\",\"body\":\"<body covering all changes, or empty string>\"}`;\n\n const text = await callOpenAi(system, `Diff:\\n${diff.slice(0, 20000)}`, this.apiKey, this.model);\n const parsed = parseJson<Partial<import(\"./types.js\").AiCommitMessageResponse>>(text, {});\n return {\n subject: parsed.subject?.trim() ?? \"chore: update files\",\n body: parsed.body?.trim() || undefined,\n };\n }\n\n async reviewPRDetailed(\n context: Parameters<import(\"./types.js\").AiClient[\"reviewPRDetailed\"]>[0]\n ): Promise<import(\"./types.js\").AiDetailedReviewResponse> {\n const { buildSeniorReviewSystem, buildSeniorReviewPrompt, parseSeniorReview } = await import(\"./reviewHelpers.js\");\n const text = await callOpenAi(\n buildSeniorReviewSystem(),\n buildSeniorReviewPrompt(context),\n this.apiKey,\n this.model\n );\n return parseSeniorReview(text);\n }\n\n async generateFix(\n context: Parameters<import(\"./types.js\").AiClient[\"generateFix\"]>[0]\n ): Promise<import(\"./types.js\").AiFixResponse> {\n const { buildFixSystem, buildFixPrompt, parseFixResponse } = await import(\"./reviewHelpers.js\");\n const text = await callOpenAi(\n buildFixSystem(),\n buildFixPrompt(context),\n this.apiKey,\n this.model\n );\n return parseFixResponse(text, context.filePath, context.line);\n }\n\n async ask(\n question: string,\n context: import(\"./types.js\").AiAskContext\n ): Promise<import(\"./types.js\").AiAskResponse> {\n const { buildAskSystem, buildAskPrompt, parseAskResponse } = await import(\"./reviewHelpers.js\");\n const text = await callOpenAi(buildAskSystem(), buildAskPrompt(question, context), this.apiKey, this.model);\n return parseAskResponse(text);\n }\n}\n"]}
|
|
@@ -63,4 +63,28 @@ export declare function buildAskPrompt(question: string, ctx: AiAskContext): str
|
|
|
63
63
|
* Falls back to using the raw text as the answer if JSON parsing fails.
|
|
64
64
|
*/
|
|
65
65
|
export declare function parseAskResponse(raw: string): AiAskResponse;
|
|
66
|
+
export interface SuggestFixesContext {
|
|
67
|
+
comments: Array<{
|
|
68
|
+
body: string;
|
|
69
|
+
path?: string;
|
|
70
|
+
line?: number;
|
|
71
|
+
author?: string;
|
|
72
|
+
}>;
|
|
73
|
+
prTitle?: string;
|
|
74
|
+
prBody?: string;
|
|
75
|
+
/** Full unified diff of the PR — tells the AI what changed vs. the base */
|
|
76
|
+
diff?: string;
|
|
77
|
+
/** File contents keyed by relative path (with line numbers prefixed) */
|
|
78
|
+
fileContents?: Record<string, string>;
|
|
79
|
+
}
|
|
80
|
+
export interface SuggestFixesResponse {
|
|
81
|
+
suggestedEdits: Array<{
|
|
82
|
+
path: string;
|
|
83
|
+
rationale: string;
|
|
84
|
+
unifiedDiff: string;
|
|
85
|
+
}>;
|
|
86
|
+
}
|
|
87
|
+
export declare function buildSuggestFixesSystem(): string;
|
|
88
|
+
export declare function buildSuggestFixesPrompt(ctx: SuggestFixesContext): string;
|
|
89
|
+
export declare function parseSuggestFixesResponse(raw: string): SuggestFixesResponse;
|
|
66
90
|
//# sourceMappingURL=reviewHelpers.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reviewHelpers.d.ts","sourceRoot":"","sources":["../../src/ai/reviewHelpers.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,wBAAwB,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAIvG,wBAAgB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GAIG;AACH,wBAAgB,cAAc,IAAI,MAAM,CAgCvC;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,EAAE,YAAY,GAAG,MAAM,CAoE1E;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,GAAG,aAAa,CAa3D;AAID,MAAM,WAAW,mBAAmB;IAClC,QAAQ,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACjF,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,2EAA2E;IAC3E,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,wEAAwE;IACxE,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACvC;AAED,MAAM,WAAW,oBAAoB;IACnC,cAAc,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAC;QAAC,WAAW,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CACjF;AAED,wBAAgB,uBAAuB,IAAI,MAAM,CA0BhD;AAED,wBAAgB,uBAAuB,CAAC,GAAG,EAAE,mBAAmB,GAAG,MAAM,CAmCxE;AAED,wBAAgB,yBAAyB,CAAC,GAAG,EAAE,MAAM,GAAG,oBAAoB,CAa3E"}
|
package/dist/ai/reviewHelpers.js
CHANGED
|
@@ -430,7 +430,7 @@ const GITX_COMMAND_REFERENCE = `
|
|
|
430
430
|
| gitx config set <key> [value] | Set a single config value (provider, token, model, etc.) |
|
|
431
431
|
| gitx commit [-m msg] [--push] [--dry-run] | AI-generate commit message → commit (optionally push) |
|
|
432
432
|
| gitx push [-b branch] [--staged] [--dry-run] | Stage → AI-commit → push in one step; --staged uses already-staged files only |
|
|
433
|
-
| gitx sync [--base branch] [--strategy merge|rebase] [--continue] [--abort] |
|
|
433
|
+
| 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. |
|
|
434
434
|
| gitx port <target…> [--base branch] [--no-pr] [--draft] [--continue] [--abort] | Cherry-pick commits onto other branches with incremental detection |
|
|
435
435
|
| gitx implement "<task>" [--mode plan|guided|semi-auto|auto] [--dry-run] | AI-plan and implement a task end-to-end |
|
|
436
436
|
| gitx pr list [--state open|closed|all] | List pull requests |
|
|
@@ -439,6 +439,8 @@ const GITX_COMMAND_REFERENCE = `
|
|
|
439
439
|
| gitx pr resolve <number> [--no-commit] [--no-push] [--dry-run] | AI-fix review comments in code; --no-commit applies fixes without committing |
|
|
440
440
|
| gitx pr merge <number> [--strategy squash|merge|rebase] [--delete-branch] | Merge a PR |
|
|
441
441
|
| gitx pr close <number> [-f] | Close a PR |
|
|
442
|
+
| gitx pr cherry-pick <number> [--dry-run] [--no-confirm] | Cherry-pick all commits from a PR into the current branch |
|
|
443
|
+
| 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) |
|
|
442
444
|
| gitx ask "<question>" [--pr] | Ask a question about the repo using AI + live git context |
|
|
443
445
|
|
|
444
446
|
## Supported Providers
|
|
@@ -571,4 +573,71 @@ export function parseAskResponse(raw) {
|
|
|
571
573
|
return { answer: raw.trim(), suggestedCommands: [] };
|
|
572
574
|
}
|
|
573
575
|
}
|
|
576
|
+
export function buildSuggestFixesSystem() {
|
|
577
|
+
return `You are a senior software engineer resolving pull request review comments by making precise code fixes.
|
|
578
|
+
|
|
579
|
+
You are given:
|
|
580
|
+
1. The PR title and description (for context)
|
|
581
|
+
2. The unified diff of the PR (shows exactly what changed vs. the base branch)
|
|
582
|
+
3. The current file contents of every file that has comments (with line numbers)
|
|
583
|
+
4. The review comments, each tagged with the file and line they target
|
|
584
|
+
|
|
585
|
+
Your job:
|
|
586
|
+
- For each comment that requires a code change, produce a minimal, correct unified diff that fixes it
|
|
587
|
+
- The diff MUST apply cleanly to the CURRENT file content shown (not the base)
|
|
588
|
+
- Preserve the existing code style, indentation, and patterns
|
|
589
|
+
- If a comment is a question or praise (no code change needed), omit it from suggestedEdits
|
|
590
|
+
- Do NOT fix things not mentioned in the comments — minimal targeted changes only
|
|
591
|
+
|
|
592
|
+
Respond with ONLY valid JSON (no markdown fences):
|
|
593
|
+
{
|
|
594
|
+
"suggestedEdits": [
|
|
595
|
+
{
|
|
596
|
+
"path": "<relative file path>",
|
|
597
|
+
"rationale": "<one sentence: which comment this fixes and how>",
|
|
598
|
+
"unifiedDiff": "<valid unified diff that applies to the current file content>"
|
|
599
|
+
}
|
|
600
|
+
]
|
|
601
|
+
}`;
|
|
602
|
+
}
|
|
603
|
+
export function buildSuggestFixesPrompt(ctx) {
|
|
604
|
+
const parts = [];
|
|
605
|
+
parts.push(`PR Title: ${ctx.prTitle ?? "(none)"}`);
|
|
606
|
+
if (ctx.prBody?.trim()) {
|
|
607
|
+
parts.push(`\nPR Description:\n${ctx.prBody.trim()}`);
|
|
608
|
+
}
|
|
609
|
+
// Unified diff — gives the AI the before/after context for every changed line
|
|
610
|
+
const DIFF_BUDGET = 30_000;
|
|
611
|
+
if (ctx.diff?.trim()) {
|
|
612
|
+
const diffSlice = ctx.diff.slice(0, DIFF_BUDGET);
|
|
613
|
+
const truncated = diffSlice.length < ctx.diff.length;
|
|
614
|
+
parts.push(`\n### PR Unified Diff${truncated ? " (truncated)" : ""}\n\`\`\`diff\n${diffSlice}\n\`\`\``);
|
|
615
|
+
}
|
|
616
|
+
// Review comments
|
|
617
|
+
const commentsText = ctx.comments
|
|
618
|
+
.map((c) => `[${c.author ?? "reviewer"}${c.path ? ` on ${c.path}:${c.line ?? "?"}` : ""}]:\n${c.body}`)
|
|
619
|
+
.join("\n\n---\n\n");
|
|
620
|
+
parts.push(`\n### Review Comments\n${commentsText}`);
|
|
621
|
+
// Current file contents (with line numbers so the diff is anchored correctly)
|
|
622
|
+
if (ctx.fileContents && Object.keys(ctx.fileContents).length > 0) {
|
|
623
|
+
parts.push(`\n### Current File Contents (line numbers are exact — use them for your diffs)`);
|
|
624
|
+
for (const [path, content] of Object.entries(ctx.fileContents)) {
|
|
625
|
+
parts.push(`\n#### ${path}\n\`\`\`\n${content}\n\`\`\``);
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
return parts.join("\n");
|
|
629
|
+
}
|
|
630
|
+
export function parseSuggestFixesResponse(raw) {
|
|
631
|
+
try {
|
|
632
|
+
const parsed = JSON.parse(raw);
|
|
633
|
+
return {
|
|
634
|
+
suggestedEdits: Array.isArray(parsed.suggestedEdits)
|
|
635
|
+
? parsed.suggestedEdits.filter((e) => typeof e?.path === "string" && typeof e?.unifiedDiff === "string")
|
|
636
|
+
: [],
|
|
637
|
+
};
|
|
638
|
+
}
|
|
639
|
+
catch {
|
|
640
|
+
return { suggestedEdits: [] };
|
|
641
|
+
}
|
|
642
|
+
}
|
|
574
643
|
//# sourceMappingURL=reviewHelpers.js.map
|
|
@@ -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,E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AAC,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 // ── 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] | Sync current branch with base; AI resolves conflicts |\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 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;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,WA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AAC,EAAE,CAAC;YAC/D,KAAK,CAAC,IAAI,CAAC,UAAU,IAAI,aAAa,OAAO,UAAU,CAAC,CAAC;QAC3D,CAAC;IACH,CAAC;IAED,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC1B,CAAC;AAED,MAAM,UAAU,yBAAyB,CAAC,GAAW;IACnD,IAAI,CAAC;QACH,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAkC,CAAC;QAChE,OAAO;YACL,cAAc,EAAE,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,cAAc,CAAC;gBAClD,CAAC,CAAC,MAAM,CAAC,cAAc,CAAC,MAAM,CAC1B,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,EAAE,IAAI,KAAK,QAAQ,IAAI,OAAO,CAAC,EAAE,WAAW,KAAK,QAAQ,CACzE;gBACH,CAAC,CAAC,EAAE;SACP,CAAC;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,EAAE,cAAc,EAAE,EAAE,EAAE,CAAC;IAChC,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 // ── 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"}
|