@caupulican/pi-adaptative 0.81.6 → 0.81.8
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/CHANGELOG.md +33 -0
- package/dist/cli/initial-message.d.ts.map +1 -1
- package/dist/cli/initial-message.js +9 -8
- package/dist/cli/initial-message.js.map +1 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +12 -14
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/background-lane-controller.d.ts +1 -0
- package/dist/core/background-lane-controller.d.ts.map +1 -1
- package/dist/core/background-lane-controller.js +7 -3
- package/dist/core/background-lane-controller.js.map +1 -1
- package/dist/core/bash-execution-controller.d.ts +1 -1
- package/dist/core/bash-execution-controller.d.ts.map +1 -1
- package/dist/core/bash-execution-controller.js +9 -6
- package/dist/core/bash-execution-controller.js.map +1 -1
- package/dist/core/delegation/worker-actions.d.ts.map +1 -1
- package/dist/core/delegation/worker-actions.js +1 -1
- package/dist/core/delegation/worker-actions.js.map +1 -1
- package/dist/core/exec.d.ts.map +1 -1
- package/dist/core/exec.js +7 -2
- package/dist/core/exec.js.map +1 -1
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +19 -5
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/failure-corpus.d.ts.map +1 -1
- package/dist/core/failure-corpus.js +1 -1
- package/dist/core/failure-corpus.js.map +1 -1
- package/dist/core/learning/reflection-engine.d.ts.map +1 -1
- package/dist/core/learning/reflection-engine.js +3 -1
- package/dist/core/learning/reflection-engine.js.map +1 -1
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +33 -3
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/model-router/tool-escalation.d.ts.map +1 -1
- package/dist/core/model-router/tool-escalation.js +2 -2
- package/dist/core/model-router/tool-escalation.js.map +1 -1
- package/dist/core/scout-controller.d.ts +5 -0
- package/dist/core/scout-controller.d.ts.map +1 -1
- package/dist/core/scout-controller.js +4 -1
- package/dist/core/scout-controller.js.map +1 -1
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +1 -1
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/tools/edit-diff.d.ts +6 -10
- package/dist/core/tools/edit-diff.d.ts.map +1 -1
- package/dist/core/tools/edit-diff.js +70 -18
- package/dist/core/tools/edit-diff.js.map +1 -1
- package/dist/core/tools/git-filter.d.ts.map +1 -1
- package/dist/core/tools/git-filter.js +3 -4
- package/dist/core/tools/git-filter.js.map +1 -1
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +12 -2
- package/dist/core/tools/read.js.map +1 -1
- package/dist/migrations.d.ts +1 -0
- package/dist/migrations.d.ts.map +1 -1
- package/dist/migrations.js +7 -1
- package/dist/migrations.js.map +1 -1
- package/dist/modes/interactive/auto-learn-controller.d.ts.map +1 -1
- package/dist/modes/interactive/auto-learn-controller.js +14 -6
- package/dist/modes/interactive/auto-learn-controller.js.map +1 -1
- package/dist/modes/interactive/components/session-selector.d.ts +1 -0
- package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector.js +11 -4
- package/dist/modes/interactive/components/session-selector.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +5 -0
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +22 -7
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/utils/tools-manager.d.ts +1 -0
- package/dist/utils/tools-manager.d.ts.map +1 -1
- package/dist/utils/tools-manager.js +14 -1
- package/dist/utils/tools-manager.js.map +1 -1
- package/docs/bug-ledger.md +37 -22
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +12 -12
- package/package.json +4 -4
|
@@ -22,10 +22,7 @@ export interface FuzzyMatchResult {
|
|
|
22
22
|
matchLength: number;
|
|
23
23
|
/** Whether fuzzy matching was used (false = exact match) */
|
|
24
24
|
usedFuzzyMatch: boolean;
|
|
25
|
-
/**
|
|
26
|
-
* The content to use for replacement operations.
|
|
27
|
-
* When exact match: original content. When fuzzy match: normalized content.
|
|
28
|
-
*/
|
|
25
|
+
/** The original content replacements should be applied to. */
|
|
29
26
|
contentForReplacement: string;
|
|
30
27
|
}
|
|
31
28
|
export interface Edit {
|
|
@@ -38,9 +35,8 @@ export interface AppliedEditsResult {
|
|
|
38
35
|
}
|
|
39
36
|
/**
|
|
40
37
|
* Find oldText in content, trying exact match first, then fuzzy match.
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
-
* Unicode quotes/dashes normalized to ASCII).
|
|
38
|
+
* Fuzzy matching searches normalized text, but returned spans still refer to
|
|
39
|
+
* the original content so replacement does not normalize unrelated text.
|
|
44
40
|
*/
|
|
45
41
|
export declare function fuzzyFindText(content: string, oldText: string): FuzzyMatchResult;
|
|
46
42
|
/** Strip UTF-8 BOM if present, return both the BOM (if any) and the text without it */
|
|
@@ -52,9 +48,9 @@ export declare function stripBom(content: string): {
|
|
|
52
48
|
* Apply one or more exact-text replacements to LF-normalized content.
|
|
53
49
|
*
|
|
54
50
|
* All edits are matched against the same original content. Replacements are
|
|
55
|
-
* then applied in reverse order so offsets remain stable.
|
|
56
|
-
*
|
|
57
|
-
*
|
|
51
|
+
* then applied in reverse order so offsets remain stable. Fuzzy matching uses
|
|
52
|
+
* normalized text only for finding the span; the final splice is always made
|
|
53
|
+
* into the original content.
|
|
58
54
|
*/
|
|
59
55
|
export declare function applyEditsToNormalizedContent(normalizedContent: string, edits: Edit[], path: string): AppliedEditsResult;
|
|
60
56
|
/** Generate a standard unified patch. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"edit-diff.d.ts","sourceRoot":"","sources":["../../../src/core/tools/edit-diff.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAOH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAM/D;AAED,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAElD;AAED,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,MAAM,CAE9E;AAED;;;;;;GAMG;AACH,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAqB3D;AAED,MAAM,WAAW,gBAAgB;IAChC,gCAAgC;IAChC,KAAK,EAAE,OAAO,CAAC;IACf,4FAA4F;IAC5F,KAAK,EAAE,MAAM,CAAC;IACd,iCAAiC;IACjC,WAAW,EAAE,MAAM,CAAC;IACpB,4DAA4D;IAC5D,cAAc,EAAE,OAAO,CAAC;IACxB;;;OAGG;IACH,qBAAqB,EAAE,MAAM,CAAC;CAC9B;AAED,MAAM,WAAW,IAAI;IACpB,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;CAChB;AASD,MAAM,WAAW,kBAAkB;IAClC,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;CACnB;AAED;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,gBAAgB,CAsChF;AAED,uFAAuF;AACvF,wBAAgB,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAEvE;AA8CD;;;;;;;GAOG;AACH,wBAAgB,6BAA6B,CAC5C,iBAAiB,EAAE,MAAM,EACzB,KAAK,EAAE,IAAI,EAAE,EACb,IAAI,EAAE,MAAM,GACV,kBAAkB,CA+DpB;AAED,yCAAyC;AACzC,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,YAAY,SAAI,GAAG,MAAM,CAKnH;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CACjC,UAAU,EAAE,MAAM,EAClB,UAAU,EAAE,MAAM,EAClB,YAAY,SAAI,GACd;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,gBAAgB,EAAE,MAAM,GAAG,SAAS,CAAA;CAAE,CAuHxD;AAED,MAAM,WAAW,cAAc;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,gBAAgB,EAAE,MAAM,GAAG,SAAS,CAAC;CACrC;AAED,MAAM,WAAW,aAAa;IAC7B,KAAK,EAAE,MAAM,CAAC;CACd;AAED;;;GAGG;AACH,wBAAsB,gBAAgB,CACrC,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,IAAI,EAAE,EACb,GAAG,EAAE,MAAM,GACT,OAAO,CAAC,cAAc,GAAG,aAAa,CAAC,CAyBzC;AAED;;;GAGG;AACH,wBAAsB,eAAe,CACpC,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,MAAM,GACT,OAAO,CAAC,cAAc,GAAG,aAAa,CAAC,CAEzC","sourcesContent":["/**\n * Shared diff computation utilities for the edit tool.\n * Used by both edit.ts (for execution) and tool-execution.ts (for preview rendering).\n */\n\nimport * as Diff from \"diff\";\nimport { constants } from \"fs\";\nimport { access, readFile } from \"fs/promises\";\nimport { resolveToCwd } from \"./path-utils.ts\";\n\nexport function detectLineEnding(content: string): \"\\r\\n\" | \"\\n\" {\n\tconst crlfIdx = content.indexOf(\"\\r\\n\");\n\tconst lfIdx = content.indexOf(\"\\n\");\n\tif (lfIdx === -1) return \"\\n\";\n\tif (crlfIdx === -1) return \"\\n\";\n\treturn crlfIdx < lfIdx ? \"\\r\\n\" : \"\\n\";\n}\n\nexport function normalizeToLF(text: string): string {\n\treturn text.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\");\n}\n\nexport function restoreLineEndings(text: string, ending: \"\\r\\n\" | \"\\n\"): string {\n\treturn ending === \"\\r\\n\" ? text.replace(/\\n/g, \"\\r\\n\") : text;\n}\n\n/**\n * Normalize text for fuzzy matching. Applies progressive transformations:\n * - Strip trailing whitespace from each line\n * - Normalize smart quotes to ASCII equivalents\n * - Normalize Unicode dashes/hyphens to ASCII hyphen\n * - Normalize special Unicode spaces to regular space\n */\nexport function normalizeForFuzzyMatch(text: string): string {\n\treturn (\n\t\ttext\n\t\t\t.normalize(\"NFKC\")\n\t\t\t// Strip trailing whitespace per line\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => line.trimEnd())\n\t\t\t.join(\"\\n\")\n\t\t\t// Smart single quotes → '\n\t\t\t.replace(/[\\u2018\\u2019\\u201A\\u201B]/g, \"'\")\n\t\t\t// Smart double quotes → \"\n\t\t\t.replace(/[\\u201C\\u201D\\u201E\\u201F]/g, '\"')\n\t\t\t// Various dashes/hyphens → -\n\t\t\t// U+2010 hyphen, U+2011 non-breaking hyphen, U+2012 figure dash,\n\t\t\t// U+2013 en-dash, U+2014 em-dash, U+2015 horizontal bar, U+2212 minus\n\t\t\t.replace(/[\\u2010\\u2011\\u2012\\u2013\\u2014\\u2015\\u2212]/g, \"-\")\n\t\t\t// Special spaces → regular space\n\t\t\t// U+00A0 NBSP, U+2002-U+200A various spaces, U+202F narrow NBSP,\n\t\t\t// U+205F medium math space, U+3000 ideographic space\n\t\t\t.replace(/[\\u00A0\\u2002-\\u200A\\u202F\\u205F\\u3000]/g, \" \")\n\t);\n}\n\nexport interface FuzzyMatchResult {\n\t/** Whether a match was found */\n\tfound: boolean;\n\t/** The index where the match starts (in the content that should be used for replacement) */\n\tindex: number;\n\t/** Length of the matched text */\n\tmatchLength: number;\n\t/** Whether fuzzy matching was used (false = exact match) */\n\tusedFuzzyMatch: boolean;\n\t/**\n\t * The content to use for replacement operations.\n\t * When exact match: original content. When fuzzy match: normalized content.\n\t */\n\tcontentForReplacement: string;\n}\n\nexport interface Edit {\n\toldText: string;\n\tnewText: string;\n}\n\ninterface MatchedEdit {\n\teditIndex: number;\n\tmatchIndex: number;\n\tmatchLength: number;\n\tnewText: string;\n}\n\nexport interface AppliedEditsResult {\n\tbaseContent: string;\n\tnewContent: string;\n}\n\n/**\n * Find oldText in content, trying exact match first, then fuzzy match.\n * When fuzzy matching is used, the returned contentForReplacement is the\n * fuzzy-normalized version of the content (trailing whitespace stripped,\n * Unicode quotes/dashes normalized to ASCII).\n */\nexport function fuzzyFindText(content: string, oldText: string): FuzzyMatchResult {\n\t// Try exact match first\n\tconst exactIndex = content.indexOf(oldText);\n\tif (exactIndex !== -1) {\n\t\treturn {\n\t\t\tfound: true,\n\t\t\tindex: exactIndex,\n\t\t\tmatchLength: oldText.length,\n\t\t\tusedFuzzyMatch: false,\n\t\t\tcontentForReplacement: content,\n\t\t};\n\t}\n\n\t// Try fuzzy match - work entirely in normalized space\n\tconst fuzzyContent = normalizeForFuzzyMatch(content);\n\tconst fuzzyOldText = normalizeForFuzzyMatch(oldText);\n\tconst fuzzyIndex = fuzzyContent.indexOf(fuzzyOldText);\n\n\tif (fuzzyIndex === -1) {\n\t\treturn {\n\t\t\tfound: false,\n\t\t\tindex: -1,\n\t\t\tmatchLength: 0,\n\t\t\tusedFuzzyMatch: false,\n\t\t\tcontentForReplacement: content,\n\t\t};\n\t}\n\n\t// When fuzzy matching, we work in the normalized space for replacement.\n\t// This means the output will have normalized whitespace/quotes/dashes,\n\t// which is acceptable since we're fixing minor formatting differences anyway.\n\treturn {\n\t\tfound: true,\n\t\tindex: fuzzyIndex,\n\t\tmatchLength: fuzzyOldText.length,\n\t\tusedFuzzyMatch: true,\n\t\tcontentForReplacement: fuzzyContent,\n\t};\n}\n\n/** Strip UTF-8 BOM if present, return both the BOM (if any) and the text without it */\nexport function stripBom(content: string): { bom: string; text: string } {\n\treturn content.startsWith(\"\\uFEFF\") ? { bom: \"\\uFEFF\", text: content.slice(1) } : { bom: \"\", text: content };\n}\n\nfunction countOccurrences(content: string, oldText: string): number {\n\tconst fuzzyContent = normalizeForFuzzyMatch(content);\n\tconst fuzzyOldText = normalizeForFuzzyMatch(oldText);\n\treturn fuzzyContent.split(fuzzyOldText).length - 1;\n}\n\nfunction getNotFoundError(path: string, editIndex: number, totalEdits: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(\n\t\t\t`Could not find the exact text in ${path}. The old text must match exactly including all whitespace and newlines.`,\n\t\t);\n\t}\n\treturn new Error(\n\t\t`Could not find edits[${editIndex}] in ${path}. The oldText must match exactly including all whitespace and newlines.`,\n\t);\n}\n\nfunction getDuplicateError(path: string, editIndex: number, totalEdits: number, occurrences: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(\n\t\t\t`Found ${occurrences} occurrences of the text in ${path}. The text must be unique. Please provide more context to make it unique.`,\n\t\t);\n\t}\n\treturn new Error(\n\t\t`Found ${occurrences} occurrences of edits[${editIndex}] in ${path}. Each oldText must be unique. Please provide more context to make it unique.`,\n\t);\n}\n\nfunction getEmptyOldTextError(path: string, editIndex: number, totalEdits: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(`oldText must not be empty in ${path}.`);\n\t}\n\treturn new Error(`edits[${editIndex}].oldText must not be empty in ${path}.`);\n}\n\nfunction getNoChangeError(path: string, totalEdits: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(\n\t\t\t`No changes made to ${path}. The replacement produced identical content. This might indicate an issue with special characters or the text not existing as expected.`,\n\t\t);\n\t}\n\treturn new Error(`No changes made to ${path}. The replacements produced identical content.`);\n}\n\n/**\n * Apply one or more exact-text replacements to LF-normalized content.\n *\n * All edits are matched against the same original content. Replacements are\n * then applied in reverse order so offsets remain stable. If any edit needs\n * fuzzy matching, the operation runs in fuzzy-normalized content space to\n * preserve current single-edit behavior.\n */\nexport function applyEditsToNormalizedContent(\n\tnormalizedContent: string,\n\tedits: Edit[],\n\tpath: string,\n): AppliedEditsResult {\n\tconst normalizedEdits = edits.map((edit) => ({\n\t\toldText: normalizeToLF(edit.oldText),\n\t\tnewText: normalizeToLF(edit.newText),\n\t}));\n\n\tfor (let i = 0; i < normalizedEdits.length; i++) {\n\t\tif (normalizedEdits[i].oldText.length === 0) {\n\t\t\tthrow getEmptyOldTextError(path, i, normalizedEdits.length);\n\t\t}\n\t}\n\n\tconst initialMatches = normalizedEdits.map((edit) => fuzzyFindText(normalizedContent, edit.oldText));\n\tconst baseContent = initialMatches.some((match) => match.usedFuzzyMatch)\n\t\t? normalizeForFuzzyMatch(normalizedContent)\n\t\t: normalizedContent;\n\n\tconst matchedEdits: MatchedEdit[] = [];\n\tfor (let i = 0; i < normalizedEdits.length; i++) {\n\t\tconst edit = normalizedEdits[i];\n\t\tconst matchResult = fuzzyFindText(baseContent, edit.oldText);\n\t\tif (!matchResult.found) {\n\t\t\tthrow getNotFoundError(path, i, normalizedEdits.length);\n\t\t}\n\n\t\tconst occurrences = countOccurrences(baseContent, edit.oldText);\n\t\tif (occurrences > 1) {\n\t\t\tthrow getDuplicateError(path, i, normalizedEdits.length, occurrences);\n\t\t}\n\n\t\tmatchedEdits.push({\n\t\t\teditIndex: i,\n\t\t\tmatchIndex: matchResult.index,\n\t\t\tmatchLength: matchResult.matchLength,\n\t\t\tnewText: edit.newText,\n\t\t});\n\t}\n\n\tmatchedEdits.sort((a, b) => a.matchIndex - b.matchIndex);\n\tfor (let i = 1; i < matchedEdits.length; i++) {\n\t\tconst previous = matchedEdits[i - 1];\n\t\tconst current = matchedEdits[i];\n\t\tif (previous.matchIndex + previous.matchLength > current.matchIndex) {\n\t\t\tthrow new Error(\n\t\t\t\t`edits[${previous.editIndex}] and edits[${current.editIndex}] overlap in ${path}. Merge them into one edit or target disjoint regions.`,\n\t\t\t);\n\t\t}\n\t}\n\n\tlet newContent = baseContent;\n\tfor (let i = matchedEdits.length - 1; i >= 0; i--) {\n\t\tconst edit = matchedEdits[i];\n\t\tnewContent =\n\t\t\tnewContent.substring(0, edit.matchIndex) +\n\t\t\tedit.newText +\n\t\t\tnewContent.substring(edit.matchIndex + edit.matchLength);\n\t}\n\n\tif (baseContent === newContent) {\n\t\tthrow getNoChangeError(path, normalizedEdits.length);\n\t}\n\n\treturn { baseContent, newContent };\n}\n\n/** Generate a standard unified patch. */\nexport function generateUnifiedPatch(path: string, oldContent: string, newContent: string, contextLines = 4): string {\n\treturn Diff.createTwoFilesPatch(path, path, oldContent, newContent, undefined, undefined, {\n\t\tcontext: contextLines,\n\t\theaderOptions: Diff.FILE_HEADERS_ONLY,\n\t});\n}\n\n/**\n * Generate a display-oriented diff string with line numbers and context.\n * Returns both the diff string and the first changed line number (in the new file).\n */\nexport function generateDiffString(\n\toldContent: string,\n\tnewContent: string,\n\tcontextLines = 4,\n): { diff: string; firstChangedLine: number | undefined } {\n\tconst parts = Diff.diffLines(oldContent, newContent);\n\tconst output: string[] = [];\n\n\tconst oldLines = oldContent.split(\"\\n\");\n\tconst newLines = newContent.split(\"\\n\");\n\tconst maxLineNum = Math.max(oldLines.length, newLines.length);\n\tconst lineNumWidth = String(maxLineNum).length;\n\n\tlet oldLineNum = 1;\n\tlet newLineNum = 1;\n\tlet lastWasChange = false;\n\tlet firstChangedLine: number | undefined;\n\n\tfor (let i = 0; i < parts.length; i++) {\n\t\tconst part = parts[i];\n\t\tconst raw = part.value.split(\"\\n\");\n\t\tif (raw[raw.length - 1] === \"\") {\n\t\t\traw.pop();\n\t\t}\n\n\t\tif (part.added || part.removed) {\n\t\t\t// Capture the first changed line (in the new file)\n\t\t\tif (firstChangedLine === undefined) {\n\t\t\t\tfirstChangedLine = newLineNum;\n\t\t\t}\n\n\t\t\t// Show the change\n\t\t\tfor (const line of raw) {\n\t\t\t\tif (part.added) {\n\t\t\t\t\tconst lineNum = String(newLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(`+${lineNum} ${line}`);\n\t\t\t\t\tnewLineNum++;\n\t\t\t\t} else {\n\t\t\t\t\t// removed\n\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(`-${lineNum} ${line}`);\n\t\t\t\t\toldLineNum++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tlastWasChange = true;\n\t\t} else {\n\t\t\t// Context lines - only show a few before/after changes\n\t\t\tconst nextPartIsChange = i < parts.length - 1 && (parts[i + 1].added || parts[i + 1].removed);\n\t\t\tconst hasLeadingChange = lastWasChange;\n\t\t\tconst hasTrailingChange = nextPartIsChange;\n\n\t\t\tif (hasLeadingChange && hasTrailingChange) {\n\t\t\t\tif (raw.length <= contextLines * 2) {\n\t\t\t\t\tfor (const line of raw) {\n\t\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\t\toldLineNum++;\n\t\t\t\t\t\tnewLineNum++;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tconst leadingLines = raw.slice(0, contextLines);\n\t\t\t\t\tconst trailingLines = raw.slice(raw.length - contextLines);\n\t\t\t\t\tconst skippedLines = raw.length - leadingLines.length - trailingLines.length;\n\n\t\t\t\t\tfor (const line of leadingLines) {\n\t\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\t\toldLineNum++;\n\t\t\t\t\t\tnewLineNum++;\n\t\t\t\t\t}\n\n\t\t\t\t\toutput.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n\t\t\t\t\toldLineNum += skippedLines;\n\t\t\t\t\tnewLineNum += skippedLines;\n\n\t\t\t\t\tfor (const line of trailingLines) {\n\t\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\t\toldLineNum++;\n\t\t\t\t\t\tnewLineNum++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (hasLeadingChange) {\n\t\t\t\tconst shownLines = raw.slice(0, contextLines);\n\t\t\t\tconst skippedLines = raw.length - shownLines.length;\n\n\t\t\t\tfor (const line of shownLines) {\n\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\toldLineNum++;\n\t\t\t\t\tnewLineNum++;\n\t\t\t\t}\n\n\t\t\t\tif (skippedLines > 0) {\n\t\t\t\t\toutput.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n\t\t\t\t\toldLineNum += skippedLines;\n\t\t\t\t\tnewLineNum += skippedLines;\n\t\t\t\t}\n\t\t\t} else if (hasTrailingChange) {\n\t\t\t\tconst skippedLines = Math.max(0, raw.length - contextLines);\n\t\t\t\tif (skippedLines > 0) {\n\t\t\t\t\toutput.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n\t\t\t\t\toldLineNum += skippedLines;\n\t\t\t\t\tnewLineNum += skippedLines;\n\t\t\t\t}\n\n\t\t\t\tfor (const line of raw.slice(skippedLines)) {\n\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\toldLineNum++;\n\t\t\t\t\tnewLineNum++;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Skip these context lines entirely\n\t\t\t\toldLineNum += raw.length;\n\t\t\t\tnewLineNum += raw.length;\n\t\t\t}\n\n\t\t\tlastWasChange = false;\n\t\t}\n\t}\n\n\treturn { diff: output.join(\"\\n\"), firstChangedLine };\n}\n\nexport interface EditDiffResult {\n\tdiff: string;\n\tfirstChangedLine: number | undefined;\n}\n\nexport interface EditDiffError {\n\terror: string;\n}\n\n/**\n * Compute the diff for one or more edit operations without applying them.\n * Used for preview rendering in the TUI before the tool executes.\n */\nexport async function computeEditsDiff(\n\tpath: string,\n\tedits: Edit[],\n\tcwd: string,\n): Promise<EditDiffResult | EditDiffError> {\n\tconst absolutePath = resolveToCwd(path, cwd);\n\n\ttry {\n\t\t// Check if file exists and is readable\n\t\ttry {\n\t\t\tawait access(absolutePath, constants.R_OK);\n\t\t} catch (error: unknown) {\n\t\t\tconst errorMessage = error instanceof Error && \"code\" in error ? `Error code: ${error.code}` : String(error);\n\t\t\treturn { error: `Could not edit file: ${path}. ${errorMessage}.` };\n\t\t}\n\n\t\t// Read the file\n\t\tconst rawContent = await readFile(absolutePath, \"utf-8\");\n\n\t\t// Strip BOM before matching (LLM won't include invisible BOM in oldText)\n\t\tconst { text: content } = stripBom(rawContent);\n\t\tconst normalizedContent = normalizeToLF(content);\n\t\tconst { baseContent, newContent } = applyEditsToNormalizedContent(normalizedContent, edits, path);\n\n\t\t// Generate the diff\n\t\treturn generateDiffString(baseContent, newContent);\n\t} catch (err) {\n\t\treturn { error: err instanceof Error ? err.message : String(err) };\n\t}\n}\n\n/**\n * Compute the diff for a single edit operation without applying it.\n * Kept as a convenience wrapper for single-edit callers.\n */\nexport async function computeEditDiff(\n\tpath: string,\n\toldText: string,\n\tnewText: string,\n\tcwd: string,\n): Promise<EditDiffResult | EditDiffError> {\n\treturn computeEditsDiff(path, [{ oldText, newText }], cwd);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"edit-diff.d.ts","sourceRoot":"","sources":["../../../src/core/tools/edit-diff.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAOH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAM/D;AAED,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM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,EAClB,UAAU,EAAE,MAAM,EAClB,YAAY,SAAI,GACd;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,gBAAgB,EAAE,MAAM,GAAG,SAAS,CAAA;CAAE,CAuHxD;AAED,MAAM,WAAW,cAAc;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,gBAAgB,EAAE,MAAM,GAAG,SAAS,CAAC;CACrC;AAED,MAAM,WAAW,aAAa;IAC7B,KAAK,EAAE,MAAM,CAAC;CACd;AAED;;;GAGG;AACH,wBAAsB,gBAAgB,CACrC,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,IAAI,EAAE,EACb,GAAG,EAAE,MAAM,GACT,OAAO,CAAC,cAAc,GAAG,aAAa,CAAC,CAyBzC;AAED;;;GAGG;AACH,wBAAsB,eAAe,CACpC,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,MAAM,GACT,OAAO,CAAC,cAAc,GAAG,aAAa,CAAC,CAEzC","sourcesContent":["/**\n * Shared diff computation utilities for the edit tool.\n * Used by both edit.ts (for execution) and tool-execution.ts (for preview rendering).\n */\n\nimport * as Diff from \"diff\";\nimport { constants } from \"fs\";\nimport { access, readFile } from \"fs/promises\";\nimport { resolveToCwd } from \"./path-utils.ts\";\n\nexport function detectLineEnding(content: string): \"\\r\\n\" | \"\\n\" {\n\tconst crlfIdx = content.indexOf(\"\\r\\n\");\n\tconst lfIdx = content.indexOf(\"\\n\");\n\tif (lfIdx === -1) return \"\\n\";\n\tif (crlfIdx === -1) return \"\\n\";\n\treturn crlfIdx < lfIdx ? \"\\r\\n\" : \"\\n\";\n}\n\nexport function normalizeToLF(text: string): string {\n\treturn text.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\");\n}\n\nexport function restoreLineEndings(text: string, ending: \"\\r\\n\" | \"\\n\"): string {\n\treturn ending === \"\\r\\n\" ? text.replace(/\\n/g, \"\\r\\n\") : text;\n}\n\n/**\n * Normalize text for fuzzy matching. Applies progressive transformations:\n * - Strip trailing whitespace from each line\n * - Normalize smart quotes to ASCII equivalents\n * - Normalize Unicode dashes/hyphens to ASCII hyphen\n * - Normalize special Unicode spaces to regular space\n */\nexport function normalizeForFuzzyMatch(text: string): string {\n\treturn (\n\t\ttext\n\t\t\t.normalize(\"NFKC\")\n\t\t\t// Strip trailing whitespace per line\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => line.trimEnd())\n\t\t\t.join(\"\\n\")\n\t\t\t// Smart single quotes → '\n\t\t\t.replace(/[\\u2018\\u2019\\u201A\\u201B]/g, \"'\")\n\t\t\t// Smart double quotes → \"\n\t\t\t.replace(/[\\u201C\\u201D\\u201E\\u201F]/g, '\"')\n\t\t\t// Various dashes/hyphens → -\n\t\t\t// U+2010 hyphen, U+2011 non-breaking hyphen, U+2012 figure dash,\n\t\t\t// U+2013 en-dash, U+2014 em-dash, U+2015 horizontal bar, U+2212 minus\n\t\t\t.replace(/[\\u2010\\u2011\\u2012\\u2013\\u2014\\u2015\\u2212]/g, \"-\")\n\t\t\t// Special spaces → regular space\n\t\t\t// U+00A0 NBSP, U+2002-U+200A various spaces, U+202F narrow NBSP,\n\t\t\t// U+205F medium math space, U+3000 ideographic space\n\t\t\t.replace(/[\\u00A0\\u2002-\\u200A\\u202F\\u205F\\u3000]/g, \" \")\n\t);\n}\n\nexport interface FuzzyMatchResult {\n\t/** Whether a match was found */\n\tfound: boolean;\n\t/** The index where the match starts (in the content that should be used for replacement) */\n\tindex: number;\n\t/** Length of the matched text */\n\tmatchLength: number;\n\t/** Whether fuzzy matching was used (false = exact match) */\n\tusedFuzzyMatch: boolean;\n\t/** The original content replacements should be applied to. */\n\tcontentForReplacement: string;\n}\n\nexport interface Edit {\n\toldText: string;\n\tnewText: string;\n}\n\ninterface MatchedEdit {\n\teditIndex: number;\n\tmatchIndex: number;\n\tmatchLength: number;\n\tnewText: string;\n}\n\nexport interface AppliedEditsResult {\n\tbaseContent: string;\n\tnewContent: string;\n}\n\n/**\n * Find oldText in content, trying exact match first, then fuzzy match.\n * Fuzzy matching searches normalized text, but returned spans still refer to\n * the original content so replacement does not normalize unrelated text.\n */\nexport function fuzzyFindText(content: string, oldText: string): FuzzyMatchResult {\n\t// Try exact match first\n\tconst exactIndex = content.indexOf(oldText);\n\tif (exactIndex !== -1) {\n\t\treturn {\n\t\t\tfound: true,\n\t\t\tindex: exactIndex,\n\t\t\tmatchLength: oldText.length,\n\t\t\tusedFuzzyMatch: false,\n\t\t\tcontentForReplacement: content,\n\t\t};\n\t}\n\n\t// Try fuzzy match - work entirely in normalized space\n\tconst fuzzyContent = normalizeForFuzzyMatch(content);\n\tconst fuzzyOldText = normalizeForFuzzyMatch(oldText);\n\tconst fuzzyIndex = fuzzyContent.indexOf(fuzzyOldText);\n\n\tif (fuzzyIndex === -1) {\n\t\treturn {\n\t\t\tfound: false,\n\t\t\tindex: -1,\n\t\t\tmatchLength: 0,\n\t\t\tusedFuzzyMatch: false,\n\t\t\tcontentForReplacement: content,\n\t\t};\n\t}\n\n\treturn {\n\t\tfound: true,\n\t\tindex: fuzzyIndex,\n\t\tmatchLength: fuzzyOldText.length,\n\t\tusedFuzzyMatch: true,\n\t\tcontentForReplacement: content,\n\t};\n}\n\n/** Strip UTF-8 BOM if present, return both the BOM (if any) and the text without it */\nexport function stripBom(content: string): { bom: string; text: string } {\n\treturn content.startsWith(\"\\uFEFF\") ? { bom: \"\\uFEFF\", text: content.slice(1) } : { bom: \"\", text: content };\n}\n\nfunction countExactOccurrences(content: string, oldText: string): number {\n\treturn content.split(oldText).length - 1;\n}\n\nfunction countFuzzyOccurrences(content: string, oldText: string): number {\n\tconst fuzzyContent = normalizeForFuzzyMatch(content);\n\tconst fuzzyOldText = normalizeForFuzzyMatch(oldText);\n\treturn fuzzyContent.split(fuzzyOldText).length - 1;\n}\n\nfunction getLineStarts(content: string): number[] {\n\tconst starts = [0];\n\tfor (let i = 0; i < content.length; i++) {\n\t\tif (content[i] === \"\\n\") starts.push(i + 1);\n\t}\n\treturn starts;\n}\n\nfunction lineColumnAt(lineStarts: number[], index: number): { lineIndex: number; column: number } {\n\tlet low = 0;\n\tlet high = lineStarts.length - 1;\n\twhile (low <= high) {\n\t\tconst mid = Math.floor((low + high) / 2);\n\t\tif (lineStarts[mid] <= index) low = mid + 1;\n\t\telse high = mid - 1;\n\t}\n\tconst lineIndex = Math.max(0, high);\n\treturn { lineIndex, column: index - lineStarts[lineIndex] };\n}\n\nfunction lineTextAt(content: string, lineStarts: number[], lineIndex: number): string {\n\tconst start = lineStarts[lineIndex];\n\tconst nextStart = lineStarts[lineIndex + 1] ?? content.length;\n\tconst end = nextStart > start && content[nextStart - 1] === \"\\n\" ? nextStart - 1 : nextStart;\n\treturn content.slice(start, end);\n}\n\nfunction normalizedColumnToOriginalColumn(line: string, normalizedColumn: number): number {\n\tif (normalizedColumn <= 0) return 0;\n\tlet originalColumn = 0;\n\tfor (const char of line) {\n\t\tconst nextColumn = originalColumn + char.length;\n\t\tif (normalizeForFuzzyMatch(line.slice(0, nextColumn)).length >= normalizedColumn) return nextColumn;\n\t\toriginalColumn = nextColumn;\n\t}\n\treturn line.length;\n}\n\nfunction mapFuzzySpanToOriginal(\n\toriginalContent: string,\n\tnormalizedIndex: number,\n\tnormalizedLength: number,\n): { index: number; length: number } {\n\tconst fuzzyContent = normalizeForFuzzyMatch(originalContent);\n\tconst fuzzyLineStarts = getLineStarts(fuzzyContent);\n\tconst originalLineStarts = getLineStarts(originalContent);\n\tconst start = lineColumnAt(fuzzyLineStarts, normalizedIndex);\n\tconst end = lineColumnAt(fuzzyLineStarts, normalizedIndex + normalizedLength);\n\tconst startLine = lineTextAt(originalContent, originalLineStarts, start.lineIndex);\n\tconst endLine = lineTextAt(originalContent, originalLineStarts, end.lineIndex);\n\tconst originalStart =\n\t\toriginalLineStarts[start.lineIndex] + normalizedColumnToOriginalColumn(startLine, start.column);\n\tconst originalEnd = originalLineStarts[end.lineIndex] + normalizedColumnToOriginalColumn(endLine, end.column);\n\treturn { index: originalStart, length: originalEnd - originalStart };\n}\n\nfunction getNotFoundError(path: string, editIndex: number, totalEdits: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(\n\t\t\t`Could not find the exact text in ${path}. The old text must match exactly including all whitespace and newlines.`,\n\t\t);\n\t}\n\treturn new Error(\n\t\t`Could not find edits[${editIndex}] in ${path}. The oldText must match exactly including all whitespace and newlines.`,\n\t);\n}\n\nfunction getDuplicateError(path: string, editIndex: number, totalEdits: number, occurrences: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(\n\t\t\t`Found ${occurrences} occurrences of the text in ${path}. The text must be unique. Please provide more context to make it unique.`,\n\t\t);\n\t}\n\treturn new Error(\n\t\t`Found ${occurrences} occurrences of edits[${editIndex}] in ${path}. Each oldText must be unique. Please provide more context to make it unique.`,\n\t);\n}\n\nfunction getEmptyOldTextError(path: string, editIndex: number, totalEdits: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(`oldText must not be empty in ${path}.`);\n\t}\n\treturn new Error(`edits[${editIndex}].oldText must not be empty in ${path}.`);\n}\n\nfunction getNoChangeError(path: string, totalEdits: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(\n\t\t\t`No changes made to ${path}. The replacement produced identical content. This might indicate an issue with special characters or the text not existing as expected.`,\n\t\t);\n\t}\n\treturn new Error(`No changes made to ${path}. The replacements produced identical content.`);\n}\n\n/**\n * Apply one or more exact-text replacements to LF-normalized content.\n *\n * All edits are matched against the same original content. Replacements are\n * then applied in reverse order so offsets remain stable. Fuzzy matching uses\n * normalized text only for finding the span; the final splice is always made\n * into the original content.\n */\nexport function applyEditsToNormalizedContent(\n\tnormalizedContent: string,\n\tedits: Edit[],\n\tpath: string,\n): AppliedEditsResult {\n\tconst normalizedEdits = edits.map((edit) => ({\n\t\toldText: normalizeToLF(edit.oldText),\n\t\tnewText: normalizeToLF(edit.newText),\n\t}));\n\n\tfor (let i = 0; i < normalizedEdits.length; i++) {\n\t\tif (normalizedEdits[i].oldText.length === 0) {\n\t\t\tthrow getEmptyOldTextError(path, i, normalizedEdits.length);\n\t\t}\n\t}\n\n\tconst baseContent = normalizedContent;\n\tconst matchedEdits: MatchedEdit[] = [];\n\tfor (let i = 0; i < normalizedEdits.length; i++) {\n\t\tconst edit = normalizedEdits[i];\n\t\tconst matchResult = fuzzyFindText(baseContent, edit.oldText);\n\t\tif (!matchResult.found) {\n\t\t\tthrow getNotFoundError(path, i, normalizedEdits.length);\n\t\t}\n\n\t\tconst occurrences = matchResult.usedFuzzyMatch\n\t\t\t? countFuzzyOccurrences(baseContent, edit.oldText)\n\t\t\t: countExactOccurrences(baseContent, edit.oldText);\n\t\tif (occurrences > 1) {\n\t\t\tthrow getDuplicateError(path, i, normalizedEdits.length, occurrences);\n\t\t}\n\n\t\tconst replacementSpan = matchResult.usedFuzzyMatch\n\t\t\t? mapFuzzySpanToOriginal(baseContent, matchResult.index, matchResult.matchLength)\n\t\t\t: { index: matchResult.index, length: matchResult.matchLength };\n\n\t\tmatchedEdits.push({\n\t\t\teditIndex: i,\n\t\t\tmatchIndex: replacementSpan.index,\n\t\t\tmatchLength: replacementSpan.length,\n\t\t\tnewText: edit.newText,\n\t\t});\n\t}\n\n\tmatchedEdits.sort((a, b) => a.matchIndex - b.matchIndex);\n\tfor (let i = 1; i < matchedEdits.length; i++) {\n\t\tconst previous = matchedEdits[i - 1];\n\t\tconst current = matchedEdits[i];\n\t\tif (previous.matchIndex + previous.matchLength > current.matchIndex) {\n\t\t\tthrow new Error(\n\t\t\t\t`edits[${previous.editIndex}] and edits[${current.editIndex}] overlap in ${path}. Merge them into one edit or target disjoint regions.`,\n\t\t\t);\n\t\t}\n\t}\n\n\tlet newContent = baseContent;\n\tfor (let i = matchedEdits.length - 1; i >= 0; i--) {\n\t\tconst edit = matchedEdits[i];\n\t\tnewContent =\n\t\t\tnewContent.substring(0, edit.matchIndex) +\n\t\t\tedit.newText +\n\t\t\tnewContent.substring(edit.matchIndex + edit.matchLength);\n\t}\n\n\tif (baseContent === newContent) {\n\t\tthrow getNoChangeError(path, normalizedEdits.length);\n\t}\n\n\treturn { baseContent, newContent };\n}\n\n/** Generate a standard unified patch. */\nexport function generateUnifiedPatch(path: string, oldContent: string, newContent: string, contextLines = 4): string {\n\treturn Diff.createTwoFilesPatch(path, path, oldContent, newContent, undefined, undefined, {\n\t\tcontext: contextLines,\n\t\theaderOptions: Diff.FILE_HEADERS_ONLY,\n\t});\n}\n\n/**\n * Generate a display-oriented diff string with line numbers and context.\n * Returns both the diff string and the first changed line number (in the new file).\n */\nexport function generateDiffString(\n\toldContent: string,\n\tnewContent: string,\n\tcontextLines = 4,\n): { diff: string; firstChangedLine: number | undefined } {\n\tconst parts = Diff.diffLines(oldContent, newContent);\n\tconst output: string[] = [];\n\n\tconst oldLines = oldContent.split(\"\\n\");\n\tconst newLines = newContent.split(\"\\n\");\n\tconst maxLineNum = Math.max(oldLines.length, newLines.length);\n\tconst lineNumWidth = String(maxLineNum).length;\n\n\tlet oldLineNum = 1;\n\tlet newLineNum = 1;\n\tlet lastWasChange = false;\n\tlet firstChangedLine: number | undefined;\n\n\tfor (let i = 0; i < parts.length; i++) {\n\t\tconst part = parts[i];\n\t\tconst raw = part.value.split(\"\\n\");\n\t\tif (raw[raw.length - 1] === \"\") {\n\t\t\traw.pop();\n\t\t}\n\n\t\tif (part.added || part.removed) {\n\t\t\t// Capture the first changed line (in the new file)\n\t\t\tif (firstChangedLine === undefined) {\n\t\t\t\tfirstChangedLine = newLineNum;\n\t\t\t}\n\n\t\t\t// Show the change\n\t\t\tfor (const line of raw) {\n\t\t\t\tif (part.added) {\n\t\t\t\t\tconst lineNum = String(newLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(`+${lineNum} ${line}`);\n\t\t\t\t\tnewLineNum++;\n\t\t\t\t} else {\n\t\t\t\t\t// removed\n\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(`-${lineNum} ${line}`);\n\t\t\t\t\toldLineNum++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tlastWasChange = true;\n\t\t} else {\n\t\t\t// Context lines - only show a few before/after changes\n\t\t\tconst nextPartIsChange = i < parts.length - 1 && (parts[i + 1].added || parts[i + 1].removed);\n\t\t\tconst hasLeadingChange = lastWasChange;\n\t\t\tconst hasTrailingChange = nextPartIsChange;\n\n\t\t\tif (hasLeadingChange && hasTrailingChange) {\n\t\t\t\tif (raw.length <= contextLines * 2) {\n\t\t\t\t\tfor (const line of raw) {\n\t\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\t\toldLineNum++;\n\t\t\t\t\t\tnewLineNum++;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tconst leadingLines = raw.slice(0, contextLines);\n\t\t\t\t\tconst trailingLines = raw.slice(raw.length - contextLines);\n\t\t\t\t\tconst skippedLines = raw.length - leadingLines.length - trailingLines.length;\n\n\t\t\t\t\tfor (const line of leadingLines) {\n\t\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\t\toldLineNum++;\n\t\t\t\t\t\tnewLineNum++;\n\t\t\t\t\t}\n\n\t\t\t\t\toutput.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n\t\t\t\t\toldLineNum += skippedLines;\n\t\t\t\t\tnewLineNum += skippedLines;\n\n\t\t\t\t\tfor (const line of trailingLines) {\n\t\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\t\toldLineNum++;\n\t\t\t\t\t\tnewLineNum++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (hasLeadingChange) {\n\t\t\t\tconst shownLines = raw.slice(0, contextLines);\n\t\t\t\tconst skippedLines = raw.length - shownLines.length;\n\n\t\t\t\tfor (const line of shownLines) {\n\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\toldLineNum++;\n\t\t\t\t\tnewLineNum++;\n\t\t\t\t}\n\n\t\t\t\tif (skippedLines > 0) {\n\t\t\t\t\toutput.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n\t\t\t\t\toldLineNum += skippedLines;\n\t\t\t\t\tnewLineNum += skippedLines;\n\t\t\t\t}\n\t\t\t} else if (hasTrailingChange) {\n\t\t\t\tconst skippedLines = Math.max(0, raw.length - contextLines);\n\t\t\t\tif (skippedLines > 0) {\n\t\t\t\t\toutput.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n\t\t\t\t\toldLineNum += skippedLines;\n\t\t\t\t\tnewLineNum += skippedLines;\n\t\t\t\t}\n\n\t\t\t\tfor (const line of raw.slice(skippedLines)) {\n\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\toldLineNum++;\n\t\t\t\t\tnewLineNum++;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Skip these context lines entirely\n\t\t\t\toldLineNum += raw.length;\n\t\t\t\tnewLineNum += raw.length;\n\t\t\t}\n\n\t\t\tlastWasChange = false;\n\t\t}\n\t}\n\n\treturn { diff: output.join(\"\\n\"), firstChangedLine };\n}\n\nexport interface EditDiffResult {\n\tdiff: string;\n\tfirstChangedLine: number | undefined;\n}\n\nexport interface EditDiffError {\n\terror: string;\n}\n\n/**\n * Compute the diff for one or more edit operations without applying them.\n * Used for preview rendering in the TUI before the tool executes.\n */\nexport async function computeEditsDiff(\n\tpath: string,\n\tedits: Edit[],\n\tcwd: string,\n): Promise<EditDiffResult | EditDiffError> {\n\tconst absolutePath = resolveToCwd(path, cwd);\n\n\ttry {\n\t\t// Check if file exists and is readable\n\t\ttry {\n\t\t\tawait access(absolutePath, constants.R_OK);\n\t\t} catch (error: unknown) {\n\t\t\tconst errorMessage = error instanceof Error && \"code\" in error ? `Error code: ${error.code}` : String(error);\n\t\t\treturn { error: `Could not edit file: ${path}. ${errorMessage}.` };\n\t\t}\n\n\t\t// Read the file\n\t\tconst rawContent = await readFile(absolutePath, \"utf-8\");\n\n\t\t// Strip BOM before matching (LLM won't include invisible BOM in oldText)\n\t\tconst { text: content } = stripBom(rawContent);\n\t\tconst normalizedContent = normalizeToLF(content);\n\t\tconst { baseContent, newContent } = applyEditsToNormalizedContent(normalizedContent, edits, path);\n\n\t\t// Generate the diff\n\t\treturn generateDiffString(baseContent, newContent);\n\t} catch (err) {\n\t\treturn { error: err instanceof Error ? err.message : String(err) };\n\t}\n}\n\n/**\n * Compute the diff for a single edit operation without applying it.\n * Kept as a convenience wrapper for single-edit callers.\n */\nexport async function computeEditDiff(\n\tpath: string,\n\toldText: string,\n\tnewText: string,\n\tcwd: string,\n): Promise<EditDiffResult | EditDiffError> {\n\treturn computeEditsDiff(path, [{ oldText, newText }], cwd);\n}\n"]}
|
|
@@ -50,9 +50,8 @@ export function normalizeForFuzzyMatch(text) {
|
|
|
50
50
|
}
|
|
51
51
|
/**
|
|
52
52
|
* Find oldText in content, trying exact match first, then fuzzy match.
|
|
53
|
-
*
|
|
54
|
-
*
|
|
55
|
-
* Unicode quotes/dashes normalized to ASCII).
|
|
53
|
+
* Fuzzy matching searches normalized text, but returned spans still refer to
|
|
54
|
+
* the original content so replacement does not normalize unrelated text.
|
|
56
55
|
*/
|
|
57
56
|
export function fuzzyFindText(content, oldText) {
|
|
58
57
|
// Try exact match first
|
|
@@ -79,26 +78,77 @@ export function fuzzyFindText(content, oldText) {
|
|
|
79
78
|
contentForReplacement: content,
|
|
80
79
|
};
|
|
81
80
|
}
|
|
82
|
-
// When fuzzy matching, we work in the normalized space for replacement.
|
|
83
|
-
// This means the output will have normalized whitespace/quotes/dashes,
|
|
84
|
-
// which is acceptable since we're fixing minor formatting differences anyway.
|
|
85
81
|
return {
|
|
86
82
|
found: true,
|
|
87
83
|
index: fuzzyIndex,
|
|
88
84
|
matchLength: fuzzyOldText.length,
|
|
89
85
|
usedFuzzyMatch: true,
|
|
90
|
-
contentForReplacement:
|
|
86
|
+
contentForReplacement: content,
|
|
91
87
|
};
|
|
92
88
|
}
|
|
93
89
|
/** Strip UTF-8 BOM if present, return both the BOM (if any) and the text without it */
|
|
94
90
|
export function stripBom(content) {
|
|
95
91
|
return content.startsWith("\uFEFF") ? { bom: "\uFEFF", text: content.slice(1) } : { bom: "", text: content };
|
|
96
92
|
}
|
|
97
|
-
function
|
|
93
|
+
function countExactOccurrences(content, oldText) {
|
|
94
|
+
return content.split(oldText).length - 1;
|
|
95
|
+
}
|
|
96
|
+
function countFuzzyOccurrences(content, oldText) {
|
|
98
97
|
const fuzzyContent = normalizeForFuzzyMatch(content);
|
|
99
98
|
const fuzzyOldText = normalizeForFuzzyMatch(oldText);
|
|
100
99
|
return fuzzyContent.split(fuzzyOldText).length - 1;
|
|
101
100
|
}
|
|
101
|
+
function getLineStarts(content) {
|
|
102
|
+
const starts = [0];
|
|
103
|
+
for (let i = 0; i < content.length; i++) {
|
|
104
|
+
if (content[i] === "\n")
|
|
105
|
+
starts.push(i + 1);
|
|
106
|
+
}
|
|
107
|
+
return starts;
|
|
108
|
+
}
|
|
109
|
+
function lineColumnAt(lineStarts, index) {
|
|
110
|
+
let low = 0;
|
|
111
|
+
let high = lineStarts.length - 1;
|
|
112
|
+
while (low <= high) {
|
|
113
|
+
const mid = Math.floor((low + high) / 2);
|
|
114
|
+
if (lineStarts[mid] <= index)
|
|
115
|
+
low = mid + 1;
|
|
116
|
+
else
|
|
117
|
+
high = mid - 1;
|
|
118
|
+
}
|
|
119
|
+
const lineIndex = Math.max(0, high);
|
|
120
|
+
return { lineIndex, column: index - lineStarts[lineIndex] };
|
|
121
|
+
}
|
|
122
|
+
function lineTextAt(content, lineStarts, lineIndex) {
|
|
123
|
+
const start = lineStarts[lineIndex];
|
|
124
|
+
const nextStart = lineStarts[lineIndex + 1] ?? content.length;
|
|
125
|
+
const end = nextStart > start && content[nextStart - 1] === "\n" ? nextStart - 1 : nextStart;
|
|
126
|
+
return content.slice(start, end);
|
|
127
|
+
}
|
|
128
|
+
function normalizedColumnToOriginalColumn(line, normalizedColumn) {
|
|
129
|
+
if (normalizedColumn <= 0)
|
|
130
|
+
return 0;
|
|
131
|
+
let originalColumn = 0;
|
|
132
|
+
for (const char of line) {
|
|
133
|
+
const nextColumn = originalColumn + char.length;
|
|
134
|
+
if (normalizeForFuzzyMatch(line.slice(0, nextColumn)).length >= normalizedColumn)
|
|
135
|
+
return nextColumn;
|
|
136
|
+
originalColumn = nextColumn;
|
|
137
|
+
}
|
|
138
|
+
return line.length;
|
|
139
|
+
}
|
|
140
|
+
function mapFuzzySpanToOriginal(originalContent, normalizedIndex, normalizedLength) {
|
|
141
|
+
const fuzzyContent = normalizeForFuzzyMatch(originalContent);
|
|
142
|
+
const fuzzyLineStarts = getLineStarts(fuzzyContent);
|
|
143
|
+
const originalLineStarts = getLineStarts(originalContent);
|
|
144
|
+
const start = lineColumnAt(fuzzyLineStarts, normalizedIndex);
|
|
145
|
+
const end = lineColumnAt(fuzzyLineStarts, normalizedIndex + normalizedLength);
|
|
146
|
+
const startLine = lineTextAt(originalContent, originalLineStarts, start.lineIndex);
|
|
147
|
+
const endLine = lineTextAt(originalContent, originalLineStarts, end.lineIndex);
|
|
148
|
+
const originalStart = originalLineStarts[start.lineIndex] + normalizedColumnToOriginalColumn(startLine, start.column);
|
|
149
|
+
const originalEnd = originalLineStarts[end.lineIndex] + normalizedColumnToOriginalColumn(endLine, end.column);
|
|
150
|
+
return { index: originalStart, length: originalEnd - originalStart };
|
|
151
|
+
}
|
|
102
152
|
function getNotFoundError(path, editIndex, totalEdits) {
|
|
103
153
|
if (totalEdits === 1) {
|
|
104
154
|
return new Error(`Could not find the exact text in ${path}. The old text must match exactly including all whitespace and newlines.`);
|
|
@@ -127,9 +177,9 @@ function getNoChangeError(path, totalEdits) {
|
|
|
127
177
|
* Apply one or more exact-text replacements to LF-normalized content.
|
|
128
178
|
*
|
|
129
179
|
* All edits are matched against the same original content. Replacements are
|
|
130
|
-
* then applied in reverse order so offsets remain stable.
|
|
131
|
-
*
|
|
132
|
-
*
|
|
180
|
+
* then applied in reverse order so offsets remain stable. Fuzzy matching uses
|
|
181
|
+
* normalized text only for finding the span; the final splice is always made
|
|
182
|
+
* into the original content.
|
|
133
183
|
*/
|
|
134
184
|
export function applyEditsToNormalizedContent(normalizedContent, edits, path) {
|
|
135
185
|
const normalizedEdits = edits.map((edit) => ({
|
|
@@ -141,10 +191,7 @@ export function applyEditsToNormalizedContent(normalizedContent, edits, path) {
|
|
|
141
191
|
throw getEmptyOldTextError(path, i, normalizedEdits.length);
|
|
142
192
|
}
|
|
143
193
|
}
|
|
144
|
-
const
|
|
145
|
-
const baseContent = initialMatches.some((match) => match.usedFuzzyMatch)
|
|
146
|
-
? normalizeForFuzzyMatch(normalizedContent)
|
|
147
|
-
: normalizedContent;
|
|
194
|
+
const baseContent = normalizedContent;
|
|
148
195
|
const matchedEdits = [];
|
|
149
196
|
for (let i = 0; i < normalizedEdits.length; i++) {
|
|
150
197
|
const edit = normalizedEdits[i];
|
|
@@ -152,14 +199,19 @@ export function applyEditsToNormalizedContent(normalizedContent, edits, path) {
|
|
|
152
199
|
if (!matchResult.found) {
|
|
153
200
|
throw getNotFoundError(path, i, normalizedEdits.length);
|
|
154
201
|
}
|
|
155
|
-
const occurrences =
|
|
202
|
+
const occurrences = matchResult.usedFuzzyMatch
|
|
203
|
+
? countFuzzyOccurrences(baseContent, edit.oldText)
|
|
204
|
+
: countExactOccurrences(baseContent, edit.oldText);
|
|
156
205
|
if (occurrences > 1) {
|
|
157
206
|
throw getDuplicateError(path, i, normalizedEdits.length, occurrences);
|
|
158
207
|
}
|
|
208
|
+
const replacementSpan = matchResult.usedFuzzyMatch
|
|
209
|
+
? mapFuzzySpanToOriginal(baseContent, matchResult.index, matchResult.matchLength)
|
|
210
|
+
: { index: matchResult.index, length: matchResult.matchLength };
|
|
159
211
|
matchedEdits.push({
|
|
160
212
|
editIndex: i,
|
|
161
|
-
matchIndex:
|
|
162
|
-
matchLength:
|
|
213
|
+
matchIndex: replacementSpan.index,
|
|
214
|
+
matchLength: replacementSpan.length,
|
|
163
215
|
newText: edit.newText,
|
|
164
216
|
});
|
|
165
217
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"edit-diff.js","sourceRoot":"","sources":["../../../src/core/tools/edit-diff.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC;AAC/B,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAE/C,MAAM,UAAU,gBAAgB,CAAC,OAAe,EAAiB;IAChE,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACxC,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IACpC,IAAI,KAAK,KAAK,CAAC,CAAC;QAAE,OAAO,IAAI,CAAC;IAC9B,IAAI,OAAO,KAAK,CAAC,CAAC;QAAE,OAAO,IAAI,CAAC;IAChC,OAAO,OAAO,GAAG,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC;AAAA,CACvC;AAED,MAAM,UAAU,aAAa,CAAC,IAAY,EAAU;IACnD,OAAO,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;AAAA,C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CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YAC7G,OAAO,EAAE,KAAK,EAAE,wBAAwB,IAAI,KAAK,YAAY,GAAG,EAAE,CAAC;QACpE,CAAC;QAED,gBAAgB;QAChB,MAAM,UAAU,GAAG,MAAM,QAAQ,CAAC,YAAY,EAAE,OAAO,CAAC,CAAC;QAEzD,yEAAyE;QACzE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,QAAQ,CAAC,UAAU,CAAC,CAAC;QAC/C,MAAM,iBAAiB,GAAG,aAAa,CAAC,OAAO,CAAC,CAAC;QACjD,MAAM,EAAE,WAAW,EAAE,UAAU,EAAE,GAAG,6BAA6B,CAAC,iBAAiB,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC;QAElG,oBAAoB;QACpB,OAAO,kBAAkB,CAAC,WAAW,EAAE,UAAU,CAAC,CAAC;IACpD,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACd,OAAO,EAAE,KAAK,EAAE,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC;IACpE,CAAC;AAAA,CACD;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe,CACpC,IAAY,EACZ,OAAe,EACf,OAAe,EACf,GAAW,EAC+B;IAC1C,OAAO,gBAAgB,CAAC,IAAI,EAAE,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,GAAG,CAAC,CAAC;AAAA,CAC3D","sourcesContent":["/**\n * Shared diff computation utilities for the edit tool.\n * Used by both edit.ts (for execution) and tool-execution.ts (for preview rendering).\n */\n\nimport * as Diff from \"diff\";\nimport { constants } from \"fs\";\nimport { access, readFile } from \"fs/promises\";\nimport { resolveToCwd } from \"./path-utils.ts\";\n\nexport function detectLineEnding(content: string): \"\\r\\n\" | \"\\n\" {\n\tconst crlfIdx = content.indexOf(\"\\r\\n\");\n\tconst lfIdx = content.indexOf(\"\\n\");\n\tif (lfIdx === -1) return \"\\n\";\n\tif (crlfIdx === -1) return \"\\n\";\n\treturn crlfIdx < lfIdx ? \"\\r\\n\" : \"\\n\";\n}\n\nexport function normalizeToLF(text: string): string {\n\treturn text.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\");\n}\n\nexport function restoreLineEndings(text: string, ending: \"\\r\\n\" | \"\\n\"): string {\n\treturn ending === \"\\r\\n\" ? text.replace(/\\n/g, \"\\r\\n\") : text;\n}\n\n/**\n * Normalize text for fuzzy matching. Applies progressive transformations:\n * - Strip trailing whitespace from each line\n * - Normalize smart quotes to ASCII equivalents\n * - Normalize Unicode dashes/hyphens to ASCII hyphen\n * - Normalize special Unicode spaces to regular space\n */\nexport function normalizeForFuzzyMatch(text: string): string {\n\treturn (\n\t\ttext\n\t\t\t.normalize(\"NFKC\")\n\t\t\t// Strip trailing whitespace per line\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => line.trimEnd())\n\t\t\t.join(\"\\n\")\n\t\t\t// Smart single quotes → '\n\t\t\t.replace(/[\\u2018\\u2019\\u201A\\u201B]/g, \"'\")\n\t\t\t// Smart double quotes → \"\n\t\t\t.replace(/[\\u201C\\u201D\\u201E\\u201F]/g, '\"')\n\t\t\t// Various dashes/hyphens → -\n\t\t\t// U+2010 hyphen, U+2011 non-breaking hyphen, U+2012 figure dash,\n\t\t\t// U+2013 en-dash, U+2014 em-dash, U+2015 horizontal bar, U+2212 minus\n\t\t\t.replace(/[\\u2010\\u2011\\u2012\\u2013\\u2014\\u2015\\u2212]/g, \"-\")\n\t\t\t// Special spaces → regular space\n\t\t\t// U+00A0 NBSP, U+2002-U+200A various spaces, U+202F narrow NBSP,\n\t\t\t// U+205F medium math space, U+3000 ideographic space\n\t\t\t.replace(/[\\u00A0\\u2002-\\u200A\\u202F\\u205F\\u3000]/g, \" \")\n\t);\n}\n\nexport interface FuzzyMatchResult {\n\t/** Whether a match was found */\n\tfound: boolean;\n\t/** The index where the match starts (in the content that should be used for replacement) */\n\tindex: number;\n\t/** Length of the matched text */\n\tmatchLength: number;\n\t/** Whether fuzzy matching was used (false = exact match) */\n\tusedFuzzyMatch: boolean;\n\t/**\n\t * The content to use for replacement operations.\n\t * When exact match: original content. When fuzzy match: normalized content.\n\t */\n\tcontentForReplacement: string;\n}\n\nexport interface Edit {\n\toldText: string;\n\tnewText: string;\n}\n\ninterface MatchedEdit {\n\teditIndex: number;\n\tmatchIndex: number;\n\tmatchLength: number;\n\tnewText: string;\n}\n\nexport interface AppliedEditsResult {\n\tbaseContent: string;\n\tnewContent: string;\n}\n\n/**\n * Find oldText in content, trying exact match first, then fuzzy match.\n * When fuzzy matching is used, the returned contentForReplacement is the\n * fuzzy-normalized version of the content (trailing whitespace stripped,\n * Unicode quotes/dashes normalized to ASCII).\n */\nexport function fuzzyFindText(content: string, oldText: string): FuzzyMatchResult {\n\t// Try exact match first\n\tconst exactIndex = content.indexOf(oldText);\n\tif (exactIndex !== -1) {\n\t\treturn {\n\t\t\tfound: true,\n\t\t\tindex: exactIndex,\n\t\t\tmatchLength: oldText.length,\n\t\t\tusedFuzzyMatch: false,\n\t\t\tcontentForReplacement: content,\n\t\t};\n\t}\n\n\t// Try fuzzy match - work entirely in normalized space\n\tconst fuzzyContent = normalizeForFuzzyMatch(content);\n\tconst fuzzyOldText = normalizeForFuzzyMatch(oldText);\n\tconst fuzzyIndex = fuzzyContent.indexOf(fuzzyOldText);\n\n\tif (fuzzyIndex === -1) {\n\t\treturn {\n\t\t\tfound: false,\n\t\t\tindex: -1,\n\t\t\tmatchLength: 0,\n\t\t\tusedFuzzyMatch: false,\n\t\t\tcontentForReplacement: content,\n\t\t};\n\t}\n\n\t// When fuzzy matching, we work in the normalized space for replacement.\n\t// This means the output will have normalized whitespace/quotes/dashes,\n\t// which is acceptable since we're fixing minor formatting differences anyway.\n\treturn {\n\t\tfound: true,\n\t\tindex: fuzzyIndex,\n\t\tmatchLength: fuzzyOldText.length,\n\t\tusedFuzzyMatch: true,\n\t\tcontentForReplacement: fuzzyContent,\n\t};\n}\n\n/** Strip UTF-8 BOM if present, return both the BOM (if any) and the text without it */\nexport function stripBom(content: string): { bom: string; text: string } {\n\treturn content.startsWith(\"\\uFEFF\") ? { bom: \"\\uFEFF\", text: content.slice(1) } : { bom: \"\", text: content };\n}\n\nfunction countOccurrences(content: string, oldText: string): number {\n\tconst fuzzyContent = normalizeForFuzzyMatch(content);\n\tconst fuzzyOldText = normalizeForFuzzyMatch(oldText);\n\treturn fuzzyContent.split(fuzzyOldText).length - 1;\n}\n\nfunction getNotFoundError(path: string, editIndex: number, totalEdits: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(\n\t\t\t`Could not find the exact text in ${path}. The old text must match exactly including all whitespace and newlines.`,\n\t\t);\n\t}\n\treturn new Error(\n\t\t`Could not find edits[${editIndex}] in ${path}. The oldText must match exactly including all whitespace and newlines.`,\n\t);\n}\n\nfunction getDuplicateError(path: string, editIndex: number, totalEdits: number, occurrences: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(\n\t\t\t`Found ${occurrences} occurrences of the text in ${path}. The text must be unique. Please provide more context to make it unique.`,\n\t\t);\n\t}\n\treturn new Error(\n\t\t`Found ${occurrences} occurrences of edits[${editIndex}] in ${path}. Each oldText must be unique. Please provide more context to make it unique.`,\n\t);\n}\n\nfunction getEmptyOldTextError(path: string, editIndex: number, totalEdits: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(`oldText must not be empty in ${path}.`);\n\t}\n\treturn new Error(`edits[${editIndex}].oldText must not be empty in ${path}.`);\n}\n\nfunction getNoChangeError(path: string, totalEdits: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(\n\t\t\t`No changes made to ${path}. The replacement produced identical content. This might indicate an issue with special characters or the text not existing as expected.`,\n\t\t);\n\t}\n\treturn new Error(`No changes made to ${path}. The replacements produced identical content.`);\n}\n\n/**\n * Apply one or more exact-text replacements to LF-normalized content.\n *\n * All edits are matched against the same original content. Replacements are\n * then applied in reverse order so offsets remain stable. If any edit needs\n * fuzzy matching, the operation runs in fuzzy-normalized content space to\n * preserve current single-edit behavior.\n */\nexport function applyEditsToNormalizedContent(\n\tnormalizedContent: string,\n\tedits: Edit[],\n\tpath: string,\n): AppliedEditsResult {\n\tconst normalizedEdits = edits.map((edit) => ({\n\t\toldText: normalizeToLF(edit.oldText),\n\t\tnewText: normalizeToLF(edit.newText),\n\t}));\n\n\tfor (let i = 0; i < normalizedEdits.length; i++) {\n\t\tif (normalizedEdits[i].oldText.length === 0) {\n\t\t\tthrow getEmptyOldTextError(path, i, normalizedEdits.length);\n\t\t}\n\t}\n\n\tconst initialMatches = normalizedEdits.map((edit) => fuzzyFindText(normalizedContent, edit.oldText));\n\tconst baseContent = initialMatches.some((match) => match.usedFuzzyMatch)\n\t\t? normalizeForFuzzyMatch(normalizedContent)\n\t\t: normalizedContent;\n\n\tconst matchedEdits: MatchedEdit[] = [];\n\tfor (let i = 0; i < normalizedEdits.length; i++) {\n\t\tconst edit = normalizedEdits[i];\n\t\tconst matchResult = fuzzyFindText(baseContent, edit.oldText);\n\t\tif (!matchResult.found) {\n\t\t\tthrow getNotFoundError(path, i, normalizedEdits.length);\n\t\t}\n\n\t\tconst occurrences = countOccurrences(baseContent, edit.oldText);\n\t\tif (occurrences > 1) {\n\t\t\tthrow getDuplicateError(path, i, normalizedEdits.length, occurrences);\n\t\t}\n\n\t\tmatchedEdits.push({\n\t\t\teditIndex: i,\n\t\t\tmatchIndex: matchResult.index,\n\t\t\tmatchLength: matchResult.matchLength,\n\t\t\tnewText: edit.newText,\n\t\t});\n\t}\n\n\tmatchedEdits.sort((a, b) => a.matchIndex - b.matchIndex);\n\tfor (let i = 1; i < matchedEdits.length; i++) {\n\t\tconst previous = matchedEdits[i - 1];\n\t\tconst current = matchedEdits[i];\n\t\tif (previous.matchIndex + previous.matchLength > current.matchIndex) {\n\t\t\tthrow new Error(\n\t\t\t\t`edits[${previous.editIndex}] and edits[${current.editIndex}] overlap in ${path}. Merge them into one edit or target disjoint regions.`,\n\t\t\t);\n\t\t}\n\t}\n\n\tlet newContent = baseContent;\n\tfor (let i = matchedEdits.length - 1; i >= 0; i--) {\n\t\tconst edit = matchedEdits[i];\n\t\tnewContent =\n\t\t\tnewContent.substring(0, edit.matchIndex) +\n\t\t\tedit.newText +\n\t\t\tnewContent.substring(edit.matchIndex + edit.matchLength);\n\t}\n\n\tif (baseContent === newContent) {\n\t\tthrow getNoChangeError(path, normalizedEdits.length);\n\t}\n\n\treturn { baseContent, newContent };\n}\n\n/** Generate a standard unified patch. */\nexport function generateUnifiedPatch(path: string, oldContent: string, newContent: string, contextLines = 4): string {\n\treturn Diff.createTwoFilesPatch(path, path, oldContent, newContent, undefined, undefined, {\n\t\tcontext: contextLines,\n\t\theaderOptions: Diff.FILE_HEADERS_ONLY,\n\t});\n}\n\n/**\n * Generate a display-oriented diff string with line numbers and context.\n * Returns both the diff string and the first changed line number (in the new file).\n */\nexport function generateDiffString(\n\toldContent: string,\n\tnewContent: string,\n\tcontextLines = 4,\n): { diff: string; firstChangedLine: number | undefined } {\n\tconst parts = Diff.diffLines(oldContent, newContent);\n\tconst output: string[] = [];\n\n\tconst oldLines = oldContent.split(\"\\n\");\n\tconst newLines = newContent.split(\"\\n\");\n\tconst maxLineNum = Math.max(oldLines.length, newLines.length);\n\tconst lineNumWidth = String(maxLineNum).length;\n\n\tlet oldLineNum = 1;\n\tlet newLineNum = 1;\n\tlet lastWasChange = false;\n\tlet firstChangedLine: number | undefined;\n\n\tfor (let i = 0; i < parts.length; i++) {\n\t\tconst part = parts[i];\n\t\tconst raw = part.value.split(\"\\n\");\n\t\tif (raw[raw.length - 1] === \"\") {\n\t\t\traw.pop();\n\t\t}\n\n\t\tif (part.added || part.removed) {\n\t\t\t// Capture the first changed line (in the new file)\n\t\t\tif (firstChangedLine === undefined) {\n\t\t\t\tfirstChangedLine = newLineNum;\n\t\t\t}\n\n\t\t\t// Show the change\n\t\t\tfor (const line of raw) {\n\t\t\t\tif (part.added) {\n\t\t\t\t\tconst lineNum = String(newLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(`+${lineNum} ${line}`);\n\t\t\t\t\tnewLineNum++;\n\t\t\t\t} else {\n\t\t\t\t\t// removed\n\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(`-${lineNum} ${line}`);\n\t\t\t\t\toldLineNum++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tlastWasChange = true;\n\t\t} else {\n\t\t\t// Context lines - only show a few before/after changes\n\t\t\tconst nextPartIsChange = i < parts.length - 1 && (parts[i + 1].added || parts[i + 1].removed);\n\t\t\tconst hasLeadingChange = lastWasChange;\n\t\t\tconst hasTrailingChange = nextPartIsChange;\n\n\t\t\tif (hasLeadingChange && hasTrailingChange) {\n\t\t\t\tif (raw.length <= contextLines * 2) {\n\t\t\t\t\tfor (const line of raw) {\n\t\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\t\toldLineNum++;\n\t\t\t\t\t\tnewLineNum++;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tconst leadingLines = raw.slice(0, contextLines);\n\t\t\t\t\tconst trailingLines = raw.slice(raw.length - contextLines);\n\t\t\t\t\tconst skippedLines = raw.length - leadingLines.length - trailingLines.length;\n\n\t\t\t\t\tfor (const line of leadingLines) {\n\t\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\t\toldLineNum++;\n\t\t\t\t\t\tnewLineNum++;\n\t\t\t\t\t}\n\n\t\t\t\t\toutput.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n\t\t\t\t\toldLineNum += skippedLines;\n\t\t\t\t\tnewLineNum += skippedLines;\n\n\t\t\t\t\tfor (const line of trailingLines) {\n\t\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\t\toldLineNum++;\n\t\t\t\t\t\tnewLineNum++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (hasLeadingChange) {\n\t\t\t\tconst shownLines = raw.slice(0, contextLines);\n\t\t\t\tconst skippedLines = raw.length - shownLines.length;\n\n\t\t\t\tfor (const line of shownLines) {\n\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\toldLineNum++;\n\t\t\t\t\tnewLineNum++;\n\t\t\t\t}\n\n\t\t\t\tif (skippedLines > 0) {\n\t\t\t\t\toutput.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n\t\t\t\t\toldLineNum += skippedLines;\n\t\t\t\t\tnewLineNum += skippedLines;\n\t\t\t\t}\n\t\t\t} else if (hasTrailingChange) {\n\t\t\t\tconst skippedLines = Math.max(0, raw.length - contextLines);\n\t\t\t\tif (skippedLines > 0) {\n\t\t\t\t\toutput.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n\t\t\t\t\toldLineNum += skippedLines;\n\t\t\t\t\tnewLineNum += skippedLines;\n\t\t\t\t}\n\n\t\t\t\tfor (const line of raw.slice(skippedLines)) {\n\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\toldLineNum++;\n\t\t\t\t\tnewLineNum++;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Skip these context lines entirely\n\t\t\t\toldLineNum += raw.length;\n\t\t\t\tnewLineNum += raw.length;\n\t\t\t}\n\n\t\t\tlastWasChange = false;\n\t\t}\n\t}\n\n\treturn { diff: output.join(\"\\n\"), firstChangedLine };\n}\n\nexport interface EditDiffResult {\n\tdiff: string;\n\tfirstChangedLine: number | undefined;\n}\n\nexport interface EditDiffError {\n\terror: string;\n}\n\n/**\n * Compute the diff for one or more edit operations without applying them.\n * Used for preview rendering in the TUI before the tool executes.\n */\nexport async function computeEditsDiff(\n\tpath: string,\n\tedits: Edit[],\n\tcwd: string,\n): Promise<EditDiffResult | EditDiffError> {\n\tconst absolutePath = resolveToCwd(path, cwd);\n\n\ttry {\n\t\t// Check if file exists and is readable\n\t\ttry {\n\t\t\tawait access(absolutePath, constants.R_OK);\n\t\t} catch (error: unknown) {\n\t\t\tconst errorMessage = error instanceof Error && \"code\" in error ? `Error code: ${error.code}` : String(error);\n\t\t\treturn { error: `Could not edit file: ${path}. ${errorMessage}.` };\n\t\t}\n\n\t\t// Read the file\n\t\tconst rawContent = await readFile(absolutePath, \"utf-8\");\n\n\t\t// Strip BOM before matching (LLM won't include invisible BOM in oldText)\n\t\tconst { text: content } = stripBom(rawContent);\n\t\tconst normalizedContent = normalizeToLF(content);\n\t\tconst { baseContent, newContent } = applyEditsToNormalizedContent(normalizedContent, edits, path);\n\n\t\t// Generate the diff\n\t\treturn generateDiffString(baseContent, newContent);\n\t} catch (err) {\n\t\treturn { error: err instanceof Error ? err.message : String(err) };\n\t}\n}\n\n/**\n * Compute the diff for a single edit operation without applying it.\n * Kept as a convenience wrapper for single-edit callers.\n */\nexport async function computeEditDiff(\n\tpath: string,\n\toldText: string,\n\tnewText: string,\n\tcwd: string,\n): Promise<EditDiffResult | EditDiffError> {\n\treturn computeEditsDiff(path, [{ oldText, newText }], cwd);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"edit-diff.js","sourceRoot":"","sources":["../../../src/core/tools/edit-diff.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC;AAC/B,OAAO,EAAE,MAAM,EAAE,QAAQ,EAA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ACpE,CAAC;QAED,gBAAgB;QAChB,MAAM,UAAU,GAAG,MAAM,QAAQ,CAAC,YAAY,EAAE,OAAO,CAAC,CAAC;QAEzD,yEAAyE;QACzE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,QAAQ,CAAC,UAAU,CAAC,CAAC;QAC/C,MAAM,iBAAiB,GAAG,aAAa,CAAC,OAAO,CAAC,CAAC;QACjD,MAAM,EAAE,WAAW,EAAE,UAAU,EAAE,GAAG,6BAA6B,CAAC,iBAAiB,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC;QAElG,oBAAoB;QACpB,OAAO,kBAAkB,CAAC,WAAW,EAAE,UAAU,CAAC,CAAC;IACpD,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACd,OAAO,EAAE,KAAK,EAAE,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC;IACpE,CAAC;AAAA,CACD;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe,CACpC,IAAY,EACZ,OAAe,EACf,OAAe,EACf,GAAW,EAC+B;IAC1C,OAAO,gBAAgB,CAAC,IAAI,EAAE,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,GAAG,CAAC,CAAC;AAAA,CAC3D","sourcesContent":["/**\n * Shared diff computation utilities for the edit tool.\n * Used by both edit.ts (for execution) and tool-execution.ts (for preview rendering).\n */\n\nimport * as Diff from \"diff\";\nimport { constants } from \"fs\";\nimport { access, readFile } from \"fs/promises\";\nimport { resolveToCwd } from \"./path-utils.ts\";\n\nexport function detectLineEnding(content: string): \"\\r\\n\" | \"\\n\" {\n\tconst crlfIdx = content.indexOf(\"\\r\\n\");\n\tconst lfIdx = content.indexOf(\"\\n\");\n\tif (lfIdx === -1) return \"\\n\";\n\tif (crlfIdx === -1) return \"\\n\";\n\treturn crlfIdx < lfIdx ? \"\\r\\n\" : \"\\n\";\n}\n\nexport function normalizeToLF(text: string): string {\n\treturn text.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\");\n}\n\nexport function restoreLineEndings(text: string, ending: \"\\r\\n\" | \"\\n\"): string {\n\treturn ending === \"\\r\\n\" ? text.replace(/\\n/g, \"\\r\\n\") : text;\n}\n\n/**\n * Normalize text for fuzzy matching. Applies progressive transformations:\n * - Strip trailing whitespace from each line\n * - Normalize smart quotes to ASCII equivalents\n * - Normalize Unicode dashes/hyphens to ASCII hyphen\n * - Normalize special Unicode spaces to regular space\n */\nexport function normalizeForFuzzyMatch(text: string): string {\n\treturn (\n\t\ttext\n\t\t\t.normalize(\"NFKC\")\n\t\t\t// Strip trailing whitespace per line\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => line.trimEnd())\n\t\t\t.join(\"\\n\")\n\t\t\t// Smart single quotes → '\n\t\t\t.replace(/[\\u2018\\u2019\\u201A\\u201B]/g, \"'\")\n\t\t\t// Smart double quotes → \"\n\t\t\t.replace(/[\\u201C\\u201D\\u201E\\u201F]/g, '\"')\n\t\t\t// Various dashes/hyphens → -\n\t\t\t// U+2010 hyphen, U+2011 non-breaking hyphen, U+2012 figure dash,\n\t\t\t// U+2013 en-dash, U+2014 em-dash, U+2015 horizontal bar, U+2212 minus\n\t\t\t.replace(/[\\u2010\\u2011\\u2012\\u2013\\u2014\\u2015\\u2212]/g, \"-\")\n\t\t\t// Special spaces → regular space\n\t\t\t// U+00A0 NBSP, U+2002-U+200A various spaces, U+202F narrow NBSP,\n\t\t\t// U+205F medium math space, U+3000 ideographic space\n\t\t\t.replace(/[\\u00A0\\u2002-\\u200A\\u202F\\u205F\\u3000]/g, \" \")\n\t);\n}\n\nexport interface FuzzyMatchResult {\n\t/** Whether a match was found */\n\tfound: boolean;\n\t/** The index where the match starts (in the content that should be used for replacement) */\n\tindex: number;\n\t/** Length of the matched text */\n\tmatchLength: number;\n\t/** Whether fuzzy matching was used (false = exact match) */\n\tusedFuzzyMatch: boolean;\n\t/** The original content replacements should be applied to. */\n\tcontentForReplacement: string;\n}\n\nexport interface Edit {\n\toldText: string;\n\tnewText: string;\n}\n\ninterface MatchedEdit {\n\teditIndex: number;\n\tmatchIndex: number;\n\tmatchLength: number;\n\tnewText: string;\n}\n\nexport interface AppliedEditsResult {\n\tbaseContent: string;\n\tnewContent: string;\n}\n\n/**\n * Find oldText in content, trying exact match first, then fuzzy match.\n * Fuzzy matching searches normalized text, but returned spans still refer to\n * the original content so replacement does not normalize unrelated text.\n */\nexport function fuzzyFindText(content: string, oldText: string): FuzzyMatchResult {\n\t// Try exact match first\n\tconst exactIndex = content.indexOf(oldText);\n\tif (exactIndex !== -1) {\n\t\treturn {\n\t\t\tfound: true,\n\t\t\tindex: exactIndex,\n\t\t\tmatchLength: oldText.length,\n\t\t\tusedFuzzyMatch: false,\n\t\t\tcontentForReplacement: content,\n\t\t};\n\t}\n\n\t// Try fuzzy match - work entirely in normalized space\n\tconst fuzzyContent = normalizeForFuzzyMatch(content);\n\tconst fuzzyOldText = normalizeForFuzzyMatch(oldText);\n\tconst fuzzyIndex = fuzzyContent.indexOf(fuzzyOldText);\n\n\tif (fuzzyIndex === -1) {\n\t\treturn {\n\t\t\tfound: false,\n\t\t\tindex: -1,\n\t\t\tmatchLength: 0,\n\t\t\tusedFuzzyMatch: false,\n\t\t\tcontentForReplacement: content,\n\t\t};\n\t}\n\n\treturn {\n\t\tfound: true,\n\t\tindex: fuzzyIndex,\n\t\tmatchLength: fuzzyOldText.length,\n\t\tusedFuzzyMatch: true,\n\t\tcontentForReplacement: content,\n\t};\n}\n\n/** Strip UTF-8 BOM if present, return both the BOM (if any) and the text without it */\nexport function stripBom(content: string): { bom: string; text: string } {\n\treturn content.startsWith(\"\\uFEFF\") ? { bom: \"\\uFEFF\", text: content.slice(1) } : { bom: \"\", text: content };\n}\n\nfunction countExactOccurrences(content: string, oldText: string): number {\n\treturn content.split(oldText).length - 1;\n}\n\nfunction countFuzzyOccurrences(content: string, oldText: string): number {\n\tconst fuzzyContent = normalizeForFuzzyMatch(content);\n\tconst fuzzyOldText = normalizeForFuzzyMatch(oldText);\n\treturn fuzzyContent.split(fuzzyOldText).length - 1;\n}\n\nfunction getLineStarts(content: string): number[] {\n\tconst starts = [0];\n\tfor (let i = 0; i < content.length; i++) {\n\t\tif (content[i] === \"\\n\") starts.push(i + 1);\n\t}\n\treturn starts;\n}\n\nfunction lineColumnAt(lineStarts: number[], index: number): { lineIndex: number; column: number } {\n\tlet low = 0;\n\tlet high = lineStarts.length - 1;\n\twhile (low <= high) {\n\t\tconst mid = Math.floor((low + high) / 2);\n\t\tif (lineStarts[mid] <= index) low = mid + 1;\n\t\telse high = mid - 1;\n\t}\n\tconst lineIndex = Math.max(0, high);\n\treturn { lineIndex, column: index - lineStarts[lineIndex] };\n}\n\nfunction lineTextAt(content: string, lineStarts: number[], lineIndex: number): string {\n\tconst start = lineStarts[lineIndex];\n\tconst nextStart = lineStarts[lineIndex + 1] ?? content.length;\n\tconst end = nextStart > start && content[nextStart - 1] === \"\\n\" ? nextStart - 1 : nextStart;\n\treturn content.slice(start, end);\n}\n\nfunction normalizedColumnToOriginalColumn(line: string, normalizedColumn: number): number {\n\tif (normalizedColumn <= 0) return 0;\n\tlet originalColumn = 0;\n\tfor (const char of line) {\n\t\tconst nextColumn = originalColumn + char.length;\n\t\tif (normalizeForFuzzyMatch(line.slice(0, nextColumn)).length >= normalizedColumn) return nextColumn;\n\t\toriginalColumn = nextColumn;\n\t}\n\treturn line.length;\n}\n\nfunction mapFuzzySpanToOriginal(\n\toriginalContent: string,\n\tnormalizedIndex: number,\n\tnormalizedLength: number,\n): { index: number; length: number } {\n\tconst fuzzyContent = normalizeForFuzzyMatch(originalContent);\n\tconst fuzzyLineStarts = getLineStarts(fuzzyContent);\n\tconst originalLineStarts = getLineStarts(originalContent);\n\tconst start = lineColumnAt(fuzzyLineStarts, normalizedIndex);\n\tconst end = lineColumnAt(fuzzyLineStarts, normalizedIndex + normalizedLength);\n\tconst startLine = lineTextAt(originalContent, originalLineStarts, start.lineIndex);\n\tconst endLine = lineTextAt(originalContent, originalLineStarts, end.lineIndex);\n\tconst originalStart =\n\t\toriginalLineStarts[start.lineIndex] + normalizedColumnToOriginalColumn(startLine, start.column);\n\tconst originalEnd = originalLineStarts[end.lineIndex] + normalizedColumnToOriginalColumn(endLine, end.column);\n\treturn { index: originalStart, length: originalEnd - originalStart };\n}\n\nfunction getNotFoundError(path: string, editIndex: number, totalEdits: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(\n\t\t\t`Could not find the exact text in ${path}. The old text must match exactly including all whitespace and newlines.`,\n\t\t);\n\t}\n\treturn new Error(\n\t\t`Could not find edits[${editIndex}] in ${path}. The oldText must match exactly including all whitespace and newlines.`,\n\t);\n}\n\nfunction getDuplicateError(path: string, editIndex: number, totalEdits: number, occurrences: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(\n\t\t\t`Found ${occurrences} occurrences of the text in ${path}. The text must be unique. Please provide more context to make it unique.`,\n\t\t);\n\t}\n\treturn new Error(\n\t\t`Found ${occurrences} occurrences of edits[${editIndex}] in ${path}. Each oldText must be unique. Please provide more context to make it unique.`,\n\t);\n}\n\nfunction getEmptyOldTextError(path: string, editIndex: number, totalEdits: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(`oldText must not be empty in ${path}.`);\n\t}\n\treturn new Error(`edits[${editIndex}].oldText must not be empty in ${path}.`);\n}\n\nfunction getNoChangeError(path: string, totalEdits: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(\n\t\t\t`No changes made to ${path}. The replacement produced identical content. This might indicate an issue with special characters or the text not existing as expected.`,\n\t\t);\n\t}\n\treturn new Error(`No changes made to ${path}. The replacements produced identical content.`);\n}\n\n/**\n * Apply one or more exact-text replacements to LF-normalized content.\n *\n * All edits are matched against the same original content. Replacements are\n * then applied in reverse order so offsets remain stable. Fuzzy matching uses\n * normalized text only for finding the span; the final splice is always made\n * into the original content.\n */\nexport function applyEditsToNormalizedContent(\n\tnormalizedContent: string,\n\tedits: Edit[],\n\tpath: string,\n): AppliedEditsResult {\n\tconst normalizedEdits = edits.map((edit) => ({\n\t\toldText: normalizeToLF(edit.oldText),\n\t\tnewText: normalizeToLF(edit.newText),\n\t}));\n\n\tfor (let i = 0; i < normalizedEdits.length; i++) {\n\t\tif (normalizedEdits[i].oldText.length === 0) {\n\t\t\tthrow getEmptyOldTextError(path, i, normalizedEdits.length);\n\t\t}\n\t}\n\n\tconst baseContent = normalizedContent;\n\tconst matchedEdits: MatchedEdit[] = [];\n\tfor (let i = 0; i < normalizedEdits.length; i++) {\n\t\tconst edit = normalizedEdits[i];\n\t\tconst matchResult = fuzzyFindText(baseContent, edit.oldText);\n\t\tif (!matchResult.found) {\n\t\t\tthrow getNotFoundError(path, i, normalizedEdits.length);\n\t\t}\n\n\t\tconst occurrences = matchResult.usedFuzzyMatch\n\t\t\t? countFuzzyOccurrences(baseContent, edit.oldText)\n\t\t\t: countExactOccurrences(baseContent, edit.oldText);\n\t\tif (occurrences > 1) {\n\t\t\tthrow getDuplicateError(path, i, normalizedEdits.length, occurrences);\n\t\t}\n\n\t\tconst replacementSpan = matchResult.usedFuzzyMatch\n\t\t\t? mapFuzzySpanToOriginal(baseContent, matchResult.index, matchResult.matchLength)\n\t\t\t: { index: matchResult.index, length: matchResult.matchLength };\n\n\t\tmatchedEdits.push({\n\t\t\teditIndex: i,\n\t\t\tmatchIndex: replacementSpan.index,\n\t\t\tmatchLength: replacementSpan.length,\n\t\t\tnewText: edit.newText,\n\t\t});\n\t}\n\n\tmatchedEdits.sort((a, b) => a.matchIndex - b.matchIndex);\n\tfor (let i = 1; i < matchedEdits.length; i++) {\n\t\tconst previous = matchedEdits[i - 1];\n\t\tconst current = matchedEdits[i];\n\t\tif (previous.matchIndex + previous.matchLength > current.matchIndex) {\n\t\t\tthrow new Error(\n\t\t\t\t`edits[${previous.editIndex}] and edits[${current.editIndex}] overlap in ${path}. Merge them into one edit or target disjoint regions.`,\n\t\t\t);\n\t\t}\n\t}\n\n\tlet newContent = baseContent;\n\tfor (let i = matchedEdits.length - 1; i >= 0; i--) {\n\t\tconst edit = matchedEdits[i];\n\t\tnewContent =\n\t\t\tnewContent.substring(0, edit.matchIndex) +\n\t\t\tedit.newText +\n\t\t\tnewContent.substring(edit.matchIndex + edit.matchLength);\n\t}\n\n\tif (baseContent === newContent) {\n\t\tthrow getNoChangeError(path, normalizedEdits.length);\n\t}\n\n\treturn { baseContent, newContent };\n}\n\n/** Generate a standard unified patch. */\nexport function generateUnifiedPatch(path: string, oldContent: string, newContent: string, contextLines = 4): string {\n\treturn Diff.createTwoFilesPatch(path, path, oldContent, newContent, undefined, undefined, {\n\t\tcontext: contextLines,\n\t\theaderOptions: Diff.FILE_HEADERS_ONLY,\n\t});\n}\n\n/**\n * Generate a display-oriented diff string with line numbers and context.\n * Returns both the diff string and the first changed line number (in the new file).\n */\nexport function generateDiffString(\n\toldContent: string,\n\tnewContent: string,\n\tcontextLines = 4,\n): { diff: string; firstChangedLine: number | undefined } {\n\tconst parts = Diff.diffLines(oldContent, newContent);\n\tconst output: string[] = [];\n\n\tconst oldLines = oldContent.split(\"\\n\");\n\tconst newLines = newContent.split(\"\\n\");\n\tconst maxLineNum = Math.max(oldLines.length, newLines.length);\n\tconst lineNumWidth = String(maxLineNum).length;\n\n\tlet oldLineNum = 1;\n\tlet newLineNum = 1;\n\tlet lastWasChange = false;\n\tlet firstChangedLine: number | undefined;\n\n\tfor (let i = 0; i < parts.length; i++) {\n\t\tconst part = parts[i];\n\t\tconst raw = part.value.split(\"\\n\");\n\t\tif (raw[raw.length - 1] === \"\") {\n\t\t\traw.pop();\n\t\t}\n\n\t\tif (part.added || part.removed) {\n\t\t\t// Capture the first changed line (in the new file)\n\t\t\tif (firstChangedLine === undefined) {\n\t\t\t\tfirstChangedLine = newLineNum;\n\t\t\t}\n\n\t\t\t// Show the change\n\t\t\tfor (const line of raw) {\n\t\t\t\tif (part.added) {\n\t\t\t\t\tconst lineNum = String(newLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(`+${lineNum} ${line}`);\n\t\t\t\t\tnewLineNum++;\n\t\t\t\t} else {\n\t\t\t\t\t// removed\n\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(`-${lineNum} ${line}`);\n\t\t\t\t\toldLineNum++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tlastWasChange = true;\n\t\t} else {\n\t\t\t// Context lines - only show a few before/after changes\n\t\t\tconst nextPartIsChange = i < parts.length - 1 && (parts[i + 1].added || parts[i + 1].removed);\n\t\t\tconst hasLeadingChange = lastWasChange;\n\t\t\tconst hasTrailingChange = nextPartIsChange;\n\n\t\t\tif (hasLeadingChange && hasTrailingChange) {\n\t\t\t\tif (raw.length <= contextLines * 2) {\n\t\t\t\t\tfor (const line of raw) {\n\t\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\t\toldLineNum++;\n\t\t\t\t\t\tnewLineNum++;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tconst leadingLines = raw.slice(0, contextLines);\n\t\t\t\t\tconst trailingLines = raw.slice(raw.length - contextLines);\n\t\t\t\t\tconst skippedLines = raw.length - leadingLines.length - trailingLines.length;\n\n\t\t\t\t\tfor (const line of leadingLines) {\n\t\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\t\toldLineNum++;\n\t\t\t\t\t\tnewLineNum++;\n\t\t\t\t\t}\n\n\t\t\t\t\toutput.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n\t\t\t\t\toldLineNum += skippedLines;\n\t\t\t\t\tnewLineNum += skippedLines;\n\n\t\t\t\t\tfor (const line of trailingLines) {\n\t\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\t\toldLineNum++;\n\t\t\t\t\t\tnewLineNum++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (hasLeadingChange) {\n\t\t\t\tconst shownLines = raw.slice(0, contextLines);\n\t\t\t\tconst skippedLines = raw.length - shownLines.length;\n\n\t\t\t\tfor (const line of shownLines) {\n\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\toldLineNum++;\n\t\t\t\t\tnewLineNum++;\n\t\t\t\t}\n\n\t\t\t\tif (skippedLines > 0) {\n\t\t\t\t\toutput.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n\t\t\t\t\toldLineNum += skippedLines;\n\t\t\t\t\tnewLineNum += skippedLines;\n\t\t\t\t}\n\t\t\t} else if (hasTrailingChange) {\n\t\t\t\tconst skippedLines = Math.max(0, raw.length - contextLines);\n\t\t\t\tif (skippedLines > 0) {\n\t\t\t\t\toutput.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n\t\t\t\t\toldLineNum += skippedLines;\n\t\t\t\t\tnewLineNum += skippedLines;\n\t\t\t\t}\n\n\t\t\t\tfor (const line of raw.slice(skippedLines)) {\n\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\toldLineNum++;\n\t\t\t\t\tnewLineNum++;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Skip these context lines entirely\n\t\t\t\toldLineNum += raw.length;\n\t\t\t\tnewLineNum += raw.length;\n\t\t\t}\n\n\t\t\tlastWasChange = false;\n\t\t}\n\t}\n\n\treturn { diff: output.join(\"\\n\"), firstChangedLine };\n}\n\nexport interface EditDiffResult {\n\tdiff: string;\n\tfirstChangedLine: number | undefined;\n}\n\nexport interface EditDiffError {\n\terror: string;\n}\n\n/**\n * Compute the diff for one or more edit operations without applying them.\n * Used for preview rendering in the TUI before the tool executes.\n */\nexport async function computeEditsDiff(\n\tpath: string,\n\tedits: Edit[],\n\tcwd: string,\n): Promise<EditDiffResult | EditDiffError> {\n\tconst absolutePath = resolveToCwd(path, cwd);\n\n\ttry {\n\t\t// Check if file exists and is readable\n\t\ttry {\n\t\t\tawait access(absolutePath, constants.R_OK);\n\t\t} catch (error: unknown) {\n\t\t\tconst errorMessage = error instanceof Error && \"code\" in error ? `Error code: ${error.code}` : String(error);\n\t\t\treturn { error: `Could not edit file: ${path}. ${errorMessage}.` };\n\t\t}\n\n\t\t// Read the file\n\t\tconst rawContent = await readFile(absolutePath, \"utf-8\");\n\n\t\t// Strip BOM before matching (LLM won't include invisible BOM in oldText)\n\t\tconst { text: content } = stripBom(rawContent);\n\t\tconst normalizedContent = normalizeToLF(content);\n\t\tconst { baseContent, newContent } = applyEditsToNormalizedContent(normalizedContent, edits, path);\n\n\t\t// Generate the diff\n\t\treturn generateDiffString(baseContent, newContent);\n\t} catch (err) {\n\t\treturn { error: err instanceof Error ? err.message : String(err) };\n\t}\n}\n\n/**\n * Compute the diff for a single edit operation without applying it.\n * Kept as a convenience wrapper for single-edit callers.\n */\nexport async function computeEditDiff(\n\tpath: string,\n\toldText: string,\n\tnewText: string,\n\tcwd: string,\n): Promise<EditDiffResult | EditDiffError> {\n\treturn computeEditsDiff(path, [{ oldText, newText }], cwd);\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"git-filter.d.ts","sourceRoot":"","sources":["../../../src/core/tools/git-filter.ts"],"names":[],"mappings":"AAyCA,MAAM,WAAW,YAAY;IAC5B,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,mGA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AM,EAAE,CAAC;IACzB,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC1B,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAClC,CA4DA;AAED,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAYvD;AAmHD,wBAAgB,WAAW,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,SAAM,GAAG;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,OAAO,CAAA;CAAE,CAgEzG;AA4RD,wBAAsB,kBAAkB,CACvC,GAAG,EAAE,MAAM,EACX,UAAU,EAAE,MAAM,EAClB,aAAa,EAAE,MAAM,EAAE,EACvB,cAAc,EAAE,MAAM,EAAE,EACxB,OAAO,CAAC,EAAE,gBAAgB,GACxB,OAAO,CAAC,YAAY,CAAC,CA6BvB;AAED,wBAAgB,wBAAwB,CAAC,aAAa,EAAE,MAAM,EAAE,EAAE,UAAU,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,MAAM,CAE5G","sourcesContent":["import { spawn } from \"node:child_process\";\nimport { randomBytes } from \"node:crypto\";\nimport { existsSync, type WriteStream } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\nimport { waitForChildProcess } from \"../../utils/child-process.ts\";\nimport { createSafeWriteStream } from \"../../utils/safe-write-stream.ts\";\nimport { killProcessTree, trackDetachedChildPid, untrackDetachedChildPid } from \"../../utils/shell.ts\";\n\n/**\n * Retention budget for git output held in memory while filtering. Output beyond\n * the budget is spilled to a temp file so a giant `git log -p`/`git diff` cannot\n * exhaust the V8 heap. Override with PI_GIT_FILTER_MAX_RETAINED_BYTES.\n */\nconst DEFAULT_MAX_RETAINED_GIT_OUTPUT_BYTES = 48 * 1024 * 1024;\nconst MAX_RETAINED_GIT_STDERR_BYTES = 8 * 1024 * 1024;\n\nfunction maxRetainedGitOutputBytes(): number {\n\tconst raw = process.env.PI_GIT_FILTER_MAX_RETAINED_BYTES;\n\tif (raw !== undefined) {\n\t\tconst parsed = Number.parseInt(raw, 10);\n\t\tif (Number.isFinite(parsed) && parsed > 0) return parsed;\n\t}\n\treturn DEFAULT_MAX_RETAINED_GIT_OUTPUT_BYTES;\n}\n\nconst SUPPORTED_SUBCOMMANDS = new Set([\n\t\"status\",\n\t\"log\",\n\t\"diff\",\n\t\"show\",\n\t\"add\",\n\t\"commit\",\n\t\"push\",\n\t\"pull\",\n\t\"branch\",\n\t\"fetch\",\n\t\"stash\",\n\t\"worktree\",\n]);\n\nexport interface FilterResult {\n\toutput: string;\n\texitCode: number;\n\trawOut: string;\n\trawBytes?: Buffer;\n\t/** Set when git output exceeded the in-memory retention budget; the file holds the full output. */\n\tfullOutputPath?: string;\n}\n\ninterface GitQueryResult {\n\tstdout: string;\n\tstderr: string;\n\tstatus: number | null;\n\t/** Full raw output (stderr then stdout). Absent when output overflowed to disk. */\n\trawBytes?: Buffer;\n\t/** Set when stdout exceeded the retention budget and was spilled to a temp file. */\n\toverflow?: { fullOutputPath: string; totalBytes: number };\n}\n\ninterface GitFilterOptions {\n\tsignal?: AbortSignal;\n\ttimeout?: number;\n}\n\nexport function unicodeTruncate(str: string, maxLength: number): string {\n\tconst chars = Array.from(str);\n\tif (chars.length <= maxLength) return str;\n\treturn `${chars.slice(0, maxLength).join(\"\")}...`;\n}\n\nexport function tokenizeCommand(command: string): string[] | null {\n\tconst args: string[] = [];\n\tlet current = \"\";\n\tlet inDoubleQuotes = false;\n\tlet inSingleQuotes = false;\n\tlet escapeNext = false;\n\n\tfor (let i = 0; i < command.length; i++) {\n\t\tconst char = command[i];\n\t\tif (escapeNext) {\n\t\t\tcurrent += char;\n\t\t\tescapeNext = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === \"\\\\\" && !inSingleQuotes) {\n\t\t\tescapeNext = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === '\"' && !inSingleQuotes) {\n\t\t\tinDoubleQuotes = !inDoubleQuotes;\n\t\t} else if (char === \"'\" && !inDoubleQuotes) {\n\t\t\tinSingleQuotes = !inSingleQuotes;\n\t\t} else if (/\\s/.test(char) && !inDoubleQuotes && !inSingleQuotes) {\n\t\t\tif (current) {\n\t\t\t\targs.push(current);\n\t\t\t\tcurrent = \"\";\n\t\t\t}\n\t\t} else {\n\t\t\tcurrent += char;\n\t\t}\n\t}\n\tif (inDoubleQuotes || inSingleQuotes || escapeNext) return null;\n\tif (current) args.push(current);\n\treturn args;\n}\n\nexport interface ParsedCommand {\n\tenvVars: Record<string, string>;\n\tcoreCommandTokens: string[];\n}\n\nexport function parseCommandPrefixes(command: string): ParsedCommand | null {\n\tconst tokens = tokenizeCommand(command);\n\tif (!tokens || tokens.length === 0) return null;\n\n\tconst envVars: Record<string, string> = {};\n\tlet i = 0;\n\tconst envPattern = /^([a-zA-Z_][a-zA-Z0-9_]*)=(.*)$/;\n\n\twhile (i < tokens.length) {\n\t\tconst token = tokens[i];\n\t\tconst match = token.match(envPattern);\n\t\tif (!match) break;\n\t\tlet value = match[2];\n\t\tif ((value.startsWith('\"') && value.endsWith('\"')) || (value.startsWith(\"'\") && value.endsWith(\"'\"))) {\n\t\t\tvalue = value.slice(1, -1);\n\t\t}\n\t\tenvVars[match[1]] = value;\n\t\ti++;\n\t}\n\n\treturn { envVars, coreCommandTokens: tokens.slice(i) };\n}\n\nexport function isComplexShellCommand(command: string): boolean {\n\treturn /[|><&;\\n\\r$`()*?[\\]#]/.test(command);\n}\n\nfunction quoteForShell(arg: string): string {\n\tif (/^[A-Za-z0-9_./:=+-]+$/.test(arg)) return arg;\n\treturn `'${arg.replace(/'/g, `'\"'\"'`)}'`;\n}\n\nfunction gitCommand(globalOptions: string[], args: string[]): string {\n\treturn [\"git\", ...globalOptions, ...args].map(quoteForShell).join(\" \");\n}\n\nfunction rawText(res: GitQueryResult, combine = false): string {\n\tif (combine) return `${res.stderr}${res.stderr && res.stdout ? \"\\n\" : \"\"}${res.stdout}`;\n\treturn res.stderr || res.stdout;\n}\n\nfunction applyOverflowDisclosure(res: GitQueryResult, result: FilterResult): FilterResult {\n\tif (!res.overflow) return result;\n\tconst totalMb = (res.overflow.totalBytes / (1024 * 1024)).toFixed(1);\n\treturn {\n\t\t...result,\n\t\toutput: `${result.output}\\n\\n[git output was ${totalMb}MB; filtered view computed from the retained head. Full output: ${res.overflow.fullOutputPath}]`,\n\t\tfullOutputPath: res.overflow.fullOutputPath,\n\t};\n}\n\nfunction resultFromQuery(res: GitQueryResult, output: string, exitCode = res.status ?? 0): FilterResult {\n\treturn applyOverflowDisclosure(res, { output, exitCode, rawOut: rawText(res), rawBytes: res.rawBytes });\n}\n\nexport async function runGitQuery(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<GitQueryResult> {\n\tif (options?.signal?.aborted) throw new Error(\"aborted\");\n\n\tconst child = spawn(\"git\", [...globalOptions, ...args], {\n\t\tcwd,\n\t\tdetached: process.platform !== \"win32\",\n\t\tenv: { ...process.env, LC_ALL: \"C\" },\n\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\twindowsHide: true,\n\t});\n\tif (child.pid) trackDetachedChildPid(child.pid);\n\n\tconst stdoutChunks: Buffer[] = [];\n\tconst stderrChunks: Buffer[] = [];\n\tconst maxRetainedBytes = maxRetainedGitOutputBytes();\n\tlet retainedStdoutBytes = 0;\n\tlet totalStdoutBytes = 0;\n\tlet retainedStderrBytes = 0;\n\tlet overflowPath: string | undefined;\n\tlet overflowStream: WriteStream | undefined;\n\tlet overflowStreamEnded = false;\n\tlet overflowWriteError: Error | undefined;\n\tlet timedOut = false;\n\tconst timeoutSeconds = options?.timeout;\n\tlet timeoutHandle: NodeJS.Timeout | undefined;\n\tconst killChild = () => {\n\t\tif (child.pid) killProcessTree(child.pid);\n\t};\n\n\ttry {\n\t\tif (timeoutSeconds !== undefined && timeoutSeconds > 0) {\n\t\t\ttimeoutHandle = setTimeout(() => {\n\t\t\t\ttimedOut = true;\n\t\t\t\tkillChild();\n\t\t\t}, timeoutSeconds * 1000);\n\t\t}\n\t\tif (options?.signal) {\n\t\t\tif (options.signal.aborted) killChild();\n\t\t\telse options.signal.addEventListener(\"abort\", killChild, { once: true });\n\t\t}\n\n\t\tchild.stdout?.on(\"data\", (chunk: Buffer) => {\n\t\t\ttotalStdoutBytes += chunk.length;\n\t\t\tif (overflowStream) {\n\t\t\t\toverflowStream.write(chunk);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tstdoutChunks.push(chunk);\n\t\t\tretainedStdoutBytes += chunk.length;\n\t\t\tif (retainedStdoutBytes > maxRetainedBytes) {\n\t\t\t\toverflowPath = join(tmpdir(), `pi-git-${randomBytes(8).toString(\"hex\")}.log`);\n\t\t\t\toverflowStream = createSafeWriteStream(overflowPath, (error) => {\n\t\t\t\t\toverflowWriteError = error;\n\t\t\t\t});\n\t\t\t\tfor (const retained of stdoutChunks) overflowStream.write(retained);\n\t\t\t}\n\t\t});\n\t\tchild.stderr?.on(\"data\", (chunk: Buffer) => {\n\t\t\tstderrChunks.push(chunk);\n\t\t\tretainedStderrBytes += chunk.length;\n\t\t\twhile (retainedStderrBytes > MAX_RETAINED_GIT_STDERR_BYTES && stderrChunks.length > 1) {\n\t\t\t\tretainedStderrBytes -= stderrChunks.shift()?.length ?? 0;\n\t\t\t}\n\t\t});\n\t\tconst status = await waitForChildProcess(child);\n\t\tif (options?.signal?.aborted) throw new Error(\"aborted\");\n\t\tif (timedOut) throw new Error(`timeout:${timeoutSeconds}`);\n\t\tconst stdoutBuffer = Buffer.concat(stdoutChunks);\n\t\tconst stderrBuffer = Buffer.concat(stderrChunks);\n\t\tif (overflowStream !== undefined && overflowPath !== undefined) {\n\t\t\tif (stderrBuffer.length > 0 && !overflowStream.writableEnded) {\n\t\t\t\toverflowStream.write(\"\\n--- stderr ---\\n\");\n\t\t\t\toverflowStream.write(stderrBuffer);\n\t\t\t}\n\t\t\tconst stream = overflowStream;\n\t\t\tawait new Promise<void>((resolveEnd) => {\n\t\t\t\tstream.end(() => resolveEnd());\n\t\t\t});\n\t\t\toverflowStreamEnded = true;\n\t\t\tif (overflowWriteError !== undefined) {\n\t\t\t\t// Spill failed (e.g. disk full): disclose the loss instead of pointing\n\t\t\t\t// consumers at a broken artifact, and keep the retained head usable.\n\t\t\t\treturn {\n\t\t\t\t\tstdout: stdoutBuffer.toString(\"utf-8\"),\n\t\t\t\t\tstderr: `${stderrBuffer.toString(\"utf-8\")}\\n[git output overflow spill failed: ${overflowWriteError.message}; output beyond the retained head was lost]`,\n\t\t\t\t\tstatus,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tstdout: stdoutBuffer.toString(\"utf-8\"),\n\t\t\t\tstderr: stderrBuffer.toString(\"utf-8\"),\n\t\t\t\tstatus,\n\t\t\t\toverflow: { fullOutputPath: overflowPath, totalBytes: totalStdoutBytes },\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tstdout: stdoutBuffer.toString(\"utf-8\"),\n\t\t\tstderr: stderrBuffer.toString(\"utf-8\"),\n\t\t\tstatus,\n\t\t\trawBytes: Buffer.concat([stderrBuffer, stdoutBuffer]),\n\t\t};\n\t} finally {\n\t\tif (child.pid) untrackDetachedChildPid(child.pid);\n\t\tif (timeoutHandle) clearTimeout(timeoutHandle);\n\t\tif (options?.signal) options.signal.removeEventListener(\"abort\", killChild);\n\t\tif (overflowStream !== undefined && !overflowStreamEnded) overflowStream.end();\n\t}\n}\n\nexport function classifyGitCommand(\n\tcommand: string,\n\tparentEnv?: NodeJS.ProcessEnv,\n): {\n\teligible: boolean;\n\tsubcommand?: string;\n\tglobalOptions?: string[];\n\tsubcommandArgs?: string[];\n\tlocalEnv?: Record<string, string>;\n} {\n\tif (isComplexShellCommand(command)) return { eligible: false };\n\n\tconst parsed = parseCommandPrefixes(command);\n\tif (!parsed || parsed.coreCommandTokens.length === 0) return { eligible: false };\n\n\tconst { envVars, coreCommandTokens } = parsed;\n\tconst toolFilterDisabled =\n\t\tprocess.env.PI_TOOL_FILTER_DISABLED === \"1\" ||\n\t\tparentEnv?.PI_TOOL_FILTER_DISABLED === \"1\" ||\n\t\tenvVars.PI_TOOL_FILTER_DISABLED === \"1\";\n\tconst gitFilterDisabled =\n\t\tprocess.env.PI_GIT_FILTER_DISABLED === \"1\" ||\n\t\tparentEnv?.PI_GIT_FILTER_DISABLED === \"1\" ||\n\t\tenvVars.PI_GIT_FILTER_DISABLED === \"1\";\n\tif (toolFilterDisabled || gitFilterDisabled) return { eligible: false };\n\n\tconst envKeys = Object.keys(envVars).filter(\n\t\t(key) => key !== \"PI_TOOL_FILTER_DISABLED\" && key !== \"PI_GIT_FILTER_DISABLED\",\n\t);\n\tif (envKeys.length > 0) return { eligible: false };\n\n\tconst cmdName = coreCommandTokens[0];\n\tif (cmdName !== \"git\" && cmdName !== \"yadm\") return { eligible: false };\n\n\tlet idx = 1;\n\tconst globalOptions: string[] = [];\n\twhile (idx < coreCommandTokens.length) {\n\t\tconst token = coreCommandTokens[idx];\n\t\tif (token === \"-C\" || token === \"-c\" || token === \"--git-dir\" || token === \"--work-tree\") {\n\t\t\tif (idx + 1 >= coreCommandTokens.length) return { eligible: false };\n\t\t\tglobalOptions.push(token, coreCommandTokens[idx + 1]);\n\t\t\tidx += 2;\n\t\t} else if (token.startsWith(\"--git-dir=\") || token.startsWith(\"--work-tree=\")) {\n\t\t\tglobalOptions.push(token);\n\t\t\tidx++;\n\t\t} else if (\n\t\t\ttoken === \"--no-pager\" ||\n\t\t\ttoken === \"--no-optional-locks\" ||\n\t\t\ttoken === \"--bare\" ||\n\t\t\ttoken === \"--literal-pathspecs\"\n\t\t) {\n\t\t\tglobalOptions.push(token);\n\t\t\tidx++;\n\t\t} else {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (idx === coreCommandTokens.length) return { eligible: false };\n\tconst subcommand = coreCommandTokens[idx];\n\tif (!SUPPORTED_SUBCOMMANDS.has(subcommand)) return { eligible: false };\n\n\treturn {\n\t\teligible: true,\n\t\tsubcommand,\n\t\tglobalOptions,\n\t\tsubcommandArgs: coreCommandTokens.slice(idx + 1),\n\t\tlocalEnv: envVars,\n\t};\n}\n\nexport function detectGitState(gitDir: string): string[] {\n\tconst states: string[] = [];\n\tif (!gitDir) return states;\n\tif (existsSync(join(gitDir, \"rebase-merge\")) || existsSync(join(gitDir, \"rebase-apply\"))) {\n\t\tstates.push(\"rebase in progress\");\n\t}\n\tif (existsSync(join(gitDir, \"MERGE_HEAD\"))) states.push(\"merge in progress\");\n\tif (existsSync(join(gitDir, \"CHERRY_PICK_HEAD\"))) states.push(\"cherry-pick in progress\");\n\tif (existsSync(join(gitDir, \"REVERT_HEAD\"))) states.push(\"revert in progress\");\n\tif (existsSync(join(gitDir, \"BISECT_LOG\"))) states.push(\"bisect in progress\");\n\tif (existsSync(join(gitDir, \"applying\"))) states.push(\"am in progress\");\n\treturn states;\n}\n\nasync function handleStatus(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst isSimple =\n\t\targs.length === 0 || args.every((arg) => arg === \"-s\" || arg === \"--short\" || arg === \"-b\" || arg === \"--branch\");\n\n\tif (!isSimple) {\n\t\tconst res = await runGitQuery(cwd, globalOptions, [\"status\", ...args], options);\n\t\tconst rawOut = rawText(res);\n\t\tif (res.status !== 0) return { output: rawOut, exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\t\tconst cleanedLines = res.stdout\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => line.trimEnd())\n\t\t\t.filter((line) => line.length > 0 && !line.trim().startsWith(\"(use \"));\n\t\tconst output = cleanedLines.join(\"\\n\");\n\t\treturn resultFromQuery(res, output || \"success\", 0);\n\t}\n\n\tconst res = await runGitQuery(cwd, globalOptions, [\"status\", \"--porcelain=v1\", \"-b\"], options);\n\tlet rawOut = rawText(res);\n\tif (res.status !== 0) {\n\t\tif (rawOut.includes(\"not a git repository\")) rawOut = \"fatal: not a git repository\";\n\t\treturn { output: rawOut.trim(), exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\t}\n\n\tconst lines = res.stdout.split(\"\\n\").filter((line) => line.trim().length > 0);\n\tlet branchLine = \"\";\n\tconst fileLines: string[] = [];\n\tfor (const line of lines) {\n\t\tif (line.startsWith(\"##\")) branchLine = line;\n\t\telse fileLines.push(line);\n\t}\n\n\tlet statePrefix = \"\";\n\tconst gitDirRes = await runGitQuery(cwd, globalOptions, [\"rev-parse\", \"--git-dir\"], options);\n\tif (gitDirRes.status === 0) {\n\t\tconst gitDir = resolve(cwd, gitDirRes.stdout.trim());\n\t\tconst states = detectGitState(gitDir);\n\t\tif (states.length > 0) statePrefix = `[${states.join(\", \")}]\\n`;\n\t}\n\n\tif (branchLine.includes(\"HEAD (no branch)\")) {\n\t\tconst headHashRes = await runGitQuery(cwd, globalOptions, [\"rev-parse\", \"--short\", \"HEAD\"], options);\n\t\tconst hash = headHashRes.status === 0 ? headHashRes.stdout.trim() : \"unknown\";\n\t\tbranchLine = `## HEAD (detached at ${hash})`;\n\t}\n\n\tif (fileLines.length === 0) {\n\t\treturn resultFromQuery(res, `${statePrefix}${branchLine}\\nnothing to commit, working tree clean`, 0);\n\t}\n\treturn resultFromQuery(res, `${statePrefix}${branchLine}\\n${fileLines.join(\"\\n\")}`, 0);\n}\n\nasync function handleLog(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst hasLimit = args.some(\n\t\t(arg) => /^-n\\d+$/.test(arg) || arg === \"-n\" || /^-?\\d+$/.test(arg) || arg.startsWith(\"--max-count\"),\n\t);\n\tconst hasPretty = args.some(\n\t\t(arg) => arg.startsWith(\"--pretty\") || arg.startsWith(\"--format\") || arg === \"--oneline\",\n\t);\n\n\tif (hasLimit || hasPretty) {\n\t\tconst res = await runGitQuery(cwd, globalOptions, [\"log\", ...args], options);\n\t\treturn resultFromQuery(res, rawText(res), res.status ?? 0);\n\t}\n\n\tconst res = await runGitQuery(cwd, globalOptions, [\"log\", \"-n\", \"10\", \"--no-merges\"], options);\n\tconst rawOut = rawText(res);\n\tif (res.status !== 0) return { output: rawOut, exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\n\tconst commits = res.stdout.split(/(?=^commit [0-9a-f]{7,40})/m).filter((commit) => commit.trim().length > 0);\n\tconst compactedCommits: string[] = [];\n\tconst trailerPrefixes = [\n\t\t\"Signed-off-by:\",\n\t\t\"Co-authored-by:\",\n\t\t\"Reported-by:\",\n\t\t\"Reviewed-by:\",\n\t\t\"Tested-by:\",\n\t\t\"Suggested-by:\",\n\t\t\"CC:\",\n\t];\n\n\tfor (const commit of commits) {\n\t\tconst lines = commit.split(\"\\n\");\n\t\tconst commitLine = lines[0];\n\t\tif (!commitLine) continue;\n\t\tconst shortCommitLine = commitLine.replace(/^commit ([0-9a-f]{7})[0-9a-f]+/, \"commit $1\");\n\t\tconst bodyLines: string[] = [];\n\t\tfor (let i = 1; i < lines.length; i++) {\n\t\t\tconst line = lines[i];\n\t\t\tconst trimmed = line.trim();\n\t\t\tif (!trimmed) continue;\n\t\t\tif (line.startsWith(\"Author:\") || line.startsWith(\"Date:\") || line.startsWith(\"Merge:\")) continue;\n\t\t\tif (trailerPrefixes.some((prefix) => trimmed.startsWith(prefix))) continue;\n\t\t\tbodyLines.push(line);\n\t\t}\n\t\tconst displayBody = bodyLines.slice(0, 3).map((line) => unicodeTruncate(line, 160));\n\t\tconst omitted = bodyLines.length - displayBody.length;\n\t\tif (omitted > 0) displayBody.push(` ... (${omitted} lines omitted)`);\n\t\tcompactedCommits.push(`${shortCommitLine}\\n${displayBody.join(\"\\n\")}`);\n\t}\n\n\treturn resultFromQuery(res, compactedCommits.join(\"\\n\\n\"), 0);\n}\n\nexport function compactDiff(diffOutput: string, maxLines = 150): { compacted: string; truncated: boolean } {\n\tconst lines = diffOutput.split(\"\\n\");\n\tconst output: string[] = [];\n\tlet linesCount = 0;\n\tlet truncated = false;\n\tlet contextBuffer: string[] = [];\n\tlet trailingContextRemaining = 0;\n\n\tfor (const line of lines) {\n\t\tif (linesCount >= maxLines) {\n\t\t\ttruncated = true;\n\t\t\tbreak;\n\t\t}\n\t\tif (\n\t\t\tline.startsWith(\"diff --git\") ||\n\t\t\tline.startsWith(\"--- \") ||\n\t\t\tline.startsWith(\"+++ \") ||\n\t\t\tline.startsWith(\"index \")\n\t\t) {\n\t\t\tcontextBuffer = [];\n\t\t\ttrailingContextRemaining = 0;\n\t\t\toutput.push(line);\n\t\t\tlinesCount++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (line.startsWith(\"@@ \")) {\n\t\t\tcontextBuffer = [];\n\t\t\ttrailingContextRemaining = 0;\n\t\t\toutput.push(line);\n\t\t\tlinesCount++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (line.startsWith(\"+\") || line.startsWith(\"-\")) {\n\t\t\tfor (const ctx of contextBuffer) {\n\t\t\t\tif (linesCount >= maxLines) {\n\t\t\t\t\ttruncated = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\toutput.push(ctx);\n\t\t\t\tlinesCount++;\n\t\t\t}\n\t\t\tcontextBuffer = [];\n\t\t\tif (truncated) break;\n\t\t\toutput.push(line);\n\t\t\tlinesCount++;\n\t\t\ttrailingContextRemaining = 3;\n\t\t\tcontinue;\n\t\t}\n\t\tif (line.startsWith(\" \")) {\n\t\t\tif (trailingContextRemaining > 0) {\n\t\t\t\toutput.push(line);\n\t\t\t\tlinesCount++;\n\t\t\t\ttrailingContextRemaining--;\n\t\t\t} else {\n\t\t\t\tcontextBuffer.push(line);\n\t\t\t\tif (contextBuffer.length > 3) contextBuffer.shift();\n\t\t\t}\n\t\t} else {\n\t\t\toutput.push(line);\n\t\t\tlinesCount++;\n\t\t}\n\t}\n\n\treturn { compacted: output.join(\"\\n\"), truncated };\n}\n\nasync function handleDiff(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst cleanArgs = [...args];\n\tconst noCompactIndex = cleanArgs.indexOf(\"--no-compact\");\n\tconst optOut = noCompactIndex !== -1;\n\tif (optOut) cleanArgs.splice(noCompactIndex, 1);\n\n\tconst statFlags = [\"--stat\", \"--numstat\", \"--shortstat\", \"--summary\", \"--name-only\", \"--name-status\", \"--check\"];\n\tconst isStatOnly = cleanArgs.some((arg) => statFlags.includes(arg));\n\tif (optOut || isStatOnly) {\n\t\tconst res = await runGitQuery(cwd, globalOptions, [\"diff\", ...cleanArgs], options);\n\t\treturn resultFromQuery(res, rawText(res), res.status ?? 0);\n\t}\n\n\tconst hasDoubleDash = cleanArgs.includes(\"--\");\n\tif (!hasDoubleDash) {\n\t\tconst pathIdx = cleanArgs.findIndex((arg) => {\n\t\t\tif (arg.startsWith(\"-\")) return false;\n\t\t\tif (!(arg.includes(\"/\") || arg.includes(\".\") || existsSync(join(cwd, arg)))) return false;\n\t\t\treturn existsSync(resolve(cwd, arg));\n\t\t});\n\t\tif (pathIdx !== -1) cleanArgs.splice(pathIdx, 0, \"--\");\n\t}\n\n\tconst statRes = await runGitQuery(cwd, globalOptions, [\"diff\", \"--stat\", ...cleanArgs], options);\n\tif (statRes.status !== 0) return resultFromQuery(statRes, rawText(statRes), statRes.status ?? 1);\n\tconst diffRes = await runGitQuery(cwd, globalOptions, [\"diff\", ...cleanArgs], options);\n\tif (diffRes.status !== 0) return resultFromQuery(diffRes, rawText(diffRes), diffRes.status ?? 1);\n\n\tconst { compacted, truncated } = compactDiff(diffRes.stdout);\n\tlet output = `${statRes.stdout.trimEnd()}\\n\\n${compacted}`.trim();\n\tif (truncated) output += \"\\n\\n[Diff truncated. Re-run with: git diff --no-compact]\";\n\treturn applyOverflowDisclosure(diffRes, { output, exitCode: 0, rawOut: diffRes.stdout, rawBytes: diffRes.rawBytes });\n}\n\nasync function handleShow(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst statFlags = [\"--stat\", \"--numstat\", \"--shortstat\", \"--summary\", \"--name-only\", \"--name-status\", \"--check\"];\n\tconst hasStatOnly = args.some((arg) => statFlags.includes(arg));\n\tconst hasPretty = args.some(\n\t\t(arg) => arg.startsWith(\"--pretty\") || arg.startsWith(\"--format\") || arg === \"--oneline\",\n\t);\n\tconst hasBlob = args.some((arg) => !arg.startsWith(\"-\") && arg.includes(\":\"));\n\tif (hasStatOnly || hasPretty || hasBlob) {\n\t\tconst res = await runGitQuery(cwd, globalOptions, [\"show\", ...args], options);\n\t\treturn resultFromQuery(res, rawText(res), res.status ?? 0);\n\t}\n\n\tconst showRes = await runGitQuery(cwd, globalOptions, [\"show\", ...args], options);\n\tconst rawOut = rawText(showRes);\n\tif (showRes.status !== 0)\n\t\treturn { output: rawOut, exitCode: showRes.status ?? 1, rawOut, rawBytes: showRes.rawBytes };\n\n\tconst lines = showRes.stdout.split(\"\\n\");\n\tconst diffStart = lines.findIndex((line) => line.startsWith(\"diff --git\"));\n\tconst headerLines = diffStart === -1 ? lines : lines.slice(0, diffStart);\n\tconst diffLines = diffStart === -1 ? [] : lines.slice(diffStart);\n\tconst summaryLines = headerLines.filter((line) => {\n\t\tconst trimmed = line.trim();\n\t\tif (!trimmed) return false;\n\t\tif (line.startsWith(\"Author:\") || line.startsWith(\"Date:\") || line.startsWith(\"Merge:\")) return false;\n\t\treturn true;\n\t});\n\tconst shortSummary = summaryLines\n\t\t.slice(0, 4)\n\t\t.map((line) => unicodeTruncate(line.replace(/^commit ([0-9a-f]{7})[0-9a-f]+/, \"commit $1\"), 160));\n\tconst { compacted, truncated } = compactDiff(diffLines.join(\"\\n\"));\n\tlet output = shortSummary.join(\"\\n\");\n\tif (compacted.trim()) output += `\\n\\n${compacted}`;\n\tif (truncated) output += \"\\n\\n[Diff truncated.]\";\n\treturn resultFromQuery(showRes, output.trim(), 0);\n}\n\nasync function handlePassthroughGit(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst res = await runGitQuery(cwd, globalOptions, args, options);\n\treturn resultFromQuery(res, rawText(res, true).trim(), res.status ?? 0);\n}\n\nasync function handleAdd(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tif (args.length === 0) return handlePassthroughGit(cwd, globalOptions, [\"add\"], options);\n\tconst addRes = await runGitQuery(cwd, globalOptions, [\"add\", ...args], options);\n\tconst rawOut = rawText(addRes);\n\tif (addRes.status !== 0) return { output: rawOut, exitCode: addRes.status ?? 1, rawOut, rawBytes: addRes.rawBytes };\n\tconst statRes = await runGitQuery(cwd, globalOptions, [\"diff\", \"--cached\", \"--stat\"], options);\n\tif (statRes.status === 0 && statRes.stdout.trim().length > 0) {\n\t\treturn { output: `Staged changes:\\n${statRes.stdout.trim()}`, exitCode: 0, rawOut, rawBytes: addRes.rawBytes };\n\t}\n\treturn { output: rawOut.trim() || \"Successfully staged.\", exitCode: 0, rawOut, rawBytes: addRes.rawBytes };\n}\n\nasync function handleCommit(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst hasMsg = args.some(\n\t\t(arg) => arg === \"-m\" || arg === \"-F\" || arg.startsWith(\"--message\") || arg.startsWith(\"--file\"),\n\t);\n\tif (!hasMsg) return { output: \"\", exitCode: -100, rawOut: \"\" };\n\tconst res = await runGitQuery(cwd, globalOptions, [\"commit\", ...args], options);\n\tconst rawOut = rawText(res, true);\n\tif (res.status !== 0) return { output: rawOut, exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\tif (rawOut.includes(\"nothing to commit\") || rawOut.includes(\"working tree clean\")) {\n\t\treturn { output: \"nothing to commit, working tree clean\", exitCode: 0, rawOut, rawBytes: res.rawBytes };\n\t}\n\tconst firstLine = rawOut\n\t\t.split(\"\\n\")\n\t\t.find((line) => line.trim().length > 0)\n\t\t?.trim();\n\treturn { output: firstLine || \"Committed successfully.\", exitCode: 0, rawOut, rawBytes: res.rawBytes };\n}\n\nasync function handlePush(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst res = await runGitQuery(cwd, globalOptions, [\"push\", ...args], options);\n\tconst rawOut = rawText(res, true);\n\tconst outputLines = rawOut\n\t\t.split(\"\\n\")\n\t\t.map((line) => line.trimEnd())\n\t\t.filter((line) => {\n\t\t\tconst trimmed = line.trim();\n\t\t\tif (!trimmed) return false;\n\t\t\treturn ![\"Writing objects:\", \"Counting objects:\", \"Delta compression\", \"Compressing objects:\", \"Total \"].some(\n\t\t\t\t(prefix) => trimmed.startsWith(prefix),\n\t\t\t);\n\t\t});\n\tif (res.status !== 0)\n\t\treturn { output: outputLines.join(\"\\n\"), exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\tif (outputLines.some((line) => line.includes(\"Everything up-to-date\"))) {\n\t\treturn { output: \"Everything up-to-date.\", exitCode: 0, rawOut, rawBytes: res.rawBytes };\n\t}\n\tconst remoteMessages = outputLines.filter((line) => line.trim().startsWith(\"remote:\"));\n\tconst pushDetail = outputLines.find((line) => line.includes(\"->\"));\n\tconst summary = pushDetail ? `Pushed: ${pushDetail.trim()}` : \"Push successful.\";\n\treturn { output: [...remoteMessages, summary].join(\"\\n\"), exitCode: 0, rawOut, rawBytes: res.rawBytes };\n}\n\nasync function handlePull(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst res = await runGitQuery(cwd, globalOptions, [\"pull\", ...args], options);\n\tconst rawOut = rawText(res, true);\n\tif (res.status !== 0) return { output: rawOut, exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\tif (rawOut.includes(\"Already up to date.\"))\n\t\treturn { output: \"Already up to date.\", exitCode: 0, rawOut, rawBytes: res.rawBytes };\n\tconst lines = rawOut.split(\"\\n\");\n\tconst summary = lines.filter(\n\t\t(line) => line.includes(\"Fast-forward\") || line.includes(\"file changed\") || line.includes(\"files changed\"),\n\t);\n\treturn { output: summary.join(\"\\n\") || \"Pull successful.\", exitCode: 0, rawOut, rawBytes: res.rawBytes };\n}\n\nasync function handleFetch(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst res = await runGitQuery(cwd, globalOptions, [\"fetch\", ...args], options);\n\tconst rawOut = rawText(res, true);\n\tif (res.status !== 0) return { output: rawOut, exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\tconst refs = rawOut\n\t\t.split(\"\\n\")\n\t\t.filter((line) => line.includes(\"[new branch]\") || line.includes(\"[new tag]\") || line.includes(\"->\"));\n\treturn {\n\t\toutput: refs.length\n\t\t\t? `Fetched:\\n${refs.map((line) => line.trim()).join(\"\\n\")}`\n\t\t\t: \"Fetch successful (no new refs).\",\n\t\texitCode: 0,\n\t\trawOut,\n\t\trawBytes: res.rawBytes,\n\t};\n}\n\nasync function handleBranch(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tif (args.includes(\"--show-current\")) {\n\t\tconst res = await runGitQuery(cwd, globalOptions, [\"branch\", \"--show-current\"], options);\n\t\treturn { output: res.stdout.trim(), exitCode: res.status ?? 0, rawOut: rawText(res), rawBytes: res.rawBytes };\n\t}\n\tconst isWrite = args.some(\n\t\t(arg) =>\n\t\t\targ === \"-d\" || arg === \"-D\" || arg === \"-m\" || arg === \"-M\" || (!arg.startsWith(\"-\") && args.length === 1),\n\t);\n\tif (isWrite) {\n\t\tconst res = await runGitQuery(cwd, globalOptions, [\"branch\", ...args], options);\n\t\tconst rawOut = rawText(res);\n\t\tif (res.status !== 0) return { output: rawOut, exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\t\treturn { output: rawOut.trim() || \"Branch updated successfully.\", exitCode: 0, rawOut, rawBytes: res.rawBytes };\n\t}\n\tconst res = await runGitQuery(cwd, globalOptions, [\"branch\", \"--no-color\", ...args], options);\n\tconst rawOut = rawText(res);\n\tif (res.status !== 0) return { output: rawOut, exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\tconst lines = res.stdout.split(\"\\n\").filter((line) => line.trim().length > 0);\n\tconst remoteBranches = lines.filter((line) => line.includes(\"remotes/\"));\n\tconst localBranches = lines.filter((line) => !line.includes(\"remotes/\"));\n\tconst remoteDisplay = remoteBranches.slice(0, 5);\n\tconst omitted = remoteBranches.length - remoteDisplay.length;\n\tif (omitted > 0) remoteDisplay.push(` remotes/... (${omitted} more remote branches)`);\n\treturn { output: [...localBranches, ...remoteDisplay].join(\"\\n\"), exitCode: 0, rawOut, rawBytes: res.rawBytes };\n}\n\nasync function handleStash(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst sub = args[0] || \"push\";\n\tconst res = await runGitQuery(cwd, globalOptions, [\"stash\", ...args], options);\n\tconst rawOut = rawText(res);\n\tif (res.status !== 0) return { output: rawOut, exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\tif (sub === \"list\")\n\t\treturn { output: res.stdout.trim() || \"No stashes found.\", exitCode: 0, rawOut, rawBytes: res.rawBytes };\n\tif (sub === \"show\") {\n\t\tconst { compacted, truncated } = compactDiff(res.stdout);\n\t\treturn applyOverflowDisclosure(res, {\n\t\t\toutput: `${compacted.trim()}${truncated ? \"\\n\\n[Diff truncated.]\" : \"\"}`,\n\t\t\texitCode: 0,\n\t\t\trawOut,\n\t\t\trawBytes: res.rawBytes,\n\t\t});\n\t}\n\tif (res.stdout.includes(\"No local changes to save\"))\n\t\treturn { output: \"No local changes to save.\", exitCode: 0, rawOut, rawBytes: res.rawBytes };\n\tconst firstLine = res.stdout\n\t\t.split(\"\\n\")\n\t\t.find((line) => line.trim().length > 0)\n\t\t?.trim();\n\treturn { output: firstLine || \"Stash successful.\", exitCode: 0, rawOut, rawBytes: res.rawBytes };\n}\n\nasync function handleWorktree(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst sub = args[0] || \"list\";\n\tconst res = await runGitQuery(cwd, globalOptions, [\"worktree\", ...(sub === \"list\" ? [\"list\"] : args)], options);\n\tconst rawOut = rawText(res, true);\n\tif (res.status !== 0) return { output: rawOut, exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\tif (sub !== \"list\") return { output: rawOut.trim(), exitCode: 0, rawOut, rawBytes: res.rawBytes };\n\tconst home = process.env.HOME || \"\";\n\tconst output = res.stdout\n\t\t.split(\"\\n\")\n\t\t.map((line) => (home && line.startsWith(home) ? `~${line.slice(home.length)}` : line))\n\t\t.join(\"\\n\")\n\t\t.trim();\n\treturn { output, exitCode: 0, rawOut, rawBytes: res.rawBytes };\n}\n\nexport async function executeFilteredGit(\n\tcwd: string,\n\tsubcommand: string,\n\tglobalOptions: string[],\n\tsubcommandArgs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tswitch (subcommand) {\n\t\tcase \"status\":\n\t\t\treturn handleStatus(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"log\":\n\t\t\treturn handleLog(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"diff\":\n\t\t\treturn handleDiff(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"show\":\n\t\t\treturn handleShow(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"add\":\n\t\t\treturn handleAdd(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"commit\":\n\t\t\treturn handleCommit(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"push\":\n\t\t\treturn handlePush(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"pull\":\n\t\t\treturn handlePull(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"branch\":\n\t\t\treturn handleBranch(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"fetch\":\n\t\t\treturn handleFetch(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"stash\":\n\t\t\treturn handleStash(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"worktree\":\n\t\t\treturn handleWorktree(cwd, globalOptions, subcommandArgs, options);\n\t\tdefault:\n\t\t\treturn { output: \"\", exitCode: -100, rawOut: \"\" };\n\t}\n}\n\nexport function makeGitCommandForDisplay(globalOptions: string[], subcommand: string, args: string[]): string {\n\treturn gitCommand(globalOptions, [subcommand, ...args]);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"git-filter.d.ts","sourceRoot":"","sources":["../../../src/core/tools/git-filter.ts"],"names":[],"mappings":"AAyCA,MAAM,WAAW,YAAY;IAC5B,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,mGAAmG;IACnG,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,UAAU,cAAc;IACvB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,mFAAmF;IACnF,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,oFAAoF;IACpF,QAAQ,CAAC,EAAE;QAAE,cAAc,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,CAAA;KAAE,CAAC;CAC1D;AAED,UAAU,gBAAgB;IACzB,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,OAAO,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAA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EAAE,gBAAgB,GACxB,OAAO,CAAC,YAAY,CAAC,CA6BvB;AAED,wBAAgB,wBAAwB,CAAC,aAAa,EAAE,MAAM,EAAE,EAAE,UAAU,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,MAAM,CAE5G","sourcesContent":["import { spawn } from \"node:child_process\";\nimport { randomBytes } from \"node:crypto\";\nimport { existsSync, type WriteStream } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\nimport { waitForChildProcess } from \"../../utils/child-process.ts\";\nimport { createSafeWriteStream } from \"../../utils/safe-write-stream.ts\";\nimport { killProcessTree, trackDetachedChildPid, untrackDetachedChildPid } from \"../../utils/shell.ts\";\n\n/**\n * Retention budget for git output held in memory while filtering. Output beyond\n * the budget is spilled to a temp file so a giant `git log -p`/`git diff` cannot\n * exhaust the V8 heap. Override with PI_GIT_FILTER_MAX_RETAINED_BYTES.\n */\nconst DEFAULT_MAX_RETAINED_GIT_OUTPUT_BYTES = 48 * 1024 * 1024;\nconst MAX_RETAINED_GIT_STDERR_BYTES = 8 * 1024 * 1024;\n\nfunction maxRetainedGitOutputBytes(): number {\n\tconst raw = process.env.PI_GIT_FILTER_MAX_RETAINED_BYTES;\n\tif (raw !== undefined) {\n\t\tconst parsed = Number.parseInt(raw, 10);\n\t\tif (Number.isFinite(parsed) && parsed > 0) return parsed;\n\t}\n\treturn DEFAULT_MAX_RETAINED_GIT_OUTPUT_BYTES;\n}\n\nconst SUPPORTED_SUBCOMMANDS = new Set([\n\t\"status\",\n\t\"log\",\n\t\"diff\",\n\t\"show\",\n\t\"add\",\n\t\"commit\",\n\t\"push\",\n\t\"pull\",\n\t\"branch\",\n\t\"fetch\",\n\t\"stash\",\n\t\"worktree\",\n]);\n\nexport interface FilterResult {\n\toutput: string;\n\texitCode: number;\n\trawOut: string;\n\trawBytes?: Buffer;\n\t/** Set when git output exceeded the in-memory retention budget; the file holds the full output. */\n\tfullOutputPath?: string;\n}\n\ninterface GitQueryResult {\n\tstdout: string;\n\tstderr: string;\n\tstatus: number | null;\n\t/** Full raw output (stderr then stdout). Absent when output overflowed to disk. */\n\trawBytes?: Buffer;\n\t/** Set when stdout exceeded the retention budget and was spilled to a temp file. */\n\toverflow?: { fullOutputPath: string; totalBytes: number };\n}\n\ninterface GitFilterOptions {\n\tsignal?: AbortSignal;\n\ttimeout?: number;\n}\n\nexport function unicodeTruncate(str: string, maxLength: number): string {\n\tconst chars = Array.from(str);\n\tif (chars.length <= maxLength) return str;\n\treturn `${chars.slice(0, maxLength).join(\"\")}...`;\n}\n\nexport function tokenizeCommand(command: string): string[] | null {\n\tconst args: string[] = [];\n\tlet current = \"\";\n\tlet inDoubleQuotes = false;\n\tlet inSingleQuotes = false;\n\tlet escapeNext = false;\n\n\tfor (let i = 0; i < command.length; i++) {\n\t\tconst char = command[i];\n\t\tif (escapeNext) {\n\t\t\tcurrent += char;\n\t\t\tescapeNext = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === \"\\\\\" && !inSingleQuotes) {\n\t\t\tescapeNext = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === '\"' && !inSingleQuotes) {\n\t\t\tinDoubleQuotes = !inDoubleQuotes;\n\t\t} else if (char === \"'\" && !inDoubleQuotes) {\n\t\t\tinSingleQuotes = !inSingleQuotes;\n\t\t} else if (/\\s/.test(char) && !inDoubleQuotes && !inSingleQuotes) {\n\t\t\tif (current) {\n\t\t\t\targs.push(current);\n\t\t\t\tcurrent = \"\";\n\t\t\t}\n\t\t} else {\n\t\t\tcurrent += char;\n\t\t}\n\t}\n\tif (inDoubleQuotes || inSingleQuotes || escapeNext) return null;\n\tif (current) args.push(current);\n\treturn args;\n}\n\nexport interface ParsedCommand {\n\tenvVars: Record<string, string>;\n\tcoreCommandTokens: string[];\n}\n\nexport function parseCommandPrefixes(command: string): ParsedCommand | null {\n\tconst tokens = tokenizeCommand(command);\n\tif (!tokens || tokens.length === 0) return null;\n\n\tconst envVars: Record<string, string> = {};\n\tlet i = 0;\n\tconst envPattern = /^([a-zA-Z_][a-zA-Z0-9_]*)=(.*)$/;\n\n\twhile (i < tokens.length) {\n\t\tconst token = tokens[i];\n\t\tconst match = token.match(envPattern);\n\t\tif (!match) break;\n\t\tlet value = match[2];\n\t\tif ((value.startsWith('\"') && value.endsWith('\"')) || (value.startsWith(\"'\") && value.endsWith(\"'\"))) {\n\t\t\tvalue = value.slice(1, -1);\n\t\t}\n\t\tenvVars[match[1]] = value;\n\t\ti++;\n\t}\n\n\treturn { envVars, coreCommandTokens: tokens.slice(i) };\n}\n\nexport function isComplexShellCommand(command: string): boolean {\n\treturn /[|><&;\\n\\r$`()*?[\\]#]/.test(command);\n}\n\nfunction quoteForShell(arg: string): string {\n\tif (/^[A-Za-z0-9_./:=+-]+$/.test(arg)) return arg;\n\treturn `'${arg.replace(/'/g, `'\"'\"'`)}'`;\n}\n\nfunction gitCommand(globalOptions: string[], args: string[]): string {\n\treturn [\"git\", ...globalOptions, ...args].map(quoteForShell).join(\" \");\n}\n\nfunction rawText(res: GitQueryResult, combine = false): string {\n\tif (combine) return `${res.stderr}${res.stderr && res.stdout ? \"\\n\" : \"\"}${res.stdout}`;\n\treturn res.stderr || res.stdout;\n}\n\nfunction applyOverflowDisclosure(res: GitQueryResult, result: FilterResult): FilterResult {\n\tif (!res.overflow) return result;\n\tconst totalMb = (res.overflow.totalBytes / (1024 * 1024)).toFixed(1);\n\treturn {\n\t\t...result,\n\t\toutput: `${result.output}\\n\\n[git output was ${totalMb}MB; filtered view computed from the retained head. Full output: ${res.overflow.fullOutputPath}]`,\n\t\tfullOutputPath: res.overflow.fullOutputPath,\n\t};\n}\n\nfunction resultFromQuery(res: GitQueryResult, output: string, exitCode = res.status ?? 0): FilterResult {\n\treturn applyOverflowDisclosure(res, { output, exitCode, rawOut: rawText(res), rawBytes: res.rawBytes });\n}\n\nexport async function runGitQuery(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<GitQueryResult> {\n\tif (options?.signal?.aborted) throw new Error(\"aborted\");\n\n\tconst child = spawn(\"git\", [...globalOptions, ...args], {\n\t\tcwd,\n\t\tdetached: process.platform !== \"win32\",\n\t\tenv: { ...process.env, LC_ALL: \"C\" },\n\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\twindowsHide: true,\n\t});\n\tif (child.pid) trackDetachedChildPid(child.pid);\n\n\tconst stdoutChunks: Buffer[] = [];\n\tconst stderrChunks: Buffer[] = [];\n\tconst maxRetainedBytes = maxRetainedGitOutputBytes();\n\tlet retainedStdoutBytes = 0;\n\tlet totalStdoutBytes = 0;\n\tlet retainedStderrBytes = 0;\n\tlet overflowPath: string | undefined;\n\tlet overflowStream: WriteStream | undefined;\n\tlet overflowStreamEnded = false;\n\tlet overflowWriteError: Error | undefined;\n\tlet timedOut = false;\n\tconst timeoutSeconds = options?.timeout;\n\tlet timeoutHandle: NodeJS.Timeout | undefined;\n\tconst killChild = () => {\n\t\tif (child.pid) killProcessTree(child.pid);\n\t};\n\n\ttry {\n\t\tif (timeoutSeconds !== undefined && timeoutSeconds > 0) {\n\t\t\ttimeoutHandle = setTimeout(() => {\n\t\t\t\ttimedOut = true;\n\t\t\t\tkillChild();\n\t\t\t}, timeoutSeconds * 1000);\n\t\t}\n\t\tif (options?.signal) {\n\t\t\tif (options.signal.aborted) killChild();\n\t\t\telse options.signal.addEventListener(\"abort\", killChild, { once: true });\n\t\t}\n\n\t\tchild.stdout?.on(\"data\", (chunk: Buffer) => {\n\t\t\ttotalStdoutBytes += chunk.length;\n\t\t\tif (overflowStream) {\n\t\t\t\toverflowStream.write(chunk);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tstdoutChunks.push(chunk);\n\t\t\tretainedStdoutBytes += chunk.length;\n\t\t\tif (retainedStdoutBytes > maxRetainedBytes) {\n\t\t\t\toverflowPath = join(tmpdir(), `pi-git-${randomBytes(8).toString(\"hex\")}.log`);\n\t\t\t\toverflowStream = createSafeWriteStream(overflowPath, (error) => {\n\t\t\t\t\toverflowWriteError = error;\n\t\t\t\t});\n\t\t\t\tfor (const retained of stdoutChunks) overflowStream.write(retained);\n\t\t\t}\n\t\t});\n\t\tchild.stderr?.on(\"data\", (chunk: Buffer) => {\n\t\t\tstderrChunks.push(chunk);\n\t\t\tretainedStderrBytes += chunk.length;\n\t\t\twhile (retainedStderrBytes > MAX_RETAINED_GIT_STDERR_BYTES && stderrChunks.length > 1) {\n\t\t\t\tretainedStderrBytes -= stderrChunks.shift()?.length ?? 0;\n\t\t\t}\n\t\t});\n\t\tconst status = await waitForChildProcess(child);\n\t\tif (options?.signal?.aborted) throw new Error(\"aborted\");\n\t\tif (timedOut) throw new Error(`timeout:${timeoutSeconds}`);\n\t\tconst stdoutBuffer = Buffer.concat(stdoutChunks);\n\t\tconst stderrBuffer = Buffer.concat(stderrChunks);\n\t\tif (overflowStream !== undefined && overflowPath !== undefined) {\n\t\t\tif (stderrBuffer.length > 0 && !overflowStream.writableEnded) {\n\t\t\t\toverflowStream.write(\"\\n--- stderr ---\\n\");\n\t\t\t\toverflowStream.write(stderrBuffer);\n\t\t\t}\n\t\t\tconst stream = overflowStream;\n\t\t\tawait new Promise<void>((resolveEnd) => {\n\t\t\t\tstream.end(() => resolveEnd());\n\t\t\t});\n\t\t\toverflowStreamEnded = true;\n\t\t\tif (overflowWriteError !== undefined) {\n\t\t\t\t// Spill failed (e.g. disk full): disclose the loss instead of pointing\n\t\t\t\t// consumers at a broken artifact, and keep the retained head usable.\n\t\t\t\treturn {\n\t\t\t\t\tstdout: stdoutBuffer.toString(\"utf-8\"),\n\t\t\t\t\tstderr: `${stderrBuffer.toString(\"utf-8\")}\\n[git output overflow spill failed: ${overflowWriteError.message}; output beyond the retained head was lost]`,\n\t\t\t\t\tstatus,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tstdout: stdoutBuffer.toString(\"utf-8\"),\n\t\t\t\tstderr: stderrBuffer.toString(\"utf-8\"),\n\t\t\t\tstatus,\n\t\t\t\toverflow: { fullOutputPath: overflowPath, totalBytes: totalStdoutBytes },\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tstdout: stdoutBuffer.toString(\"utf-8\"),\n\t\t\tstderr: stderrBuffer.toString(\"utf-8\"),\n\t\t\tstatus,\n\t\t\trawBytes: Buffer.concat([stderrBuffer, stdoutBuffer]),\n\t\t};\n\t} finally {\n\t\tif (child.pid) untrackDetachedChildPid(child.pid);\n\t\tif (timeoutHandle) clearTimeout(timeoutHandle);\n\t\tif (options?.signal) options.signal.removeEventListener(\"abort\", killChild);\n\t\tif (overflowStream !== undefined && !overflowStreamEnded) overflowStream.end();\n\t}\n}\n\nexport function classifyGitCommand(\n\tcommand: string,\n\tparentEnv?: NodeJS.ProcessEnv,\n): {\n\teligible: boolean;\n\tsubcommand?: string;\n\tglobalOptions?: string[];\n\tsubcommandArgs?: string[];\n\tlocalEnv?: Record<string, string>;\n} {\n\tif (isComplexShellCommand(command)) return { eligible: false };\n\n\tconst parsed = parseCommandPrefixes(command);\n\tif (!parsed || parsed.coreCommandTokens.length === 0) return { eligible: false };\n\n\tconst { envVars, coreCommandTokens } = parsed;\n\tconst toolFilterDisabled =\n\t\tprocess.env.PI_TOOL_FILTER_DISABLED === \"1\" ||\n\t\tparentEnv?.PI_TOOL_FILTER_DISABLED === \"1\" ||\n\t\tenvVars.PI_TOOL_FILTER_DISABLED === \"1\";\n\tconst gitFilterDisabled =\n\t\tprocess.env.PI_GIT_FILTER_DISABLED === \"1\" ||\n\t\tparentEnv?.PI_GIT_FILTER_DISABLED === \"1\" ||\n\t\tenvVars.PI_GIT_FILTER_DISABLED === \"1\";\n\tif (toolFilterDisabled || gitFilterDisabled) return { eligible: false };\n\n\tconst envKeys = Object.keys(envVars).filter(\n\t\t(key) => key !== \"PI_TOOL_FILTER_DISABLED\" && key !== \"PI_GIT_FILTER_DISABLED\",\n\t);\n\tif (envKeys.length > 0) return { eligible: false };\n\n\tconst cmdName = coreCommandTokens[0];\n\tif (cmdName !== \"git\" && cmdName !== \"yadm\") return { eligible: false };\n\n\tlet idx = 1;\n\tconst globalOptions: string[] = [];\n\twhile (idx < coreCommandTokens.length) {\n\t\tconst token = coreCommandTokens[idx];\n\t\tif (token === \"-C\" || token === \"-c\" || token === \"--git-dir\" || token === \"--work-tree\") {\n\t\t\tif (idx + 1 >= coreCommandTokens.length) return { eligible: false };\n\t\t\tglobalOptions.push(token, coreCommandTokens[idx + 1]);\n\t\t\tidx += 2;\n\t\t} else if (token.startsWith(\"--git-dir=\") || token.startsWith(\"--work-tree=\")) {\n\t\t\tglobalOptions.push(token);\n\t\t\tidx++;\n\t\t} else if (\n\t\t\ttoken === \"--no-pager\" ||\n\t\t\ttoken === \"--no-optional-locks\" ||\n\t\t\ttoken === \"--bare\" ||\n\t\t\ttoken === \"--literal-pathspecs\"\n\t\t) {\n\t\t\tglobalOptions.push(token);\n\t\t\tidx++;\n\t\t} else {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (idx === coreCommandTokens.length) return { eligible: false };\n\tconst subcommand = coreCommandTokens[idx];\n\tif (!SUPPORTED_SUBCOMMANDS.has(subcommand)) return { eligible: false };\n\n\treturn {\n\t\teligible: true,\n\t\tsubcommand,\n\t\tglobalOptions,\n\t\tsubcommandArgs: coreCommandTokens.slice(idx + 1),\n\t\tlocalEnv: envVars,\n\t};\n}\n\nexport function detectGitState(gitDir: string): string[] {\n\tconst states: string[] = [];\n\tif (!gitDir) return states;\n\tif (existsSync(join(gitDir, \"rebase-merge\")) || existsSync(join(gitDir, \"rebase-apply\"))) {\n\t\tstates.push(\"rebase in progress\");\n\t}\n\tif (existsSync(join(gitDir, \"MERGE_HEAD\"))) states.push(\"merge in progress\");\n\tif (existsSync(join(gitDir, \"CHERRY_PICK_HEAD\"))) states.push(\"cherry-pick in progress\");\n\tif (existsSync(join(gitDir, \"REVERT_HEAD\"))) states.push(\"revert in progress\");\n\tif (existsSync(join(gitDir, \"BISECT_LOG\"))) states.push(\"bisect in progress\");\n\tif (existsSync(join(gitDir, \"applying\"))) states.push(\"am in progress\");\n\treturn states;\n}\n\nasync function handleStatus(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst isSimple =\n\t\targs.length === 0 || args.every((arg) => arg === \"-s\" || arg === \"--short\" || arg === \"-b\" || arg === \"--branch\");\n\n\tif (!isSimple) {\n\t\tconst res = await runGitQuery(cwd, globalOptions, [\"status\", ...args], options);\n\t\tconst rawOut = rawText(res);\n\t\tif (res.status !== 0) return { output: rawOut, exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\t\tconst cleanedLines = res.stdout\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => line.trimEnd())\n\t\t\t.filter((line) => line.length > 0 && !line.trim().startsWith(\"(use \"));\n\t\tconst output = cleanedLines.join(\"\\n\");\n\t\treturn resultFromQuery(res, output || \"success\", 0);\n\t}\n\n\tconst res = await runGitQuery(cwd, globalOptions, [\"status\", \"--porcelain=v1\", \"-b\"], options);\n\tlet rawOut = rawText(res);\n\tif (res.status !== 0) {\n\t\tif (rawOut.includes(\"not a git repository\")) rawOut = \"fatal: not a git repository\";\n\t\treturn { output: rawOut.trim(), exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\t}\n\n\tconst lines = res.stdout.split(\"\\n\").filter((line) => line.trim().length > 0);\n\tlet branchLine = \"\";\n\tconst fileLines: string[] = [];\n\tfor (const line of lines) {\n\t\tif (line.startsWith(\"##\")) branchLine = line;\n\t\telse fileLines.push(line);\n\t}\n\n\tlet statePrefix = \"\";\n\tconst gitDirRes = await runGitQuery(cwd, globalOptions, [\"rev-parse\", \"--git-dir\"], options);\n\tif (gitDirRes.status === 0) {\n\t\tconst gitDir = resolve(cwd, gitDirRes.stdout.trim());\n\t\tconst states = detectGitState(gitDir);\n\t\tif (states.length > 0) statePrefix = `[${states.join(\", \")}]\\n`;\n\t}\n\n\tif (branchLine.includes(\"HEAD (no branch)\")) {\n\t\tconst headHashRes = await runGitQuery(cwd, globalOptions, [\"rev-parse\", \"--short\", \"HEAD\"], options);\n\t\tconst hash = headHashRes.status === 0 ? headHashRes.stdout.trim() : \"unknown\";\n\t\tbranchLine = `## HEAD (detached at ${hash})`;\n\t}\n\n\tif (fileLines.length === 0) {\n\t\treturn resultFromQuery(res, `${statePrefix}${branchLine}\\nnothing to commit, working tree clean`, 0);\n\t}\n\treturn resultFromQuery(res, `${statePrefix}${branchLine}\\n${fileLines.join(\"\\n\")}`, 0);\n}\n\nasync function handleLog(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst hasLimit = args.some(\n\t\t(arg) => /^-n\\d+$/.test(arg) || arg === \"-n\" || /^-?\\d+$/.test(arg) || arg.startsWith(\"--max-count\"),\n\t);\n\tconst hasPretty = args.some(\n\t\t(arg) => arg.startsWith(\"--pretty\") || arg.startsWith(\"--format\") || arg === \"--oneline\",\n\t);\n\n\tconst logArgs = hasLimit ? [\"log\", ...args] : [\"log\", \"-n\", \"10\", \"--no-merges\", ...args];\n\tconst res = await runGitQuery(cwd, globalOptions, logArgs, options);\n\tif (hasPretty) return resultFromQuery(res, rawText(res), res.status ?? 0);\n\n\tconst rawOut = rawText(res);\n\tif (res.status !== 0) return { output: rawOut, exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\n\tconst commits = res.stdout.split(/(?=^commit [0-9a-f]{7,40})/m).filter((commit) => commit.trim().length > 0);\n\tconst compactedCommits: string[] = [];\n\tconst trailerPrefixes = [\n\t\t\"Signed-off-by:\",\n\t\t\"Co-authored-by:\",\n\t\t\"Reported-by:\",\n\t\t\"Reviewed-by:\",\n\t\t\"Tested-by:\",\n\t\t\"Suggested-by:\",\n\t\t\"CC:\",\n\t];\n\n\tfor (const commit of commits) {\n\t\tconst lines = commit.split(\"\\n\");\n\t\tconst commitLine = lines[0];\n\t\tif (!commitLine) continue;\n\t\tconst shortCommitLine = commitLine.replace(/^commit ([0-9a-f]{7})[0-9a-f]+/, \"commit $1\");\n\t\tconst bodyLines: string[] = [];\n\t\tfor (let i = 1; i < lines.length; i++) {\n\t\t\tconst line = lines[i];\n\t\t\tconst trimmed = line.trim();\n\t\t\tif (!trimmed) continue;\n\t\t\tif (line.startsWith(\"Author:\") || line.startsWith(\"Date:\") || line.startsWith(\"Merge:\")) continue;\n\t\t\tif (trailerPrefixes.some((prefix) => trimmed.startsWith(prefix))) continue;\n\t\t\tbodyLines.push(line);\n\t\t}\n\t\tconst displayBody = bodyLines.slice(0, 3).map((line) => unicodeTruncate(line, 160));\n\t\tconst omitted = bodyLines.length - displayBody.length;\n\t\tif (omitted > 0) displayBody.push(` ... (${omitted} lines omitted)`);\n\t\tcompactedCommits.push(`${shortCommitLine}\\n${displayBody.join(\"\\n\")}`);\n\t}\n\n\treturn resultFromQuery(res, compactedCommits.join(\"\\n\\n\"), 0);\n}\n\nexport function compactDiff(diffOutput: string, maxLines = 150): { compacted: string; truncated: boolean } {\n\tconst lines = diffOutput.split(\"\\n\");\n\tconst output: string[] = [];\n\tlet linesCount = 0;\n\tlet truncated = false;\n\tlet contextBuffer: string[] = [];\n\tlet trailingContextRemaining = 0;\n\n\tfor (const line of lines) {\n\t\tif (linesCount >= maxLines) {\n\t\t\ttruncated = true;\n\t\t\tbreak;\n\t\t}\n\t\tif (\n\t\t\tline.startsWith(\"diff --git\") ||\n\t\t\tline.startsWith(\"--- \") ||\n\t\t\tline.startsWith(\"+++ \") ||\n\t\t\tline.startsWith(\"index \")\n\t\t) {\n\t\t\tcontextBuffer = [];\n\t\t\ttrailingContextRemaining = 0;\n\t\t\toutput.push(line);\n\t\t\tlinesCount++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (line.startsWith(\"@@ \")) {\n\t\t\tcontextBuffer = [];\n\t\t\ttrailingContextRemaining = 0;\n\t\t\toutput.push(line);\n\t\t\tlinesCount++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (line.startsWith(\"+\") || line.startsWith(\"-\")) {\n\t\t\tfor (const ctx of contextBuffer) {\n\t\t\t\tif (linesCount >= maxLines) {\n\t\t\t\t\ttruncated = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\toutput.push(ctx);\n\t\t\t\tlinesCount++;\n\t\t\t}\n\t\t\tcontextBuffer = [];\n\t\t\tif (truncated) break;\n\t\t\toutput.push(line);\n\t\t\tlinesCount++;\n\t\t\ttrailingContextRemaining = 3;\n\t\t\tcontinue;\n\t\t}\n\t\tif (line.startsWith(\" \")) {\n\t\t\tif (trailingContextRemaining > 0) {\n\t\t\t\toutput.push(line);\n\t\t\t\tlinesCount++;\n\t\t\t\ttrailingContextRemaining--;\n\t\t\t} else {\n\t\t\t\tcontextBuffer.push(line);\n\t\t\t\tif (contextBuffer.length > 3) contextBuffer.shift();\n\t\t\t}\n\t\t} else {\n\t\t\toutput.push(line);\n\t\t\tlinesCount++;\n\t\t}\n\t}\n\n\treturn { compacted: output.join(\"\\n\"), truncated };\n}\n\nasync function handleDiff(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst cleanArgs = [...args];\n\tconst noCompactIndex = cleanArgs.indexOf(\"--no-compact\");\n\tconst optOut = noCompactIndex !== -1;\n\tif (optOut) cleanArgs.splice(noCompactIndex, 1);\n\n\tconst statFlags = [\"--stat\", \"--numstat\", \"--shortstat\", \"--summary\", \"--name-only\", \"--name-status\", \"--check\"];\n\tconst isStatOnly = cleanArgs.some((arg) => statFlags.includes(arg));\n\tif (optOut || isStatOnly) {\n\t\tconst res = await runGitQuery(cwd, globalOptions, [\"diff\", ...cleanArgs], options);\n\t\treturn resultFromQuery(res, rawText(res), res.status ?? 0);\n\t}\n\n\tconst hasDoubleDash = cleanArgs.includes(\"--\");\n\tif (!hasDoubleDash) {\n\t\tconst pathIdx = cleanArgs.findIndex((arg) => {\n\t\t\tif (arg.startsWith(\"-\")) return false;\n\t\t\tif (!(arg.includes(\"/\") || arg.includes(\".\") || existsSync(join(cwd, arg)))) return false;\n\t\t\treturn existsSync(resolve(cwd, arg));\n\t\t});\n\t\tif (pathIdx !== -1) cleanArgs.splice(pathIdx, 0, \"--\");\n\t}\n\n\tconst statRes = await runGitQuery(cwd, globalOptions, [\"diff\", \"--stat\", ...cleanArgs], options);\n\tif (statRes.status !== 0) return resultFromQuery(statRes, rawText(statRes), statRes.status ?? 1);\n\tconst diffRes = await runGitQuery(cwd, globalOptions, [\"diff\", ...cleanArgs], options);\n\tif (diffRes.status !== 0) return resultFromQuery(diffRes, rawText(diffRes), diffRes.status ?? 1);\n\n\tconst { compacted, truncated } = compactDiff(diffRes.stdout);\n\tlet output = `${statRes.stdout.trimEnd()}\\n\\n${compacted}`.trim();\n\tif (truncated) output += \"\\n\\n[Diff truncated. Re-run with: git diff --no-compact]\";\n\treturn applyOverflowDisclosure(diffRes, { output, exitCode: 0, rawOut: diffRes.stdout, rawBytes: diffRes.rawBytes });\n}\n\nasync function handleShow(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst statFlags = [\"--stat\", \"--numstat\", \"--shortstat\", \"--summary\", \"--name-only\", \"--name-status\", \"--check\"];\n\tconst hasStatOnly = args.some((arg) => statFlags.includes(arg));\n\tconst hasPretty = args.some(\n\t\t(arg) => arg.startsWith(\"--pretty\") || arg.startsWith(\"--format\") || arg === \"--oneline\",\n\t);\n\tconst hasBlob = args.some((arg) => !arg.startsWith(\"-\") && arg.includes(\":\"));\n\tif (hasStatOnly || hasPretty || hasBlob) {\n\t\tconst res = await runGitQuery(cwd, globalOptions, [\"show\", ...args], options);\n\t\treturn resultFromQuery(res, rawText(res), res.status ?? 0);\n\t}\n\n\tconst showRes = await runGitQuery(cwd, globalOptions, [\"show\", ...args], options);\n\tconst rawOut = rawText(showRes);\n\tif (showRes.status !== 0)\n\t\treturn { output: rawOut, exitCode: showRes.status ?? 1, rawOut, rawBytes: showRes.rawBytes };\n\n\tconst lines = showRes.stdout.split(\"\\n\");\n\tconst diffStart = lines.findIndex((line) => line.startsWith(\"diff --git\"));\n\tconst headerLines = diffStart === -1 ? lines : lines.slice(0, diffStart);\n\tconst diffLines = diffStart === -1 ? [] : lines.slice(diffStart);\n\tconst summaryLines = headerLines.filter((line) => {\n\t\tconst trimmed = line.trim();\n\t\tif (!trimmed) return false;\n\t\tif (line.startsWith(\"Author:\") || line.startsWith(\"Date:\") || line.startsWith(\"Merge:\")) return false;\n\t\treturn true;\n\t});\n\tconst shortSummary = summaryLines\n\t\t.slice(0, 4)\n\t\t.map((line) => unicodeTruncate(line.replace(/^commit ([0-9a-f]{7})[0-9a-f]+/, \"commit $1\"), 160));\n\tconst { compacted, truncated } = compactDiff(diffLines.join(\"\\n\"));\n\tlet output = shortSummary.join(\"\\n\");\n\tif (compacted.trim()) output += `\\n\\n${compacted}`;\n\tif (truncated) output += \"\\n\\n[Diff truncated.]\";\n\treturn resultFromQuery(showRes, output.trim(), 0);\n}\n\nasync function handlePassthroughGit(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst res = await runGitQuery(cwd, globalOptions, args, options);\n\treturn resultFromQuery(res, rawText(res, true).trim(), res.status ?? 0);\n}\n\nasync function handleAdd(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tif (args.length === 0) return handlePassthroughGit(cwd, globalOptions, [\"add\"], options);\n\tconst addRes = await runGitQuery(cwd, globalOptions, [\"add\", ...args], options);\n\tconst rawOut = rawText(addRes);\n\tif (addRes.status !== 0) return { output: rawOut, exitCode: addRes.status ?? 1, rawOut, rawBytes: addRes.rawBytes };\n\tconst statRes = await runGitQuery(cwd, globalOptions, [\"diff\", \"--cached\", \"--stat\"], options);\n\tif (statRes.status === 0 && statRes.stdout.trim().length > 0) {\n\t\treturn { output: `Staged changes:\\n${statRes.stdout.trim()}`, exitCode: 0, rawOut, rawBytes: addRes.rawBytes };\n\t}\n\treturn { output: rawOut.trim() || \"Successfully staged.\", exitCode: 0, rawOut, rawBytes: addRes.rawBytes };\n}\n\nasync function handleCommit(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst hasMsg = args.some(\n\t\t(arg) => arg === \"-m\" || arg === \"-F\" || arg.startsWith(\"--message\") || arg.startsWith(\"--file\"),\n\t);\n\tif (!hasMsg) return { output: \"\", exitCode: -100, rawOut: \"\" };\n\tconst res = await runGitQuery(cwd, globalOptions, [\"commit\", ...args], options);\n\tconst rawOut = rawText(res, true);\n\tif (res.status !== 0) return { output: rawOut, exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\tif (rawOut.includes(\"nothing to commit\") || rawOut.includes(\"working tree clean\")) {\n\t\treturn { output: \"nothing to commit, working tree clean\", exitCode: 0, rawOut, rawBytes: res.rawBytes };\n\t}\n\tconst firstLine = rawOut\n\t\t.split(\"\\n\")\n\t\t.find((line) => line.trim().length > 0)\n\t\t?.trim();\n\treturn { output: firstLine || \"Committed successfully.\", exitCode: 0, rawOut, rawBytes: res.rawBytes };\n}\n\nasync function handlePush(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst res = await runGitQuery(cwd, globalOptions, [\"push\", ...args], options);\n\tconst rawOut = rawText(res, true);\n\tconst outputLines = rawOut\n\t\t.split(\"\\n\")\n\t\t.map((line) => line.trimEnd())\n\t\t.filter((line) => {\n\t\t\tconst trimmed = line.trim();\n\t\t\tif (!trimmed) return false;\n\t\t\treturn ![\"Writing objects:\", \"Counting objects:\", \"Delta compression\", \"Compressing objects:\", \"Total \"].some(\n\t\t\t\t(prefix) => trimmed.startsWith(prefix),\n\t\t\t);\n\t\t});\n\tif (res.status !== 0)\n\t\treturn { output: outputLines.join(\"\\n\"), exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\tif (outputLines.some((line) => line.includes(\"Everything up-to-date\"))) {\n\t\treturn { output: \"Everything up-to-date.\", exitCode: 0, rawOut, rawBytes: res.rawBytes };\n\t}\n\tconst remoteMessages = outputLines.filter((line) => line.trim().startsWith(\"remote:\"));\n\tconst pushDetail = outputLines.find((line) => line.includes(\"->\"));\n\tconst summary = pushDetail ? `Pushed: ${pushDetail.trim()}` : \"Push successful.\";\n\treturn { output: [...remoteMessages, summary].join(\"\\n\"), exitCode: 0, rawOut, rawBytes: res.rawBytes };\n}\n\nasync function handlePull(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst res = await runGitQuery(cwd, globalOptions, [\"pull\", ...args], options);\n\tconst rawOut = rawText(res, true);\n\tif (res.status !== 0) return { output: rawOut, exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\tif (rawOut.includes(\"Already up to date.\"))\n\t\treturn { output: \"Already up to date.\", exitCode: 0, rawOut, rawBytes: res.rawBytes };\n\tconst lines = rawOut.split(\"\\n\");\n\tconst summary = lines.filter(\n\t\t(line) => line.includes(\"Fast-forward\") || line.includes(\"file changed\") || line.includes(\"files changed\"),\n\t);\n\treturn { output: summary.join(\"\\n\") || \"Pull successful.\", exitCode: 0, rawOut, rawBytes: res.rawBytes };\n}\n\nasync function handleFetch(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst res = await runGitQuery(cwd, globalOptions, [\"fetch\", ...args], options);\n\tconst rawOut = rawText(res, true);\n\tif (res.status !== 0) return { output: rawOut, exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\tconst refs = rawOut\n\t\t.split(\"\\n\")\n\t\t.filter((line) => line.includes(\"[new branch]\") || line.includes(\"[new tag]\") || line.includes(\"->\"));\n\treturn {\n\t\toutput: refs.length\n\t\t\t? `Fetched:\\n${refs.map((line) => line.trim()).join(\"\\n\")}`\n\t\t\t: \"Fetch successful (no new refs).\",\n\t\texitCode: 0,\n\t\trawOut,\n\t\trawBytes: res.rawBytes,\n\t};\n}\n\nasync function handleBranch(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tif (args.includes(\"--show-current\")) {\n\t\tconst res = await runGitQuery(cwd, globalOptions, [\"branch\", \"--show-current\"], options);\n\t\treturn { output: res.stdout.trim(), exitCode: res.status ?? 0, rawOut: rawText(res), rawBytes: res.rawBytes };\n\t}\n\tconst isWrite = args.some(\n\t\t(arg) =>\n\t\t\targ === \"-d\" || arg === \"-D\" || arg === \"-m\" || arg === \"-M\" || (!arg.startsWith(\"-\") && args.length === 1),\n\t);\n\tif (isWrite) {\n\t\tconst res = await runGitQuery(cwd, globalOptions, [\"branch\", ...args], options);\n\t\tconst rawOut = rawText(res);\n\t\tif (res.status !== 0) return { output: rawOut, exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\t\treturn { output: rawOut.trim() || \"Branch updated successfully.\", exitCode: 0, rawOut, rawBytes: res.rawBytes };\n\t}\n\tconst res = await runGitQuery(cwd, globalOptions, [\"branch\", \"--no-color\", ...args], options);\n\tconst rawOut = rawText(res);\n\tif (res.status !== 0) return { output: rawOut, exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\tconst lines = res.stdout.split(\"\\n\").filter((line) => line.trim().length > 0);\n\tconst remoteBranches = lines.filter((line) => line.includes(\"remotes/\"));\n\tconst localBranches = lines.filter((line) => !line.includes(\"remotes/\"));\n\tconst remoteDisplay = remoteBranches.slice(0, 5);\n\tconst omitted = remoteBranches.length - remoteDisplay.length;\n\tif (omitted > 0) remoteDisplay.push(` remotes/... (${omitted} more remote branches)`);\n\treturn { output: [...localBranches, ...remoteDisplay].join(\"\\n\"), exitCode: 0, rawOut, rawBytes: res.rawBytes };\n}\n\nasync function handleStash(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst sub = args[0] || \"push\";\n\tconst res = await runGitQuery(cwd, globalOptions, [\"stash\", ...args], options);\n\tconst rawOut = rawText(res);\n\tif (res.status !== 0) return { output: rawOut, exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\tif (sub === \"list\")\n\t\treturn { output: res.stdout.trim() || \"No stashes found.\", exitCode: 0, rawOut, rawBytes: res.rawBytes };\n\tif (sub === \"show\") {\n\t\tconst { compacted, truncated } = compactDiff(res.stdout);\n\t\treturn applyOverflowDisclosure(res, {\n\t\t\toutput: `${compacted.trim()}${truncated ? \"\\n\\n[Diff truncated.]\" : \"\"}`,\n\t\t\texitCode: 0,\n\t\t\trawOut,\n\t\t\trawBytes: res.rawBytes,\n\t\t});\n\t}\n\tif (res.stdout.includes(\"No local changes to save\"))\n\t\treturn { output: \"No local changes to save.\", exitCode: 0, rawOut, rawBytes: res.rawBytes };\n\tconst firstLine = res.stdout\n\t\t.split(\"\\n\")\n\t\t.find((line) => line.trim().length > 0)\n\t\t?.trim();\n\treturn { output: firstLine || \"Stash successful.\", exitCode: 0, rawOut, rawBytes: res.rawBytes };\n}\n\nasync function handleWorktree(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst sub = args[0] || \"list\";\n\tconst res = await runGitQuery(cwd, globalOptions, [\"worktree\", ...(sub === \"list\" ? [\"list\"] : args)], options);\n\tconst rawOut = rawText(res, true);\n\tif (res.status !== 0) return { output: rawOut, exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\tif (sub !== \"list\") return { output: rawOut.trim(), exitCode: 0, rawOut, rawBytes: res.rawBytes };\n\tconst home = process.env.HOME || \"\";\n\tconst output = res.stdout\n\t\t.split(\"\\n\")\n\t\t.map((line) => (home && line.startsWith(home) ? `~${line.slice(home.length)}` : line))\n\t\t.join(\"\\n\")\n\t\t.trim();\n\treturn { output, exitCode: 0, rawOut, rawBytes: res.rawBytes };\n}\n\nexport async function executeFilteredGit(\n\tcwd: string,\n\tsubcommand: string,\n\tglobalOptions: string[],\n\tsubcommandArgs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tswitch (subcommand) {\n\t\tcase \"status\":\n\t\t\treturn handleStatus(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"log\":\n\t\t\treturn handleLog(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"diff\":\n\t\t\treturn handleDiff(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"show\":\n\t\t\treturn handleShow(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"add\":\n\t\t\treturn handleAdd(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"commit\":\n\t\t\treturn handleCommit(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"push\":\n\t\t\treturn handlePush(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"pull\":\n\t\t\treturn handlePull(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"branch\":\n\t\t\treturn handleBranch(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"fetch\":\n\t\t\treturn handleFetch(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"stash\":\n\t\t\treturn handleStash(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"worktree\":\n\t\t\treturn handleWorktree(cwd, globalOptions, subcommandArgs, options);\n\t\tdefault:\n\t\t\treturn { output: \"\", exitCode: -100, rawOut: \"\" };\n\t}\n}\n\nexport function makeGitCommandForDisplay(globalOptions: string[], subcommand: string, args: string[]): string {\n\treturn gitCommand(globalOptions, [subcommand, ...args]);\n}\n"]}
|