@aaac/runtime 0.3.1 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +1 -1
  2. package/bin/dev-team.mjs +6018 -0
  3. package/dist/adapters/claude-agent-sdk.d.ts +1 -1
  4. package/dist/adapters/claude-agent-sdk.js +1 -1
  5. package/dist/adapters/mock.d.ts +1 -1
  6. package/dist/adapters/openai-agents-sdk.d.ts +1 -1
  7. package/dist/adapters/openai-agents-sdk.js +2 -2
  8. package/dist/{chunk-BHTHXGA3.js → chunk-4RFPLCKG.js} +7 -6
  9. package/dist/{chunk-BHTHXGA3.js.map → chunk-4RFPLCKG.js.map} +1 -1
  10. package/dist/{chunk-N2EA3TGS.js → chunk-BLPWSV4T.js} +7 -3
  11. package/dist/chunk-BLPWSV4T.js.map +1 -0
  12. package/dist/{chunk-EBMQHLXY.js → chunk-CRKN7CIO.js} +2 -2
  13. package/dist/{chunk-KTVMMG33.js → chunk-DX3RJTWJ.js} +2 -17
  14. package/dist/{chunk-KTVMMG33.js.map → chunk-DX3RJTWJ.js.map} +1 -1
  15. package/dist/{chunk-GGBNVCPV.js → chunk-EYK4E3XE.js} +3 -3
  16. package/dist/{chunk-5ZDW4RP7.js → chunk-K5XDDJFK.js} +2 -2
  17. package/dist/{chunk-2SG3TBI3.js → chunk-QQTFYLUX.js} +2 -2
  18. package/dist/{chunk-EA4V5DVD.js → chunk-RIXKPQFC.js} +1 -2
  19. package/dist/{chunk-EA4V5DVD.js.map → chunk-RIXKPQFC.js.map} +1 -1
  20. package/dist/claude-bundles/full.js +1 -1
  21. package/dist/claude-bundles/lean.js +1 -1
  22. package/dist/generator/index.js +2 -2
  23. package/dist/{hooks-lite-BtOGc2F_.d.ts → hooks-lite-inKV2rv8.d.ts} +5 -5
  24. package/dist/index.d.ts +16 -9
  25. package/dist/index.js +110 -139
  26. package/dist/index.js.map +1 -1
  27. package/dist/lib/claude-native/hooks-lite.d.ts +1 -1
  28. package/dist/lib/claude-native/hooks-lite.js +4 -4
  29. package/dist/lib/claude-native/hooks-prompt.js +4 -4
  30. package/dist/lib/claude-native/index.d.ts +1 -1
  31. package/dist/lib/claude-native/index.js +7 -7
  32. package/dist/{task-runner-CgQx1KUq.d.ts → task-runner-Cpr-GTrl.d.ts} +4 -6
  33. package/package.json +10 -18
  34. package/dist/adapters/adk-sdk.d.ts +0 -139
  35. package/dist/adapters/adk-sdk.js +0 -312
  36. package/dist/adapters/adk-sdk.js.map +0 -1
  37. package/dist/chunk-N2EA3TGS.js.map +0 -1
  38. /package/dist/{chunk-EBMQHLXY.js.map → chunk-CRKN7CIO.js.map} +0 -0
  39. /package/dist/{chunk-GGBNVCPV.js.map → chunk-EYK4E3XE.js.map} +0 -0
  40. /package/dist/{chunk-5ZDW4RP7.js.map → chunk-K5XDDJFK.js.map} +0 -0
  41. /package/dist/{chunk-2SG3TBI3.js.map → chunk-QQTFYLUX.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/lib/guardrail-hooks.ts","../src/lib/command-body-files.ts"],"sourcesContent":["/**\n * SDK Guardrail Hook Bridge — generic adapter from guardrail check functions to\n * SDK-compatible hook responses.\n *\n * Embedded guardrail rules are converted via createGuardrailHooksFromRules(),\n * which delegates to createGuardrailHooks(). All hook logic lives here.\n *\n * Every check this module runs arrives as an ARGUMENT. It has no ambient\n * source: it does not know what a plugin is, and it reaches for no registry, so\n * what a route enforces is decided by that route and is readable at its call\n * site. This is also what keeps the module light enough to sit on the lean\n * hot-path graph — see `PluginRegistry.guardrailChecks` for the measurement and\n * for which layer supplies the plugin source.\n */\n\nimport { realpathSync } from \"node:fs\";\nimport { basename, dirname, isAbsolute, join, relative, resolve, sep } from \"node:path\";\nimport { commandScanText } from \"./command-body-files.js\";\n\n/**\n * Enforcement action of a guardrail.\n *\n * `block` / `warn` / `shadow` / `info` are DECLARED by the active guardrail\n * policy. `unresolved` is not an enforcement level a policy can declare: it is\n * the state of a guardrail that has a binding implementation while the active\n * policy declares no action for it (no `active_guardrail_policy` in the project\n * manifest, an unknown policy name, or a policy with no rule for the guardrail).\n *\n * An unresolved guardrail DENIES — see `getBlockingViolations`. Substituting a\n * permissive default here is what turned every `action: block` guardrail in a\n * policy-less project into a no-op while the guardrail cache still listed it\n * (#293); the action is not knowable, so the operation the guardrail covers is\n * refused and the message says how to fix the manifest.\n *\n * ONE declaration for the set, so the type and the check `isGuardrailRuleData`\n * performs cannot name different ones — a bare union has nothing a predicate\n * can read, and the rules cross a process boundary as JSON.\n */\nexport const GUARDRAIL_ACTIONS = [\n \"block\",\n \"warn\",\n \"shadow\",\n \"info\",\n \"unresolved\",\n] as const;\n\nexport type GuardrailAction = (typeof GUARDRAIL_ACTIONS)[number];\n\n/** The action of a guardrail whose active policy declares none (see GuardrailAction). */\nexport const UNRESOLVED_GUARDRAIL_ACTION = \"unresolved\" as const;\n\nexport interface GuardrailCheckResult {\n guardrail_id: string;\n passed: boolean;\n action: GuardrailAction;\n message: string;\n}\n\n/**\n * What a guardrail hook answers.\n *\n * A refusal CARRIES ITS MESSAGE — one fact, not two independently optional\n * ones. Declared as separate optionals, every consumer had to supply a value\n * for a case no producer can reach (`beforeShellExecution`, `preToolUse` and\n * `afterFileEdit` all refuse through `denyResponse`, which always writes one),\n * and they supplied three different ones: two hand-written copies of \"Command\n * blocked by guardrail\" in the PreToolUse routes and a fall-back to\n * `agent_message` in the SDK adapter (#311). Nothing rejected a fourth, and\n * nothing noticed when one of them drifted, because a string literal that\n * disagrees with another string literal is not a type error.\n *\n * So the union states what the producer already guarantees, and the question\n * disappears instead of being answered in more places.\n */\nexport type HookResponse =\n | {\n permission: \"deny\";\n /** Every blocking violation, rendered. Never empty — a refusal has a cause. */\n user_message: string;\n agent_message: string;\n additionalContext?: undefined;\n }\n | {\n permission?: undefined;\n user_message?: undefined;\n agent_message?: undefined;\n /** Violations to surface to the agent without refusing. */\n additionalContext?: string;\n };\n\nexport interface GuardrailRule {\n guardrail_id: string;\n pattern: string;\n action: GuardrailAction;\n message: string;\n file_glob?: string;\n exclude_glob?: string;\n}\n\nexport interface GuardrailRuleData {\n commandRules: GuardrailRule[];\n fileRules: GuardrailRule[];\n contentRules: GuardrailRule[];\n}\n\nfunction isGuardrailRule(value: unknown): value is GuardrailRule {\n if (typeof value !== \"object\" || value === null) return false;\n const rule = value as Record<string, unknown>;\n return (\n typeof rule.guardrail_id === \"string\" &&\n typeof rule.pattern === \"string\" &&\n GUARDRAIL_ACTIONS.includes(rule.action as GuardrailAction) &&\n typeof rule.message === \"string\" &&\n (rule.file_glob === undefined || typeof rule.file_glob === \"string\") &&\n (rule.exclude_glob === undefined || typeof rule.exclude_glob === \"string\")\n );\n}\n\n/**\n * The single gate in front of {@link GuardrailRuleData}, next to the type it\n * grants — the rules are written to a cache file by one process and read back by\n * another, so the reader has only bytes and this predicate is what turns them\n * into rules the PreToolUse guard may run.\n *\n * Every declared field is checked, `action` against {@link GUARDRAIL_ACTIONS} —\n * the rules decide whether an operation is refused, so a rule carrying an action\n * the evaluator does not implement is not one this guard may run.\n */\nexport function isGuardrailRuleData(value: unknown): value is GuardrailRuleData {\n if (typeof value !== \"object\" || value === null) return false;\n const data = value as Record<string, unknown>;\n return (\n Array.isArray(data.commandRules) &&\n data.commandRules.every(isGuardrailRule) &&\n Array.isArray(data.fileRules) &&\n data.fileRules.every(isGuardrailRule) &&\n Array.isArray(data.contentRules) &&\n data.contentRules.every(isGuardrailRule)\n );\n}\n\nexport interface GuardrailCheckFunctions {\n checkCommand: (command: string) => GuardrailCheckResult[];\n checkFilePath: (filePath: string) => GuardrailCheckResult[];\n checkContent: (filePath: string, content: string) => GuardrailCheckResult[];\n}\n\nfunction globFragmentToRegex(fragment: string): string {\n let out = \"\";\n for (const ch of fragment) {\n if (ch === \"*\") out += \"[^/]*\";\n else if (ch === \"?\") out += \"[^/]\";\n else if (\".+^$|()[]\\\\\".includes(ch)) out += \"\\\\\" + ch;\n else out += ch;\n }\n return out;\n}\n\n/**\n * A pattern ending in `/` denotes a DIRECTORY and matches everything under it\n * (#262). This is the dominant style in artifact `path_patterns` — the embedded\n * dev-team DSL (`src/`, `lib/`, `tests/`, `.cursor/rules/`) and every\n * artifact-contracts registry rely on it. Without this, such a pattern compiles\n * to `^src/$`, which no file path can ever equal, so path → artifact reverse\n * lookup silently matched nothing and the artifact edit guard never fired.\n *\n * The rewrite is monotonic: file paths never end in `/`, so a pattern that\n * matched something before still matches exactly the same paths.\n */\nfunction expandDirectoryPattern(pattern: string): string {\n return pattern.endsWith(\"/\") ? `${pattern}**` : pattern;\n}\n\nexport function matchGlob(rawPattern: string, path: string): boolean {\n const pattern = expandDirectoryPattern(rawPattern);\n let regex = \"\";\n let i = 0;\n while (i < pattern.length) {\n if (pattern[i] === \"*\" && pattern[i + 1] === \"*\" && pattern[i + 2] === \"/\") {\n regex += \"(?:.+/)?\";\n i += 3;\n } else if (pattern[i] === \"*\" && pattern[i + 1] === \"*\") {\n regex += \".*\";\n i += 2;\n } else if (pattern[i] === \"*\") {\n regex += \"[^/]*\";\n i += 1;\n } else if (pattern[i] === \"?\") {\n regex += \"[^/]\";\n i += 1;\n } else if (pattern[i] === \"{\") {\n const end = pattern.indexOf(\"}\", i);\n if (end !== -1) {\n const alts = pattern.slice(i + 1, end).split(\",\").map(globFragmentToRegex);\n regex += \"(?:\" + alts.join(\"|\") + \")\";\n i = end + 1;\n } else {\n regex += \"\\\\{\";\n i += 1;\n }\n } else if (\".+^$|()[]\\\\\".includes(pattern[i])) {\n regex += \"\\\\\" + pattern[i];\n i += 1;\n } else {\n regex += pattern[i];\n i += 1;\n }\n }\n return new RegExp(\"^\" + regex + \"$\").test(path);\n}\n\n/**\n * Does this tool-input key name a file the call acts on?\n *\n * Derived from the naming convention rather than from a census of today's\n * tools. `NotebookEdit` calls its target `notebook_path`, so a reader that knew\n * only `file_path`/`path` classified that call correctly and then judged\n * nothing — the artifact guard was reached and found no path to protect (#309).\n * Every such key so far ends in `path`, so the rule follows the suffix and the\n * next tool to name an `output_path` is already covered.\n *\n * `file` / `filename` carry no suffix; they are the SDK progress-event\n * spellings the task runner reads, and are named for that reason.\n */\nfunction namesTargetFile(key: string): boolean {\n return (\n key === \"path\" || key === \"file\" || key === \"filename\" || key.endsWith(\"_path\")\n );\n}\n\n/**\n * Does this tool-input key carry text the call is about to WRITE?\n *\n * The same convention rule as `namesTargetFile`, over the other half of a file\n * edit. `Write` calls it `content`; `Edit` and `NotebookEdit` prefix the value\n * they are installing with `new_` (`new_string`, `new_source`), so the rule\n * follows the prefix and a tool that arrives naming a `new_text` is covered.\n *\n * The exclusions are the point. `old_string` is the text being REMOVED, and\n * scanning it would refuse the very edit that takes a forbidden string OUT of a\n * file — a content guardrail that fights its own repair. `file_path` and the\n * `cell_id` / `edit_mode` sort of parameter are neither. So \"everything the\n * payload happens to hold\" is not an available answer; the key has to say it is\n * the incoming value.\n */\nfunction namesPendingContent(key: string): boolean {\n return key === \"content\" || key.startsWith(\"new_\");\n}\n\n/**\n * The first non-empty string value under a key `names` accepts, or `\"\"`.\n *\n * Keys are scanned in sorted order, so the answer cannot depend on the order a\n * payload happened to serialize its properties in.\n *\n * Reads TOP-LEVEL string values only, and returns the first match: a payload\n * carrying its files in an array (`file_paths`) or nested (`edits[].new_string`)\n * is not covered, and no built-in has that shape today (#309).\n */\nfunction firstStringValue(\n toolInput: Record<string, unknown> | undefined | null,\n names: (key: string) => boolean,\n): string {\n if (!toolInput) return \"\";\n for (const key of Object.keys(toolInput).sort()) {\n if (!names(key)) continue;\n const value = toolInput[key];\n if (typeof value === \"string\" && value) return value;\n }\n return \"\";\n}\n\n/**\n * The file a tool call names as its target, or `\"\"` when it names none.\n *\n * ONE reader for every consumer that asks \"which file is this call about\": the\n * `preToolUse` file guardrails below, both Claude Code PreToolUse routes, the\n * `guard evaluate` CLI, the Claude SDK adapter and the task runner's\n * `process.edit` events. They had four spellings of it between them, agreeing\n * on `file_path` and diverging after — and a reader that knows fewer keys than\n * the tool writes turns a guard that runs into a guard that decides nothing.\n *\n * Scope is a TOOL INPUT. The after-file-edit payloads (`afterFileEdit` here,\n * the Cursor hook input in `guard-commands`) are not tool inputs: their\n * `file_path` is a top-level protocol field and is the whole interface.\n */\nexport function toolTargetPath(\n toolInput: Record<string, unknown> | undefined | null,\n): string {\n return firstStringValue(toolInput, namesTargetFile);\n}\n\n/**\n * Claude Code tools that cannot modify a file in the working tree — the ONLY\n * calls a `file_glob` / `content_regex` guardrail lets past unexamined.\n *\n * This list is inverted on purpose. Naming the tools to guard (`Edit`, `Write`,\n * `MultiEdit`) meant the guard covered exactly the tools that existed when it\n * was written, and `NotebookEdit` — a first-party file editor — walked through\n * a `manual_edit: forbidden` artifact for as long as it has existed (#309).\n * Every future tool would have arrived the same way, silently, because a name\n * that is missing from an allowlist looks identical to a name that is absent\n * for a reason.\n *\n * Naming the tools NOT to guard puts the staleness on the harmless side. An\n * unrecognised tool is judged instead of waved through, and being judged costs\n * it nothing unless it names a covered file: `toolTargetPath` reads the file out\n * of the call, so a tool that targets no file resolves to nothing and is\n * allowed. \"Deny by default\" here therefore means \"examined by default\", not\n * \"refused by default\" — a new Claude Code release does not lock the session\n * down.\n *\n * Every name is a Claude Code built-in, pinned against an independent\n * transcription of the tool reference in `__tests__/fixtures/`.\n */\nexport const NON_MUTATING_TOOLS: ReadonlySet<string> = new Set([\n // Name a path in their input and only ever read it.\n \"Read\",\n \"Glob\",\n \"Grep\",\n \"LSP\",\n // Load or delegate: whatever they set in motion arrives at the same guard as\n // its own tool call, and is guarded there.\n \"Task\",\n \"Agent\",\n \"Skill\",\n // Reach outside the working tree entirely.\n \"WebFetch\",\n \"WebSearch\",\n // Session-local state rather than files.\n \"TodoWrite\",\n \"AskUserQuestion\",\n \"ToolSearch\",\n \"EnterPlanMode\",\n \"ExitPlanMode\",\n]);\n\n/**\n * `path` with its symlinks resolved, as far as the filesystem has it.\n *\n * The target of a `Write` usually does not exist yet, so the deepest ancestor\n * that does is resolved and the rest is re-attached. A root and a target reached\n * through different spellings of one directory — macOS's `/tmp` and\n * `/private/tmp` — then compare equal.\n */\nfunction realPathAsFarAsItExists(path: string): string {\n const missing: string[] = [];\n let head = path;\n for (;;) {\n try {\n return join(realpathSync(head), ...missing);\n } catch {\n const parent = dirname(head);\n if (parent === head) return path;\n missing.unshift(basename(head));\n head = parent;\n }\n }\n}\n\n/**\n * A tool call's target as the file guards match it: relative to `root`, with\n * `/` separators, when it lies inside it — the space `path_patterns` and\n * `file_glob` patterns are written in — and absolute when it does not.\n *\n * Claude Code names every file by absolute path. Matched as given, a pattern\n * like `.claude/agents/` or `implementation-plan.yaml` never equals one; only a\n * `**`-prefixed pattern does. A relative target is read against `root`. A\n * target outside the root stays absolute, which keeps a\n * `**`-prefixed rule — the credential-file globs — applying to it and puts it\n * in no artifact.\n */\nfunction rootRelativeTarget(path: string, root: string): string {\n const absolute = resolve(root, path);\n const rel = relative(realPathAsFarAsItExists(root), realPathAsFarAsItExists(absolute));\n const outside = rel === \"\" || isAbsolute(rel) || rel.split(sep)[0] === \"..\";\n return outside ? absolute : rel.split(sep).join(\"/\");\n}\n\n/**\n * The file this call may WRITE, or `\"\"` when there is none — relative to `root`\n * when it lies inside it (`rootRelativeTarget`). `root` is the directory the\n * project's patterns are written against; `undefined` stands for the working\n * directory, which is where a relative path already resolves.\n *\n * ONE answer to \"which operations do the file guards cover, and which path do\n * they judge\", for every route: the `preToolUse` gate below, both Claude Code\n * PreToolUse routes (through `artifactGuardTarget`), the `guard evaluate` CLI\n * and the Claude SDK adapter. The artifact guard and the file guardrails read\n * the same string because they read it here.\n *\n * `file_glob` and `content_regex` guard WRITES. That is not a reading of what\n * the matcher could mean — it is what every rule declared against it says:\n * across `agents/bindings/runtime.yaml`, `examples/governance/bindings/runtime.yaml`\n * and the bindings `aaac init` bootstraps a new project with, all 19 messages\n * are \"Writing to … is blocked\", \"Generated files must not be hand-edited\" or\n * \"Do not write … at repo root\". None is about reading one. So a guard that\n * refused `Read` would refuse an operation no rule in this repo asks it to, and\n * `protect-generated-files` — `action: block` under the default policy — would\n * stop an agent reading the generated code it has to read to work.\n *\n * Answering it HERE rather than in the hook is what keeps the routes on one\n * verdict. Answered per-consumer, it went two ways immediately: the workspace\n * PreToolUse route filtered by this set and the single-component one did not, so\n * the same `Read secrets/prod.env` was allowed by one and refused by the other\n * (#316).\n */\nexport function toolWriteTarget(\n toolName: string | undefined,\n toolInput: Record<string, unknown> | undefined | null,\n root: string | undefined,\n): string {\n if (NON_MUTATING_TOOLS.has(toolName ?? \"\")) return \"\";\n const target = toolTargetPath(toolInput);\n return target && rootRelativeTarget(target, root ?? process.cwd());\n}\n\n/**\n * The text a tool call is about to write into `toolTargetPath`, or `\"\"`.\n *\n * The companion reader, and the reason `content_regex` guardrails are decided\n * BEFORE the write rather than reported after it. Claude Code hands PreToolUse\n * the tool's parameters in full, so the pending content is already in the\n * payload; the only event that could carry it afterwards is PostToolUse, whose\n * `block` cannot un-write the file and would answer the same declared\n * `action: block` differently from every other route (#316).\n */\nexport function toolPendingContent(\n toolInput: Record<string, unknown> | undefined | null,\n): string {\n return firstStringValue(toolInput, namesPendingContent);\n}\n\n/**\n * What one check is asked about: a command, a path, or a path and the content\n * about to go into it. Nothing here names an AGENT.\n *\n * Which rules an agent is checked against is settled before an evaluator\n * exists, by the layer that knows where rules come from — see\n * `createAgentGuardrailHooks` in `execute.ts`, the one constructor of per-agent\n * hooks. An agent id travelling inside the context would mean that same\n * question could also be answered later, from in here, and it did: a second\n * per-agent constructor exported beside that one wrote `agentId` on every\n * context it forwarded, no gate read it, and the two disagreed on memoisation\n * and on what an agent with no rules gets (#333).\n *\n * So the field is gone, and an OBJECT LITERAL naming an agent is now TS2353 —\n * which is what makes that constructor un-pasteable verbatim.\n * `adapter-guardrail-hooks.test.ts` pins the absence with a `@ts-expect-error`\n * that turns into TS2578 if the field returns.\n *\n * That is the whole of what the type says, and it is less than it sounds.\n * Excess-property checking reaches object literals only: an `as HookContext`\n * cast, an interface that extends this one, a literal bound to a variable\n * first, and a plain `Record<string, unknown>` all compile — measured, not\n * assumed. And a second per-agent constructor that simply never writes an agent\n * id needs none of them and compiles as it is. What is removed here is the\n * AFFORDANCE the duplicate happened to use, not the possibility of another one.\n * The invariant — ONE constructor of per-agent hooks — is held by the\n * declaration on `createAgentGuardrailHooks` and by reading it, and nothing\n * mechanical will fail if it is broken.\n */\nexport interface HookContext {\n command?: string;\n filePath?: string;\n content?: string;\n}\n\n/**\n * The guardrail gates, one per payload SHAPE — not one per rule kind.\n *\n * Which gate a caller picks is decided by what it holds, never by which rules\n * it wants consulted: every gate runs every rule the context can answer. An\n * object with four methods hid the opposite for as long as this existed — the\n * Claude Code PreToolUse route called `beforeShellExecution` and nothing else,\n * so a project's `file_glob` and `content_regex` guardrails were enforced by\n * `guard evaluate` and by the SDK adapter while the session a person actually\n * works in never consulted them, and no type or single-route test could say so\n * (#316).\n */\n/**\n * A shell command about to run, and the directory it runs in — which resolves a\n * message body the command passes by file (`commandScanText`). Without `cwd`\n * the hook process's own directory is used.\n */\nexport interface ShellCommandInput {\n command?: string;\n cwd?: string;\n}\n\nexport interface GuardrailHooks {\n /** A command about to run. Claude Code PreToolUse (both routes), `guard evaluate`. */\n beforeShellExecution: (input: ShellCommandInput) => HookResponse;\n /**\n * The checks {@link GuardrailHooks.beforeShellExecution} decides on — the\n * command plus any body it passes by file. `guard evaluate` reports these, so\n * the list it prints is the one its verdict came from.\n */\n checkShellCommand: (input: ShellCommandInput) => GuardrailCheckResult[];\n /**\n * A TOOL INPUT, verbatim: `toolWriteTarget` reads the file out of it, relative\n * to `root` — the directory the rules' patterns are written against, the\n * working directory when absent — and `toolPendingContent` the text about to\n * go in. The single-component Claude Code PreToolUse route, `guard evaluate`\n * and the Claude SDK adapter.\n */\n preToolUse: (input: {\n tool_name?: string;\n tool_input?: Record<string, unknown>;\n root?: string;\n }) => HookResponse;\n /**\n * A file write whose path and content the caller has ALREADY extracted —\n * Cursor's after-file-edit event, where both are top-level protocol fields,\n * and the workspace Claude Code PreToolUse route, which must ask about the\n * member-repo-relative path (`stripMemberPrefix`) rather than the one the\n * tool named, because member guardrail patterns are written in that space.\n */\n afterFileEdit: (input: { file_path?: string; content?: string }) => HookResponse;\n /** The shared check runner. Not a gate: `getBlockingViolations` is what refuses. */\n runChecks: (ctx: HookContext) => GuardrailCheckResult[];\n}\n\n/**\n * Does this action refuse the operation? `block` because the policy says so,\n * `unresolved` because the policy says nothing and a guardrail whose action is\n * unknown must not be permissive (#293). Single definition — every deny gate\n * (shell / pre-tool-use / after-file-edit hooks, `guard evaluate`'s exit code,\n * the OpenAI Agents SDK tripwire) reads it through `getBlockingViolations`.\n */\nfunction isDenyAction(action: GuardrailAction): boolean {\n return action === \"block\" || action === UNRESOLVED_GUARDRAIL_ACTION;\n}\n\nexport function getBlockingViolations(results: GuardrailCheckResult[]): GuardrailCheckResult[] {\n return results.filter((r) => !r.passed && isDenyAction(r.action));\n}\n\nexport function getWarnings(results: GuardrailCheckResult[]): GuardrailCheckResult[] {\n return results.filter((r) => !r.passed && r.action === \"warn\");\n}\n\nexport function hasBlockingViolation(results: GuardrailCheckResult[]): boolean {\n return getBlockingViolations(results).length > 0;\n}\n\n/**\n * How a guardrail violation reads: `[guardrail-id] message`, one per line.\n *\n * Single definition — the shell, pre-tool-use and after-file-edit hooks all\n * refuse in the same words, a warning reads the same as the refusal it would\n * have been under a stricter policy, and the ADK adapter throws the same text\n * where it has no hook response to return. Exported for that last one only:\n * not re-exported from the package barrel, because no consumer outside this\n * runtime renders a violation.\n */\nexport function renderViolations(results: GuardrailCheckResult[]): string {\n return results.map((r) => `[${r.guardrail_id}] ${r.message}`).join(\"\\n\");\n}\n\n/**\n * The refusal every guardrail hook returns.\n *\n * The message is written HERE, once, rather than at each of the three hooks —\n * that is what makes `HookResponse`'s \"a denial carries its message\" a fact\n * about the code and not a convention. `user_message` and `agent_message` are\n * the same text on purpose: the agent is told exactly what the user is told.\n */\nfunction denyResponse(blocks: GuardrailCheckResult[]): HookResponse {\n const message = renderViolations(blocks);\n return { permission: \"deny\", user_message: message, agent_message: message };\n}\n\n/**\n * Create SDK hook functions from guardrail check functions.\n *\n * Returns hook functions in the format expected by the Claude SDK, plus a\n * generic runChecks() for programmatic use.\n *\n * Takes any number of check SOURCES and asks every one of them every question\n * the context can answer — which is the same rule `GuardrailHooks` states about\n * its gates, one level down. A source is not a rule kind and not a route: it is\n * one supplier of checks, and the hooks it produces cannot tell which supplier a\n * verdict came from. That is what lets a second supplier be added (the execution\n * layer adds the process's plugin guardrails, see\n * `PluginRegistry.guardrailChecks`) without there being a second EVALUATOR —\n * the property #304 and #316 exist to hold.\n *\n * Ordering is by question, then by source, so the sources a caller lists are\n * consulted in the order it listed them and a refusal reads the same way every\n * time (`renderViolations` joins in result order).\n *\n * Zero sources is a legitimate answer, not a degenerate one: it is what an agent\n * with no resolved rules and no plugins has, and the hooks it gets deny nothing.\n */\nexport function createGuardrailHooks(...sources: GuardrailCheckFunctions[]): GuardrailHooks {\n function runChecks(ctx: HookContext): GuardrailCheckResult[] {\n const results: GuardrailCheckResult[] = [];\n\n if (ctx.command) {\n for (const source of sources) results.push(...source.checkCommand(ctx.command));\n }\n\n if (ctx.filePath) {\n for (const source of sources) results.push(...source.checkFilePath(ctx.filePath));\n }\n\n if (ctx.filePath && ctx.content) {\n for (const source of sources) {\n results.push(...source.checkContent(ctx.filePath, ctx.content));\n }\n }\n\n return results;\n }\n\n function checkShellCommand(input: ShellCommandInput): GuardrailCheckResult[] {\n const command = input.command ?? \"\";\n if (!command) return [];\n return runChecks({ command: commandScanText(command, input.cwd) });\n }\n\n function beforeShellExecution(input: ShellCommandInput): HookResponse {\n const results = checkShellCommand(input);\n if (results.length === 0) return {};\n const blocks = getBlockingViolations(results);\n const warns = getWarnings(results);\n\n if (blocks.length > 0) {\n return denyResponse(blocks);\n }\n\n if (warns.length > 0) {\n return { additionalContext: renderViolations(warns) };\n }\n\n return {};\n }\n\n /**\n * The verdict on one file write — the ONE gate behind both file-shaped hooks\n * below, so `file_glob` and `content_regex` are decided together and cannot\n * be decided differently depending on which payload shape arrived.\n *\n * They diverged before: `preToolUse` asked `runChecks({ filePath })` and so\n * consulted `checkFilePath` alone, while `afterFileEdit` asked with the\n * content and got both. The rules a project declares are the same rules\n * either way (#316).\n */\n function fileWriteVerdict(filePath: string, content: string): HookResponse {\n if (!filePath) return {};\n\n const blocks = getBlockingViolations(runChecks({ filePath, content }));\n return blocks.length > 0 ? denyResponse(blocks) : {};\n }\n\n function preToolUse(input: {\n tool_name?: string;\n tool_input?: Record<string, unknown>;\n root?: string;\n }): HookResponse {\n return fileWriteVerdict(\n toolWriteTarget(input.tool_name, input.tool_input, input.root),\n toolPendingContent(input.tool_input),\n );\n }\n\n function afterFileEdit(input: { file_path?: string; content?: string }): HookResponse {\n return fileWriteVerdict(input.file_path ?? \"\", input.content ?? \"\");\n }\n\n return { beforeShellExecution, checkShellCommand, preToolUse, afterFileEdit, runChecks };\n}\n\n/** Compile a guardrail regex pattern, supporting inline `(?i)` case-insensitivity prefix. */\nexport function compileGuardrailPattern(pattern: string): RegExp {\n if (pattern.startsWith(\"(?i)\")) {\n return new RegExp(pattern.slice(4), \"i\");\n }\n return new RegExp(pattern);\n}\n\n/**\n * Create SDK hook functions from embedded guardrail rule data.\n *\n * The rules are the first check source; `extraSources` are consulted after\n * them, on every question. This is the funnel every route reaches the evaluator\n * through — both Claude Code PreToolUse routes, `guard evaluate` and the\n * execution layer — so what distinguishes those routes is visible here as an\n * argument list and nowhere else.\n */\nexport function createGuardrailHooksFromRules(\n rules: GuardrailRuleData,\n ...extraSources: GuardrailCheckFunctions[]\n): GuardrailHooks {\n const commandChecks = rules.commandRules.map((rule) => ({\n guardrail_id: rule.guardrail_id,\n pattern: compileGuardrailPattern(rule.pattern),\n action: rule.action,\n message: rule.message,\n }));\n\n const fileChecks = rules.fileRules;\n\n const contentChecks = rules.contentRules.map((rule) => ({\n guardrail_id: rule.guardrail_id,\n pattern: compileGuardrailPattern(rule.pattern),\n action: rule.action,\n message: rule.message,\n file_glob: rule.file_glob,\n exclude_glob: rule.exclude_glob,\n }));\n\n return createGuardrailHooks({\n checkCommand(command: string): GuardrailCheckResult[] {\n const results: GuardrailCheckResult[] = [];\n for (const check of commandChecks) {\n const passed = !check.pattern.test(command);\n results.push({\n guardrail_id: check.guardrail_id,\n passed,\n action: check.action,\n message: passed ? \"\" : check.message,\n });\n }\n return results;\n },\n\n checkFilePath(filePath: string): GuardrailCheckResult[] {\n const results: GuardrailCheckResult[] = [];\n for (const check of fileChecks) {\n if (check.exclude_glob && matchGlob(check.exclude_glob, filePath)) {\n continue;\n }\n const matched = matchGlob(check.pattern, filePath);\n results.push({\n guardrail_id: check.guardrail_id,\n passed: !matched,\n action: check.action,\n message: matched ? check.message : \"\",\n });\n }\n return results;\n },\n\n checkContent(filePath: string, content: string): GuardrailCheckResult[] {\n const results: GuardrailCheckResult[] = [];\n for (const check of contentChecks) {\n if (check.file_glob && !matchGlob(check.file_glob, filePath)) {\n continue;\n }\n if (check.exclude_glob && matchGlob(check.exclude_glob, filePath)) {\n continue;\n }\n const matched = check.pattern.test(content);\n results.push({\n guardrail_id: check.guardrail_id,\n passed: !matched,\n action: check.action,\n message: matched ? check.message : \"\",\n });\n }\n return results;\n },\n }, ...extraSources);\n}\n","/**\n * The text a command guardrail scans for a shell command: the command itself,\n * plus the contents of any message body it passes by file.\n *\n * `gh pr create --body-file body.md`, `gh issue comment -F body.md`,\n * `gh release create --notes-file notes.md` and `git commit -F msg.txt` carry\n * the same text a heredoc would put on the command line. Scanning only the\n * command string let a rule that stops the heredoc form pass the file form.\n *\n * Only a plain path is resolved — bare, or wrapped whole in one pair of quotes.\n * `-` (stdin), a path built from a variable, and anything that is not a regular\n * file (a FIFO would block the hook) are left out, and the command string alone\n * is what gets scanned for them, as before. The file text is joined on a new\n * line, so a pattern's `.` never spans the command and the body, and a pattern\n * anchored at `^` still means the start of the command.\n */\nimport { readFileSync, statSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\n\nconst BODY_FILE_FLAG =\n /(?:^|\\s)(?:--body-file|--notes-file|--file|-F)(?:=|\\s+)(?:'([^']*)'|\"([^\"]*)\"|([^\\s;|&]+))/g;\n\nexport function commandScanText(command: string, cwd?: string): string {\n const bodies: string[] = [];\n for (const match of command.matchAll(BODY_FILE_FLAG)) {\n const path = match[1] ?? match[2] ?? match[3];\n if (!path || path === \"-\") continue;\n const absPath = resolve(cwd ?? process.cwd(), path);\n try {\n if (!statSync(absPath).isFile()) continue;\n bodies.push(readFileSync(absPath, \"utf8\"));\n } catch {\n continue;\n }\n }\n return bodies.length === 0 ? command : [command, ...bodies].join(\"\\n\");\n}\n"],"mappings":";AAeA,SAAS,oBAAoB;AAC7B,SAAS,UAAU,SAAS,YAAY,MAAM,UAAU,WAAAA,UAAS,WAAW;;;ACA5E,SAAS,cAAc,gBAAgB;AACvC,SAAS,eAAe;AAExB,IAAM,iBACJ;AAEK,SAAS,gBAAgB,SAAiB,KAAsB;AACrE,QAAM,SAAmB,CAAC;AAC1B,aAAW,SAAS,QAAQ,SAAS,cAAc,GAAG;AACpD,UAAM,OAAO,MAAM,CAAC,KAAK,MAAM,CAAC,KAAK,MAAM,CAAC;AAC5C,QAAI,CAAC,QAAQ,SAAS,IAAK;AAC3B,UAAM,UAAU,QAAQ,OAAO,QAAQ,IAAI,GAAG,IAAI;AAClD,QAAI;AACF,UAAI,CAAC,SAAS,OAAO,EAAE,OAAO,EAAG;AACjC,aAAO,KAAK,aAAa,SAAS,MAAM,CAAC;AAAA,IAC3C,QAAQ;AACN;AAAA,IACF;AAAA,EACF;AACA,SAAO,OAAO,WAAW,IAAI,UAAU,CAAC,SAAS,GAAG,MAAM,EAAE,KAAK,IAAI;AACvE;;;ADEO,IAAM,oBAAoB;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAKO,IAAM,8BAA8B;AAwD3C,SAAS,gBAAgB,OAAwC;AAC/D,MA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GAAG,YAAY;AACpB;","names":["resolve","resolve"]}
1
+ {"version":3,"sources":["../src/lib/guardrail-hooks.ts","../src/lib/command-body-files.ts"],"sourcesContent":["/**\n * SDK Guardrail Hook Bridge — generic adapter from guardrail check functions to\n * SDK-compatible hook responses.\n *\n * Embedded guardrail rules are converted via createGuardrailHooksFromRules(),\n * which delegates to createGuardrailHooks(). All hook logic lives here.\n *\n * Every check this module runs arrives as an ARGUMENT. It has no ambient\n * source: it does not know what a plugin is, and it reaches for no registry, so\n * what a route enforces is decided by that route and is readable at its call\n * site. This is also what keeps the module light enough to sit on the lean\n * hot-path graph — see `PluginRegistry.guardrailChecks` for the measurement and\n * for which layer supplies the plugin source.\n */\n\nimport { realpathSync } from \"node:fs\";\nimport { basename, dirname, isAbsolute, join, relative, resolve, sep } from \"node:path\";\nimport { commandScanText } from \"./command-body-files.js\";\n\n/**\n * Enforcement action of a guardrail.\n *\n * `block` / `warn` / `shadow` / `info` are DECLARED by the active guardrail\n * policy. `unresolved` is not an enforcement level a policy can declare: it is\n * the state of a guardrail that has a binding implementation while the active\n * policy declares no action for it (no `active_guardrail_policy` in the project\n * manifest, an unknown policy name, or a policy with no rule for the guardrail).\n *\n * An unresolved guardrail DENIES — see `getBlockingViolations`. Substituting a\n * permissive default here is what turned every `action: block` guardrail in a\n * policy-less project into a no-op while the guardrail cache still listed it\n * (#293); the action is not knowable, so the operation the guardrail covers is\n * refused and the message says how to fix the manifest.\n *\n * ONE declaration for the set, so the type and the check `isGuardrailRuleData`\n * performs cannot name different ones — a bare union has nothing a predicate\n * can read, and the rules cross a process boundary as JSON.\n */\nexport const GUARDRAIL_ACTIONS = [\n \"block\",\n \"warn\",\n \"shadow\",\n \"info\",\n \"unresolved\",\n] as const;\n\nexport type GuardrailAction = (typeof GUARDRAIL_ACTIONS)[number];\n\n/** The action of a guardrail whose active policy declares none (see GuardrailAction). */\nexport const UNRESOLVED_GUARDRAIL_ACTION = \"unresolved\" as const;\n\nexport interface GuardrailCheckResult {\n guardrail_id: string;\n passed: boolean;\n action: GuardrailAction;\n message: string;\n}\n\n/**\n * What a guardrail hook answers.\n *\n * A refusal CARRIES ITS MESSAGE — one fact, not two independently optional\n * ones. Declared as separate optionals, every consumer had to supply a value\n * for a case no producer can reach (`beforeShellExecution`, `preToolUse` and\n * `afterFileEdit` all refuse through `denyResponse`, which always writes one),\n * and they supplied three different ones: two hand-written copies of \"Command\n * blocked by guardrail\" in the PreToolUse routes and a fall-back to\n * `agent_message` in the SDK adapter (#311). Nothing rejected a fourth, and\n * nothing noticed when one of them drifted, because a string literal that\n * disagrees with another string literal is not a type error.\n *\n * So the union states what the producer already guarantees, and the question\n * disappears instead of being answered in more places.\n */\nexport type HookResponse =\n | {\n permission: \"deny\";\n /** Every blocking violation, rendered. Never empty — a refusal has a cause. */\n user_message: string;\n agent_message: string;\n additionalContext?: undefined;\n }\n | {\n permission?: undefined;\n user_message?: undefined;\n agent_message?: undefined;\n /** Violations to surface to the agent without refusing. */\n additionalContext?: string;\n };\n\nexport interface GuardrailRule {\n guardrail_id: string;\n pattern: string;\n action: GuardrailAction;\n message: string;\n file_glob?: string;\n exclude_glob?: string;\n}\n\nexport interface GuardrailRuleData {\n commandRules: GuardrailRule[];\n fileRules: GuardrailRule[];\n contentRules: GuardrailRule[];\n}\n\nfunction isGuardrailRule(value: unknown): value is GuardrailRule {\n if (typeof value !== \"object\" || value === null) return false;\n const rule = value as Record<string, unknown>;\n return (\n typeof rule.guardrail_id === \"string\" &&\n typeof rule.pattern === \"string\" &&\n GUARDRAIL_ACTIONS.includes(rule.action as GuardrailAction) &&\n typeof rule.message === \"string\" &&\n (rule.file_glob === undefined || typeof rule.file_glob === \"string\") &&\n (rule.exclude_glob === undefined || typeof rule.exclude_glob === \"string\")\n );\n}\n\n/**\n * The single gate in front of {@link GuardrailRuleData}, next to the type it\n * grants — the rules are written to a cache file by one process and read back by\n * another, so the reader has only bytes and this predicate is what turns them\n * into rules the PreToolUse guard may run.\n *\n * Every declared field is checked, `action` against {@link GUARDRAIL_ACTIONS} —\n * the rules decide whether an operation is refused, so a rule carrying an action\n * the evaluator does not implement is not one this guard may run.\n */\nexport function isGuardrailRuleData(value: unknown): value is GuardrailRuleData {\n if (typeof value !== \"object\" || value === null) return false;\n const data = value as Record<string, unknown>;\n return (\n Array.isArray(data.commandRules) &&\n data.commandRules.every(isGuardrailRule) &&\n Array.isArray(data.fileRules) &&\n data.fileRules.every(isGuardrailRule) &&\n Array.isArray(data.contentRules) &&\n data.contentRules.every(isGuardrailRule)\n );\n}\n\nexport interface GuardrailCheckFunctions {\n checkCommand: (command: string) => GuardrailCheckResult[];\n checkFilePath: (filePath: string) => GuardrailCheckResult[];\n checkContent: (filePath: string, content: string) => GuardrailCheckResult[];\n}\n\nfunction globFragmentToRegex(fragment: string): string {\n let out = \"\";\n for (const ch of fragment) {\n if (ch === \"*\") out += \"[^/]*\";\n else if (ch === \"?\") out += \"[^/]\";\n else if (\".+^$|()[]\\\\\".includes(ch)) out += \"\\\\\" + ch;\n else out += ch;\n }\n return out;\n}\n\n/**\n * A pattern ending in `/` denotes a DIRECTORY and matches everything under it\n * (#262). This is the dominant style in artifact `path_patterns` — the embedded\n * dev-team DSL (`src/`, `lib/`, `tests/`, `.cursor/rules/`) and every\n * artifact-contracts registry rely on it. Without this, such a pattern compiles\n * to `^src/$`, which no file path can ever equal, so path → artifact reverse\n * lookup silently matched nothing and the artifact edit guard never fired.\n *\n * The rewrite is monotonic: file paths never end in `/`, so a pattern that\n * matched something before still matches exactly the same paths.\n */\nfunction expandDirectoryPattern(pattern: string): string {\n return pattern.endsWith(\"/\") ? `${pattern}**` : pattern;\n}\n\nexport function matchGlob(rawPattern: string, path: string): boolean {\n const pattern = expandDirectoryPattern(rawPattern);\n let regex = \"\";\n let i = 0;\n while (i < pattern.length) {\n if (pattern[i] === \"*\" && pattern[i + 1] === \"*\" && pattern[i + 2] === \"/\") {\n regex += \"(?:.+/)?\";\n i += 3;\n } else if (pattern[i] === \"*\" && pattern[i + 1] === \"*\") {\n regex += \".*\";\n i += 2;\n } else if (pattern[i] === \"*\") {\n regex += \"[^/]*\";\n i += 1;\n } else if (pattern[i] === \"?\") {\n regex += \"[^/]\";\n i += 1;\n } else if (pattern[i] === \"{\") {\n const end = pattern.indexOf(\"}\", i);\n if (end !== -1) {\n const alts = pattern.slice(i + 1, end).split(\",\").map(globFragmentToRegex);\n regex += \"(?:\" + alts.join(\"|\") + \")\";\n i = end + 1;\n } else {\n regex += \"\\\\{\";\n i += 1;\n }\n } else if (\".+^$|()[]\\\\\".includes(pattern[i])) {\n regex += \"\\\\\" + pattern[i];\n i += 1;\n } else {\n regex += pattern[i];\n i += 1;\n }\n }\n return new RegExp(\"^\" + regex + \"$\").test(path);\n}\n\n/**\n * Does this tool-input key name a file the call acts on?\n *\n * Derived from the naming convention rather than from a census of today's\n * tools. `NotebookEdit` calls its target `notebook_path`, so a reader that knew\n * only `file_path`/`path` classified that call correctly and then judged\n * nothing — the artifact guard was reached and found no path to protect (#309).\n * Every such key so far ends in `path`, so the rule follows the suffix and the\n * next tool to name an `output_path` is already covered.\n *\n * `file` / `filename` carry no suffix; they are the SDK progress-event\n * spellings the task runner reads, and are named for that reason.\n */\nfunction namesTargetFile(key: string): boolean {\n return (\n key === \"path\" || key === \"file\" || key === \"filename\" || key.endsWith(\"_path\")\n );\n}\n\n/**\n * Does this tool-input key carry text the call is about to WRITE?\n *\n * The same convention rule as `namesTargetFile`, over the other half of a file\n * edit. `Write` calls it `content`; `Edit` and `NotebookEdit` prefix the value\n * they are installing with `new_` (`new_string`, `new_source`), so the rule\n * follows the prefix and a tool that arrives naming a `new_text` is covered.\n *\n * The exclusions are the point. `old_string` is the text being REMOVED, and\n * scanning it would refuse the very edit that takes a forbidden string OUT of a\n * file — a content guardrail that fights its own repair. `file_path` and the\n * `cell_id` / `edit_mode` sort of parameter are neither. So \"everything the\n * payload happens to hold\" is not an available answer; the key has to say it is\n * the incoming value.\n */\nfunction namesPendingContent(key: string): boolean {\n return key === \"content\" || key.startsWith(\"new_\");\n}\n\n/**\n * The first non-empty string value under a key `names` accepts, or `\"\"`.\n *\n * Keys are scanned in sorted order, so the answer cannot depend on the order a\n * payload happened to serialize its properties in.\n *\n * Reads TOP-LEVEL string values only, and returns the first match: a payload\n * carrying its files in an array (`file_paths`) or nested (`edits[].new_string`)\n * is not covered, and no built-in has that shape today (#309).\n */\nfunction firstStringValue(\n toolInput: Record<string, unknown> | undefined | null,\n names: (key: string) => boolean,\n): string {\n if (!toolInput) return \"\";\n for (const key of Object.keys(toolInput).sort()) {\n if (!names(key)) continue;\n const value = toolInput[key];\n if (typeof value === \"string\" && value) return value;\n }\n return \"\";\n}\n\n/**\n * The file a tool call names as its target, or `\"\"` when it names none.\n *\n * ONE reader for every consumer that asks \"which file is this call about\": the\n * `preToolUse` file guardrails below, both Claude Code PreToolUse routes, the\n * `guard evaluate` CLI, the Claude SDK adapter and the task runner's\n * `process.edit` events. They had four spellings of it between them, agreeing\n * on `file_path` and diverging after — and a reader that knows fewer keys than\n * the tool writes turns a guard that runs into a guard that decides nothing.\n *\n * Scope is a TOOL INPUT. The after-file-edit payloads (`afterFileEdit` here,\n * the Cursor hook input in `guard-commands`) are not tool inputs: their\n * `file_path` is a top-level protocol field and is the whole interface.\n */\nexport function toolTargetPath(\n toolInput: Record<string, unknown> | undefined | null,\n): string {\n return firstStringValue(toolInput, namesTargetFile);\n}\n\n/**\n * Claude Code tools that cannot modify a file in the working tree — the ONLY\n * calls a `file_glob` / `content_regex` guardrail lets past unexamined.\n *\n * This list is inverted on purpose. Naming the tools to guard (`Edit`, `Write`,\n * `MultiEdit`) meant the guard covered exactly the tools that existed when it\n * was written, and `NotebookEdit` — a first-party file editor — walked through\n * a `manual_edit: forbidden` artifact for as long as it has existed (#309).\n * Every future tool would have arrived the same way, silently, because a name\n * that is missing from an allowlist looks identical to a name that is absent\n * for a reason.\n *\n * Naming the tools NOT to guard puts the staleness on the harmless side. An\n * unrecognised tool is judged instead of waved through, and being judged costs\n * it nothing unless it names a covered file: `toolTargetPath` reads the file out\n * of the call, so a tool that targets no file resolves to nothing and is\n * allowed. \"Deny by default\" here therefore means \"examined by default\", not\n * \"refused by default\" — a new Claude Code release does not lock the session\n * down.\n *\n * Every name is a Claude Code built-in, pinned against an independent\n * transcription of the tool reference in `__tests__/fixtures/`.\n */\nexport const NON_MUTATING_TOOLS: ReadonlySet<string> = new Set([\n // Name a path in their input and only ever read it.\n \"Read\",\n \"Glob\",\n \"Grep\",\n \"LSP\",\n // Load or delegate: whatever they set in motion arrives at the same guard as\n // its own tool call, and is guarded there.\n \"Task\",\n \"Agent\",\n \"Skill\",\n // Reach outside the working tree entirely.\n \"WebFetch\",\n \"WebSearch\",\n // Session-local state rather than files.\n \"TodoWrite\",\n \"AskUserQuestion\",\n \"ToolSearch\",\n \"EnterPlanMode\",\n \"ExitPlanMode\",\n]);\n\n/**\n * `path` with its symlinks resolved, as far as the filesystem has it.\n *\n * The target of a `Write` usually does not exist yet, so the deepest ancestor\n * that does is resolved and the rest is re-attached. A root and a target reached\n * through different spellings of one directory — macOS's `/tmp` and\n * `/private/tmp` — then compare equal.\n */\nfunction realPathAsFarAsItExists(path: string): string {\n const missing: string[] = [];\n let head = path;\n for (;;) {\n try {\n return join(realpathSync(head), ...missing);\n } catch {\n const parent = dirname(head);\n if (parent === head) return path;\n missing.unshift(basename(head));\n head = parent;\n }\n }\n}\n\n/**\n * A tool call's target as the file guards match it: relative to `root`, with\n * `/` separators, when it lies inside it — the space `path_patterns` and\n * `file_glob` patterns are written in — and absolute when it does not.\n *\n * Claude Code names every file by absolute path. Matched as given, a pattern\n * like `.claude/agents/` or `implementation-plan.yaml` never equals one; only a\n * `**`-prefixed pattern does. A relative target is read against `root`. A\n * target outside the root stays absolute, which keeps a\n * `**`-prefixed rule — the credential-file globs — applying to it and puts it\n * in no artifact.\n */\nfunction rootRelativeTarget(path: string, root: string): string {\n const absolute = resolve(root, path);\n const rel = relative(realPathAsFarAsItExists(root), realPathAsFarAsItExists(absolute));\n const outside = rel === \"\" || isAbsolute(rel) || rel.split(sep)[0] === \"..\";\n return outside ? absolute : rel.split(sep).join(\"/\");\n}\n\n/**\n * The file this call may WRITE, or `\"\"` when there is none — relative to `root`\n * when it lies inside it (`rootRelativeTarget`). `root` is the directory the\n * project's patterns are written against; `undefined` stands for the working\n * directory, which is where a relative path already resolves.\n *\n * ONE answer to \"which operations do the file guards cover, and which path do\n * they judge\", for every route: the `preToolUse` gate below, both Claude Code\n * PreToolUse routes (through `artifactGuardTarget`), the `guard evaluate` CLI\n * and the Claude SDK adapter. The artifact guard and the file guardrails read\n * the same string because they read it here.\n *\n * `file_glob` and `content_regex` guard WRITES. That is not a reading of what\n * the matcher could mean — it is what every rule declared against it says:\n * across `agents/bindings/runtime.yaml`, `examples/governance/bindings/runtime.yaml`\n * and the bindings `aaac init` bootstraps a new project with, all 19 messages\n * are \"Writing to … is blocked\", \"Generated files must not be hand-edited\" or\n * \"Do not write … at repo root\". None is about reading one. So a guard that\n * refused `Read` would refuse an operation no rule in this repo asks it to, and\n * `protect-generated-files` — `action: block` under the default policy — would\n * stop an agent reading the generated code it has to read to work.\n *\n * Answering it HERE rather than in the hook is what keeps the routes on one\n * verdict. Answered per-consumer, it went two ways immediately: the workspace\n * PreToolUse route filtered by this set and the single-component one did not, so\n * the same `Read secrets/prod.env` was allowed by one and refused by the other\n * (#316).\n */\nexport function toolWriteTarget(\n toolName: string | undefined,\n toolInput: Record<string, unknown> | undefined | null,\n root: string | undefined,\n): string {\n if (NON_MUTATING_TOOLS.has(toolName ?? \"\")) return \"\";\n const target = toolTargetPath(toolInput);\n return target && rootRelativeTarget(target, root ?? process.cwd());\n}\n\n/**\n * The text a tool call is about to write into `toolTargetPath`, or `\"\"`.\n *\n * The companion reader, and the reason `content_regex` guardrails are decided\n * BEFORE the write rather than reported after it. Claude Code hands PreToolUse\n * the tool's parameters in full, so the pending content is already in the\n * payload; the only event that could carry it afterwards is PostToolUse, whose\n * `block` cannot un-write the file and would answer the same declared\n * `action: block` differently from every other route (#316).\n */\nexport function toolPendingContent(\n toolInput: Record<string, unknown> | undefined | null,\n): string {\n return firstStringValue(toolInput, namesPendingContent);\n}\n\n/**\n * What one check is asked about: a command, a path, or a path and the content\n * about to go into it. Nothing here names an AGENT.\n *\n * Which rules an agent is checked against is settled before an evaluator\n * exists, by the layer that knows where rules come from — see\n * `createAgentGuardrailHooks` in `execute.ts`, the one constructor of per-agent\n * hooks. An agent id travelling inside the context would mean that same\n * question could also be answered later, from in here, and it did: a second\n * per-agent constructor exported beside that one wrote `agentId` on every\n * context it forwarded, no gate read it, and the two disagreed on memoisation\n * and on what an agent with no rules gets (#333).\n *\n * So the field is gone, and an OBJECT LITERAL naming an agent is now TS2353 —\n * which is what makes that constructor un-pasteable verbatim.\n * `adapter-guardrail-hooks.test.ts` pins the absence with a `@ts-expect-error`\n * that turns into TS2578 if the field returns.\n *\n * That is the whole of what the type says, and it is less than it sounds.\n * Excess-property checking reaches object literals only: an `as HookContext`\n * cast, an interface that extends this one, a literal bound to a variable\n * first, and a plain `Record<string, unknown>` all compile — measured, not\n * assumed. And a second per-agent constructor that simply never writes an agent\n * id needs none of them and compiles as it is. What is removed here is the\n * AFFORDANCE the duplicate happened to use, not the possibility of another one.\n * The invariant — ONE constructor of per-agent hooks — is held by the\n * declaration on `createAgentGuardrailHooks` and by reading it, and nothing\n * mechanical will fail if it is broken.\n */\nexport interface HookContext {\n command?: string;\n filePath?: string;\n content?: string;\n}\n\n/**\n * The guardrail gates, one per payload SHAPE — not one per rule kind.\n *\n * Which gate a caller picks is decided by what it holds, never by which rules\n * it wants consulted: every gate runs every rule the context can answer. An\n * object with four methods hid the opposite for as long as this existed — the\n * Claude Code PreToolUse route called `beforeShellExecution` and nothing else,\n * so a project's `file_glob` and `content_regex` guardrails were enforced by\n * `guard evaluate` and by the SDK adapter while the session a person actually\n * works in never consulted them, and no type or single-route test could say so\n * (#316).\n */\n/**\n * A shell command about to run, and the directory it runs in — which resolves a\n * message body the command passes by file (`commandScanText`). Without `cwd`\n * the hook process's own directory is used.\n */\nexport interface ShellCommandInput {\n command?: string;\n cwd?: string;\n}\n\nexport interface GuardrailHooks {\n /** A command about to run. Claude Code PreToolUse (both routes), `guard evaluate`. */\n beforeShellExecution: (input: ShellCommandInput) => HookResponse;\n /**\n * The checks {@link GuardrailHooks.beforeShellExecution} decides on — the\n * command plus any body it passes by file. `guard evaluate` reports these, so\n * the list it prints is the one its verdict came from.\n */\n checkShellCommand: (input: ShellCommandInput) => GuardrailCheckResult[];\n /**\n * A TOOL INPUT, verbatim: `toolWriteTarget` reads the file out of it, relative\n * to `root` — the directory the rules' patterns are written against, the\n * working directory when absent — and `toolPendingContent` the text about to\n * go in. The single-component Claude Code PreToolUse route, `guard evaluate`\n * and the Claude SDK adapter.\n */\n preToolUse: (input: {\n tool_name?: string;\n tool_input?: Record<string, unknown>;\n root?: string;\n }) => HookResponse;\n /**\n * A file write whose path and content the caller has ALREADY extracted —\n * Cursor's after-file-edit event, where both are top-level protocol fields,\n * and the workspace Claude Code PreToolUse route, which must ask about the\n * member-repo-relative path (`stripMemberPrefix`) rather than the one the\n * tool named, because member guardrail patterns are written in that space.\n */\n afterFileEdit: (input: { file_path?: string; content?: string }) => HookResponse;\n /** The shared check runner. Not a gate: `getBlockingViolations` is what refuses. */\n runChecks: (ctx: HookContext) => GuardrailCheckResult[];\n}\n\n/**\n * Does this action refuse the operation? `block` because the policy says so,\n * `unresolved` because the policy says nothing and a guardrail whose action is\n * unknown must not be permissive (#293). Single definition — every deny gate\n * (shell / pre-tool-use / after-file-edit hooks, `guard evaluate`'s exit code,\n * the OpenAI Agents SDK tripwire) reads it through `getBlockingViolations`.\n */\nfunction isDenyAction(action: GuardrailAction): boolean {\n return action === \"block\" || action === UNRESOLVED_GUARDRAIL_ACTION;\n}\n\nexport function getBlockingViolations(results: GuardrailCheckResult[]): GuardrailCheckResult[] {\n return results.filter((r) => !r.passed && isDenyAction(r.action));\n}\n\nexport function getWarnings(results: GuardrailCheckResult[]): GuardrailCheckResult[] {\n return results.filter((r) => !r.passed && r.action === \"warn\");\n}\n\nexport function hasBlockingViolation(results: GuardrailCheckResult[]): boolean {\n return getBlockingViolations(results).length > 0;\n}\n\n/**\n * How a guardrail violation reads: `[guardrail-id] message`, one per line.\n *\n * Single definition — the shell, pre-tool-use and after-file-edit hooks all\n * refuse in the same words, a warning reads the same as the refusal it would\n * have been under a stricter policy.\n */\nfunction renderViolations(results: GuardrailCheckResult[]): string {\n return results.map((r) => `[${r.guardrail_id}] ${r.message}`).join(\"\\n\");\n}\n\n/**\n * The refusal every guardrail hook returns.\n *\n * The message is written HERE, once, rather than at each of the three hooks —\n * that is what makes `HookResponse`'s \"a denial carries its message\" a fact\n * about the code and not a convention. `user_message` and `agent_message` are\n * the same text on purpose: the agent is told exactly what the user is told.\n */\nfunction denyResponse(blocks: GuardrailCheckResult[]): HookResponse {\n const message = renderViolations(blocks);\n return { permission: \"deny\", user_message: message, agent_message: message };\n}\n\n/**\n * Create SDK hook functions from guardrail check functions.\n *\n * Returns hook functions in the format expected by the Claude SDK, plus a\n * generic runChecks() for programmatic use.\n *\n * Takes any number of check SOURCES and asks every one of them every question\n * the context can answer — which is the same rule `GuardrailHooks` states about\n * its gates, one level down. A source is not a rule kind and not a route: it is\n * one supplier of checks, and the hooks it produces cannot tell which supplier a\n * verdict came from. That is what lets a second supplier be added (the execution\n * layer adds the process's plugin guardrails, see\n * `PluginRegistry.guardrailChecks`) without there being a second EVALUATOR —\n * the property #304 and #316 exist to hold.\n *\n * Ordering is by question, then by source, so the sources a caller lists are\n * consulted in the order it listed them and a refusal reads the same way every\n * time (`renderViolations` joins in result order).\n *\n * Zero sources is a legitimate answer, not a degenerate one: it is what an agent\n * with no resolved rules and no plugins has, and the hooks it gets deny nothing.\n */\nexport function createGuardrailHooks(...sources: GuardrailCheckFunctions[]): GuardrailHooks {\n function runChecks(ctx: HookContext): GuardrailCheckResult[] {\n const results: GuardrailCheckResult[] = [];\n\n if (ctx.command) {\n for (const source of sources) results.push(...source.checkCommand(ctx.command));\n }\n\n if (ctx.filePath) {\n for (const source of sources) results.push(...source.checkFilePath(ctx.filePath));\n }\n\n if (ctx.filePath && ctx.content) {\n for (const source of sources) {\n results.push(...source.checkContent(ctx.filePath, ctx.content));\n }\n }\n\n return results;\n }\n\n function checkShellCommand(input: ShellCommandInput): GuardrailCheckResult[] {\n const command = input.command ?? \"\";\n if (!command) return [];\n return runChecks({ command: commandScanText(command, input.cwd) });\n }\n\n function beforeShellExecution(input: ShellCommandInput): HookResponse {\n const results = checkShellCommand(input);\n if (results.length === 0) return {};\n const blocks = getBlockingViolations(results);\n const warns = getWarnings(results);\n\n if (blocks.length > 0) {\n return denyResponse(blocks);\n }\n\n if (warns.length > 0) {\n return { additionalContext: renderViolations(warns) };\n }\n\n return {};\n }\n\n /**\n * The verdict on one file write — the ONE gate behind both file-shaped hooks\n * below, so `file_glob` and `content_regex` are decided together and cannot\n * be decided differently depending on which payload shape arrived.\n *\n * They diverged before: `preToolUse` asked `runChecks({ filePath })` and so\n * consulted `checkFilePath` alone, while `afterFileEdit` asked with the\n * content and got both. The rules a project declares are the same rules\n * either way (#316).\n */\n function fileWriteVerdict(filePath: string, content: string): HookResponse {\n if (!filePath) return {};\n\n const blocks = getBlockingViolations(runChecks({ filePath, content }));\n return blocks.length > 0 ? denyResponse(blocks) : {};\n }\n\n function preToolUse(input: {\n tool_name?: string;\n tool_input?: Record<string, unknown>;\n root?: string;\n }): HookResponse {\n return fileWriteVerdict(\n toolWriteTarget(input.tool_name, input.tool_input, input.root),\n toolPendingContent(input.tool_input),\n );\n }\n\n function afterFileEdit(input: { file_path?: string; content?: string }): HookResponse {\n return fileWriteVerdict(input.file_path ?? \"\", input.content ?? \"\");\n }\n\n return { beforeShellExecution, checkShellCommand, preToolUse, afterFileEdit, runChecks };\n}\n\n/** Compile a guardrail regex pattern, supporting inline `(?i)` case-insensitivity prefix. */\nexport function compileGuardrailPattern(pattern: string): RegExp {\n if (pattern.startsWith(\"(?i)\")) {\n return new RegExp(pattern.slice(4), \"i\");\n }\n return new RegExp(pattern);\n}\n\n/**\n * Create SDK hook functions from embedded guardrail rule data.\n *\n * The rules are the first check source; `extraSources` are consulted after\n * them, on every question. This is the funnel every route reaches the evaluator\n * through — both Claude Code PreToolUse routes, `guard evaluate` and the\n * execution layer — so what distinguishes those routes is visible here as an\n * argument list and nowhere else.\n */\nexport function createGuardrailHooksFromRules(\n rules: GuardrailRuleData,\n ...extraSources: GuardrailCheckFunctions[]\n): GuardrailHooks {\n const commandChecks = rules.commandRules.map((rule) => ({\n guardrail_id: rule.guardrail_id,\n pattern: compileGuardrailPattern(rule.pattern),\n action: rule.action,\n message: rule.message,\n }));\n\n const fileChecks = rules.fileRules;\n\n const contentChecks = rules.contentRules.map((rule) => ({\n guardrail_id: rule.guardrail_id,\n pattern: compileGuardrailPattern(rule.pattern),\n action: rule.action,\n message: rule.message,\n file_glob: rule.file_glob,\n exclude_glob: rule.exclude_glob,\n }));\n\n return createGuardrailHooks({\n checkCommand(command: string): GuardrailCheckResult[] {\n const results: GuardrailCheckResult[] = [];\n for (const check of commandChecks) {\n const passed = !check.pattern.test(command);\n results.push({\n guardrail_id: check.guardrail_id,\n passed,\n action: check.action,\n message: passed ? \"\" : check.message,\n });\n }\n return results;\n },\n\n checkFilePath(filePath: string): GuardrailCheckResult[] {\n const results: GuardrailCheckResult[] = [];\n for (const check of fileChecks) {\n if (check.exclude_glob && matchGlob(check.exclude_glob, filePath)) {\n continue;\n }\n const matched = matchGlob(check.pattern, filePath);\n results.push({\n guardrail_id: check.guardrail_id,\n passed: !matched,\n action: check.action,\n message: matched ? check.message : \"\",\n });\n }\n return results;\n },\n\n checkContent(filePath: string, content: string): GuardrailCheckResult[] {\n const results: GuardrailCheckResult[] = [];\n for (const check of contentChecks) {\n if (check.file_glob && !matchGlob(check.file_glob, filePath)) {\n continue;\n }\n if (check.exclude_glob && matchGlob(check.exclude_glob, filePath)) {\n continue;\n }\n const matched = check.pattern.test(content);\n results.push({\n guardrail_id: check.guardrail_id,\n passed: !matched,\n action: check.action,\n message: matched ? check.message : \"\",\n });\n }\n return results;\n },\n }, ...extraSources);\n}\n","/**\n * The text a command guardrail scans for a shell command: the command itself,\n * plus the contents of any message body it passes by file.\n *\n * `gh pr create --body-file body.md`, `gh issue comment -F body.md`,\n * `gh release create --notes-file notes.md` and `git commit -F msg.txt` carry\n * the same text a heredoc would put on the command line. Scanning only the\n * command string let a rule that stops the heredoc form pass the file form.\n *\n * Only a plain path is resolved — bare, or wrapped whole in one pair of quotes.\n * `-` (stdin), a path built from a variable, and anything that is not a regular\n * file (a FIFO would block the hook) are left out, and the command string alone\n * is what gets scanned for them, as before. The file text is joined on a new\n * line, so a pattern's `.` never spans the command and the body, and a pattern\n * anchored at `^` still means the start of the command.\n */\nimport { readFileSync, statSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\n\nconst BODY_FILE_FLAG =\n /(?:^|\\s)(?:--body-file|--notes-file|--file|-F)(?:=|\\s+)(?:'([^']*)'|\"([^\"]*)\"|([^\\s;|&]+))/g;\n\nexport function commandScanText(command: string, cwd?: string): string {\n const bodies: string[] = [];\n for (const match of command.matchAll(BODY_FILE_FLAG)) {\n const path = match[1] ?? match[2] ?? match[3];\n if (!path || path === \"-\") continue;\n const absPath = resolve(cwd ?? process.cwd(), path);\n try {\n if (!statSync(absPath).isFile()) continue;\n bodies.push(readFileSync(absPath, \"utf8\"));\n } catch {\n continue;\n }\n }\n return bodies.length === 0 ? command : [command, ...bodies].join(\"\\n\");\n}\n"],"mappings":";AAeA,SAAS,oBAAoB;AAC7B,SAAS,UAAU,SAAS,YAAY,MAAM,UAAU,WAAAA,UAAS,WAAW;;;ACA5E,SAAS,cAAc,gBAAgB;AACvC,SAAS,eAAe;AAExB,IAAM,iBACJ;AAEK,SAAS,gBAAgB,SAAiB,KAAsB;AACrE,QAAM,SAAmB,CAAC;AAC1B,aAAW,SAAS,QAAQ,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,UACd,SAAS,UAAU,MAAM,UAAU;AAAA,QACrC,CAAC;AAAA,MACH;AACA,aAAO;AAAA,IACT;AAAA,IAEA,aAAa,UAAkB,SAAyC;AACtE,YAAM,UAAkC,CAAC;AACzC,iBAAW,SAAS,eAAe;AACjC,YAAI,MAAM,aAAa,CAAC,UAAU,MAAM,WAAW,QAAQ,GAAG;AAC5D;AAAA,QACF;AACA,YAAI,MAAM,gBAAgB,UAAU,MAAM,cAAc,QAAQ,GAAG;AACjE;AAAA,QACF;AACA,cAAM,UAAU,MAAM,QAAQ,KAAK,OAAO;AAC1C,gBAAQ,KAAK;AAAA,UACX,cAAc,MAAM;AAAA,UACpB,QAAQ,CAAC;AAAA,UACT,QAAQ,MAAM;AAAA,UACd,SAAS,UAAU,MAAM,UAAU;AAAA,QACrC,CAAC;AAAA,MACH;AACA,aAAO;AAAA,IACT;AAAA,EACF,GAAG,GAAG,YAAY;AACpB;","names":["resolve","resolve"]}
@@ -1042,7 +1042,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
1042
1042
  `)),this.name="DslValidationError",this.missing=e}};function I$e(e){let t=e.agents??{},n={};for(let[i,r]of Object.entries(t)){let o=(r.mode??"read-only")==="read-write"?"read-write":"read-only",s=du(r,"x-authority");n[i]={id:i,role_name:r.role_name??i,purpose:r.purpose??"",description:du(r,"x-description"),mode:o,responsibilities:r.responsibilities??[],constraints:r.constraints??[],rules:r.rules??[],can_invoke_agents:r.can_invoke_agents??void 0,can_execute_tools:r.can_execute_tools??void 0,dispatch_only:r.dispatch_only??void 0,can_read_artifacts:r.can_read_artifacts??[],can_write_artifacts:r.can_write_artifacts??[],can_return_handoffs:r.can_return_handoffs??[],can_perform_validations:r.can_perform_validations??[],anti_patterns:r.anti_patterns??[],escalation_criteria:r.escalation_criteria??[],authority:s,audit_checklist:du(r,"x-audit-checklist")??[],sections:(r.sections??[]).map(u=>lN(u,e)).filter(u=>u!==void 0)}}return n}function O$e(e){let t={};for(let[n,i]of Object.entries(e))t[n]={id:n,description:i.description??"",target_agent:i.target_agent??"",result_handoff:i.result_handoff??"",completion_criteria:i.completion_criteria??[],model_class:i.model_class};return t}function P$e(e){return e.type==="gate"?{type:"gate",gate_kind:e.gate_kind??"",description:e.description??"",model_class:e.model_class,depends_on:e.depends_on}:e.type==="evaluate"?{type:"evaluate",task:e.task??"",from_agent:e.from_agent??"",evaluator_agent:e.evaluator_agent,description:e.description,loop_to:e.loop_to??"",max_iterations:e.max_iterations??1,inject_as:e.inject_as,on_exhausted:e.on_exhausted,depends_on:e.depends_on}:{type:"delegate",task:e.task??"",from_agent:e.from_agent??"",description:e.description??"",optional:du(e,"x-optional")??!1,max_retries:e.max_retries??0,max_follow_ups:e.max_follow_ups,depends_on:e.depends_on,instruction:du(e,"x-instruction"),receives:du(e,"x-receives"),retry:e.retry}}function j$e(e){let t={};for(let[n,i]of Object.entries(e)){let r=(i.steps??[]).map(P$e);t[n]={id:n,description:i.description??"",steps:r}}return t}function N$e(e,t){let n=e.handoff_types??{},i=e.components??{},r=i.schemas??i,a={};for(let[o,s]of Object.entries(n)){let u=s.schema;u&&(a[o]=t(u,r))}return a}async function B$e(e){let{resolveSchemaRefs:t}=await Promise.resolve().then(()=>(qc(),Uc)),n=N$e(e,t),i=e.handoff_types??{};return{...e,handoff_types:Object.fromEntries(Object.entries(i).map(([r,a])=>[r,Object.prototype.hasOwnProperty.call(n,r)?{...a,schema:n[r]}:a]))}}function T$e(e){let t={};for(let[n,i]of Object.entries(e)){let r=i.schema;r&&(t[n]=up(r))}return t}function F$e(e){let t=e.tasks??{},n=e.workflow??{},i=e.handoff_types??{};return{agentRegistry:I$e(e),taskRegistry:O$e(t),workflowRegistry:j$e(n),handoffSchemas:T$e(i)}}function R$e(e,t){let n=[],i=e.workflow??{},r=e.tasks??{},a=e.handoff_types??{};if(t.workflows)for(let o of t.workflows)o in i||n.push(`workflow "${o}" is required by the CLI but not found in the resolved DSL`);if(t.tasks)for(let o of t.tasks){if(!(o in r)){n.push(`task "${o}" is required by the CLI but not found in the resolved DSL`);continue}let s=r[o],u=s.invocation_handoff,l=s.result_handoff;u&&!(u in a)&&n.push(`handoff_type "${u}" (invocation_handoff of task "${o}") not found`),l&&!(l in a)&&n.push(`handoff_type "${l}" (result_handoff of task "${o}") not found`)}if(t.workflows)for(let o of t.workflows){if(!(o in i))continue;let u=i[o].steps??[];for(let l of u){if(l.type!=="delegate")continue;let c=l.task;if(c&&c in r){let p=r[c].result_handoff;p&&!(p in a)&&n.push(`handoff_type "${p}" (result of task "${c}" in workflow "${o}") not found`)}}}if(n.length>0)throw new x$e(n)}async function z$e(e){let t;if(e.projectDslPath){let{resolve:i,mergeDsl:r,expandDefaults:a}=await Promise.resolve().then(()=>(qc(),Uc)),o=await D$e(e.projectDslPath,"utf8"),s=zJ.default.parse(o);if(typeof s!="object"||s===null||Array.isArray(s))throw new Error(`${e.projectDslPath} is not a DSL document (expected a YAML mapping)`);let u=s;if(u.extends==="/$embedded/"){let{extends:l,...c}=u,d=r(e.embeddedDsl,c);t=a(d)}else{let l=await i(e.projectDslPath),c=r(e.embeddedDsl,l.data);t=a(c)}}else t=e.embeddedDsl;return e.requiredEntities&&R$e(t,e.requiredEntities),{registries:F$e(await B$e(t)),dsl:t}}function M$e(e){return{guardrail_id:e.guardrail_id,pattern:e.pattern,action:e.action,message:e.message}}function U$e(e){return{guardrail_id:e.guardrail_id,pattern:e.pattern,action:e.action,message:e.message,...e.exclude_glob?{exclude_glob:e.exclude_glob}:{}}}function q$e(e){return{guardrail_id:e.guardrail_id,pattern:e.pattern,action:e.action,message:e.message,...e.file_glob?{file_glob:e.file_glob}:{},...e.exclude_glob?{exclude_glob:e.exclude_glob}:{}}}function V$e(e,t){let n=i=>t?i.filter(r=>t.has(r.guardrail_id)):i;return{commandRules:n(e.commandChecks).map(M$e),fileRules:n(e.fileChecks).map(U$e),contentRules:n(e.contentChecks).map(q$e)}}var Z$e={commandChecks:[],fileChecks:[],contentChecks:[],allChecks:[],hasGuardrails:!1,diagnostics:[]};async function K$e(e,t,n,i){if(!t||t.length===0)return Z$e;let r={commandChecks:[],fileChecks:[],contentChecks:[],allChecks:[],hasGuardrails:!1,diagnostics:[]},a=new Set;for(let o of t){let s;try{s=await L$e(o,"utf8")}catch(d){if(i?.skipMissing&&d.code==="ENOENT")continue;throw d}let u=LJ.default.parse(s);if(typeof u!="object"||u===null||Array.isArray(u))throw new Error(`${o} is not a binding document (expected a YAML mapping)`);let c=mN(e,u,n);r.commandChecks.push(...c.commandChecks),r.fileChecks.push(...c.fileChecks),r.contentChecks.push(...c.contentChecks),r.allChecks.push(...c.allChecks),r.hasGuardrails=r.hasGuardrails||c.hasGuardrails;for(let d of c.diagnostics){let p=`${d.path} :: ${d.message}`;a.has(p)||(a.add(p),r.diagnostics.push(d))}}return r}async function G$e(e){return k$e({dsl:await J$e(e),artifactBinding:e.artifactBinding,paths:e.paths})}async function J$e(e){if(e.embeddedDsl!=null)return e.projectDslPath?(await z$e({embeddedDsl:e.embeddedDsl,projectDslPath:e.projectDslPath})).dsl:e.embeddedDsl;if(e.projectDslPath){let{resolve:t}=await Promise.resolve().then(()=>(qc(),Uc));return(await t(e.projectDslPath)).data}throw new Error("resolveNavigationDsl requires embeddedDsl or projectDslPath")}async function MJ(e){let t=[],n=await G$e(e),i=n.dsl;t.push(...n.diagnostics);let{validateSchema:r,buildNavigationIndex:a}=await Promise.resolve().then(()=>(qc(),Uc)),o=r(i),s=o.diagnostics.map(d=>({path:d.path,message:d.message,severity:d.severity??"error"}));if(t.push(...s),t.push(...dN(i).map(d=>({path:d.path,message:d.message,severity:"error"}))),!o.data)throw new Error(["DSL schema validation failed \u2014 a navigation index cannot be built from it:",...s.map(d=>` - [${d.severity}] ${d.path}: ${d.message}`)].join(`
1043
1043
  `));let u=a(o.data),l=await K$e(i,e.bindingPaths,e.activeGuardrailPolicy);t.push(...l.diagnostics);let c=l.hasGuardrails?V$e(l):void 0;return{dsl:i,navigationIndex:u,guardrailRules:c,diagnostics:t}}async function W$e(e){let t=FJ(e.projectRoot,gN);if(!TJ(t)){let a=FJ(e.projectRoot,e.dslPath);return{navigationOptions:{...e.embeddedDsl===void 0||TJ(a)?{projectDslPath:a}:{},embeddedDsl:e.embeddedDsl},sourceFiles:[t,a]}}let n=await bN(t),i=[t],r=n.dslDeclared?n.dslPath:void 0;return r&&i.push(r),n.artifactsPath&&i.push(n.artifactsPath),i.push(...n.bindingPaths),{navigationOptions:{...r?{projectDslPath:r}:{},embeddedDsl:e.embeddedDsl,...n.artifactsPath?{artifactBinding:{source:n.artifactsPath}}:{},bindingPaths:n.bindingPaths,...n.active_guardrail_policy?{activeGuardrailPolicy:n.active_guardrail_policy}:{}},sourceFiles:i}}import{readFile as tEe,writeFile as UJ,rename as rEe,stat as nEe,mkdir as iEe}from"fs/promises";import{join as aEe}from"path";import{randomBytes as oEe}from"crypto";import{stat as uEe}from"fs/promises";var H$e=["SessionStart","UserPromptSubmit","PreToolUse"],US=e=>new Error(`Not a hook payload: ${e.slice(0,100)}`),qu=e=>e===void 0||typeof e=="string";function Y$e(e){if(e===void 0)return!0;if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return qu(t.file_path)&&qu(t.path)&&qu(t.command)&&qu(t.content)}function X$e(e){if(!qu(e.session_id))return!1;switch(e.hookEventName){case"SessionStart":return e.type===void 0||typeof e.type=="string"&&["new","resume","clear","compact"].includes(e.type);case"UserPromptSubmit":return qu(e.prompt);case"PreToolUse":return qu(e.tool_name)&&Y$e(e.tool_input);default:return!1}}function qJ(e){let t=JSON.parse(e);if(typeof t!="object"||t===null||Array.isArray(t))throw US(e);let n=t;if(typeof n.hook_event_name=="string"&&n.hookEventName===void 0&&(n.hookEventName=n.hook_event_name),!H$e.includes(n.hookEventName)){if(typeof n.hookEventName=="string")return;throw US(e)}if(!X$e(n))throw US(e);return n}async function Q$e(){let e=[];for await(let n of process.stdin)e.push(Buffer.isBuffer(n)?n:Buffer.from(n));let t=Buffer.concat(e).toString("utf-8").trim();if(!t)throw new Error("Empty stdin \u2014 no hook input received");return qJ(t)}function eEe(e){process.stdout.write(JSON.stringify(e)+`
1044
1044
  `)}function Vc(e,t){return{hookSpecificOutput:{hookEventName:e,additionalContext:t}}}function aa(e){return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}}}function Zc(){return{}}var r6=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function sEe(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let n=e;return typeof n.writtenAt=="string"&&typeof n.sourceHash=="string"&&(n.sourceFiles===void 0||Array.isArray(n.sourceFiles)&&n.sourceFiles.every(i=>typeof i=="string"))&&t(n.data)}function g0(e){let{cacheDir:t}=e;function n(a){return aEe(t,`${a}.json`)}async function i(){await iEe(t,{recursive:!0})}return{async read(a,o){let s;try{s=JSON.parse(await tEe(n(a),"utf-8"))}catch{return null}return sEe(s,o)?s:null},async write(a,o,s,u){await i();let l={data:o,writtenAt:new Date().toISOString(),sourceHash:s,...u?{sourceFiles:u}:{}},c=JSON.stringify(l,null,2),d=n(a),p=`${d}.${oEe(4).toString("hex")}.tmp`;await UJ(p,c,"utf-8");try{await rEe(p,d)}catch{await UJ(d,c,"utf-8")}},async getFileMtime(a){try{return(await nEe(a)).mtimeMs}catch{return null}}}}function VJ(e){return e.map(String).join(":")}var lEe=".guardrails";function qS(e){return`${e}${lEe}`}var v0="navigation-index";async function VS(e){let t=[];for(let n of e)try{let i=await uEe(n);t.push(i.mtimeMs)}catch{t.push(`missing:${n}`)}return VJ(t)}async function Vu(e){let t=e.cacheKey??v0,n=g0({cacheDir:e.cacheDir}),i=await n.read(t,r6);if(!i?.sourceFiles||await VS(i.sourceFiles)!==i.sourceHash)return;let a=await n.read(qS(t),pO);if(a?.sourceHash===i.sourceHash)return{navigationIndex:i.data,guardrailRules:a.data}}import{isAbsolute as cEe}from"path";function n6(e,t){if(cEe(e))return[];let n=t.artifacts??{},i=[];for(let[r,a]of Object.entries(n)){let o=a?.files?.path_patterns;if(Array.isArray(o)){for(let s of o)if(typeof s=="string"&&ql(s,e)){i.push({artifactId:r,artifact:a,matchedPattern:s});break}}}return i}function dEe(e){if(e.authority==="generated")return"generated";if(e.manual_edit==="forbidden")return"forbidden"}function i6(e){let t=dEe(e.artifact.properties??{});if(t==="generated"){let n=e.artifact.routes?.regenerate,i=n?` Run '${n}' to regenerate.`:" Edit the source artifact and regenerate instead.";return{protected:!0,reason:`File belongs to generated artifact '${e.artifactId}'. Direct editing is not allowed.${i}`}}return t==="forbidden"?{protected:!0,reason:`File belongs to artifact '${e.artifactId}' which has manual_edit: forbidden. This artifact must not be edited directly.`}:{protected:!1,reason:""}}function y0(e){let t=e.artifacts??{};return Object.entries(t).map(([n,i])=>({id:n,artifact:i}))}import{resolve as GJ}from"path";function ZS(e){return e.tool_input?.command!==void 0}function ZJ(e,t){return V5(e.tool_name,e.tool_input,t)}var pEe={"navigation-index":"the artifact edit guard","guardrail-rules":"the DSL guardrails"};function a6(e,t){let n=t?` for ${t}`:"";return`[guard-unavailable] ${pEe[e]} cannot run: the \`${e}\` cache entry${n} is absent or was built from sources that have since changed, so this operation gets no verdict and is refused rather than judged by superseded rules or silently allowed. Run \`.claude/bin/ensure-navigation-index\` (SessionStart and every prompt submission do this automatically \u2014 if it keeps failing, that failure is the bug).`}function fEe(e){let t=e.guardrailRules?K5(e.guardrailRules):null;return async function(i){let r=ZJ(i,e.projectRoot);if(!t&&(ZS(i)||r))return aa(a6("guardrail-rules"));if(t){if(ZS(i)){let o=t.beforeShellExecution({command:i.tool_input?.command,cwd:i.cwd});if(o.permission==="deny")return aa(o.user_message)}let a=t.preToolUse({tool_name:i.tool_name,tool_input:i.tool_input,root:e.projectRoot});if(a.permission==="deny")return aa(a.user_message)}if(r){if(!e.navigationIndex)return aa(a6("navigation-index"));for(let a of n6(r,e.navigationIndex)){let o=i6(a);if(o.protected)return aa(o.reason)}}return Zc()}}var KJ=100;function GS(e,t){let{navigationIndex:n,maxCandidates:i=KJ}=t,r=y0(n),a=[],o=e.toLowerCase(),s=u=>mEe(t.pathPrefix,u);for(let{id:u,artifact:l}of r){let c=l.properties??{},d=l.files?.path_patterns??[];(!e||u.toLowerCase().includes(o))&&a.push({label:u,path:s(d.length>0?String(d[0]):u),kind:"artifact",authority:c.authority,manual_edit:c.manual_edit,score:hEe(u,l,e)});for(let p of d)typeof p=="string"&&(p.includes("*")||p.includes("?")||(!e||p.toLowerCase().includes(o))&&a.push({label:p,path:s(p),kind:"file",artifact:u,authority:c.authority,manual_edit:c.manual_edit,score:gEe(p,e)}))}return a.sort((u,l)=>l.score!==u.score?l.score-u.score:u.label.localeCompare(l.label)),a.slice(0,i)}function mEe(e,t){if(!e)return t;let n=e.replace(/^\.\//,"").replace(/\/+$/,"");return n?`${n}/${t}`:t}function JS(e){return e.map(t=>JSON.stringify(t)).join(`
1045
- `)}function hEe(e,t,n){let i=50,r=t.properties??{};return r.authority==="canonical"&&(i+=20),r.manual_edit==="allowed"&&(i+=10),r.type==="source"&&(i+=15),r.authority==="generated"&&(i-=20),r.manual_edit==="forbidden"&&(i-=10),n&&e.toLowerCase().startsWith(n.toLowerCase())&&(i+=20),i}function gEe(e,t){let n=40;return t&&e.toLowerCase().startsWith(t.toLowerCase())&&(n+=30),n+=Math.max(0,20-e.split("/").length*2),n}async function vEe(e,t){let n=t.trim(),i=GS(n,{navigationIndex:e});return JS(i)}async function yEe(e,t,n,i=KJ){let r=n.trim(),a=g0({cacheDir:e}),o=[];for(let s of t){let u=await a.read(s.cacheKey,r6);u&&o.push(...GS(r,{navigationIndex:u.data,pathPrefix:s.memberPath,maxCandidates:Number.POSITIVE_INFINITY}))}return o.sort((s,u)=>u.score!==s.score?u.score-s.score:s.label.localeCompare(u.label)),JS(o.slice(0,i))}function KS(e,t,n){if(!e)return null;let i=e.startsWith("/")?e:GJ(n,e),r=null,a=0;for(let o of t){let s=o.root,u=s.endsWith("/")?s:s+"/";i.startsWith(u)&&u.length>a&&(r=o,a=u.length)}return r}function JJ(e,t,n){let i=e.startsWith("/")?e:GJ(n,e),r=t.endsWith("/")?t:t+"/";return i.startsWith(r)?i.slice(r.length):e}function _Ee(e){let t=[];for(let n of e.split(/\s+/)){let i=n.replace(/^['"]+|['"]+$/g,"");i&&(i.includes("/")||i.includes("\\"))&&t.push(i)}return t}function bEe(e){let t=new Map;async function n(r){if(t.has(r.name))return t.get(r.name);let a=await Vu({cacheDir:e.cacheDir,cacheKey:r.cacheKey}),o=a?{...a,hooks:K5(a.guardrailRules)}:void 0;return t.set(r.name,o),o}function i(r){for(let a of _Ee(r)){let o=KS(a,e.members,e.workspaceRoot);if(o)return[o]}return e.members}return async function(a){if(ZS(a)){let d=a.tool_input?.command??"";for(let p of i(d)){let f=await n(p);if(!f)return aa(a6("guardrail-rules",`member "${p.name}"`));let m=f.hooks.beforeShellExecution({command:d,cwd:a.cwd});if(m.permission==="deny")return aa(m.user_message)}}let o=ZJ(a,e.workspaceRoot);if(!o)return Zc();let s=KS(o,e.members,e.workspaceRoot);if(!s)return Zc();let u=await n(s);if(!u)return aa(a6("navigation-index",`member "${s.name}"`));let l=JJ(o,s.root,e.workspaceRoot),c=u.hooks.afterFileEdit({file_path:l,content:Z5(a.tool_input)});if(c.permission==="deny")return aa(c.user_message);for(let d of n6(l,u.navigationIndex)){let p=i6(d);if(p.protected)return aa(p.reason)}return Zc()}}function _0(e){let t=e.system,n=e.artifacts??{},i=Object.keys(n),r=["## Project Navigation Index"],a=t?.name?`${t.name}${t.id?` (${t.id})`:""}`:t?.id??"unknown";if(r.push(`System: ${a}
1045
+ `)}function hEe(e,t,n){let i=50,r=t.properties??{};return r.authority==="canonical"&&(i+=20),r.manual_edit==="allowed"&&(i+=10),r.type==="source"&&(i+=15),r.authority==="generated"&&(i-=20),r.manual_edit==="forbidden"&&(i-=10),n&&e.toLowerCase().startsWith(n.toLowerCase())&&(i+=20),i}function gEe(e,t){let n=40;return t&&e.toLowerCase().startsWith(t.toLowerCase())&&(n+=30),n+=Math.max(0,20-e.split("/").length*2),n}async function vEe(e,t){let n=t.trim(),i=GS(n,{navigationIndex:e});return JS(i)}async function yEe(e,t,n,i=KJ){let r=n.trim(),a=g0({cacheDir:e}),o=[];for(let s of t){let u=await a.read(s.cacheKey,r6);u&&o.push(...GS(r,{navigationIndex:u.data,pathPrefix:s.memberPath,maxCandidates:Number.POSITIVE_INFINITY}))}return o.sort((s,u)=>u.score!==s.score?u.score-s.score:s.label.localeCompare(u.label)),JS(o.slice(0,i))}function KS(e,t,n){if(!e)return null;let i=e.startsWith("/")?e:GJ(n,e),r=null,a=0;for(let o of t){let s=o.root,u=s.endsWith("/")?s:s+"/";i.startsWith(u)&&u.length>a&&(r=o,a=u.length)}return r}function JJ(e,t,n){let i=e.startsWith("/")?e:GJ(n,e),r=t.endsWith("/")?t:t+"/";return i.startsWith(r)?i.slice(r.length):e}function _Ee(e){let t=[];for(let n of e.split(/\s+/)){let i=n.replace(/^['"]+|['"]+$/g,"");i&&(i.includes("/")||i.includes("\\"))&&t.push(i)}return t}function bEe(e){let t=new Map;async function n(r){if(t.has(r.name))return t.get(r.name);let a=await Vu({cacheDir:e.cacheDir,cacheKey:r.cacheKey}),o=a?{...a,hooks:K5(a.guardrailRules)}:void 0;return t.set(r.name,o),o}function i(r){let a=new Set;for(let o of _Ee(r)){let s=KS(o,e.members,e.workspaceRoot);s&&a.add(s)}return a.size>0?[...a]:e.members}return async function(a){if(ZS(a)){let d=a.tool_input?.command??"";for(let p of i(d)){let f=await n(p);if(!f)return aa(a6("guardrail-rules",`member "${p.name}"`));let m=f.hooks.beforeShellExecution({command:d,cwd:a.cwd});if(m.permission==="deny")return aa(m.user_message)}}let o=ZJ(a,e.workspaceRoot);if(!o)return Zc();let s=KS(o,e.members,e.workspaceRoot);if(!s)return Zc();let u=await n(s);if(!u)return aa(a6("navigation-index",`member "${s.name}"`));let l=JJ(o,s.root,e.workspaceRoot),c=u.hooks.afterFileEdit({file_path:l,content:Z5(a.tool_input)});if(c.permission==="deny")return aa(c.user_message);for(let d of n6(l,u.navigationIndex)){let p=i6(d);if(p.protected)return aa(p.reason)}return Zc()}}function _0(e){let t=e.system,n=e.artifacts??{},i=Object.keys(n),r=["## Project Navigation Index"],a=t?.name?`${t.name}${t.id?` (${t.id})`:""}`:t?.id??"unknown";if(r.push(`System: ${a}
1046
1046
  Artifacts: ${i.length}`),i.length>0){let o=[];for(let s of i){let u=n[s]??{},l=u.properties??{},c=[l.type,l.authority].filter(h=>typeof h=="string"&&h.length>0).join(", "),d=typeof l.manual_edit=="string"?`, edit:${l.manual_edit}`:"";o.push(`- ${s}${c||d?` [${c}${d}]`:""}`);let p=u.files?.path_patterns;Array.isArray(p)&&p.length>0&&o.push(` files: ${p.join(", ")}`);let f=u.relations?.derived_artifacts;Array.isArray(f)&&f.length>0&&o.push(` derived \u2192 ${f.join(", ")}`);let m=u.agents?.owners;Array.isArray(m)&&m.length>0&&o.push(` owners: ${m.join(", ")}`)}r.push(o.join(`
1047
1047
  `))}return r.join(`
1048
1048
 
@@ -4,4 +4,4 @@ import{realpathSync as J}from"fs";import{basename as Y,dirname as z,isAbsolute a
4
4
  `)}var se=["block","warn","shadow","info","unresolved"],ae="unresolved";function w(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.guardrail_id=="string"&&typeof t.pattern=="string"&&se.includes(t.action)&&typeof t.message=="string"&&(t.file_glob===void 0||typeof t.file_glob=="string")&&(t.exclude_glob===void 0||typeof t.exclude_glob=="string")}function $(e){if(typeof e!="object"||e===null)return!1;let t=e;return Array.isArray(t.commandRules)&&t.commandRules.every(w)&&Array.isArray(t.fileRules)&&t.fileRules.every(w)&&Array.isArray(t.contentRules)&&t.contentRules.every(w)}function ce(e){let t="";for(let r of e)r==="*"?t+="[^/]*":r==="?"?t+="[^/]":".+^$|()[]\\".includes(r)?t+="\\"+r:t+=r;return t}function ue(e){return e.endsWith("/")?`${e}**`:e}function h(e,t){let r=ue(e),n="",s=0;for(;s<r.length;)if(r[s]==="*"&&r[s+1]==="*"&&r[s+2]==="/")n+="(?:.+/)?",s+=3;else if(r[s]==="*"&&r[s+1]==="*")n+=".*",s+=2;else if(r[s]==="*")n+="[^/]*",s+=1;else if(r[s]==="?")n+="[^/]",s+=1;else if(r[s]==="{"){let o=r.indexOf("}",s);if(o!==-1){let c=r.slice(s+1,o).split(",").map(ce);n+="(?:"+c.join("|")+")",s=o+1}else n+="\\{",s+=1}else".+^$|()[]\\".includes(r[s])?(n+="\\"+r[s],s+=1):(n+=r[s],s+=1);return new RegExp("^"+n+"$").test(t)}function le(e){return e==="path"||e==="file"||e==="filename"||e.endsWith("_path")}function fe(e){return e==="content"||e.startsWith("new_")}function U(e,t){if(!e)return"";for(let r of Object.keys(e).sort()){if(!t(r))continue;let n=e[r];if(typeof n=="string"&&n)return n}return""}function de(e){return U(e,le)}var me=new Set(["Read","Glob","Grep","LSP","Task","Agent","Skill","WebFetch","WebSearch","TodoWrite","AskUserQuestion","ToolSearch","EnterPlanMode","ExitPlanMode"]);function D(e){let t=[],r=e;for(;;)try{return Q(J(r),...t)}catch{let n=z(r);if(n===r)return e;t.unshift(Y(r)),r=n}}function pe(e,t){let r=ee(t,e),n=Z(D(t),D(r));return n===""||X(n)||n.split(O)[0]===".."?r:n.split(O).join("/")}function k(e,t,r){if(me.has(e??""))return"";let n=de(t);return n&&pe(n,r??process.cwd())}function v(e){return U(e,fe)}function he(e){return e==="block"||e===ae}function N(e){return e.filter(t=>!t.passed&&he(t.action))}function ge(e){return e.filter(t=>!t.passed&&t.action==="warn")}function H(e){return e.map(t=>`[${t.guardrail_id}] ${t.message}`).join(`
5
5
  `)}function I(e){let t=H(e);return{permission:"deny",user_message:t,agent_message:t}}function ye(...e){function t(i){let a=[];if(i.command)for(let u of e)a.push(...u.checkCommand(i.command));if(i.filePath)for(let u of e)a.push(...u.checkFilePath(i.filePath));if(i.filePath&&i.content)for(let u of e)a.push(...u.checkContent(i.filePath,i.content));return a}function r(i){let a=i.command??"";return a?t({command:ie(a,i.cwd)}):[]}function n(i){let a=r(i);if(a.length===0)return{};let u=N(a),f=ge(a);return u.length>0?I(u):f.length>0?{additionalContext:H(f)}:{}}function s(i,a){if(!i)return{};let u=N(t({filePath:i,content:a}));return u.length>0?I(u):{}}function o(i){return s(k(i.tool_name,i.tool_input,i.root),v(i.tool_input))}function c(i){return s(i.file_path??"",i.content??"")}return{beforeShellExecution:n,checkShellCommand:r,preToolUse:o,afterFileEdit:c,runChecks:t}}function j(e){return e.startsWith("(?i)")?new RegExp(e.slice(4),"i"):new RegExp(e)}function A(e,...t){let r=e.commandRules.map(o=>({guardrail_id:o.guardrail_id,pattern:j(o.pattern),action:o.action,message:o.message})),n=e.fileRules,s=e.contentRules.map(o=>({guardrail_id:o.guardrail_id,pattern:j(o.pattern),action:o.action,message:o.message,file_glob:o.file_glob,exclude_glob:o.exclude_glob}));return ye({checkCommand(o){let c=[];for(let i of r){let a=!i.pattern.test(o);c.push({guardrail_id:i.guardrail_id,passed:a,action:i.action,message:a?"":i.message})}return c},checkFilePath(o){let c=[];for(let i of n){if(i.exclude_glob&&h(i.exclude_glob,o))continue;let a=h(i.pattern,o);c.push({guardrail_id:i.guardrail_id,passed:!a,action:i.action,message:a?i.message:""})}return c},checkContent(o,c){let i=[];for(let a of s){if(a.file_glob&&!h(a.file_glob,o)||a.exclude_glob&&h(a.exclude_glob,o))continue;let u=a.pattern.test(c);i.push({guardrail_id:a.guardrail_id,passed:!u,action:a.action,message:u?a.message:""})}return i}},...t)}import{readFile as Se,writeFile as W,rename as Re,stat as Ce,mkdir as xe}from"fs/promises";import{join as Ee}from"path";import{randomBytes as Te}from"crypto";import{stat as De}from"fs/promises";var _e=["SessionStart","UserPromptSubmit","PreToolUse"],P=e=>new Error(`Not a hook payload: ${e.slice(0,100)}`),p=e=>e===void 0||typeof e=="string";function be(e){if(e===void 0)return!0;if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return p(t.file_path)&&p(t.path)&&p(t.command)&&p(t.content)}function we(e){if(!p(e.session_id))return!1;switch(e.hookEventName){case"SessionStart":return e.type===void 0||typeof e.type=="string"&&["new","resume","clear","compact"].includes(e.type);case"UserPromptSubmit":return p(e.prompt);case"PreToolUse":return p(e.tool_name)&&be(e.tool_input);default:return!1}}function ke(e){let t=JSON.parse(e);if(typeof t!="object"||t===null||Array.isArray(t))throw P(e);let r=t;if(typeof r.hook_event_name=="string"&&r.hookEventName===void 0&&(r.hookEventName=r.hook_event_name),!_e.includes(r.hookEventName)){if(typeof r.hookEventName=="string")return;throw P(e)}if(!we(r))throw P(e);return r}async function ve(){let e=[];for await(let r of process.stdin)e.push(Buffer.isBuffer(r)?r:Buffer.from(r));let t=Buffer.concat(e).toString("utf-8").trim();if(!t)throw new Error("Empty stdin \u2014 no hook input received");return ke(t)}function Ae(e){process.stdout.write(JSON.stringify(e)+`
6
6
  `)}function Pe(e,t){return{hookSpecificOutput:{hookEventName:e,additionalContext:t}}}function m(e){return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}}}function g(){return{}}var y=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Fe(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let r=e;return typeof r.writtenAt=="string"&&typeof r.sourceHash=="string"&&(r.sourceFiles===void 0||Array.isArray(r.sourceFiles)&&r.sourceFiles.every(n=>typeof n=="string"))&&t(r.data)}function _(e){let{cacheDir:t}=e;function r(o){return Ee(t,`${o}.json`)}async function n(){await xe(t,{recursive:!0})}return{async read(o,c){let i;try{i=JSON.parse(await Se(r(o),"utf-8"))}catch{return null}return Fe(i,c)?i:null},async write(o,c,i,a){await n();let u={data:c,writtenAt:new Date().toISOString(),sourceHash:i,...a?{sourceFiles:a}:{}},f=JSON.stringify(u,null,2),d=r(o),l=`${d}.${Te(4).toString("hex")}.tmp`;await W(l,f,"utf-8");try{await Re(l,d)}catch{await W(d,f,"utf-8")}},async getFileMtime(o){try{return(await Ce(o)).mtimeMs}catch{return null}}}}function Oe(e){return e.map(String).join(":")}var Ne=".guardrails";function Ie(e){return`${e}${Ne}`}var L="navigation-index";async function je(e){let t=[];for(let r of e)try{let n=await De(r);t.push(n.mtimeMs)}catch{t.push(`missing:${r}`)}return Oe(t)}async function S(e){let t=e.cacheKey??L,r=_({cacheDir:e.cacheDir}),n=await r.read(t,y);if(!n?.sourceFiles||await je(n.sourceFiles)!==n.sourceHash)return;let o=await r.read(Ie(t),$);if(o?.sourceHash===n.sourceHash)return{navigationIndex:n.data,guardrailRules:o.data}}import{isAbsolute as $e}from"path";function R(e,t){if($e(e))return[];let r=t.artifacts??{},n=[];for(let[s,o]of Object.entries(r)){let c=o?.files?.path_patterns;if(Array.isArray(c)){for(let i of c)if(typeof i=="string"&&h(i,e)){n.push({artifactId:s,artifact:o,matchedPattern:i});break}}}return n}function Ue(e){if(e.authority==="generated")return"generated";if(e.manual_edit==="forbidden")return"forbidden"}function C(e){let t=Ue(e.artifact.properties??{});if(t==="generated"){let r=e.artifact.routes?.regenerate,n=r?` Run '${r}' to regenerate.`:" Edit the source artifact and regenerate instead.";return{protected:!0,reason:`File belongs to generated artifact '${e.artifactId}'. Direct editing is not allowed.${n}`}}return t==="forbidden"?{protected:!0,reason:`File belongs to artifact '${e.artifactId}' which has manual_edit: forbidden. This artifact must not be edited directly.`}:{protected:!1,reason:""}}function x(e){let t=e.artifacts??{};return Object.entries(t).map(([r,n])=>({id:r,artifact:n}))}import{resolve as K}from"path";function E(e){return e.tool_input?.command!==void 0}function M(e,t){return k(e.tool_name,e.tool_input,t)}var He={"navigation-index":"the artifact edit guard","guardrail-rules":"the DSL guardrails"};function b(e,t){let r=t?` for ${t}`:"";return`[guard-unavailable] ${He[e]} cannot run: the \`${e}\` cache entry${r} is absent or was built from sources that have since changed, so this operation gets no verdict and is refused rather than judged by superseded rules or silently allowed. Run \`.claude/bin/ensure-navigation-index\` (SessionStart and every prompt submission do this automatically \u2014 if it keeps failing, that failure is the bug).`}function We(e){let t=e.guardrailRules?A(e.guardrailRules):null;return async function(n){let s=M(n,e.projectRoot);if(!t&&(E(n)||s))return m(b("guardrail-rules"));if(t){if(E(n)){let c=t.beforeShellExecution({command:n.tool_input?.command,cwd:n.cwd});if(c.permission==="deny")return m(c.user_message)}let o=t.preToolUse({tool_name:n.tool_name,tool_input:n.tool_input,root:e.projectRoot});if(o.permission==="deny")return m(o.user_message)}if(s){if(!e.navigationIndex)return m(b("navigation-index"));for(let o of R(s,e.navigationIndex)){let c=C(o);if(c.protected)return m(c.reason)}}return g()}}var B=100;function q(e,t){let{navigationIndex:r,maxCandidates:n=B}=t,s=x(r),o=[],c=e.toLowerCase(),i=a=>Le(t.pathPrefix,a);for(let{id:a,artifact:u}of s){let f=u.properties??{},d=u.files?.path_patterns??[];(!e||a.toLowerCase().includes(c))&&o.push({label:a,path:i(d.length>0?String(d[0]):a),kind:"artifact",authority:f.authority,manual_edit:f.manual_edit,score:Ge(a,u,e)});for(let l of d)typeof l=="string"&&(l.includes("*")||l.includes("?")||(!e||l.toLowerCase().includes(c))&&o.push({label:l,path:i(l),kind:"file",artifact:a,authority:f.authority,manual_edit:f.manual_edit,score:Me(l,e)}))}return o.sort((a,u)=>u.score!==a.score?u.score-a.score:a.label.localeCompare(u.label)),o.slice(0,n)}function Le(e,t){if(!e)return t;let r=e.replace(/^\.\//,"").replace(/\/+$/,"");return r?`${r}/${t}`:t}function V(e){return e.map(t=>JSON.stringify(t)).join(`
7
- `)}function Ge(e,t,r){let n=50,s=t.properties??{};return s.authority==="canonical"&&(n+=20),s.manual_edit==="allowed"&&(n+=10),s.type==="source"&&(n+=15),s.authority==="generated"&&(n-=20),s.manual_edit==="forbidden"&&(n-=10),r&&e.toLowerCase().startsWith(r.toLowerCase())&&(n+=20),n}function Me(e,t){let r=40;return t&&e.toLowerCase().startsWith(t.toLowerCase())&&(r+=30),r+=Math.max(0,20-e.split("/").length*2),r}async function Be(e,t){let r=t.trim(),n=q(r,{navigationIndex:e});return V(n)}async function qe(e,t,r,n=B){let s=r.trim(),o=_({cacheDir:e}),c=[];for(let i of t){let a=await o.read(i.cacheKey,y);a&&c.push(...q(s,{navigationIndex:a.data,pathPrefix:i.memberPath,maxCandidates:Number.POSITIVE_INFINITY}))}return c.sort((i,a)=>a.score!==i.score?a.score-i.score:i.label.localeCompare(a.label)),V(c.slice(0,n))}function G(e,t,r){if(!e)return null;let n=e.startsWith("/")?e:K(r,e),s=null,o=0;for(let c of t){let i=c.root,a=i.endsWith("/")?i:i+"/";n.startsWith(a)&&a.length>o&&(s=c,o=a.length)}return s}function Ve(e,t,r){let n=e.startsWith("/")?e:K(r,e),s=t.endsWith("/")?t:t+"/";return n.startsWith(s)?n.slice(s.length):e}function Ke(e){let t=[];for(let r of e.split(/\s+/)){let n=r.replace(/^['"]+|['"]+$/g,"");n&&(n.includes("/")||n.includes("\\"))&&t.push(n)}return t}function Je(e){let t=new Map;async function r(s){if(t.has(s.name))return t.get(s.name);let o=await S({cacheDir:e.cacheDir,cacheKey:s.cacheKey}),c=o?{...o,hooks:A(o.guardrailRules)}:void 0;return t.set(s.name,c),c}function n(s){for(let o of Ke(s)){let c=G(o,e.members,e.workspaceRoot);if(c)return[c]}return e.members}return async function(o){if(E(o)){let d=o.tool_input?.command??"";for(let l of n(d)){let T=await r(l);if(!T)return m(b("guardrail-rules",`member "${l.name}"`));let F=T.hooks.beforeShellExecution({command:d,cwd:o.cwd});if(F.permission==="deny")return m(F.user_message)}}let c=M(o,e.workspaceRoot);if(!c)return g();let i=G(c,e.members,e.workspaceRoot);if(!i)return g();let a=await r(i);if(!a)return m(b("navigation-index",`member "${i.name}"`));let u=Ve(c,i.root,e.workspaceRoot),f=a.hooks.afterFileEdit({file_path:u,content:v(o.tool_input)});if(f.permission==="deny")return m(f.user_message);for(let d of R(u,a.navigationIndex)){let l=C(d);if(l.protected)return m(l.reason)}return g()}}export{L as DEFAULT_CACHE_KEY,Pe as buildContextResponse,_ as createCacheStore,We as createPreToolUseHandler,Je as createWorkspacePreToolUseHandler,Ae as emitHookOutput,Be as handleFileSuggestion,qe as handleWorkspaceFileSuggestion,y as isCachedRecord,x as listArtifacts,S as readFreshNavigationBuild,ve as readHookInput};
7
+ `)}function Ge(e,t,r){let n=50,s=t.properties??{};return s.authority==="canonical"&&(n+=20),s.manual_edit==="allowed"&&(n+=10),s.type==="source"&&(n+=15),s.authority==="generated"&&(n-=20),s.manual_edit==="forbidden"&&(n-=10),r&&e.toLowerCase().startsWith(r.toLowerCase())&&(n+=20),n}function Me(e,t){let r=40;return t&&e.toLowerCase().startsWith(t.toLowerCase())&&(r+=30),r+=Math.max(0,20-e.split("/").length*2),r}async function Be(e,t){let r=t.trim(),n=q(r,{navigationIndex:e});return V(n)}async function qe(e,t,r,n=B){let s=r.trim(),o=_({cacheDir:e}),c=[];for(let i of t){let a=await o.read(i.cacheKey,y);a&&c.push(...q(s,{navigationIndex:a.data,pathPrefix:i.memberPath,maxCandidates:Number.POSITIVE_INFINITY}))}return c.sort((i,a)=>a.score!==i.score?a.score-i.score:i.label.localeCompare(a.label)),V(c.slice(0,n))}function G(e,t,r){if(!e)return null;let n=e.startsWith("/")?e:K(r,e),s=null,o=0;for(let c of t){let i=c.root,a=i.endsWith("/")?i:i+"/";n.startsWith(a)&&a.length>o&&(s=c,o=a.length)}return s}function Ve(e,t,r){let n=e.startsWith("/")?e:K(r,e),s=t.endsWith("/")?t:t+"/";return n.startsWith(s)?n.slice(s.length):e}function Ke(e){let t=[];for(let r of e.split(/\s+/)){let n=r.replace(/^['"]+|['"]+$/g,"");n&&(n.includes("/")||n.includes("\\"))&&t.push(n)}return t}function Je(e){let t=new Map;async function r(s){if(t.has(s.name))return t.get(s.name);let o=await S({cacheDir:e.cacheDir,cacheKey:s.cacheKey}),c=o?{...o,hooks:A(o.guardrailRules)}:void 0;return t.set(s.name,c),c}function n(s){let o=new Set;for(let c of Ke(s)){let i=G(c,e.members,e.workspaceRoot);i&&o.add(i)}return o.size>0?[...o]:e.members}return async function(o){if(E(o)){let d=o.tool_input?.command??"";for(let l of n(d)){let T=await r(l);if(!T)return m(b("guardrail-rules",`member "${l.name}"`));let F=T.hooks.beforeShellExecution({command:d,cwd:o.cwd});if(F.permission==="deny")return m(F.user_message)}}let c=M(o,e.workspaceRoot);if(!c)return g();let i=G(c,e.members,e.workspaceRoot);if(!i)return g();let a=await r(i);if(!a)return m(b("navigation-index",`member "${i.name}"`));let u=Ve(c,i.root,e.workspaceRoot),f=a.hooks.afterFileEdit({file_path:u,content:v(o.tool_input)});if(f.permission==="deny")return m(f.user_message);for(let d of R(u,a.navigationIndex)){let l=C(d);if(l.protected)return m(l.reason)}return g()}}export{L as DEFAULT_CACHE_KEY,Pe as buildContextResponse,_ as createCacheStore,We as createPreToolUseHandler,Je as createWorkspacePreToolUseHandler,Ae as emitHookOutput,Be as handleFileSuggestion,qe as handleWorkspaceFileSuggestion,y as isCachedRecord,x as listArtifacts,S as readFreshNavigationBuild,ve as readHookInput};
@@ -4,8 +4,8 @@ import {
4
4
  loadProjectConfig,
5
5
  parseProjectManifest,
6
6
  readProjectManifest
7
- } from "../chunk-5ZDW4RP7.js";
8
- import "../chunk-EA4V5DVD.js";
7
+ } from "../chunk-K5XDDJFK.js";
8
+ import "../chunk-RIXKPQFC.js";
9
9
  import "../chunk-BJ7B4R26.js";
10
10
  export {
11
11
  ProjectConfigSchema,
@@ -421,11 +421,11 @@ interface WorkspacePreToolUseConfig {
421
421
  * - Denies a blocking `file_glob` / `content_regex` violation, then denies if
422
422
  * any matched artifact is protected (Phase 1).
423
423
  * - command guard, when the call carries one (#238 / C5, Phase 3):
424
- * - Routes the command to the owning member via a path token in the command
425
- * (longest-prefix match); when no member path is present, evaluates the
426
- * command against every member's rules so safety guardrails are never
427
- * silently skipped.
428
- * - Denies blocking command violations from that member's rules.
424
+ * - Routes the command to every member owning a path token in the command
425
+ * (longest-prefix match per token); when no member path is present,
426
+ * evaluates the command against every member's rules so safety guardrails
427
+ * are never silently skipped.
428
+ * - Denies blocking command violations from those members' rules.
429
429
  *
430
430
  * Artifact protection (Phase 1) and DSL guardrails (Phase 3) are independent and
431
431
  * coexist: a member with only artifact rules keeps working unchanged, and a
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { b as SdkFunctionTool, O as ObserverEmitFn, c as ObservabilityIds, S as SdkAdapter, d as TaskOutcome, e as TaskContractLike, f as AgentContractLike, g as TaskContext, L as LibraryToolRegistry, P as PromptBuilderOptions, h as MemoryStore, M as MemoryRef, i as TaskRunResult } from './task-runner-CgQx1KUq.js';
2
- export { j as AdapterError, k as AdapterErrorKind, A as AdapterSendOptions, a as AgentExecutionRequest, l as AgentProgressEvent, C as CacheConfig, m as CandidateAgent, E as EnvelopeParams, I as InMemoryStore, n as InnerSpanOptions, o as LibraryToolDefinition, p as OBSERVABILITY_ENV_VARS, R as RetryDecision, q as SplitPrompt, r as TaskRunOptions, T as TokenUsage, s as adapterErrorKind, t as buildCandidateAgents, u as buildObservabilityEnv, v as buildRetryFollowUp, w as buildSdkFunctionTools, x as buildSplitTaskPrompt, y as buildTaskPrompt, z as collectAnalyzerToolIds, B as createExecutionEnvelope, D as createLibraryToolRegistry, F as createRegistryFromSdkTools, G as emitIterationClose, H as emitIterationMetric, J as emitIterationOpen, K as emitLlmTurnClose, N as emitLlmTurnOpen, Q as emitSessionClose, U as emitSessionOpen, V as emitSubagentClose, W as emitSubagentOpen, X as emitToolExecClose, Y as emitToolExecOpen, Z as emitToolchainClose, _ as emitToolchainOpen, $ as extractStructuredResult, a0 as renderAgentSystemPrompt, a1 as renderAnalyzerExplorationMandatePrompt, a2 as runTask, a3 as serializeObserverEmit, a4 as shouldInjectAnalyzerExplorationMandate, a5 as zodSchemaToPromptDescription, a6 as zodSchemaToYamlExample } from './task-runner-CgQx1KUq.js';
1
+ import { b as SdkFunctionTool, O as ObserverEmitFn, c as ObservabilityIds, S as SdkAdapter, d as TaskOutcome, e as TaskContractLike, f as AgentContractLike, g as TaskContext, L as LibraryToolRegistry, P as PromptBuilderOptions, h as MemoryStore, M as MemoryRef, i as TaskRunResult } from './task-runner-Cpr-GTrl.js';
2
+ export { j as AdapterError, k as AdapterErrorKind, A as AdapterSendOptions, a as AgentExecutionRequest, l as AgentProgressEvent, C as CacheConfig, m as CandidateAgent, E as EnvelopeParams, I as InMemoryStore, n as InnerSpanOptions, o as LibraryToolDefinition, p as OBSERVABILITY_ENV_VARS, R as RetryDecision, q as SplitPrompt, r as TaskRunOptions, T as TokenUsage, s as adapterErrorKind, t as buildCandidateAgents, u as buildObservabilityEnv, v as buildRetryFollowUp, w as buildSdkFunctionTools, x as buildSplitTaskPrompt, y as buildTaskPrompt, z as collectAnalyzerToolIds, B as createExecutionEnvelope, D as createLibraryToolRegistry, F as createRegistryFromSdkTools, G as emitIterationClose, H as emitIterationMetric, J as emitIterationOpen, K as emitLlmTurnClose, N as emitLlmTurnOpen, Q as emitSessionClose, U as emitSessionOpen, V as emitSubagentClose, W as emitSubagentOpen, X as emitToolExecClose, Y as emitToolExecOpen, Z as emitToolchainClose, _ as emitToolchainOpen, $ as extractStructuredResult, a0 as renderAgentSystemPrompt, a1 as renderAnalyzerExplorationMandatePrompt, a2 as runTask, a3 as serializeObserverEmit, a4 as shouldInjectAnalyzerExplorationMandate, a5 as zodSchemaToPromptDescription, a6 as zodSchemaToYamlExample } from './task-runner-Cpr-GTrl.js';
3
3
  import { ProjectModelMapping, ModelClass, ComponentIR, OperationIR } from '@aaac/contracts';
4
4
  export { ModelClass } from '@aaac/contracts';
5
5
  import { z } from 'zod';
@@ -159,9 +159,9 @@ declare function renderContextPackPrompt(pack: ContextPack): string;
159
159
  * This module iterates all checks, executes them via subprocess, and
160
160
  * returns a ToolchainCheckResult[].
161
161
  *
162
- * For "drift" check types, a manifest-based fast path is available:
163
- * if a .toolchain-manifest.json exists and the toolchain_id matches,
164
- * the command execution can be skipped when the source hash is current.
162
+ * A declared check is always run — for "drift" too: the command is the most
163
+ * precise answer there is (toolchain-contracts-spec §7A.5), so a
164
+ * .toolchain-manifest.json never stands in for it.
165
165
  */
166
166
 
167
167
  declare const ToolchainManifestSchema: z.ZodObject<{
@@ -189,7 +189,7 @@ interface ToolchainCheckResult {
189
189
  interface RunToolchainChecksOptions {
190
190
  /** Absolute path to toolchain-contracts YAML */
191
191
  toolchainsPath: string;
192
- /** Absolute path to artifact-contracts YAML (optional, for manifest fast path) */
192
+ /** Absolute path to artifact-contracts YAML (optional; toolchain-contracts-spec §7A.6) */
193
193
  artifactsPath?: string;
194
194
  /** Working directory for subprocess execution */
195
195
  cwd?: string;
@@ -364,7 +364,7 @@ interface WorkflowRunOptions {
364
364
  /**
365
365
  * In-process library tools to register with every task in this workflow.
366
366
  * Passed through to each runTask() call. Adapters convert these to their
367
- * native tool format (Claude MCP, OpenAI function tools, ADK tools).
367
+ * native tool format (Claude MCP, OpenAI function tools).
368
368
  */
369
369
  libraryTools?: LibraryToolRegistry;
370
370
  /**
@@ -794,7 +794,14 @@ interface ResolvedComponent {
794
794
  toolchainsByAgent?: Map<string, ResolvedToolchain[]>;
795
795
  }
796
796
  /**
797
- * Effective guardrail IDs for an agent: entity-side bindings ∪ scope-side bindings.
797
+ * Effective guardrail IDs for an agent: entity-side bindings ∪ scope-side
798
+ * bindings ∪ every guardrail attributed to no agent.
799
+ *
800
+ * A guardrail is attributed to an agent when its `scope.agents` names the agent
801
+ * or the agent's `guardrails` lists it. One attributed to no agent at all —
802
+ * scoped only to tools, artifacts, workflows or tasks — is every agent's: the
803
+ * in-process hooks enforce it for each of them, the same rule set the Claude Code
804
+ * hook and `guard evaluate` enforce for every call.
798
805
  */
799
806
  declare function getEffectiveGuardrailIds(dsl: Record<string, unknown>, agentId: string): Set<string>;
800
807
  declare function guardrailContextToRuleData(ctx: GuardrailContext, effectiveIds?: Set<string>): GuardrailRuleData;
@@ -1063,7 +1070,7 @@ interface CreateAdapterOptions {
1063
1070
  /**
1064
1071
  * Create an SDK adapter instance by name.
1065
1072
  *
1066
- * @param name - One of: "mock", "claude", "openai", "gemini"
1073
+ * @param name - One of: "mock", "claude", "openai"
1067
1074
  * @param options - Adapter-specific configuration
1068
1075
  */
1069
1076
  declare function createAdapter(name: string, options?: CreateAdapterOptions): Promise<SdkAdapter>;