can1357/oh-my-pi · error · ApplyPatchError

Failed to find expected lines in ${path}:\n${hunk.oldLines.j

Error message

Failed to find expected lines in ${path}:\n${hunk.oldLines.join("\n")}\n\nClosest match (${similarity}% similar) near line ${closest.index + 1}:\n${preview}

What it means

The hunk's expected (removed) lines could not be found in the file, but findClosestSequenceMatch located the most similar region with nonzero confidence. The error includes the requested block, the similarity percentage, and a preview of the closest real location so the caller can see how the file differs. It is the informative variant of the plain 'Failed to find expected lines' error.

Source

Thrown at packages/coding-agent/src/edit/modes/patch.ts:1318

					originalLines,
					searchResult.matchIndices,
					searchResult.matchCount,
				);
				const strategyHint = searchResult.strategy ? ` Matching strategy: ${searchResult.strategy}.` : "";
				const previewText = previews ? `\n\n${previews}` : "";
				throw new ApplyPatchError(
					`Found ${searchResult.matchCount} matches for the text in ${path}.${strategyHint}` +
						`${previewText}\n\nAdd more surrounding context or additional @@ anchors to make it unique.`,
				);
			}
			const closest = findClosestSequenceMatch(originalLines, pattern, {
				start: lineIndex,
				eof: hunk.isEndOfFile,
			});
			if (closest.index !== undefined && closest.confidence > 0) {
				const similarity = Math.round(closest.confidence * 100);
				const preview = formatSequenceMatchPreview(originalLines, closest.index);
				throw new ApplyPatchError(
					`Failed to find expected lines in ${path}:\n${hunk.oldLines.join("\n")}\n\n` +
						`Closest match (${similarity}% similar) near line ${closest.index + 1}:\n${preview}`,
				);
			}
			throw new ApplyPatchError(`Failed to find expected lines in ${path}:\n${hunk.oldLines.join("\n")}`);
		}

		const found = searchResult.index;

		if (searchResult.strategy === "fuzzy-dominant") {
			const similarity = Math.round(searchResult.confidence * 100);
			warnings.push(`Dominant fuzzy match selected in ${path} near line ${found + 1} (${similarity}% similar).`);
		} else if (
			searchResult.strategy === "comment-prefix" ||
			searchResult.strategy === "prefix" ||
			searchResult.strategy === "substring" ||
			searchResult.strategy === "fuzzy" ||
			searchResult.strategy === "character"

View on GitHub (pinned to 9690622007)

Solutions

  1. Open the file near the reported closest-match line and copy the exact current text into the hunk's removed lines.
  2. Regenerate the patch from a fresh read of the file.
  3. Reduce the matched block to a smaller, definitely-unchanged fragment and patch around it.
  4. Check whitespace/indentation conventions (tabs vs spaces) and match them exactly.

Example fix

// before (hunk assumed old code)
-  const x = compute(a,b)

// after (matches file: spacing/renames corrected)
-  const result = compute(a, b);
Defensive patterns

Strategy: try-catch

Validate before calling

const content = await Bun.file(path).text();
if (!content.includes(hunk.oldLines.join('\n'))) {
  // stale or paraphrased hunk: re-read the file and rebuild oldLines verbatim
}

Try / catch

try {
  applyPatch(patch);
} catch (err) {
  if (err instanceof ApplyPatchError && err.message.startsWith('Failed to find expected lines')) {
    // parse 'Closest match ... near line N' from the message,
    // re-read around line N, and rebuild the hunk with exact text
  } else throw err;
}

Prevention

When it happens

Trigger: A replace hunk whose oldLines differ from the actual file content (different formatting, indentation, renamed identifiers, changed lines) such that exact, prefix, substring, and fuzzy strategies all fail, yet a near match exists.

Common situations: Patch written from an outdated read of the file; the model paraphrased code instead of copying it; tabs-vs-spaces or quote-style differences; the target lines were already modified by a previous edit in the same session.

Related errors


AI-assisted analysis of can1357/oh-my-pi@9690622007 (2026-08-31). Data as JSON: /api/errors/bb8624b272f5bdd5. Report an issue: GitHub.