{"record":{"id":"7d4f3f3f9354b01d","repo":"JuliusBrussee/caveman","slug":"caveman-code-old-string-appears-occurrences-ti","errorCode":null,"errorMessage":"caveman-code: old_string appears ${occurrences} times in ${input.path}; add surrounding context or pass replace_all","messagePattern":"caveman-code: old_string appears (.+?) times in (.+?); add surrounding context or pass replace_all","errorType":"validation","errorClass":null,"httpStatus":null,"severity":"error","filePath":"packages/agent/src/code.ts","lineNumber":352,"sourceCode":"      old_string: schema.string(),\n      new_string: schema.string(),\n      replace_all: schema.optional(schema.boolean()),\n    }),\n    effect: \"write\",\n    result: \"inline\",\n    timeoutMs: READ_TIMEOUT_MS,\n    async execute(input) {\n      if (input.old_string === input.new_string) {\n        throw new Error(\"caveman-code: old_string and new_string are identical\");\n      }\n      const target = await contained(input.path);\n      const content = await readFile(target, \"utf8\");\n      const occurrences = content.split(input.old_string).length - 1;\n      if (occurrences === 0) {\n        throw new Error(`caveman-code: old_string not found in ${input.path}`);\n      }\n      if (occurrences > 1 && input.replace_all !== true) {\n        throw new Error(\n          `caveman-code: old_string appears ${occurrences} times in ${input.path}; ` +\n          \"add surrounding context or pass replace_all\",\n        );\n      }\n      // split/join UNCONDITIONALLY. String.prototype.replace\n      // interprets `$&`, `$\\``, `$'`, `$$`, `$1`… in the REPLACEMENT even for a\n      // string pattern, so a new_string containing any of them would silently\n      // corrupt the file. The non-replace_all branch is guaranteed exactly one\n      // occurrence above, so joining replaces precisely that one.\n      const updated = content.split(input.old_string).join(input.new_string);\n      await writeFile(target, updated, \"utf8\");\n      const replaced = input.replace_all === true ? occurrences : 1;\n      return capOutput(\n        `edited ${input.path}: ${replaced} replacement${replaced === 1 ? \"\" : \"s\"}`,\n        caps.edit_file,\n      );\n    },\n  });","sourceCodeStart":334,"sourceCodeEnd":370,"githubUrl":"https://github.com/JuliusBrussee/caveman/blob/3ee70a102609e550bd2e68004bf5990a9341c851/packages/agent/src/code.ts#L334-L370","documentation":"The edit tool counts occurrences of old_string; when it matches more than once and input.replace_all is not exactly true, the replacement would be ambiguous, so it throws 'caveman-code: old_string appears N times in <path>; add surrounding context or pass replace_all'. This prevents silently editing the wrong occurrence.","triggerScenarios":"Calling the edit tool with an old_string that occurs 2+ times in the file (e.g. a common pattern like `});` or a repeated function call) while omitting replace_all, or setting replace_all to anything other than the boolean true.","commonSituations":"Replacing boilerplate that appears in many places (imports, closing braces, repeated config lines); editing minified or highly repetitive files; passing replace_all: \"true\" (string) which fails the !== true check.","solutions":["Expand old_string with surrounding context so it matches exactly one occurrence.","Pass replace_all: true (boolean) if every occurrence should be replaced.","Read the file first and pick a unique anchor (include the function/variable name) around the target.","Perform multiple targeted edits, one unique snippet each, instead of one ambiguous edit.","Ensure replace_all is the boolean true, not the string \"true\"."],"exampleFix":"// before\nedit({ path: \"a.ts\", old_string: \"return null;\" })\n// after\nedit({ path: \"a.ts\", old_string: \"function load() {\\n  return null;\\n}\", new_string: \"function load() {\\n  return undefined;\\n}\" })","handlingStrategy":"validation","validationCode":"const content = await fs.promises.readFile(path, \"utf8\");\nconst occurrences = content.split(oldString).length - 1;\nif (occurrences > 1 && replaceAll !== true) {\n  throw new Error(`old_string occurs ${occurrences} times; add context or set replace_all: true`);\n}","typeGuard":null,"tryCatchPattern":"try {\n  await edit(input);\n} catch (e) {\n  if (e.message.includes(\"times in\") && e.message.includes(\"replace_all\")) {\n    console.error(\"Ambiguous match: widen old_string with context or pass replace_all: true.\");\n  } else throw e;\n}","preventionTips":["Count occurrences of old_string before editing; require uniqueness unless replace_all is intended.","Include surrounding lines (function name, distinct context) to make the match unique.","Pass replace_all as the boolean true, never the string \"true\".","Avoid editing highly repetitive boilerplate with short snippets; split into targeted edits."],"tags":["editing","ambiguity","tooling"],"backgroundTag":"invalid-argument-value","analyzedSha":"3ee70a102609e550bd2e68004bf5990a9341c851","analyzedAt":"2026-09-20T15:53:39.229Z","contentChangedAt":"2026-09-20T15:53:39.229Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}