{"record":{"id":"635044dc316e4828","repo":"JuliusBrussee/caveman","slug":"cave-subagent-definition-cycle","errorCode":"cave_subagent_definition_cycle","errorMessage":"cave_subagent_definition_cycle","messagePattern":"cave_subagent_definition_cycle","errorType":"validation","errorClass":null,"httpStatus":null,"severity":"error","filePath":"packages/agent/src/definition-graph.ts","lineNumber":23,"sourceCode":");\n\nexport function validateAgentGraph(root: AgentDefinition): void {\n  // Memoize per inherited containment posture: the same child definition\n  // reached under a sandbox-required ancestor must be re-checked, not skipped.\n  const visited = [new Set<AgentDefinition>(), new Set<AgentDefinition>()];\n  const active = new Set<AgentDefinition>();\n\n  const visit = (\n    definition: AgentDefinition,\n    depth: number,\n    sandboxRequired: boolean,\n  ): void => {\n    if (!definition || definition.kind !== \"agent\" ||\n        !Array.isArray(definition.tools)) {\n      throw new Error(\"cave_agent_definition_invalid\");\n    }\n    if (depth > 8) throw new Error(\"cave_subagent_depth_limit\");\n    if (active.has(definition)) throw new Error(\"cave_subagent_definition_cycle\");\n    // Host mode is an opt-in the root makes for itself. A descendant cannot use\n    // it to run closures outside an ancestor's required containment.\n    if (sandboxRequired && definition.sandbox === \"host\") {\n      throw new Error(\"cave_host_sandbox_nested_under_required\");\n    }\n    const memo = visited[sandboxRequired ? 1 : 0]!;\n    if (memo.has(definition)) return;\n    active.add(definition);\n    const childSandboxRequired = sandboxRequired ||\n      definition.sandbox === \"required\";\n    const names = new Set<string>();\n    for (const declared of definition.tools) {\n      if (!declared || declared.kind !== \"tool\" ||\n          typeof declared.name !== \"string\") {\n        throw new Error(\"cave_tool_definition_invalid\");\n      }\n      if (names.has(declared.name)) throw new Error(\"cave_duplicate_tool_name\");\n      names.add(declared.name);","sourceCodeStart":5,"sourceCodeEnd":41,"githubUrl":"https://github.com/JuliusBrussee/caveman/blob/3ee70a102609e550bd2e68004bf5990a9341c851/packages/agent/src/definition-graph.ts#L5-L41","documentation":"Thrown by visit in validateAgentGraph when the same AgentDefinition object reference appears twice on the current active validation path — i.e. the subagent graph contains a cycle. Depth limiting alone would not catch cycles, so an explicit active-set detects them.","triggerScenarios":"Defining agent A whose tools include a subagent tool referencing agent B, and B (directly or transitively) references A again via runtime.definition — the same object re-entering visit while still active.","commonSituations":"Programmatically generated definitions where a parent auto-wires its children and a child points back to the parent, config referencing shared agent objects that mutually compose, or accidental reuse of one definition object at multiple levels of one path.","solutions":["Break the cycle: remove the subagent tool that points back up the chain.","Deep-clone definitions if intentional reuse across branches is desired (cycles are per-object-reference on one path; sibling reuse is fine).","Refactor mutual composition into a flat structure where both agents are siblings under a common parent."],"exampleFix":"// before\nagentA.tools.push(subagentTool(agentB));\nagentB.tools.push(subagentTool(agentA)); // cycle\n// after\nagentA.tools.push(subagentTool(agentB));\n// agentB no longer references agentA","handlingStrategy":"validation","validationCode":"function hasCycle(def: AgentDefinition, active = new Set<AgentDefinition>()): boolean {\n  if (active.has(def)) return true;\n  active.add(def);\n  const cyc = (def.tools ?? []).some(t => t.runtime?.kind === \"subagent\" && hasCycle(t.runtime.definition, active));\n  active.delete(def);\n  return cyc;\n}\nif (hasCycle(root)) throw new Error(\"subagent graph contains a cycle\");","typeGuard":null,"tryCatchPattern":"try {\n  validateAgentGraph(root);\n} catch (e) {\n  if (e instanceof Error && e.message === \"cave_subagent_definition_cycle\") {\n    console.error(\"Subagent graph is cyclic; remove the back-reference or deep-clone shared definitions\");\n  } else throw e;\n}","preventionTips":["Model agent composition as a DAG — never let a child reference an ancestor.","Deep-clone definitions when reusing the same object across branches of one path.","Run cycle detection on generated graphs before validation."],"tags":["agent-definition","cycle-detection","validation"],"backgroundTag":"invalid-state-transition","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"}