can1357/oh-my-pi · error · ApplyPatchError

Failed to find context '${displayContext}' in ${path}

Error message

Failed to find context '${displayContext}' in ${path}

What it means

The hunk declared a @@ changeContext anchor but findHierarchicalContext could not find that anchor text anywhere in the file after the current search position (index undefined, matchCount not > 1), and no fallback strategy succeeded. The anchor is expected to exist in the target file — its absence means the patch does not match the file's current content.

Source

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

				);
				if (fallback !== undefined) {
					lineIndex = fallback;
				} else if (result.matchCount !== undefined && result.matchCount > 1) {
					const displayContext = hunk.changeContext.includes("\n")
						? hunk.changeContext.split("\n").pop()
						: hunk.changeContext;
					const previews = formatSequenceMatchPreviews(originalLines, result.matchIndices, result.matchCount);
					const strategyHint = result.strategy ? ` Matching strategy: ${result.strategy}.` : "";
					const previewText = previews ? `\n\n${previews}` : "";
					throw new ApplyPatchError(
						`Found ${result.matchCount} matches for context '${displayContext}' in ${path}.${strategyHint}` +
							`${previewText}\n\nAdd more surrounding context or additional @@ anchors to make it unique.`,
					);
				} else {
					const displayContext = hunk.changeContext.includes("\n")
						? hunk.changeContext.split("\n").join(" > ")
						: hunk.changeContext;
					throw new ApplyPatchError(`Failed to find context '${displayContext}' in ${path}`);
				}
			} else {
				// If oldLines[0] matches the final context, start search at idx (not idx+1)
				// This handles the common case where @@ scope and first context line are identical
				const firstOldLine = hunk.oldLines[0];
				const finalContext = hunk.changeContext.includes("\n")
					? hunk.changeContext.split("\n").pop()?.trim()
					: hunk.changeContext.trim();
				const isHierarchicalContext =
					hunk.changeContext.includes("\n") || hunk.changeContext.trim().split(/\s+/).length > 2;
				if (firstOldLine !== undefined && (firstOldLine.trim() === finalContext || isHierarchicalContext)) {
					lineIndex = idx;
				} else {
					lineIndex = idx + 1;
				}
			}
		}

View on GitHub (pinned to 9690622007)

Solutions

  1. Re-read the current file and update the @@ anchor to text that actually exists.
  2. Remove the @@ anchor and locate the change purely via context lines in the hunk.
  3. Check for casing/whitespace differences between the anchor and the file (matching is normalization-tolerant but not unlimited).
  4. Regenerate the patch against the current file revision (fresh git diff).

Example fix

// before
@@ UserServcie
-importToken()
+importTokenNew()

// after (anchor fixed to real class name)
@@ UserService
-importToken()
+importTokenNew()
Defensive patterns

Strategy: validation

Validate before calling

const content = await Bun.file(path).text();
const anchorLine = anchor.split('\n').pop()!.trim();
if (!content.split('\n').some(l => l.trim() === anchorLine)) {
  throw new Error(`@@ anchor '${anchorLine}' does not exist in ${path}; refresh the patch.`);
}

Try / catch

try {
  applyPatch(patch);
} catch (err) {
  if (err instanceof ApplyPatchError && err.message.startsWith('Failed to find context')) {
    // re-read the file and regenerate or drop the anchor
  } else throw err;
}

Prevention

When it happens

Trigger: Applying a patch whose `@@ SomeScope` anchor (possibly hierarchical, newline- or space-separated) does not literally appear in the file; the anchor was typed from memory or from an older file revision.

Common situations: File was refactored/renamed since the patch was authored; anchor spelled with wrong casing or extra whitespace; patch written against a different branch; the class/function the anchor names was moved to another file.

Related errors


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