Skip to content

Non-invasive MCP accelerator plugin for Google Antigravity (CLI/Desktop/IDE): cuts LLM turns (-34%), token quota (-31%), and upload traffic (-40%) without affecting native UI or diffs.

feat(apply-edits): diagnose tab-vs-space and indentation mismatches with visible tab markers

wathing-wind51858b41888e
diff --git a/dist/mcp-server.mjs b/dist/mcp-server.mjs
index 0f2e711..a33db2c 100755
--- a/dist/mcp-server.mjs
+++ b/dist/mcp-server.mjs
@@ -2747,37 +2747,297 @@ function getLineWindowOffsets(text, lineStarts, startLine, endLine) {
}
var MAX_NEARBY_LINES = 26;
var MAX_DRIFT_RECOVERY_LINES = 50;
-function formatNearbyLines(text, startLine, endLine) {
+var MAX_WS_SCAN_LINES = 5e4;
+var MAX_WS_COMPARISONS = 2e5;
+var MAX_EXTRA_WS_MATCHES = 50;
+var MAX_CLOSEST_EVALUATIONS = 2e3;
+var HUGE_FILE_FALLBACK_WINDOW_RADIUS = 2e3;
+var TAB_MARKER_LEGEND = " (\u2192 = \\t tab; use real \\t in target, not \u2192)";
+function regionHasLeadingTab(fileLines, from, to) {
+ for (let ln = from; ln <= to; ln++) {
+ const lineText = fileLines[ln - 1] ?? "";
+ if (/^ *\t/.test(lineText)) return true;
+ }
+ return false;
+}
+function fileHasLeadingTabSample(fileLines, startIdx = 0, endIdx = fileLines.length - 1) {
+ const from = Math.max(0, startIdx);
+ const to = Math.min(fileLines.length - 1, endIdx, from + 5e3 - 1);
+ for (let idx = from; idx <= to; idx++) {
+ if (/^ *\t/.test(fileLines[idx] ?? "")) return true;
+ }
+ return false;
+}
+function hasLeadingTabDisplayMarker(text) {
+ return /(?:^|\n)[\t ]*→/.test(text);
+}
+function stripLeadingTabDisplayMarkers(line) {
+ return line.replace(/^[\t →]+/, (ws) => ws.replace(/→/g, " "));
+}
+function renderSnippetLine(lineText, showLeadingTabs) {
+ const rendered = showLeadingTabs ? lineText.replace(/^[\t ]+/, (ws) => ws.replace(/\t/g, "\u2192")) : lineText;
+ return rendered.length > 160 ? `${sliceSafeChars(rendered, 157)}...` : rendered;
+}
+function formatNearbyLines(fileLines, startLine, endLine) {
if (startLine === void 0 && endLine === void 0) return "";
- const lines = text.split("\n");
- if (lines.at(-1) === "") lines.pop();
const from = Math.max(1, (startLine ?? endLine ?? 1) - 2);
- const rawTo = Math.min(lines.length, (endLine ?? startLine ?? 1) + 2);
+ const rawTo = Math.min(fileLines.length, (endLine ?? startLine ?? 1) + 2);
if (from > rawTo) return "";
const truncated = rawTo - from + 1 > MAX_NEARBY_LINES;
const to = truncated ? from + MAX_NEARBY_LINES - 1 : rawTo;
+ const showLeadingTabs = regionHasLeadingTab(fileLines, from, to);
+ const tabLegend = showLeadingTabs ? TAB_MARKER_LEGEND : "";
const snippet = [];
for (let ln = from; ln <= to; ln++) {
- const lineText = lines[ln - 1] ?? "";
- snippet.push(
- ` ${ln}: ${lineText.length > 160 ? `${sliceSafeChars(lineText, 157)}...` : lineText}`
- );
+ const lineText = fileLines[ln - 1] ?? "";
+ snippet.push(` ${ln}: ${renderSnippetLine(lineText, showLeadingTabs)}`);
}
const extra = truncated ? `
... (${rawTo - to} more lines in range omitted)` : "";
return `
- Nearby lines (${from}-${to}):
+ Nearby lines (${from}-${to})${tabLegend}:
${snippet.join("\n")}${extra}`;
}
+function detectWhitespaceMismatchHint(fileLines, normTarget, rangeStartLine, rangeEndLine, outsideRangeLabel = false, preTrimmedFileLines) {
+ if (fileLines.length === 0 || !normTarget) return null;
+ const rawTargetLines = normTarget.split("\n");
+ if (normTarget.endsWith("\n") && rawTargetLines.length > 1) {
+ rawTargetLines.pop();
+ }
+ const m = rawTargetLines.length;
+ if (m === 0) return null;
+ const scanStart = Math.max(0, (rangeStartLine ?? 1) - 1);
+ const scanEnd = Math.min(
+ fileLines.length - 1,
+ (rangeEndLine ?? fileLines.length) - 1
+ );
+ if (scanStart > scanEnd) return null;
+ const scanLen = scanEnd - scanStart + 1;
+ if (scanLen < m) return null;
+ const hasLeadingArrow = hasLeadingTabDisplayMarker(normTarget);
+ const allowLocationlessArrowFallback = outsideRangeLabel || rangeStartLine === void 0 && rangeEndLine === void 0;
+ if (scanLen > MAX_WS_SCAN_LINES) {
+ if (hasLeadingArrow && allowLocationlessArrowFallback && fileHasLeadingTabSample(fileLines, scanStart, scanEnd)) {
+ return " Target contains literal '\u2192' tab display markers; replace them with real '\\t' tab characters.";
+ }
+ return null;
+ }
+ const hasValidPreTrimmed = preTrimmedFileLines !== void 0 && preTrimmedFileLines.length === fileLines.length;
+ let localTrimmed = null;
+ const getTrimmed = (idx) => {
+ if (hasValidPreTrimmed) return preTrimmedFileLines[idx];
+ if (localTrimmed === null) {
+ localTrimmed = new Array(scanLen);
+ }
+ const rel = idx - scanStart;
+ let val = localTrimmed[rel];
+ if (val === void 0) {
+ val = fileLines[idx].trim();
+ localTrimmed[rel] = val;
+ }
+ return val;
+ };
+ let comparisons = 0;
+ const pickAnchor = (trimmedTarget) => {
+ let anchorIdx = 0;
+ let bestScore = -1;
+ for (let k = 0; k < m; k++) {
+ const line = trimmedTarget[k];
+ if (line.length === 0) continue;
+ const hasIdentifier = /[A-Za-z0-9_$\u4e00-\u9fff]/.test(line);
+ const score = line.length + (hasIdentifier ? 1e3 : 0);
+ if (score > bestScore) {
+ bestScore = score;
+ anchorIdx = k;
+ }
+ }
+ return { idx: anchorIdx, text: trimmedTarget[anchorIdx] };
+ };
+ const classifyMismatch = (startIdx, effectiveTargetLines, trimmedTarget, isArrowPass) => {
+ let literalTabMarkerInTabFile = false;
+ let literalTabMarkerInSpaceFile = false;
+ let literalTabMarkerOther = false;
+ let fileTabsTargetSpaces = false;
+ let fileSpacesTargetTabs = false;
+ let mixedTabSpace = false;
+ let indentWidthDiff = false;
+ let trailingWhitespaceDiff = false;
+ for (let k = 0; k < m; k++) {
+ const fLine = fileLines[startIdx + k];
+ const rawLine = rawTargetLines[k];
+ if (fLine === rawLine) continue;
+ const effLine = effectiveTargetLines[k];
+ const lineHasArrow = isArrowPass && /^[\t ]*→/.test(rawLine);
+ if (trimmedTarget[k].length === 0) {
+ if (lineHasArrow) {
+ if (fLine.includes(" ")) {
+ literalTabMarkerInTabFile = true;
+ } else if (fLine.includes(" ")) {
+ literalTabMarkerInSpaceFile = true;
+ } else {
+ literalTabMarkerOther = true;
+ }
+ }
+ if (fLine !== effLine) {
+ trailingWhitespaceDiff = true;
+ }
+ continue;
+ }
+ const fLead = /^[\t ]*/.exec(fLine)[0];
+ const tLead = /^[\t ]*/.exec(effLine)[0];
+ const fTrail = /[\t ]*$/.exec(fLine)[0];
+ const tTrail = /[\t ]*$/.exec(effLine)[0];
+ if (lineHasArrow) {
+ if (fLead.includes(" ")) {
+ literalTabMarkerInTabFile = true;
+ } else if (fLead.includes(" ")) {
+ literalTabMarkerInSpaceFile = true;
+ } else {
+ literalTabMarkerOther = true;
+ }
+ }
+ if (fLead !== tLead) {
+ const fHasTab = fLead.includes(" ");
+ const tHasTab = tLead.includes(" ");
+ const fHasSpace = fLead.includes(" ");
+ const tHasSpace = tLead.includes(" ");
+ const rawLead = lineHasArrow ? /^[\t →]*/.exec(rawLine)[0] : "";
+ const arrowOnlyNonTabConflict = lineHasArrow && !fHasTab && !rawLead.includes(" ");
+ if (!arrowOnlyNonTabConflict) {
+ if (fHasTab && fHasSpace || tHasTab && tHasSpace) {
+ mixedTabSpace = true;
+ } else if (fHasTab && !fHasSpace && !tHasTab && tHasSpace) {
+ fileTabsTargetSpaces = true;
+ } else if (!fHasTab && fHasSpace && tHasTab && !tHasSpace) {
+ fileSpacesTargetTabs = true;
+ } else {
+ indentWidthDiff = true;
+ }
+ }
+ }
+ if (fTrail !== tTrail) {
+ trailingWhitespaceDiff = true;
+ }
+ }
+ const reasons = [];
+ if (literalTabMarkerInTabFile) {
+ reasons.push(
+ "target contains literal '\u2192' tab display markers; replace them with real '\\t' tab characters"
+ );
+ } else if (literalTabMarkerInSpaceFile) {
+ reasons.push(
+ "target contains literal '\u2192' tab display markers (file uses spaces, not tabs)"
+ );
+ } else if (literalTabMarkerOther) {
+ reasons.push("target contains literal '\u2192' tab display markers");
+ }
+ if (mixedTabSpace || fileTabsTargetSpaces && fileSpacesTargetTabs) {
+ reasons.push("mixed tab/space indentation");
+ } else if (fileTabsTargetSpaces) {
+ reasons.push("file uses tabs (\\t), target used spaces");
+ } else if (fileSpacesTargetTabs) {
+ reasons.push("file uses spaces, target used tabs (\\t)");
+ } else if (indentWidthDiff) {
+ reasons.push("indentation width mismatch");
+ }
+ if (trailingWhitespaceDiff) {
+ reasons.push("trailing horizontal whitespace mismatch");
+ }
+ return reasons;
+ };
+ const scanPass = (effectiveTargetLines, trimmedTarget, isArrowPass) => {
+ if (!trimmedTarget.some((l) => l.length > 0)) return null;
+ const anchor = pickAnchor(trimmedTarget);
+ const lastStart = scanEnd - m + 1;
+ let firstMatch = null;
+ let extraMatches = 0;
+ let cappedExtra = false;
+ for (let i = scanStart; i <= lastStart; i++) {
+ if (comparisons >= MAX_WS_COMPARISONS) {
+ if (firstMatch && extraMatches > 0) cappedExtra = true;
+ break;
+ }
+ comparisons++;
+ if (getTrimmed(i + anchor.idx) !== anchor.text) continue;
+ let matched = true;
+ let hitCap = false;
+ for (let k = 0; k < m; k++) {
+ if (k === anchor.idx) continue;
+ if (comparisons >= MAX_WS_COMPARISONS) {
+ matched = false;
+ hitCap = true;
+ break;
+ }
+ comparisons++;
+ if (getTrimmed(i + k) !== trimmedTarget[k]) {
+ matched = false;
+ break;
+ }
+ }
+ if (hitCap) {
+ if (firstMatch && extraMatches > 0) cappedExtra = true;
+ break;
+ }
+ if (!matched) continue;
+ if (!firstMatch) {
+ const reasons = classifyMismatch(i, effectiveTargetLines, trimmedTarget, isArrowPass);
+ if (reasons.length === 0) continue;
+ firstMatch = { startIdx: i, reasons };
+ } else {
+ let differs = false;
+ for (let k = 0; k < m; k++) {
+ if (fileLines[i + k] !== rawTargetLines[k]) {
+ differs = true;
+ break;
+ }
+ }
+ if (!differs) continue;
+ if (extraMatches >= MAX_EXTRA_WS_MATCHES) {
+ cappedExtra = true;
+ break;
+ }
+ extraMatches++;
+ }
+ }
+ if (!firstMatch) return null;
+ const startLn = firstMatch.startIdx + 1;
+ const endLn = firstMatch.startIdx + m;
+ const loc = startLn === endLn ? `L${startLn}` : `L${startLn}-L${endLn}`;
+ const moreSuffix = extraMatches > 0 ? ` (+${extraMatches}${cappedExtra ? "+" : ""} more)` : "";
+ const scopePrefix = outsideRangeLabel ? " outside range" : "";
+ return ` Whitespace mismatch${scopePrefix} at ${loc}${moreSuffix}: ${firstMatch.reasons.join("; ")}.`;
+ };
+ const rawTrimmedTarget = rawTargetLines.map((l) => l.trim());
+ const rawMatch = scanPass(rawTargetLines, rawTrimmedTarget, false);
+ if (rawMatch) return rawMatch;
+ if (hasLeadingArrow) {
+ const unmarkedTargetLines = rawTargetLines.map(stripLeadingTabDisplayMarkers);
+ const unmarkedTrimmedTarget = unmarkedTargetLines.map((l) => l.trim());
+ const arrowMatch = scanPass(unmarkedTargetLines, unmarkedTrimmedTarget, true);
+ if (arrowMatch) return arrowMatch;
+ if (allowLocationlessArrowFallback && fileHasLeadingTabSample(fileLines, scanStart, scanEnd)) {
+ return " Target contains literal '\u2192' tab display markers; replace them with real '\\t' tab characters.";
+ }
+ }
+ return null;
+}
function extractLineTokens(trimmedLine) {
const tokens = trimmedLine.match(/[A-Za-z0-9_$]{3,}|[\u4e00-\u9fff]{2,}/g);
if (tokens && tokens.length > 0) return tokens;
return trimmedLine.split(/\s+/).map((s) => s.trim()).filter((s) => s.length >= 2);
}
-function findClosestRegionSnippet(normalizedContent, normTarget, rangeStartLine, rangeEndLine) {
- const fileLines = normalizedContent.split("\n");
+function findClosestRegionSnippet(fileLines, normTarget, rangeStartLine, rangeEndLine, preTrimmedFileLines) {
if (fileLines.length === 0) return "";
- const targetLines = normTarget.split("\n").map((l) => l.trim()).filter((l) => l.length > 0);
+ const scanStart = Math.max(0, (rangeStartLine ?? 1) - 1);
+ const scanEnd = Math.min(
+ fileLines.length - 1,
+ (rangeEndLine ?? fileLines.length) - 1
+ );
+ if (scanStart > scanEnd) return "";
+ const scanLen = scanEnd - scanStart + 1;
+ if (scanLen > MAX_WS_SCAN_LINES) return "";
+ const normalizeArrows = hasLeadingTabDisplayMarker(normTarget) && fileHasLeadingTabSample(fileLines, scanStart, scanEnd);
+ const targetLines = normTarget.split("\n").map((l) => (normalizeArrows ? stripLeadingTabDisplayMarkers(l) : l).trim()).filter((l) => l.length > 0);
if (targetLines.length === 0) return "";
let firstAnchorIdx = 0;
for (let idx = 0; idx < targetLines.length; idx++) {
@@ -2803,13 +3063,21 @@ function findClosestRegionSnippet(normalizedContent, normTarget, rangeStartLine,
tokens: new Set(extractLineTokens(targetLines[idx]))
}));
const targetTokenSets = targetLines.map((tl) => new Set(extractLineTokens(tl)));
- const trimmedFileLines = fileLines.map((l) => l.trim());
- const scanStart = Math.max(0, (rangeStartLine ?? 1) - 1);
- const scanEnd = Math.min(
- trimmedFileLines.length - 1,
- (rangeEndLine ?? trimmedFileLines.length) - 1
- );
- if (scanStart > scanEnd) return "";
+ const hasValidPreTrimmed = preTrimmedFileLines !== void 0 && preTrimmedFileLines.length === fileLines.length;
+ let localTrimmed = null;
+ const getTrimmed = (idx) => {
+ if (hasValidPreTrimmed) return preTrimmedFileLines[idx];
+ if (localTrimmed === null) {
+ localTrimmed = new Array(scanLen);
+ }
+ const rel = idx - scanStart;
+ let val = localTrimmed[rel];
+ if (val === void 0) {
+ val = fileLines[idx].trim();
+ localTrimmed[rel] = val;
+ }
+ return val;
+ };
const evaluatedStarts = /* @__PURE__ */ new Set();
let bestStart = -1;
let bestScore = 0;
@@ -2827,8 +3095,8 @@ function findClosestRegionSnippet(normalizedContent, normTarget, rangeStartLine,
let total = 0;
for (const k of scoreIndices) {
const fIdx = candStart + k;
- if (fIdx > scanEnd || fIdx >= trimmedFileLines.length) continue;
- const fLine = trimmedFileLines[fIdx];
+ if (fIdx > scanEnd || fIdx >= fileLines.length) continue;
+ const fLine = getTrimmed(fIdx);
const tLine = targetLines[k];
if (!fLine || !tLine) continue;
const tTokens = targetTokenSets[k];
@@ -2850,8 +3118,8 @@ function findClosestRegionSnippet(normalizedContent, normTarget, rangeStartLine,
}
return total;
};
- for (let i = scanStart; i <= scanEnd; i++) {
- const line = trimmedFileLines[i];
+ for (let i = scanStart; i <= scanEnd && evaluatedStarts.size < MAX_CLOSEST_EVALUATIONS; i++) {
+ const line = getTrimmed(i);
if (!line) continue;
for (const anchor of anchors) {
let matchedAnchor = false;
@@ -2876,21 +3144,22 @@ function findClosestRegionSnippet(normalizedContent, normTarget, rangeStartLine,
bestScore = score;
bestStart = candStart;
}
+ if (evaluatedStarts.size >= MAX_CLOSEST_EVALUATIONS) break;
}
}
if (bestStart < 0 || bestScore < 2.5) return "";
const span = Math.min(Math.max(targetLines.length, 4), 8);
const from = Math.max(1, bestStart + 1 - 2);
const to = Math.min(fileLines.length, Math.min(from + 13, bestStart + 1 + span + 2));
+ const showLeadingTabs = regionHasLeadingTab(fileLines, from, to);
+ const tabLegend = showLeadingTabs ? TAB_MARKER_LEGEND : "";
const snippet = [];
for (let ln = from; ln <= to; ln++) {
const lineText = fileLines[ln - 1] ?? "";
- snippet.push(
- ` ${ln}: ${lineText.length > 160 ? `${sliceSafeChars(lineText, 157)}...` : lineText}`
- );
+ snippet.push(` ${ln}: ${renderSnippetLine(lineText, showLeadingTabs)}`);
}
return `
- Closest match near line ${bestStart + 1} (lines ${from}-${to}):
+ Closest match near line ${bestStart + 1} (lines ${from}-${to})${tabLegend}:
${snippet.join("\n")}`;
}
function planHunksForContent(normalizedContent, hunks, displayPath) {
@@ -2901,6 +3170,29 @@ function planHunksForContent(normalizedContent, hunks, displayPath) {
const spans = [];
const shiftedHunks = [];
const errors = [];
+ let cachedFileLines = null;
+ let cachedTrimmedFileLines = null;
+ const getFileLines = () => {
+ if (cachedFileLines === null) {
+ if (normalizedContent.length === 0) {
+ cachedFileLines = [];
+ } else {
+ cachedFileLines = normalizedContent.split("\n");
+ if (normalizedContent.endsWith("\n") && cachedFileLines.length > 1) {
+ cachedFileLines.pop();
+ }
+ }
+ }
+ return cachedFileLines;
+ };
+ const getTrimmedFileLines = () => {
+ const lines = getFileLines();
+ if (lines.length > MAX_WS_SCAN_LINES) return void 0;
+ if (cachedTrimmedFileLines === null) {
+ cachedTrimmedFileLines = lines.map((l) => l.trim());
+ }
+ return cachedTrimmedFileLines;
+ };
for (let idx = 0; idx < hunks.length; idx++) {
const hunk = hunks[idx];
if (!isPlainObject(hunk)) {
@@ -3004,14 +3296,64 @@ function planHunksForContent(normalizedContent, hunks, displayPath) {
}
const effStart = hunk.startLine ?? 1;
const effEnd = hunk.endLine ?? lineStarts.length;
+ const fileLines = getFileLines();
+ const trimmedFileLines = getTrimmedFileLines();
+ const outStart = fileLines.length > MAX_WS_SCAN_LINES ? Math.max(1, effStart - HUGE_FILE_FALLBACK_WINDOW_RADIUS) : void 0;
+ const outEnd = fileLines.length > MAX_WS_SCAN_LINES ? Math.min(fileLines.length, effEnd + HUGE_FILE_FALLBACK_WINDOW_RADIUS) : void 0;
+ const wsHint = detectWhitespaceMismatchHint(
+ fileLines,
+ normTarget,
+ effStart,
+ effEnd,
+ false,
+ trimmedFileLines
+ ) || detectWhitespaceMismatchHint(
+ fileLines,
+ normTarget,
+ outStart,
+ outEnd,
+ true,
+ trimmedFileLines
+ ) || "";
+ let snippetHint;
if (effEnd - effStart + 1 > MAX_NEARBY_LINES - 4) {
- hint += findClosestRegionSnippet(normalizedContent, normTarget, effStart, effEnd) || findClosestRegionSnippet(normalizedContent, normTarget) || formatNearbyLines(normalizedContent, effStart, effEnd);
+ snippetHint = findClosestRegionSnippet(
+ fileLines,
+ normTarget,
+ effStart,
+ effEnd,
+ trimmedFileLines
+ ) || findClosestRegionSnippet(
+ fileLines,
+ normTarget,
+ outStart,
+ outEnd,
+ trimmedFileLines
+ ) || formatNearbyLines(fileLines, effStart, effEnd);
} else {
- hint += formatNearbyLines(normalizedContent, hunk.startLine, hunk.endLine);
+ snippetHint = formatNearbyLines(fileLines, hunk.startLine, hunk.endLine);
}
+ hint = wsHint ? `${wsHint}${snippetHint}` : `${hint}${snippetHint}`;
}
} else {
- hint += findClosestRegionSnippet(normalizedContent, normTarget);
+ const fileLines = getFileLines();
+ const trimmedFileLines = getTrimmedFileLines();
+ const wsHint = detectWhitespaceMismatchHint(
+ fileLines,
+ normTarget,
+ void 0,
+ void 0,
+ false,
+ trimmedFileLines
+ ) || "";
+ const snippetHint = findClosestRegionSnippet(
+ fileLines,
+ normTarget,
+ void 0,
+ void 0,
+ trimmedFileLines
+ );
+ hint = wsHint ? `${wsHint}${snippetHint}` : `${hint}${snippetHint}`;
}
errors.push(
`${displayPath} hunk #${idx + 1}: target text not found${rangeNote}.${hint}`
diff --git a/src/tools/apply-edits.ts b/src/tools/apply-edits.ts
index 30cd3f3..690bbac 100644
--- a/src/tools/apply-edits.ts
+++ b/src/tools/apply-edits.ts
@@ -167,29 +167,355 @@ function getLineWindowOffsets(
const MAX_NEARBY_LINES = 26;
const MAX_DRIFT_RECOVERY_LINES = 50;
+const MAX_WS_SCAN_LINES = 50_000;
+const MAX_WS_COMPARISONS = 200_000;
+const MAX_EXTRA_WS_MATCHES = 50;
+const MAX_CLOSEST_EVALUATIONS = 2_000;
+const HUGE_FILE_FALLBACK_WINDOW_RADIUS = 2_000;
+const TAB_MARKER_LEGEND = " (→ = \\t tab; use real \\t in target, not →)";
+
+function regionHasLeadingTab(
+ fileLines: readonly string[],
+ from: number,
+ to: number,
+): boolean {
+ for (let ln = from; ln <= to; ln++) {
+ const lineText = fileLines[ln - 1] ?? "";
+ if (/^ *\t/.test(lineText)) return true;
+ }
+ return false;
+}
+
+function fileHasLeadingTabSample(
+ fileLines: readonly string[],
+ startIdx = 0,
+ endIdx = fileLines.length - 1,
+): boolean {
+ const from = Math.max(0, startIdx);
+ const to = Math.min(fileLines.length - 1, endIdx, from + 5_000 - 1);
+ for (let idx = from; idx <= to; idx++) {
+ if (/^ *\t/.test(fileLines[idx] ?? "")) return true;
+ }
+ return false;
+}
+
+function hasLeadingTabDisplayMarker(text: string): boolean {
+ return /(?:^|\n)[\t ]*→/.test(text);
+}
+
+function stripLeadingTabDisplayMarkers(line: string): string {
+ return line.replace(/^[\t →]+/, (ws) => ws.replace(/→/g, "\t"));
+}
+
+function renderSnippetLine(lineText: string, showLeadingTabs: boolean): string {
+ const rendered = showLeadingTabs
+ ? lineText.replace(/^[\t ]+/, (ws) => ws.replace(/\t/g, "→"))
+ : lineText;
+ return rendered.length > 160 ? `${sliceSafeChars(rendered, 157)}...` : rendered;
+}
function formatNearbyLines(
- text: string,
+ fileLines: readonly string[],
startLine?: number,
endLine?: number,
): string {
if (startLine === undefined && endLine === undefined) return "";
- const lines = text.split("\n");
- if (lines.at(-1) === "") lines.pop();
const from = Math.max(1, (startLine ?? endLine ?? 1) - 2);
- const rawTo = Math.min(lines.length, (endLine ?? startLine ?? 1) + 2);
+ const rawTo = Math.min(fileLines.length, (endLine ?? startLine ?? 1) + 2);
if (from > rawTo) return "";
const truncated = rawTo - from + 1 > MAX_NEARBY_LINES;
const to = truncated ? from + MAX_NEARBY_LINES - 1 : rawTo;
+ const showLeadingTabs = regionHasLeadingTab(fileLines, from, to);
+ const tabLegend = showLeadingTabs ? TAB_MARKER_LEGEND : "";
const snippet: string[] = [];
for (let ln = from; ln <= to; ln++) {
- const lineText = lines[ln - 1] ?? "";
- snippet.push(
- ` ${ln}: ${lineText.length > 160 ? `${sliceSafeChars(lineText, 157)}...` : lineText}`,
- );
+ const lineText = fileLines[ln - 1] ?? "";
+ snippet.push(` ${ln}: ${renderSnippetLine(lineText, showLeadingTabs)}`);
}
const extra = truncated ? `\n ... (${rawTo - to} more lines in range omitted)` : "";
- return `\n Nearby lines (${from}-${to}):\n${snippet.join("\n")}${extra}`;
+ return `\n Nearby lines (${from}-${to})${tabLegend}:\n${snippet.join("\n")}${extra}`;
+}
+
+export function detectWhitespaceMismatchHint(
+ fileLines: readonly string[],
+ normTarget: string,
+ rangeStartLine?: number,
+ rangeEndLine?: number,
+ outsideRangeLabel = false,
+ preTrimmedFileLines?: readonly string[],
+): string | null {
+ if (fileLines.length === 0 || !normTarget) return null;
+ const rawTargetLines = normTarget.split("\n");
+ if (normTarget.endsWith("\n") && rawTargetLines.length > 1) {
+ rawTargetLines.pop();
+ }
+ const m = rawTargetLines.length;
+ if (m === 0) return null;
+
+ const scanStart = Math.max(0, (rangeStartLine ?? 1) - 1);
+ const scanEnd = Math.min(
+ fileLines.length - 1,
+ (rangeEndLine ?? fileLines.length) - 1,
+ );
+ if (scanStart > scanEnd) return null;
+ const scanLen = scanEnd - scanStart + 1;
+ if (scanLen < m) return null;
+
+ const hasLeadingArrow = hasLeadingTabDisplayMarker(normTarget);
+ const allowLocationlessArrowFallback =
+ outsideRangeLabel || (rangeStartLine === undefined && rangeEndLine === undefined);
+
+ if (scanLen > MAX_WS_SCAN_LINES) {
+ if (
+ hasLeadingArrow &&
+ allowLocationlessArrowFallback &&
+ fileHasLeadingTabSample(fileLines, scanStart, scanEnd)
+ ) {
+ return " Target contains literal '→' tab display markers; replace them with real '\\t' tab characters.";
+ }
+ return null;
+ }
+
+ const hasValidPreTrimmed =
+ preTrimmedFileLines !== undefined && preTrimmedFileLines.length === fileLines.length;
+ let localTrimmed: (string | undefined)[] | null = null;
+ const getTrimmed = (idx: number): string => {
+ if (hasValidPreTrimmed) return preTrimmedFileLines[idx]!;
+ if (localTrimmed === null) {
+ localTrimmed = new Array<string | undefined>(scanLen);
+ }
+ const rel = idx - scanStart;
+ let val = localTrimmed[rel];
+ if (val === undefined) {
+ val = fileLines[idx]!.trim();
+ localTrimmed[rel] = val;
+ }
+ return val;
+ };
+
+ let comparisons = 0;
+
+ const pickAnchor = (trimmedTarget: readonly string[]): { idx: number; text: string } => {
+ let anchorIdx = 0;
+ let bestScore = -1;
+ for (let k = 0; k < m; k++) {
+ const line = trimmedTarget[k]!;
+ if (line.length === 0) continue;
+ // Favor lines with alphanumeric/CJK identifiers and longer text so
+ // repetitive delimiters (e.g. "},", "}") aren't picked as anchors.
+ const hasIdentifier = /[A-Za-z0-9_$\u4e00-\u9fff]/.test(line);
+ const score = line.length + (hasIdentifier ? 1000 : 0);
+ if (score > bestScore) {
+ bestScore = score;
+ anchorIdx = k;
+ }
+ }
+ return { idx: anchorIdx, text: trimmedTarget[anchorIdx]! };
+ };
+
+ const classifyMismatch = (
+ startIdx: number,
+ effectiveTargetLines: readonly string[],
+ trimmedTarget: readonly string[],
+ isArrowPass: boolean,
+ ): string[] => {
+ let literalTabMarkerInTabFile = false;
+ let literalTabMarkerInSpaceFile = false;
+ let literalTabMarkerOther = false;
+ let fileTabsTargetSpaces = false;
+ let fileSpacesTargetTabs = false;
+ let mixedTabSpace = false;
+ let indentWidthDiff = false;
+ let trailingWhitespaceDiff = false;
+
+ for (let k = 0; k < m; k++) {
+ const fLine = fileLines[startIdx + k]!;
+ const rawLine = rawTargetLines[k]!;
+ if (fLine === rawLine) continue;
+
+ const effLine = effectiveTargetLines[k]!;
+ const lineHasArrow = isArrowPass && /^[\t ]*→/.test(rawLine);
+
+ if (trimmedTarget[k]!.length === 0) {
+ if (lineHasArrow) {
+ if (fLine.includes("\t")) {
+ literalTabMarkerInTabFile = true;
+ } else if (fLine.includes(" ")) {
+ literalTabMarkerInSpaceFile = true;
+ } else {
+ literalTabMarkerOther = true;
+ }
+ }
+ if (fLine !== effLine) {
+ trailingWhitespaceDiff = true;
+ }
+ continue;
+ }
+
+ const fLead = /^[\t ]*/.exec(fLine)![0];
+ const tLead = /^[\t ]*/.exec(effLine)![0];
+ const fTrail = /[\t ]*$/.exec(fLine)![0];
+ const tTrail = /[\t ]*$/.exec(effLine)![0];
+
+ if (lineHasArrow) {
+ if (fLead.includes("\t")) {
+ literalTabMarkerInTabFile = true;
+ } else if (fLead.includes(" ")) {
+ literalTabMarkerInSpaceFile = true;
+ } else {
+ literalTabMarkerOther = true;
+ }
+ }
+
+ if (fLead !== tLead) {
+ const fHasTab = fLead.includes("\t");
+ const tHasTab = tLead.includes("\t");
+ const fHasSpace = fLead.includes(" ");
+ const tHasSpace = tLead.includes(" ");
+ const rawLead = lineHasArrow ? /^[\t →]*/.exec(rawLine)![0] : "";
+ const arrowOnlyNonTabConflict =
+ lineHasArrow && !fHasTab && !rawLead.includes("\t");
+ if (!arrowOnlyNonTabConflict) {
+ if ((fHasTab && fHasSpace) || (tHasTab && tHasSpace)) {
+ mixedTabSpace = true;
+ } else if (fHasTab && !fHasSpace && !tHasTab && tHasSpace) {
+ fileTabsTargetSpaces = true;
+ } else if (!fHasTab && fHasSpace && tHasTab && !tHasSpace) {
+ fileSpacesTargetTabs = true;
+ } else {
+ // Both sides use purely spaces (or purely tabs), differing only in count.
+ indentWidthDiff = true;
+ }
+ }
+ }
+ if (fTrail !== tTrail) {
+ trailingWhitespaceDiff = true;
+ }
+ }
+
+ const reasons: string[] = [];
+ if (literalTabMarkerInTabFile) {
+ reasons.push(
+ "target contains literal '→' tab display markers; replace them with real '\\t' tab characters",
+ );
+ } else if (literalTabMarkerInSpaceFile) {
+ reasons.push(
+ "target contains literal '→' tab display markers (file uses spaces, not tabs)",
+ );
+ } else if (literalTabMarkerOther) {
+ reasons.push("target contains literal '→' tab display markers");
+ }
+
+ if (mixedTabSpace || (fileTabsTargetSpaces && fileSpacesTargetTabs)) {
+ reasons.push("mixed tab/space indentation");
+ } else if (fileTabsTargetSpaces) {
+ reasons.push("file uses tabs (\\t), target used spaces");
+ } else if (fileSpacesTargetTabs) {
+ reasons.push("file uses spaces, target used tabs (\\t)");
+ } else if (indentWidthDiff) {
+ reasons.push("indentation width mismatch");
+ }
+
+ if (trailingWhitespaceDiff) {
+ reasons.push("trailing horizontal whitespace mismatch");
+ }
+ return reasons;
+ };
+
+ const scanPass = (
+ effectiveTargetLines: readonly string[],
+ trimmedTarget: readonly string[],
+ isArrowPass: boolean,
+ ): string | null => {
+ if (!trimmedTarget.some((l) => l.length > 0)) return null;
+
+ const anchor = pickAnchor(trimmedTarget);
+ const lastStart = scanEnd - m + 1;
+
+ let firstMatch: { startIdx: number; reasons: string[] } | null = null;
+ let extraMatches = 0;
+ let cappedExtra = false;
+
+ for (let i = scanStart; i <= lastStart; i++) {
+ if (comparisons >= MAX_WS_COMPARISONS) {
+ if (firstMatch && extraMatches > 0) cappedExtra = true;
+ break;
+ }
+ comparisons++;
+ if (getTrimmed(i + anchor.idx) !== anchor.text) continue;
+
+ let matched = true;
+ let hitCap = false;
+ for (let k = 0; k < m; k++) {
+ if (k === anchor.idx) continue;
+ if (comparisons >= MAX_WS_COMPARISONS) {
+ matched = false;
+ hitCap = true;
+ break;
+ }
+ comparisons++;
+ if (getTrimmed(i + k) !== trimmedTarget[k]!) {
+ matched = false;
+ break;
+ }
+ }
+ if (hitCap) {
+ if (firstMatch && extraMatches > 0) cappedExtra = true;
+ break;
+ }
+ if (!matched) continue;
+
+ if (!firstMatch) {
+ const reasons = classifyMismatch(i, effectiveTargetLines, trimmedTarget, isArrowPass);
+ if (reasons.length === 0) continue;
+ firstMatch = { startIdx: i, reasons };
+ } else {
+ let differs = false;
+ for (let k = 0; k < m; k++) {
+ if (fileLines[i + k] !== rawTargetLines[k]) {
+ differs = true;
+ break;
+ }
+ }
+ if (!differs) continue;
+ if (extraMatches >= MAX_EXTRA_WS_MATCHES) {
+ cappedExtra = true;
+ break;
+ }
+ extraMatches++;
+ }
+ }
+
+ if (!firstMatch) return null;
+
+ const startLn = firstMatch.startIdx + 1;
+ const endLn = firstMatch.startIdx + m;
+ const loc = startLn === endLn ? `L${startLn}` : `L${startLn}-L${endLn}`;
+ const moreSuffix =
+ extraMatches > 0 ? ` (+${extraMatches}${cappedExtra ? "+" : ""} more)` : "";
+ const scopePrefix = outsideRangeLabel ? " outside range" : "";
+ return ` Whitespace mismatch${scopePrefix} at ${loc}${moreSuffix}: ${firstMatch.reasons.join("; ")}.`;
+ };
+
+ const rawTrimmedTarget = rawTargetLines.map((l) => l.trim());
+ const rawMatch = scanPass(rawTargetLines, rawTrimmedTarget, false);
+ if (rawMatch) return rawMatch;
+
+ if (hasLeadingArrow) {
+ const unmarkedTargetLines = rawTargetLines.map(stripLeadingTabDisplayMarkers);
+ const unmarkedTrimmedTarget = unmarkedTargetLines.map((l) => l.trim());
+ const arrowMatch = scanPass(unmarkedTargetLines, unmarkedTrimmedTarget, true);
+ if (arrowMatch) return arrowMatch;
+
+ if (
+ allowLocationlessArrowFallback &&
+ fileHasLeadingTabSample(fileLines, scanStart, scanEnd)
+ ) {
+ return " Target contains literal '→' tab display markers; replace them with real '\\t' tab characters.";
+ }
+ }
+
+ return null;
}
function extractLineTokens(trimmedLine: string): string[] {
@@ -207,17 +533,29 @@ function extractLineTokens(trimmedLine: string): string[] {
* without dumping an 80-line range or doing an extra read_file round-trip.
*/
function findClosestRegionSnippet(
- normalizedContent: string,
+ fileLines: readonly string[],
normTarget: string,
rangeStartLine?: number,
rangeEndLine?: number,
+ preTrimmedFileLines?: readonly string[],
): string {
- const fileLines = normalizedContent.split("\n");
if (fileLines.length === 0) return "";
+ const scanStart = Math.max(0, (rangeStartLine ?? 1) - 1);
+ const scanEnd = Math.min(
+ fileLines.length - 1,
+ (rangeEndLine ?? fileLines.length) - 1,
+ );
+ if (scanStart > scanEnd) return "";
+ const scanLen = scanEnd - scanStart + 1;
+ if (scanLen > MAX_WS_SCAN_LINES) return "";
+
+ const normalizeArrows =
+ hasLeadingTabDisplayMarker(normTarget) &&
+ fileHasLeadingTabSample(fileLines, scanStart, scanEnd);
const targetLines = normTarget
.split("\n")
- .map((l) => l.trim())
+ .map((l) => (normalizeArrows ? stripLeadingTabDisplayMarkers(l) : l).trim())
.filter((l) => l.length > 0);
if (targetLines.length === 0) return "";
@@ -253,14 +591,22 @@ function findClosestRegionSnippet(
}));
const targetTokenSets = targetLines.map((tl) => new Set(extractLineTokens(tl)));
- const trimmedFileLines = fileLines.map((l) => l.trim());
-
- const scanStart = Math.max(0, (rangeStartLine ?? 1) - 1);
- const scanEnd = Math.min(
- trimmedFileLines.length - 1,
- (rangeEndLine ?? trimmedFileLines.length) - 1,
- );
- if (scanStart > scanEnd) return "";
+ const hasValidPreTrimmed =
+ preTrimmedFileLines !== undefined && preTrimmedFileLines.length === fileLines.length;
+ let localTrimmed: (string | undefined)[] | null = null;
+ const getTrimmed = (idx: number): string => {
+ if (hasValidPreTrimmed) return preTrimmedFileLines[idx]!;
+ if (localTrimmed === null) {
+ localTrimmed = new Array<string | undefined>(scanLen);
+ }
+ const rel = idx - scanStart;
+ let val = localTrimmed[rel];
+ if (val === undefined) {
+ val = fileLines[idx]!.trim();
+ localTrimmed[rel] = val;
+ }
+ return val;
+ };
const evaluatedStarts = new Set<number>();
let bestStart = -1;
@@ -281,8 +627,8 @@ function findClosestRegionSnippet(
let total = 0;
for (const k of scoreIndices) {
const fIdx = candStart + k;
- if (fIdx > scanEnd || fIdx >= trimmedFileLines.length) continue;
- const fLine = trimmedFileLines[fIdx]!;
+ if (fIdx > scanEnd || fIdx >= fileLines.length) continue;
+ const fLine = getTrimmed(fIdx);
const tLine = targetLines[k]!;
if (!fLine || !tLine) continue;
const tTokens = targetTokenSets[k]!;
@@ -313,8 +659,12 @@ function findClosestRegionSnippet(
return total;
};
- for (let i = scanStart; i <= scanEnd; i++) {
- const line = trimmedFileLines[i]!;
+ for (
+ let i = scanStart;
+ i <= scanEnd && evaluatedStarts.size < MAX_CLOSEST_EVALUATIONS;
+ i++
+ ) {
+ const line = getTrimmed(i);
if (!line) continue;
for (const anchor of anchors) {
@@ -349,6 +699,7 @@ function findClosestRegionSnippet(
bestScore = score;
bestStart = candStart;
}
+ if (evaluatedStarts.size >= MAX_CLOSEST_EVALUATIONS) break;
}
}
@@ -357,14 +708,14 @@ function findClosestRegionSnippet(
const span = Math.min(Math.max(targetLines.length, 4), 8);
const from = Math.max(1, bestStart + 1 - 2);
const to = Math.min(fileLines.length, Math.min(from + 13, bestStart + 1 + span + 2));
+ const showLeadingTabs = regionHasLeadingTab(fileLines, from, to);
+ const tabLegend = showLeadingTabs ? TAB_MARKER_LEGEND : "";
const snippet: string[] = [];
for (let ln = from; ln <= to; ln++) {
const lineText = fileLines[ln - 1] ?? "";
- snippet.push(
- ` ${ln}: ${lineText.length > 160 ? `${sliceSafeChars(lineText, 157)}...` : lineText}`,
- );
+ snippet.push(` ${ln}: ${renderSnippetLine(lineText, showLeadingTabs)}`);
}
- return `\n Closest match near line ${bestStart + 1} (lines ${from}-${to}):\n${snippet.join("\n")}`;
+ return `\n Closest match near line ${bestStart + 1} (lines ${from}-${to})${tabLegend}:\n${snippet.join("\n")}`;
}
function planHunksForContent(
@@ -390,6 +741,29 @@ function planHunksForContent(
const spans: MatchSpan[] = [];
const shiftedHunks: string[] = [];
const errors: string[] = [];
+ let cachedFileLines: string[] | null = null;
+ let cachedTrimmedFileLines: string[] | null = null;
+ const getFileLines = (): string[] => {
+ if (cachedFileLines === null) {
+ if (normalizedContent.length === 0) {
+ cachedFileLines = [];
+ } else {
+ cachedFileLines = normalizedContent.split("\n");
+ if (normalizedContent.endsWith("\n") && cachedFileLines.length > 1) {
+ cachedFileLines.pop();
+ }
+ }
+ }
+ return cachedFileLines;
+ };
+ const getTrimmedFileLines = (): readonly string[] | undefined => {
+ const lines = getFileLines();
+ if (lines.length > MAX_WS_SCAN_LINES) return undefined;
+ if (cachedTrimmedFileLines === null) {
+ cachedTrimmedFileLines = lines.map((l) => l.trim());
+ }
+ return cachedTrimmedFileLines;
+ };
for (let idx = 0; idx < hunks.length; idx++) {
const hunk = hunks[idx];
@@ -528,17 +902,77 @@ function planHunksForContent(
}
const effStart = hunk.startLine ?? 1;
const effEnd = hunk.endLine ?? lineStarts.length;
+ const fileLines = getFileLines();
+ const trimmedFileLines = getTrimmedFileLines();
+ const outStart =
+ fileLines.length > MAX_WS_SCAN_LINES
+ ? Math.max(1, effStart - HUGE_FILE_FALLBACK_WINDOW_RADIUS)
+ : undefined;
+ const outEnd =
+ fileLines.length > MAX_WS_SCAN_LINES
+ ? Math.min(fileLines.length, effEnd + HUGE_FILE_FALLBACK_WINDOW_RADIUS)
+ : undefined;
+ const wsHint =
+ detectWhitespaceMismatchHint(
+ fileLines,
+ normTarget,
+ effStart,
+ effEnd,
+ false,
+ trimmedFileLines,
+ ) ||
+ detectWhitespaceMismatchHint(
+ fileLines,
+ normTarget,
+ outStart,
+ outEnd,
+ true,
+ trimmedFileLines,
+ ) ||
+ "";
+ let snippetHint: string;
if (effEnd - effStart + 1 > MAX_NEARBY_LINES - 4) {
- hint +=
- findClosestRegionSnippet(normalizedContent, normTarget, effStart, effEnd) ||
- findClosestRegionSnippet(normalizedContent, normTarget) ||
- formatNearbyLines(normalizedContent, effStart, effEnd);
+ snippetHint =
+ findClosestRegionSnippet(
+ fileLines,
+ normTarget,
+ effStart,
+ effEnd,
+ trimmedFileLines,
+ ) ||
+ findClosestRegionSnippet(
+ fileLines,
+ normTarget,
+ outStart,
+ outEnd,
+ trimmedFileLines,
+ ) ||
+ formatNearbyLines(fileLines, effStart, effEnd);
} else {
- hint += formatNearbyLines(normalizedContent, hunk.startLine, hunk.endLine);
+ snippetHint = formatNearbyLines(fileLines, hunk.startLine, hunk.endLine);
}
+ hint = wsHint ? `${wsHint}${snippetHint}` : `${hint}${snippetHint}`;
}
} else {
- hint += findClosestRegionSnippet(normalizedContent, normTarget);
+ const fileLines = getFileLines();
+ const trimmedFileLines = getTrimmedFileLines();
+ const wsHint =
+ detectWhitespaceMismatchHint(
+ fileLines,
+ normTarget,
+ undefined,
+ undefined,
+ false,
+ trimmedFileLines,
+ ) || "";
+ const snippetHint = findClosestRegionSnippet(
+ fileLines,
+ normTarget,
+ undefined,
+ undefined,
+ trimmedFileLines,
+ );
+ hint = wsHint ? `${wsHint}${snippetHint}` : `${hint}${snippetHint}`;
}
errors.push(
`${displayPath} hunk #${idx + 1}: target text not found${rangeNote}.${hint}`,
diff --git a/test/apply-edits.test.ts b/test/apply-edits.test.ts
index eb4e8f4..35d822f 100644
--- a/test/apply-edits.test.ts
+++ b/test/apply-edits.test.ts
@@ -4,6 +4,7 @@ import os from "node:os";
import path from "node:path";
import { after, before, describe, it } from "node:test";
import {
+ detectWhitespaceMismatchHint,
isGitInternalPath,
isPathWithinDir,
runApplyEdits,
@@ -2077,6 +2078,7 @@ describe("apply_edits", () => {
assert.match(bulkRes.text, /Partial edit applied \(0\/49 file\(s\) written, 48 unchanged; 1 file\(s\) failed/);
assert.match(bulkRes.text, /total 0 written, 48 unchanged\)/);
});
+
it("rejects hunk edits on non-UTF-8 files without corrupting bytes while allowing explicit create+overwrite", async () => {
// CP1252 (0xe9 = 'é') + GBK (0xd6 0xd0 0xce 0xc4 = '中文') without NUL or UTF-16 BOM
const legacyBytes = Buffer.from([
@@ -2875,4 +2877,478 @@ describe("apply_edits", () => {
await fs.rm(parentTmp, { recursive: true, force: true });
}
});
+
+ it("diagnoses tab-vs-space, indent-width, and trailing-whitespace mismatches with visible tab markers only when tabs exist", async () => {
+ const goFile = path.join(tmpDir, "service.go");
+ await fs.writeFile(
+ goFile,
+ [
+ "package main",
+ "",
+ "func compute(x int) int {",
+ "\tif x > 0 {",
+ "\t\treturn x * 2",
+ "\t}",
+ "\treturn 0",
+ "}",
+ ].join("\n") + "\n",
+ "utf8",
+ );
+
+ // 1. Tab-indented file vs space-indented target -> explicit tab hint + explicit legend & visible → markers
+ const tabVsSpace = await runApplyEdits({
+ cwd: tmpDir,
+ dryRun: true,
+ edits: [
+ {
+ path: "service.go",
+ hunks: [
+ {
+ target: " if x > 0 {\n return x * 2\n }",
+ replacement: "\tif x > 0 {\n\t\treturn x * 3\n\t}",
+ },
+ ],
+ },
+ ],
+ });
+ assert.equal(tabVsSpace.isError, true);
+ assert.match(
+ tabVsSpace.text,
+ /Whitespace mismatch at L4-L6: file uses tabs \(\\t\), target used spaces\./,
+ );
+ assert.match(
+ tabVsSpace.text,
+ /Closest match near line 4 \(lines \d+-\d+\) \(→ = \\t tab; use real \\t in target, not →\):/,
+ );
+ assert.match(tabVsSpace.text, /4: →if x > 0 \{/);
+ assert.match(tabVsSpace.text, /5: →→return x \* 2/);
+
+ // 1b. Bounded range Nearby lines snippet also uses the explicit legend
+ const nearbyTabLegend = await runApplyEdits({
+ cwd: tmpDir,
+ dryRun: true,
+ edits: [
+ {
+ path: "service.go",
+ hunks: [
+ {
+ startLine: 3,
+ endLine: 7,
+ target: " if x > 0 {",
+ replacement: "\tif x > 0 {",
+ },
+ ],
+ },
+ ],
+ });
+ assert.equal(nearbyTabLegend.isError, true);
+ assert.match(
+ nearbyTabLegend.text,
+ /Nearby lines \(\d+-\d+\) \(→ = \\t tab; use real \\t in target, not →\):/,
+ );
+
+ // 2. Space-indented file vs tab-indented target, indent-width mismatch, and trailing-space mismatch
+ const pyFile = path.join(tmpDir, "calc.py");
+ await fs.writeFile(
+ pyFile,
+ [
+ "def run(val):",
+ " if val:",
+ " return val + 1 ",
+ " return 0",
+ ].join("\n") + "\n",
+ "utf8",
+ );
+
+ // 2a. File uses spaces, target used tabs -> no → legend since file region has no leading tabs
+ const spaceVsTab = await runApplyEdits({
+ cwd: tmpDir,
+ dryRun: true,
+ edits: [
+ {
+ path: "calc.py",
+ hunks: [
+ {
+ target: "\tif val:\n\t\treturn val + 1",
+ replacement: " if val:\n return val + 2",
+ },
+ ],
+ },
+ ],
+ });
+ assert.equal(spaceVsTab.isError, true);
+ assert.match(
+ spaceVsTab.text,
+ /Whitespace mismatch at L2-L3: file uses spaces, target used tabs \(\\t\); trailing horizontal whitespace mismatch\./,
+ );
+ assert.doesNotMatch(spaceVsTab.text, /\(→ = \\t tab/);
+
+ // 2b. Indentation width mismatch (2 spaces vs 4 spaces) -> non-tab snippet unaffected
+ const indentWidth = await runApplyEdits({
+ cwd: tmpDir,
+ dryRun: true,
+ edits: [
+ {
+ path: "calc.py",
+ hunks: [
+ {
+ target: " if val:\n return val + 1 ",
+ replacement: " if val:\n return val + 2",
+ },
+ ],
+ },
+ ],
+ });
+ assert.equal(indentWidth.isError, true);
+ assert.match(indentWidth.text, /Whitespace mismatch at L2-L3: indentation width mismatch\./);
+ assert.doesNotMatch(indentWidth.text, /\(→ = \\t tab/);
+
+ // 2c. Trailing horizontal whitespace mismatch only (file has trailing spaces on L3 before newline)
+ const trailingSpace = await runApplyEdits({
+ cwd: tmpDir,
+ dryRun: true,
+ edits: [
+ {
+ path: "calc.py",
+ hunks: [
+ {
+ startLine: 2,
+ endLine: 4,
+ target: " return val + 1\n return 0",
+ replacement: " return val + 2\n return 0",
+ },
+ ],
+ },
+ ],
+ });
+ assert.equal(trailingSpace.isError, true);
+ assert.match(
+ trailingSpace.text,
+ /Whitespace mismatch at L3-L4: trailing horizontal whitespace mismatch\./,
+ );
+ assert.doesNotMatch(trailingSpace.text, /\(→ = \\t tab/);
+
+ // 2d. Single-line target with extra trailing spaces not present in file
+ const targetTrailingSpace = await runApplyEdits({
+ cwd: tmpDir,
+ dryRun: true,
+ edits: [
+ {
+ path: "calc.py",
+ hunks: [
+ {
+ target: " return 0 ",
+ replacement: " return 1",
+ },
+ ],
+ },
+ ],
+ });
+ assert.equal(targetTrailingSpace.isError, true);
+ assert.match(
+ targetTrailingSpace.text,
+ /Whitespace mismatch at L4: trailing horizontal whitespace mismatch\./,
+ );
+ assert.doesNotMatch(targetTrailingSpace.text, /\(→ = \\t tab/);
+ });
+
+ it("emits targeted hint when retry target copies literal '→' tab display markers in tab-indented files", async () => {
+ const goFile = path.join(tmpDir, "arrow-retry.go");
+ await fs.writeFile(
+ goFile,
+ [
+ "package main",
+ "",
+ "func compute(x int) int {",
+ "\tif x > 0 {",
+ "\t\treturn x * 2",
+ "\t}",
+ "\treturn 0",
+ "}",
+ ].join("\n") + "\n",
+ "utf8",
+ );
+
+ // 1. Single-line retry target copying literal '→' from snippet
+ const singleArrow = await runApplyEdits({
+ cwd: tmpDir,
+ dryRun: true,
+ edits: [
+ {
+ path: "arrow-retry.go",
+ hunks: [
+ {
+ target: "→if x > 0 {",
+ replacement: "\tif x > 1 {",
+ },
+ ],
+ },
+ ],
+ });
+ assert.equal(singleArrow.isError, true);
+ assert.match(
+ singleArrow.text,
+ /Whitespace mismatch at L4: target contains literal '→' tab display markers; replace them with real '\\t' tab characters\./,
+ );
+ assert.match(
+ singleArrow.text,
+ /Closest match near line 4 \(lines \d+-\d+\) \(→ = \\t tab; use real \\t in target, not →\):/,
+ );
+ assert.match(singleArrow.text, /4: →if x > 0 \{/);
+
+ // 2. Multi-line retry target copying literal '→' markers
+ const multiArrow = await runApplyEdits({
+ cwd: tmpDir,
+ dryRun: true,
+ edits: [
+ {
+ path: "arrow-retry.go",
+ hunks: [
+ {
+ target: "→if x > 0 {\n→→return x * 2\n→}",
+ replacement: "\tif x > 0 {\n\t\treturn x * 3\n\t}",
+ },
+ ],
+ },
+ ],
+ });
+ assert.equal(multiArrow.isError, true);
+ assert.match(
+ multiArrow.text,
+ /Whitespace mismatch at L4-L6: target contains literal '→' tab display markers; replace them with real '\\t' tab characters\./,
+ );
+
+ // 3. Target with literal '→' AND a non-whitespace typo still warns about literal '→'
+ const arrowWithTypo = await runApplyEdits({
+ cwd: tmpDir,
+ dryRun: true,
+ edits: [
+ {
+ path: "arrow-retry.go",
+ hunks: [
+ {
+ target: "→if x > 0 {\n→→return x * 999",
+ replacement: "\tif x > 0 {\n\t\treturn x * 3",
+ },
+ ],
+ },
+ ],
+ });
+ assert.equal(arrowWithTypo.isError, true);
+ assert.match(
+ arrowWithTypo.text,
+ /Target contains literal '→' tab display markers; replace them with real '\\t' tab characters\./,
+ );
+ assert.match(arrowWithTypo.text, /Closest match near line 4/);
+
+ // 4. Real literal '→' bullets in a space-indented file are NOT misdiagnosed as tab markers
+ const mdFile = path.join(tmpDir, "notes.md");
+ await fs.writeFile(mdFile, " → step one\n → step two\n", "utf8");
+ const realArrow = await runApplyEdits({
+ cwd: tmpDir,
+ dryRun: true,
+ edits: [
+ {
+ path: "notes.md",
+ hunks: [{ target: " → step one", replacement: " → step 1" }],
+ },
+ ],
+ });
+ assert.equal(realArrow.isError, true);
+ assert.match(realArrow.text, /Whitespace mismatch at L1: indentation width mismatch\./);
+ assert.doesNotMatch(realArrow.text, /tab display markers/);
+ });
+
+ it("reports (+N more) on repeated trimmed matches and classifies mixed tab/space indentation accurately", async () => {
+ const repeatedFile = path.join(tmpDir, "repeated.go");
+ await fs.writeFile(
+ repeatedFile,
+ [
+ "package main",
+ "func a() {",
+ "\tif true {",
+ "\t}",
+ "\tif false {",
+ "\t}",
+ "\tfor {",
+ "\t}",
+ "\tswitch {",
+ "\t}",
+ "}",
+ ].join("\n") + "\n",
+ "utf8",
+ );
+
+ // 1. Trivial single-line target matching multiple trimmed lines reports (+N more)
+ // Matches L4, L6, L8, L10 (\t}) plus L11 (}) -> 4 extra matches
+ const multiMatch = await runApplyEdits({
+ cwd: tmpDir,
+ dryRun: true,
+ edits: [
+ {
+ path: "repeated.go",
+ hunks: [{ target: " }", replacement: "\t}" }],
+ },
+ ],
+ });
+ assert.equal(multiMatch.isError, true);
+ assert.match(
+ multiMatch.text,
+ /Whitespace mismatch at L4 \(\+4 more\): file uses tabs \(\\t\), target used spaces\./,
+ );
+
+ // 2. Cap extra matches cleanly when > 50 repeats exist
+ const manyLines = Array.from({ length: 65 }, () => "\t},");
+ const cappedHint = detectWhitespaceMismatchHint(manyLines, " },");
+ assert.ok(cappedHint);
+ assert.match(
+ cappedHint,
+ /Whitespace mismatch at L1 \(\+50\+ more\): file uses tabs \(\\t\), target used spaces\./,
+ );
+
+ // 3. Mixed tab/space indentation: "\t\t" vs " \t" must NOT be called "indentation width mismatch"
+ const mixedFile = path.join(tmpDir, "mixed.go");
+ await fs.writeFile(
+ mixedFile,
+ [
+ "package main",
+ "func mix(x int) int {",
+ "\tif x > 0 {",
+ "\t\treturn x + 1",
+ "\t}",
+ " \treturn 0",
+ "}",
+ ].join("\n") + "\n",
+ "utf8",
+ );
+
+ // 3a. File has "\t\t", target has " \t" -> mixed tab/space indentation
+ const tabsVsMixed = await runApplyEdits({
+ cwd: tmpDir,
+ dryRun: true,
+ edits: [
+ {
+ path: "mixed.go",
+ hunks: [{ target: " \treturn x + 1", replacement: "\t\treturn x + 2" }],
+ },
+ ],
+ });
+ assert.equal(tabsVsMixed.isError, true);
+ assert.match(tabsVsMixed.text, /Whitespace mismatch at L4: mixed tab\/space indentation\./);
+ assert.doesNotMatch(tabsVsMixed.text, /indentation width mismatch/);
+
+ // 3b. File has " \t", target has "\t\t" -> mixed tab/space indentation
+ const mixedVsTabs = await runApplyEdits({
+ cwd: tmpDir,
+ dryRun: true,
+ edits: [
+ {
+ path: "mixed.go",
+ hunks: [{ target: "\t\treturn 0", replacement: "\treturn 0" }],
+ },
+ ],
+ });
+ assert.equal(mixedVsTabs.isError, true);
+ assert.match(mixedVsTabs.text, /Whitespace mismatch at L6: mixed tab\/space indentation\./);
+ assert.doesNotMatch(mixedVsTabs.text, /indentation width mismatch/);
+
+ // 3c. Pure tabs with different counts ("\t\t" vs "\t\t\t" and 2-line "\t" vs "\t\t") -> indentation width mismatch
+ const pureTabsWidth = await runApplyEdits({
+ cwd: tmpDir,
+ dryRun: true,
+ edits: [
+ {
+ path: "mixed.go",
+ hunks: [{ target: "\t\t\treturn x + 1", replacement: "\t\treturn x + 2" }],
+ },
+ ],
+ });
+ assert.equal(pureTabsWidth.isError, true);
+ assert.match(pureTabsWidth.text, /Whitespace mismatch at L4: indentation width mismatch\./);
+
+ // 3d. File uses pure spaces, target uses mixed " \t" -> mixed tab/space indentation
+ const spacesVsMixed = detectWhitespaceMismatchHint([" return 1"], " \treturn 1");
+ assert.equal(spacesVsMixed, " Whitespace mismatch at L1: mixed tab/space indentation.");
+
+ // 3e. File uses mixed "\t ", target uses pure spaces -> mixed tab/space indentation
+ const mixedVsSpaces = detectWhitespaceMismatchHint(["\t return 1"], " return 1");
+ assert.equal(mixedVsSpaces, " Whitespace mismatch at L1: mixed tab/space indentation.");
+ });
+
+ it("bounds whitespace mismatch scan cost on huge repetitive files (100k lines x 500-line target)", async () => {
+ const hugeLines = Array.from({ length: 100_000 }, () => "\t},");
+ const target500 = Array.from({ length: 500 }, () => " },").join("\n");
+
+ // 1. Direct unit check on 100k identical lines x 500-line target (skips full scan > 50k)
+ const t0 = performance.now();
+ const hugeHint = detectWhitespaceMismatchHint(hugeLines, target500);
+ const directHugeMs = performance.now() - t0;
+ assert.equal(hugeHint, null);
+ assert.ok(
+ directHugeMs < 100,
+ `Expected 100k-line direct scan to skip rapidly (<100ms), took ${directHugeMs.toFixed(1)}ms`,
+ );
+
+ // 2. Worst-case non-matching 50k identical lines x 500-line target (hits comparison cap)
+ const lines50k = hugeLines.slice(0, 50_000);
+ const almostMatching500 = [
+ ...Array.from({ length: 499 }, () => " },"),
+ " };",
+ ].join("\n");
+ const t1 = performance.now();
+ const cappedMissHint = detectWhitespaceMismatchHint(lines50k, almostMatching500);
+ const cappedMissMs = performance.now() - t1;
+ assert.equal(cappedMissHint, null);
+ assert.ok(
+ cappedMissMs < 100,
+ `Expected 50k worst-case non-matching scan to stay bounded (<100ms), took ${cappedMissMs.toFixed(1)}ms`,
+ );
+
+ // 3. End-to-end runApplyEdits on a 100k-line file x 500-line target completes rapidly
+ const hugeFile = path.join(tmpDir, "huge-repetitive.json");
+ await fs.writeFile(hugeFile, hugeLines.join("\n") + "\n", "utf8");
+
+ const t2 = performance.now();
+ const res = await runApplyEdits({
+ cwd: tmpDir,
+ dryRun: true,
+ edits: [
+ {
+ path: "huge-repetitive.json",
+ hunks: [{ target: target500, replacement: "\t}," }],
+ },
+ ],
+ });
+ const e2eMs = performance.now() - t2;
+ assert.equal(res.isError, true);
+ assert.match(res.text, /target text not found/);
+ assert.ok(
+ e2eMs < 150,
+ `Expected end-to-end 100k-line apply_edits failure to complete rapidly (<150ms), took ${e2eMs.toFixed(1)}ms`,
+ );
+
+ // 4. Narrow startLine/endLine on a 100k-line file still diagnoses whitespace mismatch
+ const narrowRes = await runApplyEdits({
+ cwd: tmpDir,
+ dryRun: true,
+ edits: [
+ {
+ path: "huge-repetitive.json",
+ hunks: [
+ {
+ startLine: 75_000,
+ endLine: 75_005,
+ target: " },\n },",
+ replacement: "\t},\n\t},",
+ },
+ ],
+ },
+ ],
+ });
+ assert.equal(narrowRes.isError, true);
+ assert.match(
+ narrowRes.text,
+ /Whitespace mismatch at L75000-L75001 \(\+4 more\): file uses tabs \(\\t\), target used spaces\./,
+ );
+ });
});