{"record":{"id":"fb1d15d59c67fe11","repo":"JuliusBrussee/caveman","slug":"cave-context-segment-missing","errorCode":"cave_context_segment_missing","errorMessage":"cave_context_segment_missing:${id}","messagePattern":"cave_context_segment_missing:(.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"packages/agent/src/runtime.ts","lineNumber":2586,"sourceCode":"    [\"results_artifacts\", (bill.artifact ?? 0) + (bill.skill ?? 0) + (bill.tool_result ?? 0)],\n    [\"output\", outputMaxTokens],\n  ];\n  for (const [slot, used] of slots) {\n    if (used > plan.budgets[slot]) throw new Error(`cave_${slot}_budget_exceeded`);\n  }\n}\n\nexport function assembleSystemPrompt(\n  definition: AgentDefinition,\n  lowered: LoweredContext,\n  bodies: ReadonlyMap<string, Uint8Array> = lowered.bodies,\n): string {\n  const decoder = new TextDecoder();\n  const required = [\"agent.instructions\", ...definition.contexts.map((item) => item.id)];\n  const parts: string[] = [];\n  for (const id of required) {\n    const segment = lowered.ir.segments.find((item) => item.id === id);\n    if (!segment) throw new Error(`cave_context_segment_missing:${id}`);\n    const body = bodies.get(segment.bodyHandle);\n    if (!body) throw new Error(`cave_context_body_missing:${id}`);\n    const text = decoder.decode(body);\n    parts.push(id === \"agent.instructions\" ? text : `<cave-context id=${JSON.stringify(id)}>\\n${text}\\n</cave-context>`);\n  }\n  if (definition.output) {\n    parts.push(`<cave-output max_tokens=${definition.output.maxTokens}>Return output matching declared schema when present.</cave-output>`);\n  }\n  if (definition.memory) {\n    parts.push(\"<cave-memory>Use cave_memory_search before relying on prior-session facts. Use cave_memory_remember only for durable facts the user intended to retain.</cave-memory>\");\n  }\n  return parts.join(\"\\n\\n\");\n}\n\nasync function applyEfficiencyPlan(\n  lowered: LoweredContext,\n  plan: CavePlan | undefined,\n  engineBin: string | undefined,","sourceCodeStart":2568,"sourceCodeEnd":2604,"githubUrl":"https://github.com/JuliusBrussee/caveman/blob/3ee70a102609e550bd2e68004bf5990a9341c851/packages/agent/src/runtime.ts#L2568-L2604","documentation":"Thrown during system-prompt assembly when a required context segment id — either 'agent.instructions' or one of the ids listed in definition.contexts — cannot be found in the lowered IR's segments. The runtime builds the prompt from declared context ids and refuses to silently omit one. This is an integrity check between the agent definition and the lowering step.","triggerScenarios":"definition.contexts references a context id that the lowering step never produced as a segment in lowered.ir.segments, or the 'agent.instructions' segment is absent from the IR.","commonSituations":"A typo or rename mismatch between the context id in the agent definition and the id produced by the context loader/lowerer; a context source that failed to load and was skipped during lowering; stale definition after refactoring context ids.","solutions":["Compare the id in the error with the ids your lowering step emits for lowered.ir.segments and fix the mismatch.","Ensure every definition.contexts entry is actually loaded and lowered (check loader errors/skips upstream).","Log lowered.ir.segments.map(s => s.id) at assembly time to see which ids exist.","Remove or rename the stale context id in the agent definition."],"exampleFix":"// before\ndefinition.contexts = [{ id: \"project-docs\", ... }]; // lowerer emits \"docs\"\n// after\ndefinition.contexts = [{ id: \"docs\", ... }]; // matches lowerer output","handlingStrategy":"validation","validationCode":"const irIds = new Set(lowered.ir.segments.map(s => s.id));\nconst missing = [\"agent.instructions\", ...definition.contexts.map(c => c.id)].filter(id => !irIds.has(id));\nif (missing.length) throw new Error(`contexts not lowered: ${missing.join(\",\")}`);","typeGuard":"function allSegmentsPresent(ids: string[], segments: { id: string }[]): boolean {\n  const have = new Set(segments.map(s => s.id));\n  return ids.every(id => have.has(id));\n}","tryCatchPattern":"try {\n  const prompt = assembleSystemPrompt(definition, lowered, bodies);\n} catch (err) {\n  if (err instanceof Error && err.message.startsWith(\"cave_context_segment_missing:\")) {\n    const id = err.message.split(\":\")[1];\n    // fix definition.contexts id or fix lowerer output, then retry\n  } else throw err;\n}","preventionTips":["Keep context ids in a single shared constant/module used by both definition and lowerer.","Add a unit test asserting every declared context id survives lowering.","Log emitted segment ids during lowering in CI to catch renames early.","Never hardcode context id strings in more than one place."],"tags":["context","segment","id-mismatch","agent-runtime"],"backgroundTag":"resource-not-found","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"}