@aaac/runtime 0.2.9 → 0.3.0

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 (48) hide show
  1. package/dist/adapters/adk-sdk.d.ts +1 -1
  2. package/dist/adapters/adk-sdk.js +1 -1
  3. package/dist/adapters/claude-agent-sdk.d.ts +1 -1
  4. package/dist/adapters/claude-agent-sdk.js +5 -4
  5. package/dist/adapters/claude-agent-sdk.js.map +1 -1
  6. package/dist/adapters/openai-agents-sdk.d.ts +1 -1
  7. package/dist/adapters/openai-agents-sdk.js +1 -1
  8. package/dist/{chunk-D2UXESPT.js → chunk-2SG3TBI3.js} +4 -51
  9. package/dist/chunk-2SG3TBI3.js.map +1 -0
  10. package/dist/{chunk-Y7NORFFM.js → chunk-5ZDW4RP7.js} +2 -2
  11. package/dist/{chunk-GWNXNSGL.js → chunk-BHTHXGA3.js} +12 -9
  12. package/dist/chunk-BHTHXGA3.js.map +1 -0
  13. package/dist/{chunk-HR2Q64AO.js → chunk-EA4V5DVD.js} +29 -4
  14. package/dist/chunk-EA4V5DVD.js.map +1 -0
  15. package/dist/chunk-EBMQHLXY.js +61 -0
  16. package/dist/chunk-EBMQHLXY.js.map +1 -0
  17. package/dist/{chunk-QVMLALPF.js → chunk-GGBNVCPV.js} +5 -3
  18. package/dist/{chunk-QVMLALPF.js.map → chunk-GGBNVCPV.js.map} +1 -1
  19. package/dist/{chunk-CJLKKDKN.js → chunk-N2EA3TGS.js} +12 -12
  20. package/dist/{chunk-CJLKKDKN.js.map → chunk-N2EA3TGS.js.map} +1 -1
  21. package/dist/{chunk-MG7WSWJU.js → chunk-RTYJNZGT.js} +1 -1
  22. package/dist/chunk-RTYJNZGT.js.map +1 -0
  23. package/dist/claude-bundles/full.js +148 -148
  24. package/dist/claude-bundles/lean.js +5 -5
  25. package/dist/claude-bundles/prompt.js +2 -2
  26. package/dist/generator/index.d.ts +2 -2
  27. package/dist/generator/index.js +2 -2
  28. package/dist/{guardrail-hooks-B-qe4ebW.d.ts → guardrail-hooks-BgHe8PrP.d.ts} +6 -3
  29. package/dist/{hooks-lite-DvZu9Jhx.d.ts → hooks-lite-BtOGc2F_.d.ts} +12 -1
  30. package/dist/{index-C2DHitGz.d.ts → index-DeZsmlij.d.ts} +4 -1
  31. package/dist/index.d.ts +24 -5
  32. package/dist/index.js +144 -45
  33. package/dist/index.js.map +1 -1
  34. package/dist/lib/claude-native/hooks-lite.d.ts +2 -2
  35. package/dist/lib/claude-native/hooks-lite.js +6 -4
  36. package/dist/lib/claude-native/hooks-prompt.d.ts +3 -3
  37. package/dist/lib/claude-native/hooks-prompt.js +4 -3
  38. package/dist/lib/claude-native/index.d.ts +5 -5
  39. package/dist/lib/claude-native/index.js +11 -9
  40. package/dist/lib/claude-native/index.js.map +1 -1
  41. package/dist/{navigation-context-D1NbiipT.d.ts → navigation-context-DJjCkrcj.d.ts} +1 -1
  42. package/dist/{workspace-user-prompt-submit-aErGPoX4.d.ts → workspace-user-prompt-submit-GZwUKUHi.d.ts} +1 -1
  43. package/package.json +4 -4
  44. package/dist/chunk-D2UXESPT.js.map +0 -1
  45. package/dist/chunk-GWNXNSGL.js.map +0 -1
  46. package/dist/chunk-HR2Q64AO.js.map +0 -1
  47. package/dist/chunk-MG7WSWJU.js.map +0 -1
  48. /package/dist/{chunk-Y7NORFFM.js.map → chunk-5ZDW4RP7.js.map} +0 -0
@@ -1,3 +1,7 @@
1
+ // src/lib/guardrail-hooks.ts
2
+ import { realpathSync } from "fs";
3
+ import { basename, dirname, isAbsolute, join, relative, resolve as resolve2, sep } from "path";
4
+
1
5
  // src/lib/command-body-files.ts
2
6
  import { readFileSync, statSync } from "fs";
3
7
  import { resolve } from "path";
@@ -126,9 +130,30 @@ var NON_MUTATING_TOOLS = /* @__PURE__ */ new Set([
126
130
  "EnterPlanMode",
127
131
  "ExitPlanMode"
128
132
  ]);
129
- function toolWriteTarget(toolName, toolInput) {
133
+ function realPathAsFarAsItExists(path) {
134
+ const missing = [];
135
+ let head = path;
136
+ for (; ; ) {
137
+ try {
138
+ return join(realpathSync(head), ...missing);
139
+ } catch {
140
+ const parent = dirname(head);
141
+ if (parent === head) return path;
142
+ missing.unshift(basename(head));
143
+ head = parent;
144
+ }
145
+ }
146
+ }
147
+ function rootRelativeTarget(path, root) {
148
+ const absolute = resolve2(root, path);
149
+ const rel = relative(realPathAsFarAsItExists(root), realPathAsFarAsItExists(absolute));
150
+ const outside = rel === "" || isAbsolute(rel) || rel.split(sep)[0] === "..";
151
+ return outside ? absolute : rel.split(sep).join("/");
152
+ }
153
+ function toolWriteTarget(toolName, toolInput, root) {
130
154
  if (NON_MUTATING_TOOLS.has(toolName ?? "")) return "";
131
- return toolTargetPath(toolInput);
155
+ const target = toolTargetPath(toolInput);
156
+ return target && rootRelativeTarget(target, root ?? process.cwd());
132
157
  }
133
158
  function toolPendingContent(toolInput) {
134
159
  return firstStringValue(toolInput, namesPendingContent);
@@ -193,7 +218,7 @@ function createGuardrailHooks(...sources) {
193
218
  }
194
219
  function preToolUse(input) {
195
220
  return fileWriteVerdict(
196
- toolWriteTarget(input.tool_name, input.tool_input),
221
+ toolWriteTarget(input.tool_name, input.tool_input, input.root),
197
222
  toolPendingContent(input.tool_input)
198
223
  );
199
224
  }
@@ -290,4 +315,4 @@ export {
290
315
  createGuardrailHooks,
291
316
  createGuardrailHooksFromRules
292
317
  };
293
- //# sourceMappingURL=chunk-HR2Q64AO.js.map
318
+ //# sourceMappingURL=chunk-EA4V5DVD.js.map
@@ -0,0 +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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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"]}
@@ -0,0 +1,61 @@
1
+ import {
2
+ matchGlob
3
+ } from "./chunk-EA4V5DVD.js";
4
+
5
+ // src/lib/claude-native/artifact-resolver.ts
6
+ import { isAbsolute } from "path";
7
+ function resolvePathToArtifacts(filePath, navigationIndex) {
8
+ if (isAbsolute(filePath)) return [];
9
+ const artifacts = navigationIndex.artifacts ?? {};
10
+ const matches = [];
11
+ for (const [id, artifact] of Object.entries(artifacts)) {
12
+ const patterns = artifact?.files?.path_patterns;
13
+ if (!Array.isArray(patterns)) continue;
14
+ for (const pattern of patterns) {
15
+ if (typeof pattern !== "string") continue;
16
+ if (matchGlob(pattern, filePath)) {
17
+ matches.push({ artifactId: id, artifact, matchedPattern: pattern });
18
+ break;
19
+ }
20
+ }
21
+ }
22
+ return matches;
23
+ }
24
+ function editProtection(properties) {
25
+ if (properties.authority === "generated") return "generated";
26
+ if (properties.manual_edit === "forbidden") return "forbidden";
27
+ return void 0;
28
+ }
29
+ function isProtectedArtifact(match) {
30
+ const protection = editProtection(match.artifact.properties ?? {});
31
+ if (protection === "generated") {
32
+ const regen = match.artifact.routes?.regenerate;
33
+ const hint = regen ? ` Run '${regen}' to regenerate.` : " Edit the source artifact and regenerate instead.";
34
+ return {
35
+ protected: true,
36
+ reason: `File belongs to generated artifact '${match.artifactId}'. Direct editing is not allowed.${hint}`
37
+ };
38
+ }
39
+ if (protection === "forbidden") {
40
+ return {
41
+ protected: true,
42
+ reason: `File belongs to artifact '${match.artifactId}' which has manual_edit: forbidden. This artifact must not be edited directly.`
43
+ };
44
+ }
45
+ return { protected: false, reason: "" };
46
+ }
47
+ function listArtifacts(navigationIndex) {
48
+ const artifacts = navigationIndex.artifacts ?? {};
49
+ return Object.entries(artifacts).map(([id, artifact]) => ({
50
+ id,
51
+ artifact
52
+ }));
53
+ }
54
+
55
+ export {
56
+ resolvePathToArtifacts,
57
+ editProtection,
58
+ isProtectedArtifact,
59
+ listArtifacts
60
+ };
61
+ //# sourceMappingURL=chunk-EBMQHLXY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/claude-native/artifact-resolver.ts"],"sourcesContent":["/**\n * Artifact Resolver — reverse-lookup path to artifact_id using navigation-index.\n *\n * Uses glob matching from guardrail-hooks.ts to match file paths against\n * artifact path_patterns defined in the navigation index.\n */\n\nimport { isAbsolute } from \"node:path\";\nimport { matchGlob } from \"../guardrail-hooks.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Minimal shape of a navigation-index artifact node. */\nexport interface NavigationArtifact {\n properties?: {\n type?: string;\n authority?: string;\n manual_edit?: string;\n [key: string]: unknown;\n };\n files?: {\n path_patterns?: string[];\n [key: string]: unknown;\n };\n agents?: {\n owners?: string[];\n editors?: string[];\n [key: string]: unknown;\n };\n routes?: {\n regenerate?: string;\n [key: string]: unknown;\n };\n relations?: {\n derived_artifacts?: string[];\n [key: string]: unknown;\n };\n}\n\nexport interface ArtifactMatch {\n artifactId: string;\n artifact: NavigationArtifact;\n /** The glob pattern that matched. */\n matchedPattern: string;\n}\n\n// ---------------------------------------------------------------------------\n// Resolver\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve a file path to its artifact(s) in the navigation index.\n * Returns all matching artifacts (a file may belong to multiple artifacts).\n *\n * `filePath` is relative to the project root, the space `path_patterns` are\n * written in (`toolWriteTarget` reads a call's target that way). An absolute\n * path is one outside that root and belongs to no artifact, even where a\n * `**`-prefixed pattern would match its text.\n */\nexport function resolvePathToArtifacts(\n filePath: string,\n navigationIndex: Record<string, unknown>,\n): ArtifactMatch[] {\n if (isAbsolute(filePath)) return [];\n const artifacts =\n (navigationIndex.artifacts as Record<string, NavigationArtifact>) ?? {};\n const matches: ArtifactMatch[] = [];\n\n for (const [id, artifact] of Object.entries(artifacts)) {\n const patterns = artifact?.files?.path_patterns;\n if (!Array.isArray(patterns)) continue;\n\n for (const pattern of patterns) {\n if (typeof pattern !== \"string\") continue;\n if (matchGlob(pattern, filePath)) {\n matches.push({ artifactId: id, artifact, matchedPattern: pattern });\n break; // One match per artifact is sufficient\n }\n }\n }\n\n return matches;\n}\n\n/**\n * The protection an artifact's properties put on its files, or `undefined` for\n * none — the ONE rule for which artifacts the PreToolUse edit guard refuses\n * edits to. Asked of a navigation-index node's `properties` by\n * {@link isProtectedArtifact}, and of a DSL artifact (the same two fields, which\n * the index carries over as declared) when the CLAUDE.md block says what the\n * guard protects.\n */\nexport function editProtection(properties: {\n authority?: unknown;\n manual_edit?: unknown;\n}): \"generated\" | \"forbidden\" | undefined {\n if (properties.authority === \"generated\") return \"generated\";\n if (properties.manual_edit === \"forbidden\") return \"forbidden\";\n return undefined;\n}\n\n/**\n * Check if a file path targets a protected artifact (generated or manual_edit: forbidden).\n */\nexport function isProtectedArtifact(match: ArtifactMatch): {\n protected: boolean;\n reason: string;\n} {\n const protection = editProtection(match.artifact.properties ?? {});\n\n if (protection === \"generated\") {\n const regen = match.artifact.routes?.regenerate;\n const hint = regen\n ? ` Run '${regen}' to regenerate.`\n : \" Edit the source artifact and regenerate instead.\";\n return {\n protected: true,\n reason:\n `File belongs to generated artifact '${match.artifactId}'.` +\n ` Direct editing is not allowed.${hint}`,\n };\n }\n\n if (protection === \"forbidden\") {\n return {\n protected: true,\n reason:\n `File belongs to artifact '${match.artifactId}' which has manual_edit: forbidden.` +\n ` This artifact must not be edited directly.`,\n };\n }\n\n return { protected: false, reason: \"\" };\n}\n\n/**\n * Get all artifact entries from a navigation index as a flat list.\n */\nexport function listArtifacts(\n navigationIndex: Record<string, unknown>,\n): Array<{ id: string; artifact: NavigationArtifact }> {\n const artifacts =\n (navigationIndex.artifacts as Record<string, NavigationArtifact>) ?? {};\n return Object.entries(artifacts).map(([id, artifact]) => ({\n id,\n artifact,\n }));\n}\n"],"mappings":";;;;;AAOA,SAAS,kBAAkB;AAsDpB,SAAS,uBACd,UACA,iBACiB;AACjB,MAAI,WAAW,QAAQ,EAAG,QAAO,CAAC;AAClC,QAAM,YACH,gBAAgB,aAAoD,CAAC;AACxE,QAAM,UAA2B,CAAC;AAElC,aAAW,CAAC,IAAI,QAAQ,KAAK,OAAO,QAAQ,SAAS,GAAG;AACtD,UAAM,WAAW,UAAU,OAAO;AAClC,QAAI,CAAC,MAAM,QAAQ,QAAQ,EAAG;AAE9B,eAAW,WAAW,UAAU;AAC9B,UAAI,OAAO,YAAY,SAAU;AACjC,UAAI,UAAU,SAAS,QAAQ,GAAG;AAChC,gBAAQ,KAAK,EAAE,YAAY,IAAI,UAAU,gBAAgB,QAAQ,CAAC;AAClE;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;AAUO,SAAS,eAAe,YAGW;AACxC,MAAI,WAAW,cAAc,YAAa,QAAO;AACjD,MAAI,WAAW,gBAAgB,YAAa,QAAO;AACnD,SAAO;AACT;AAKO,SAAS,oBAAoB,OAGlC;AACA,QAAM,aAAa,eAAe,MAAM,SAAS,cAAc,CAAC,CAAC;AAEjE,MAAI,eAAe,aAAa;AAC9B,UAAM,QAAQ,MAAM,SAAS,QAAQ;AACrC,UAAM,OAAO,QACT,SAAS,KAAK,qBACd;AACJ,WAAO;AAAA,MACL,WAAW;AAAA,MACX,QACE,uCAAuC,MAAM,UAAU,oCACrB,IAAI;AAAA,IAC1C;AAAA,EACF;AAEA,MAAI,eAAe,aAAa;AAC9B,WAAO;AAAA,MACL,WAAW;AAAA,MACX,QACE,6BAA6B,MAAM,UAAU;AAAA,IAEjD;AAAA,EACF;AAEA,SAAO,EAAE,WAAW,OAAO,QAAQ,GAAG;AACxC;AAKO,SAAS,cACd,iBACqD;AACrD,QAAM,YACH,gBAAgB,aAAoD,CAAC;AACxE,SAAO,OAAO,QAAQ,SAAS,EAAE,IAAI,CAAC,CAAC,IAAI,QAAQ,OAAO;AAAA,IACxD;AAAA,IACA;AAAA,EACF,EAAE;AACJ;","names":[]}
@@ -4,9 +4,11 @@ import {
4
4
  import {
5
5
  DEFAULT_CACHE_KEY,
6
6
  buildContextResponse,
7
- listArtifacts,
8
7
  readFreshNavigationBuild
9
- } from "./chunk-D2UXESPT.js";
8
+ } from "./chunk-2SG3TBI3.js";
9
+ import {
10
+ listArtifacts
11
+ } from "./chunk-EBMQHLXY.js";
10
12
 
11
13
  // src/lib/claude-native/navigation-cache.ts
12
14
  import { spawn } from "child_process";
@@ -231,4 +233,4 @@ export {
231
233
  readFreshMemberIndices,
232
234
  createWorkspaceUserPromptSubmitHandler
233
235
  };
234
- //# sourceMappingURL=chunk-QVMLALPF.js.map
236
+ //# sourceMappingURL=chunk-GGBNVCPV.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/lib/claude-native/navigation-cache.ts","../src/lib/claude-native/user-prompt-submit.ts","../src/lib/claude-native/workspace-members.ts","../src/lib/claude-native/workspace-user-prompt-submit.ts"],"sourcesContent":["/**\n * Navigation-index cache: diagnostics rendering and escalation to the canonical\n * rebuild bin.\n *\n * Everything here is lean — `cache-store` + `node:child_process`, and NOT\n * `navigation-context`. That is the point: the interactive hooks must be able to\n * answer from a warm cache without loading the `agent-contracts` DSL loader\n * (~2.3MB of bundle, ~360ms), while still being correct when the cache is stale.\n *\n * The split of duties:\n * - deciding whether the cache is fresh → `navigation-freshness.ts`, a\n * separate module because the PreToolUse guard needs that answer and must\n * NOT be able to reach the `spawn` below (see that file's header)\n * - actually rebuilding → `ensure-navigation-index.ts`, and\n * from a lean process the `.claude/bin/ensure-navigation-index` bin that\n * wraps it. A lean hook never rebuilds in-process; it runs that bin. There\n * is exactly one rebuild implementation, reached two ways.\n */\n\nimport { spawn } from \"node:child_process\";\n\n/** One finding from a navigation-index build (artifact binding / schema). */\nexport interface NavigationDiagnostic {\n path: string;\n message: string;\n severity: string;\n}\n\n/**\n * How many diagnostics are spelled out before collapsing into a count. Sized to\n * show a whole artifact registry's binding findings (unbound + orphan) for a\n * typical project rather than truncating the picture the reader needs.\n */\nconst MAX_RENDERED_DIAGNOSTICS = 20;\n\n/**\n * Render build diagnostics as hook context lines. Returns undefined when there\n * is nothing to report, so callers can skip the section entirely.\n */\nexport function renderNavigationDiagnostics(\n diagnostics: NavigationDiagnostic[] | undefined,\n label = \"navigation-index\",\n): string | undefined {\n if (!diagnostics || diagnostics.length === 0) return undefined;\n\n const lines = diagnostics\n .slice(0, MAX_RENDERED_DIAGNOSTICS)\n .map((d) => ` - [${d.severity}] ${d.path}: ${d.message}`);\n const hidden = diagnostics.length - lines.length;\n if (hidden > 0) {\n lines.push(` - … ${hidden} more`);\n }\n\n return [`${label} diagnostics (${diagnostics.length}):`, ...lines].join(\"\\n\");\n}\n\n/**\n * Upper bound on a rebuild triggered from a hook. The rebuild loads the DSL\n * loader and walks the artifact registry — well under a second in practice — so\n * exceeding this means something is wrong, and a hook must report it rather than\n * hold up the user's prompt indefinitely. The kill produces a non-zero exit, so\n * a timed-out rebuild travels the same reporting path as any other failed one.\n */\nconst ENSURE_BIN_TIMEOUT_MS = 30_000;\n\n/**\n * What the SINGLE-COMPONENT `ensure-navigation-index` bin prints on success.\n *\n * Mirrors the emitter field for field (`buildEnsureNavigationIndexBin` in\n * @aaac/contracts claude-generator): `status`, `component` and `sources` are\n * written on every run, and `diagnostics` is spread in only when the build\n * produced findings — so that one field is optional and the rest are not.\n */\nexport interface EnsureBinComponentOutput {\n status: string;\n component: string;\n sources: string[];\n diagnostics?: NavigationDiagnostic[];\n}\n\n/** One member's line in the workspace bin's output. */\nexport interface EnsureBinMemberResult {\n member: string;\n status: string;\n diagnostics?: NavigationDiagnostic[];\n}\n\n/**\n * What the WORKSPACE `ensure-navigation-index` bin prints on success — one entry\n * per member, from `buildWorkspaceEnsureNavigationIndexBin` in the same emitter.\n */\nexport interface EnsureBinWorkspaceOutput {\n component: string;\n results: EnsureBinMemberResult[];\n}\n\n/**\n * A line printed by either bin. The union, not one shape with every field\n * optional: an all-optional shape models the emitters as looser than they are,\n * and a type that promises nothing leaves each consumer to invent its own `??`\n * — which is how both prompt hooks came to walk this line unguarded and answer\n * a malformed one with a `TypeError` instead of a prompt (#327).\n */\nexport type EnsureBinOutput = EnsureBinComponentOutput | EnsureBinWorkspaceOutput;\n\nfunction isNavigationDiagnostic(value: unknown): value is NavigationDiagnostic {\n if (typeof value !== \"object\" || value === null) return false;\n const d = value as Record<string, unknown>;\n return (\n typeof d.path === \"string\" &&\n typeof d.message === \"string\" &&\n typeof d.severity === \"string\"\n );\n}\n\n/** Absent is the emitter's \"nothing to report\"; present has to be readable. */\nfunction hasReadableDiagnostics(obj: Record<string, unknown>): boolean {\n return (\n obj.diagnostics === undefined ||\n (Array.isArray(obj.diagnostics) && obj.diagnostics.every(isNavigationDiagnostic))\n );\n}\n\nfunction isEnsureBinMemberResult(value: unknown): value is EnsureBinMemberResult {\n if (typeof value !== \"object\" || value === null) return false;\n const r = value as Record<string, unknown>;\n return (\n typeof r.member === \"string\" &&\n typeof r.status === \"string\" &&\n hasReadableDiagnostics(r)\n );\n}\n\n/**\n * The single gate between another process's stdout and the types above. What\n * passes may be walked without further guarding; what fails is not this bin's\n * output and none of it may be read as one.\n *\n * Every declared field is checked, including ones no caller reads today, because\n * the return type — not the set of fields somebody happens to dereference — is\n * what the predicate promises. `results` discriminates the two shapes: it is the\n * one field only the workspace bin writes.\n */\nfunction isEnsureBinOutput(value: unknown): value is EnsureBinOutput {\n if (typeof value !== \"object\" || value === null) return false;\n const obj = value as Record<string, unknown>;\n if (typeof obj.component !== \"string\") return false;\n if (obj.results !== undefined) {\n return Array.isArray(obj.results) && obj.results.every(isEnsureBinMemberResult);\n }\n return (\n typeof obj.status === \"string\" &&\n Array.isArray(obj.sources) &&\n obj.sources.every((s) => typeof s === \"string\") &&\n hasReadableDiagnostics(obj)\n );\n}\n\n/**\n * Run the project's own `ensure-navigation-index` bin to rebuild the cache.\n *\n * This is how a lean hook rebuilds: by invoking the canonical bin, not by\n * importing the builder. Two properties are load-bearing.\n *\n * `stdio` is fully piped. The bin writes a JSON line to ITS stdout, and the\n * calling hook writes its own hook-response JSON to the SAME stdout — inheriting\n * would interleave the two and corrupt the response Claude Code parses.\n *\n * A CHILD THAT COULD NOT REBUILD THROWS, it does not return a status. Every hook\n * bin wraps its `main()` in a catch that writes the message to stderr and exits\n * 1 — that is the single failure report in this harness, and it is exactly what\n * SessionStart already spends when the same DSL fails to load, because\n * SessionStart builds in-process and the builder throws. Handing the failure\n * back as an optional field instead made it droppable, and both callers dropped\n * it: the per-prompt hook answered `{}`, which is also its normal \"nothing to\n * inject\" response, so a broken DSL was reported by one hook and passed over in\n * silence by the other (#310). A non-zero exit is not blocking for either hook —\n * only exit 2 rejects a prompt, and neither of these hooks spends it.\n *\n * `undefined` is the OTHER answer, and it is not a failure: the child exited 0,\n * so the rebuild happened and the index is in the cache where every caller reads\n * it from. All that is missing is the line describing the rebuild.\n */\nexport async function runEnsureNavigationIndexBin(\n binPath: string,\n): Promise<EnsureBinOutput | undefined> {\n return new Promise<EnsureBinOutput | undefined>((resolve, reject) => {\n const child = spawn(process.execPath, [binPath], {\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n timeout: ENSURE_BIN_TIMEOUT_MS,\n });\n\n let stdout = \"\";\n let stderr = \"\";\n child.stdout.setEncoding(\"utf8\");\n child.stderr.setEncoding(\"utf8\");\n child.stdout.on(\"data\", (chunk: string) => (stdout += chunk));\n child.stderr.on(\"data\", (chunk: string) => (stderr += chunk));\n\n child.on(\"error\", (err) => reject(err));\n child.on(\"close\", (code) => {\n if (code !== 0) {\n reject(new Error(`ensure-navigation-index exited ${code}: ${stderr.trim()}`));\n return;\n }\n // Rebuilt, but said something we cannot read — bytes that are not JSON,\n // or JSON that is not this bin's shape. One answer for both: no\n // diagnostics. The cache is still warm, so this is not a failure for the\n // caller; whether the rebuild actually landed is answered by re-reading\n // the cache, which every caller does anyway.\n let printed: unknown;\n try {\n printed = JSON.parse(stdout.trim());\n } catch {\n // Not JSON — the gate below gives it the same answer.\n }\n resolve(isEnsureBinOutput(printed) ? printed : undefined);\n });\n });\n}\n\n/**\n * The error a hook raises when the index it exists to inject is STILL not\n * readable after the canonical rebuild reported success.\n *\n * A rebuild that exits non-zero already throws above. This is the other half:\n * the bin claimed success, so nothing was reported, yet the cache entry the hook\n * needs is absent or stale — a swallowed cache write, a source file touched\n * mid-build, or a member the bin does not warm. Returning \"no context\" there is\n * indistinguishable from a project with nothing to say, which is what made the\n * per-prompt hook silent in the first place (#310). One message producer for\n * both prompt handlers, so the single-component and workspace hooks cannot\n * describe the same state differently.\n */\nexport function navigationIndexUnavailable(cacheKey: string): Error {\n return new Error(\n `navigation-index cache \\`${cacheKey}\\` is still unreadable after ` +\n `ensure-navigation-index reported success — the rebuild did not write it, ` +\n `or wrote it against a different source list. Run ` +\n `\\`.claude/bin/ensure-navigation-index\\` directly to see why.`,\n );\n}\n","/**\n * UserPromptSubmit Hook Handler — navigation-index summary injection.\n *\n * Executed after prompt submission, before Claude processes it. Provides a\n * compact navigation-index summary so the LLM can pick candidates and delegate\n * deep exploration to `analyzer.getContextMap` (Level 2).\n *\n * ContextPack is NOT pre-injected by default (#206 Phase D).\n *\n * Hot path: this fires on every prompt submission, so it stays on the lean\n * module graph — cache read plus, when stale, a child process running the\n * project's `ensure-navigation-index` bin. It never imports the DSL loader.\n */\n\nimport { renderNavigationIndexPrompt } from \"../navigation-index-prompt.js\";\nimport {\n navigationIndexUnavailable,\n renderNavigationDiagnostics,\n runEnsureNavigationIndexBin,\n} from \"./navigation-cache.js\";\nimport {\n readFreshNavigationBuild,\n DEFAULT_CACHE_KEY,\n} from \"./navigation-freshness.js\";\nimport {\n listArtifacts,\n} from \"./artifact-resolver.js\";\nimport {\n buildContextResponse,\n type HookOutput,\n type UserPromptSubmitInput,\n} from \"./hook-protocol.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface UserPromptSubmitHandlerConfig {\n /** Absolute path to .claude/cache/ directory. */\n cacheDir: string;\n /**\n * Absolute path to this project's `.claude/bin/ensure-navigation-index`.\n *\n * This handler is on the interactive hot path — it runs on EVERY prompt\n * submission — so it must not carry the DSL loader. It answers from the warm\n * cache and, when that cache is stale, runs the project's own\n * `ensure-navigation-index` bin as a child process to refresh it. That bin is\n * the single rebuild implementation; nothing is duplicated here.\n */\n ensureBin: string;\n}\n\n// ---------------------------------------------------------------------------\n// Handler\n// ---------------------------------------------------------------------------\n\n/**\n * Create a UserPromptSubmit hook handler.\n */\nexport function createUserPromptSubmitHandler(\n config: UserPromptSubmitHandlerConfig,\n) {\n return async function handleUserPromptSubmit(\n input: UserPromptSubmitInput,\n ): Promise<HookOutput> {\n const prompt = input.prompt ?? \"\";\n\n const read = async () =>\n (await readFreshNavigationBuild({ cacheDir: config.cacheDir }))?.navigationIndex;\n\n let navigationIndex = await read();\n let diagnostics: string | undefined;\n if (!navigationIndex) {\n // Stale or cold: refresh through the canonical bin, then read again. A bin\n // that could not run throws, and this hook's bin reports that on stderr\n // and exits 1 — the same answer SessionStart gives to the same DSL error.\n const output = await runEnsureNavigationIndexBin(config.ensureBin);\n // `config.ensureBin` is the single-component bin, which reports one\n // diagnostics list for the one index it builds. The workspace shape's\n // per-member lists belong to the handler that knows the members.\n if (output && \"diagnostics\" in output) {\n diagnostics = renderNavigationDiagnostics(output.diagnostics);\n }\n navigationIndex = await read();\n }\n\n if (!navigationIndex) {\n throw navigationIndexUnavailable(DEFAULT_CACHE_KEY);\n }\n\n const sections: string[] = [\n // renderNavigationIndexPrompt already emits the \"## Project Navigation\n // Index\" heading — don't duplicate it here.\n renderNavigationIndexPrompt(navigationIndex),\n \"\",\n \"> Use `analyzer.getContextMap` with candidate paths/artifacts from the index\",\n \"> when you need structured dependency and read-target guidance.\",\n ];\n\n const candidates = renderCandidateArtifacts(prompt, navigationIndex);\n if (candidates) {\n sections.push(candidates);\n }\n if (diagnostics) {\n sections.push(\"\", diagnostics);\n }\n\n return buildContextResponse(\"UserPromptSubmit\", sections.join(\"\\n\"));\n };\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\ninterface CandidateArtifact {\n artifactId: string;\n artifact: ReturnType<typeof listArtifacts>[number][\"artifact\"];\n}\n\n/**\n * Render the prompt-keyword candidate section, or undefined when nothing matched.\n * Shared with the workspace handler, which renders one section per member.\n */\nexport function renderCandidateArtifacts(\n prompt: string,\n navigationIndex: Record<string, unknown>,\n heading = \"## Candidate Artifacts (from prompt keywords)\",\n): string | undefined {\n const candidates = extractCandidateArtifacts(prompt, navigationIndex);\n if (candidates.length === 0) return undefined;\n\n const lines = candidates.map((c) => {\n const props = c.artifact.properties ?? {};\n const tags = [props.type, props.authority, props.manual_edit ? `edit:${props.manual_edit}` : \"\"]\n .filter(Boolean)\n .join(\", \");\n return `- ${c.artifactId} [${tags}]`;\n });\n return `${heading}\\n${lines.join(\"\\n\")}`;\n}\n\nfunction extractCandidateArtifacts(\n prompt: string,\n navigationIndex: Record<string, unknown>,\n): CandidateArtifact[] {\n if (!prompt.trim()) return [];\n\n const artifacts = listArtifacts(navigationIndex);\n const lowerPrompt = prompt.toLowerCase();\n const matches: CandidateArtifact[] = [];\n const seen = new Set<string>();\n\n for (const { id, artifact } of artifacts) {\n if (lowerPrompt.includes(id.toLowerCase()) && !seen.has(id)) {\n seen.add(id);\n matches.push({ artifactId: id, artifact });\n continue;\n }\n\n const patterns = artifact.files?.path_patterns ?? [];\n for (const pattern of patterns) {\n if (typeof pattern !== \"string\") continue;\n const literal = pattern.replace(/[*?]/g, \"\").replace(/\\{.*\\}/g, \"\");\n if (literal.length > 3 && lowerPrompt.includes(literal.toLowerCase()) && !seen.has(id)) {\n seen.add(id);\n matches.push({ artifactId: id, artifact });\n break;\n }\n }\n }\n\n return matches;\n}\n","/**\n * Workspace member navigation — the shared warm-up + rendering used by every\n * workspace hook that needs per-member navigation indices (SessionStart and\n * UserPromptSubmit). One member = one navigation-index cache entry.\n *\n * LEAN module: it reads and renders, never builds. The heavy per-member warm-up\n * (`ensureMemberIndices`) lives with its only caller, the SessionStart handler,\n * so that importing member rendering does not drag `navigation-context` and the\n * `agent-contracts` DSL loader into the per-interaction hooks. Only types are\n * taken from `ensure-navigation-index`, and type imports are erased at build.\n */\n\nimport { renderNavigationIndexPrompt } from \"../navigation-index-prompt.js\";\nimport type {\n EnsureNavigationIndexOptions,\n NavigationIndexResult,\n} from \"./ensure-navigation-index.js\";\nimport { renderNavigationDiagnostics } from \"./navigation-cache.js\";\nimport { readFreshNavigationBuild } from \"./navigation-freshness.js\";\n\n/**\n * What a member needs to be READ from cache and rendered. Deliberately without\n * `navigationOptions`: the per-interaction hooks never build, so requiring build\n * options there would force them to resolve — and therefore parse — the embedded\n * DSL they exist to avoid.\n */\nexport interface WorkspaceMemberCacheConfig {\n /** Human-readable member name (e.g. `\"aaac\"`). */\n name: string;\n /**\n * Unique cache key for this member's navigation-index JSON.\n * Format: `navigation-index.<name>`.\n */\n cacheKey: string;\n}\n\n/** A member the SessionStart warm-up can also BUILD. */\nexport interface WorkspaceMemberNavConfig extends WorkspaceMemberCacheConfig {\n /** Absolute path to member root directory. */\n root: string;\n /** Source files for mtime-based cache invalidation. */\n sourceFiles: string[];\n /** Options passed to `buildNavigationContext()` on cache miss. */\n navigationOptions: EnsureNavigationIndexOptions[\"navigationOptions\"];\n}\n\nexport interface WorkspaceMemberNavResult {\n member: WorkspaceMemberCacheConfig;\n result: NavigationIndexResult;\n}\n\n/** One member's context section: index summary + freshness + build diagnostics. */\nexport function renderMemberSection({ member, result }: WorkspaceMemberNavResult): string {\n const summary = renderNavigationIndexPrompt(result.navigationIndex);\n const cacheNote = result.fromCache ? \"(loaded from cache)\" : \"(freshly built)\";\n const diagnostics = renderNavigationDiagnostics(\n result.diagnostics,\n `${member.name} navigation-index`,\n );\n return (\n `### Member: ${member.name} ${cacheNote}\\n${summary}` +\n (diagnostics ? `\\n\\n${diagnostics}` : \"\")\n );\n}\n\n/**\n * Lean read of every member's cached index.\n *\n * Members whose cache is missing or stale come back as `undefined`, so the\n * caller can run the workspace `ensure-navigation-index` bin ONCE — it warms\n * every member — and read again, instead of rebuilding per member in-process.\n */\nexport async function readFreshMemberIndices(\n cacheDir: string,\n members: WorkspaceMemberCacheConfig[],\n): Promise<\n Array<{ member: WorkspaceMemberCacheConfig; navigationIndex?: Record<string, unknown> }>\n> {\n return Promise.all(\n members.map(async (member) => ({\n member,\n navigationIndex: (\n await readFreshNavigationBuild({ cacheDir, cacheKey: member.cacheKey })\n )?.navigationIndex,\n })),\n );\n}\n","/**\n * Workspace UserPromptSubmit Hook Handler — per-member navigation context.\n *\n * The workspace hook set previously emitted the SINGLE-component ContextPack bin\n * at the workspace root (#263): SessionStart and PreToolUse were member-aware\n * while prompt submission saw only the root manifest, so no member's artifacts\n * reached the prompt. This mirrors the SessionStart handler — one index per\n * member — and adds prompt-keyword candidates per member.\n *\n * Hot path: this fires on every prompt submission, so it stays lean — it reads\n * each member's cached index and, when any is stale, runs the workspace\n * `ensure-navigation-index` bin ONCE (that bin warms every member) before\n * reading again. It never imports the DSL loader.\n */\n\nimport {\n readFreshMemberIndices,\n renderMemberSection,\n type WorkspaceMemberCacheConfig,\n} from \"./workspace-members.js\";\nimport {\n navigationIndexUnavailable,\n runEnsureNavigationIndexBin,\n type NavigationDiagnostic,\n} from \"./navigation-cache.js\";\nimport { renderCandidateArtifacts } from \"./user-prompt-submit.js\";\nimport {\n buildContextResponse,\n type HookOutput,\n type UserPromptSubmitInput,\n} from \"./hook-protocol.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface WorkspaceUserPromptSubmitConfig {\n /** Absolute path to the shared `.claude/cache/` directory. */\n cacheDir: string;\n /** Workspace members whose indices feed the prompt context. */\n members: WorkspaceMemberCacheConfig[];\n /**\n * Absolute path to this workspace's `.claude/bin/ensure-navigation-index`,\n * the single rebuild implementation. Run at most once per invocation, however\n * many members are stale, because that bin warms all of them.\n */\n ensureBin: string;\n}\n\n// ---------------------------------------------------------------------------\n// Handler\n// ---------------------------------------------------------------------------\n\nexport function createWorkspaceUserPromptSubmitHandler(\n config: WorkspaceUserPromptSubmitConfig,\n) {\n return async function handleWorkspaceUserPromptSubmit(\n input: UserPromptSubmitInput,\n ): Promise<HookOutput> {\n const prompt = input.prompt ?? \"\";\n\n let read = await readFreshMemberIndices(config.cacheDir, config.members);\n // Per-member diagnostics from a rebuild, keyed by member name.\n const rebuildDiagnostics = new Map<string, NavigationDiagnostic[]>();\n if (read.some((entry) => !entry.navigationIndex)) {\n const output = await runEnsureNavigationIndexBin(config.ensureBin);\n // `config.ensureBin` is the workspace bin, so `results` is the shape it\n // prints; a member reports `diagnostics` only when its build found any.\n if (output && \"results\" in output) {\n for (const result of output.results) {\n if (result.diagnostics) rebuildDiagnostics.set(result.member, result.diagnostics);\n }\n }\n read = await readFreshMemberIndices(config.cacheDir, config.members);\n }\n\n const sections: string[] = [];\n for (const entry of read) {\n // A member the rebuild did not leave an index for is a build failure, and\n // dropping its section renders context that LOOKS complete — the member is\n // simply not there. The workspace SessionStart handler already fails the\n // whole hook when any member cannot be built (`ensureMemberIndices` is a\n // `Promise.all`), so this reports it the same way (#310).\n if (!entry.navigationIndex) {\n throw navigationIndexUnavailable(entry.member.cacheKey);\n }\n\n sections.push(\n renderMemberSection({\n member: entry.member,\n result: {\n navigationIndex: entry.navigationIndex,\n fromCache: true,\n ...(rebuildDiagnostics.has(entry.member.name)\n ? { diagnostics: rebuildDiagnostics.get(entry.member.name) }\n : {}),\n },\n }),\n );\n const candidates = renderCandidateArtifacts(\n prompt,\n entry.navigationIndex,\n `#### Candidate Artifacts in ${entry.member.name} (from prompt keywords)`,\n );\n if (candidates) {\n sections.push(candidates);\n }\n }\n\n // Every member that IS declared rendered a section above or threw, so this is\n // reachable only for a workspace that declares no members at all: nothing to\n // inject, which is what an empty response means.\n if (sections.length === 0) {\n return {};\n }\n\n const additionalContext = [\n sections.join(\"\\n\\n\"),\n \"\",\n \"> Use `analyzer.getContextMap` with candidate paths/artifacts from a member's index\",\n \"> when you need structured dependency and read-target guidance.\",\n ].join(\"\\n\");\n\n return buildContextResponse(\"UserPromptSubmit\", additionalContext);\n };\n}\n"],"mappings":";;;;;;;;;;;AAmBA,SAAS,aAAa;AActB,IAAM,2BAA2B;AAM1B,SAAS,4BACd,aACA,QAAQ,oBACY;AACpB,MAAI,CAAC,eAAe,YAAY,WAAW,EAAG,QAAO;AAErD,QAAM,QAAQ,YACX,MAAM,GAAG,wBAAwB,EACjC,IAAI,CAAC,MAAM,QAAQ,EAAE,QAAQ,KAAK,EAAE,IAAI,KAAK,EAAE,OAAO,EAAE;AAC3D,QAAM,SAAS,YAAY,SAAS,MAAM;AAC1C,MAAI,SAAS,GAAG;AACd,UAAM,KAAK,cAAS,MAAM,OAAO;AAAA,EACnC;AAEA,SAAO,CAAC,GAAG,KAAK,iBAAiB,YAAY,MAAM,MAAM,GAAG,KAAK,EAAE,KAAK,IAAI;AAC9E;AASA,IAAM,wBAAwB;AA0C9B,SAAS,uBAAuB,OAA+C;AAC7E,MAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;AACxD,QAAM,IAAI;AACV,SACE,OAAO,EAAE,SAAS,YAClB,OAAO,EAAE,YAAY,YACrB,OAAO,EAAE,aAAa;AAE1B;AAGA,SAAS,uBAAuB,KAAuC;AACrE,SACE,IAAI,gBAAgB,UACnB,MAAM,QAAQ,IAAI,WAAW,KAAK,IAAI,YAAY,MAAM,sBAAsB;AAEnF;AAEA,SAAS,wBAAwB,OAAgD;AAC/E,MAAI,OA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,QACjB;AAAA,QACA,MAAM;AAAA,QACN,+BAA+B,MAAM,OAAO,IAAI;AAAA,MAClD;AACA,UAAI,YAAY;AACd,iBAAS,KAAK,UAAU;AAAA,MAC1B;AAAA,IACF;AAKA,QAAI,SAAS,WAAW,GAAG;AACzB,aAAO,CAAC;AAAA,IACV;AAEA,UAAM,oBAAoB;AAAA,MACxB,SAAS,KAAK,MAAM;AAAA,MACpB;AAAA,MACA;AAAA,MACA;AAAA,IACF,EAAE,KAAK,IAAI;AAEX,WAAO,qBAAqB,oBAAoB,iBAAiB;AAAA,EACnE;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/lib/claude-native/navigation-cache.ts","../src/lib/claude-native/user-prompt-submit.ts","../src/lib/claude-native/workspace-members.ts","../src/lib/claude-native/workspace-user-prompt-submit.ts"],"sourcesContent":["/**\n * Navigation-index cache: diagnostics rendering and escalation to the canonical\n * rebuild bin.\n *\n * Everything here is lean — `cache-store` + `node:child_process`, and NOT\n * `navigation-context`. That is the point: the interactive hooks must be able to\n * answer from a warm cache without loading the `agent-contracts` DSL loader\n * (~2.3MB of bundle, ~360ms), while still being correct when the cache is stale.\n *\n * The split of duties:\n * - deciding whether the cache is fresh → `navigation-freshness.ts`, a\n * separate module because the PreToolUse guard needs that answer and must\n * NOT be able to reach the `spawn` below (see that file's header)\n * - actually rebuilding → `ensure-navigation-index.ts`, and\n * from a lean process the `.claude/bin/ensure-navigation-index` bin that\n * wraps it. A lean hook never rebuilds in-process; it runs that bin. There\n * is exactly one rebuild implementation, reached two ways.\n */\n\nimport { spawn } from \"node:child_process\";\n\n/** One finding from a navigation-index build (artifact binding / schema). */\nexport interface NavigationDiagnostic {\n path: string;\n message: string;\n severity: string;\n}\n\n/**\n * How many diagnostics are spelled out before collapsing into a count. Sized to\n * show a whole artifact registry's binding findings (unbound + orphan) for a\n * typical project rather than truncating the picture the reader needs.\n */\nconst MAX_RENDERED_DIAGNOSTICS = 20;\n\n/**\n * Render build diagnostics as hook context lines. Returns undefined when there\n * is nothing to report, so callers can skip the section entirely.\n */\nexport function renderNavigationDiagnostics(\n diagnostics: NavigationDiagnostic[] | undefined,\n label = \"navigation-index\",\n): string | undefined {\n if (!diagnostics || diagnostics.length === 0) return undefined;\n\n const lines = diagnostics\n .slice(0, MAX_RENDERED_DIAGNOSTICS)\n .map((d) => ` - [${d.severity}] ${d.path}: ${d.message}`);\n const hidden = diagnostics.length - lines.length;\n if (hidden > 0) {\n lines.push(` - … ${hidden} more`);\n }\n\n return [`${label} diagnostics (${diagnostics.length}):`, ...lines].join(\"\\n\");\n}\n\n/**\n * Upper bound on a rebuild triggered from a hook. The rebuild loads the DSL\n * loader and walks the artifact registry — well under a second in practice — so\n * exceeding this means something is wrong, and a hook must report it rather than\n * hold up the user's prompt indefinitely. The kill produces a non-zero exit, so\n * a timed-out rebuild travels the same reporting path as any other failed one.\n */\nconst ENSURE_BIN_TIMEOUT_MS = 30_000;\n\n/**\n * What the SINGLE-COMPONENT `ensure-navigation-index` bin prints on success.\n *\n * Mirrors the emitter field for field (`buildEnsureNavigationIndexBin` in\n * @aaac/contracts claude-generator): `status`, `component` and `sources` are\n * written on every run, and `diagnostics` is spread in only when the build\n * produced findings — so that one field is optional and the rest are not.\n */\nexport interface EnsureBinComponentOutput {\n status: string;\n component: string;\n sources: string[];\n diagnostics?: NavigationDiagnostic[];\n}\n\n/** One member's line in the workspace bin's output. */\nexport interface EnsureBinMemberResult {\n member: string;\n status: string;\n diagnostics?: NavigationDiagnostic[];\n}\n\n/**\n * What the WORKSPACE `ensure-navigation-index` bin prints on success — one entry\n * per member, from `buildWorkspaceEnsureNavigationIndexBin` in the same emitter.\n */\nexport interface EnsureBinWorkspaceOutput {\n component: string;\n results: EnsureBinMemberResult[];\n}\n\n/**\n * A line printed by either bin. The union, not one shape with every field\n * optional: an all-optional shape models the emitters as looser than they are,\n * and a type that promises nothing leaves each consumer to invent its own `??`\n * — which is how both prompt hooks came to walk this line unguarded and answer\n * a malformed one with a `TypeError` instead of a prompt (#327).\n */\nexport type EnsureBinOutput = EnsureBinComponentOutput | EnsureBinWorkspaceOutput;\n\nfunction isNavigationDiagnostic(value: unknown): value is NavigationDiagnostic {\n if (typeof value !== \"object\" || value === null) return false;\n const d = value as Record<string, unknown>;\n return (\n typeof d.path === \"string\" &&\n typeof d.message === \"string\" &&\n typeof d.severity === \"string\"\n );\n}\n\n/** Absent is the emitter's \"nothing to report\"; present has to be readable. */\nfunction hasReadableDiagnostics(obj: Record<string, unknown>): boolean {\n return (\n obj.diagnostics === undefined ||\n (Array.isArray(obj.diagnostics) && obj.diagnostics.every(isNavigationDiagnostic))\n );\n}\n\nfunction isEnsureBinMemberResult(value: unknown): value is EnsureBinMemberResult {\n if (typeof value !== \"object\" || value === null) return false;\n const r = value as Record<string, unknown>;\n return (\n typeof r.member === \"string\" &&\n typeof r.status === \"string\" &&\n hasReadableDiagnostics(r)\n );\n}\n\n/**\n * The single gate between another process's stdout and the types above. What\n * passes may be walked without further guarding; what fails is not this bin's\n * output and none of it may be read as one.\n *\n * Every declared field is checked, including ones no caller reads today, because\n * the return type — not the set of fields somebody happens to dereference — is\n * what the predicate promises. `results` discriminates the two shapes: it is the\n * one field only the workspace bin writes.\n */\nfunction isEnsureBinOutput(value: unknown): value is EnsureBinOutput {\n if (typeof value !== \"object\" || value === null) return false;\n const obj = value as Record<string, unknown>;\n if (typeof obj.component !== \"string\") return false;\n if (obj.results !== undefined) {\n return Array.isArray(obj.results) && obj.results.every(isEnsureBinMemberResult);\n }\n return (\n typeof obj.status === \"string\" &&\n Array.isArray(obj.sources) &&\n obj.sources.every((s) => typeof s === \"string\") &&\n hasReadableDiagnostics(obj)\n );\n}\n\n/**\n * Run the project's own `ensure-navigation-index` bin to rebuild the cache.\n *\n * This is how a lean hook rebuilds: by invoking the canonical bin, not by\n * importing the builder. Two properties are load-bearing.\n *\n * `stdio` is fully piped. The bin writes a JSON line to ITS stdout, and the\n * calling hook writes its own hook-response JSON to the SAME stdout — inheriting\n * would interleave the two and corrupt the response Claude Code parses.\n *\n * A CHILD THAT COULD NOT REBUILD THROWS, it does not return a status. Every hook\n * bin wraps its `main()` in a catch that writes the message to stderr and exits\n * 1 — that is the single failure report in this harness, and it is exactly what\n * SessionStart already spends when the same DSL fails to load, because\n * SessionStart builds in-process and the builder throws. Handing the failure\n * back as an optional field instead made it droppable, and both callers dropped\n * it: the per-prompt hook answered `{}`, which is also its normal \"nothing to\n * inject\" response, so a broken DSL was reported by one hook and passed over in\n * silence by the other (#310). A non-zero exit is not blocking for either hook —\n * only exit 2 rejects a prompt, and neither of these hooks spends it.\n *\n * `undefined` is the OTHER answer, and it is not a failure: the child exited 0,\n * so the rebuild happened and the index is in the cache where every caller reads\n * it from. All that is missing is the line describing the rebuild.\n */\nexport async function runEnsureNavigationIndexBin(\n binPath: string,\n): Promise<EnsureBinOutput | undefined> {\n return new Promise<EnsureBinOutput | undefined>((resolve, reject) => {\n const child = spawn(process.execPath, [binPath], {\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n timeout: ENSURE_BIN_TIMEOUT_MS,\n });\n\n let stdout = \"\";\n let stderr = \"\";\n child.stdout.setEncoding(\"utf8\");\n child.stderr.setEncoding(\"utf8\");\n child.stdout.on(\"data\", (chunk: string) => (stdout += chunk));\n child.stderr.on(\"data\", (chunk: string) => (stderr += chunk));\n\n child.on(\"error\", (err) => reject(err));\n child.on(\"close\", (code) => {\n if (code !== 0) {\n reject(new Error(`ensure-navigation-index exited ${code}: ${stderr.trim()}`));\n return;\n }\n // Rebuilt, but said something we cannot read — bytes that are not JSON,\n // or JSON that is not this bin's shape. One answer for both: no\n // diagnostics. The cache is still warm, so this is not a failure for the\n // caller; whether the rebuild actually landed is answered by re-reading\n // the cache, which every caller does anyway.\n let printed: unknown;\n try {\n printed = JSON.parse(stdout.trim());\n } catch {\n // Not JSON — the gate below gives it the same answer.\n }\n resolve(isEnsureBinOutput(printed) ? printed : undefined);\n });\n });\n}\n\n/**\n * The error a hook raises when the index it exists to inject is STILL not\n * readable after the canonical rebuild reported success.\n *\n * A rebuild that exits non-zero already throws above. This is the other half:\n * the bin claimed success, so nothing was reported, yet the cache entry the hook\n * needs is absent or stale — a swallowed cache write, a source file touched\n * mid-build, or a member the bin does not warm. Returning \"no context\" there is\n * indistinguishable from a project with nothing to say, which is what made the\n * per-prompt hook silent in the first place (#310). One message producer for\n * both prompt handlers, so the single-component and workspace hooks cannot\n * describe the same state differently.\n */\nexport function navigationIndexUnavailable(cacheKey: string): Error {\n return new Error(\n `navigation-index cache \\`${cacheKey}\\` is still unreadable after ` +\n `ensure-navigation-index reported success — the rebuild did not write it, ` +\n `or wrote it against a different source list. Run ` +\n `\\`.claude/bin/ensure-navigation-index\\` directly to see why.`,\n );\n}\n","/**\n * UserPromptSubmit Hook Handler — navigation-index summary injection.\n *\n * Executed after prompt submission, before Claude processes it. Provides a\n * compact navigation-index summary so the LLM can pick candidates and delegate\n * deep exploration to `analyzer.getContextMap` (Level 2).\n *\n * ContextPack is NOT pre-injected by default (#206 Phase D).\n *\n * Hot path: this fires on every prompt submission, so it stays on the lean\n * module graph — cache read plus, when stale, a child process running the\n * project's `ensure-navigation-index` bin. It never imports the DSL loader.\n */\n\nimport { renderNavigationIndexPrompt } from \"../navigation-index-prompt.js\";\nimport {\n navigationIndexUnavailable,\n renderNavigationDiagnostics,\n runEnsureNavigationIndexBin,\n} from \"./navigation-cache.js\";\nimport {\n readFreshNavigationBuild,\n DEFAULT_CACHE_KEY,\n} from \"./navigation-freshness.js\";\nimport {\n listArtifacts,\n} from \"./artifact-resolver.js\";\nimport {\n buildContextResponse,\n type HookOutput,\n type UserPromptSubmitInput,\n} from \"./hook-protocol.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface UserPromptSubmitHandlerConfig {\n /** Absolute path to .claude/cache/ directory. */\n cacheDir: string;\n /**\n * Absolute path to this project's `.claude/bin/ensure-navigation-index`.\n *\n * This handler is on the interactive hot path — it runs on EVERY prompt\n * submission — so it must not carry the DSL loader. It answers from the warm\n * cache and, when that cache is stale, runs the project's own\n * `ensure-navigation-index` bin as a child process to refresh it. That bin is\n * the single rebuild implementation; nothing is duplicated here.\n */\n ensureBin: string;\n}\n\n// ---------------------------------------------------------------------------\n// Handler\n// ---------------------------------------------------------------------------\n\n/**\n * Create a UserPromptSubmit hook handler.\n */\nexport function createUserPromptSubmitHandler(\n config: UserPromptSubmitHandlerConfig,\n) {\n return async function handleUserPromptSubmit(\n input: UserPromptSubmitInput,\n ): Promise<HookOutput> {\n const prompt = input.prompt ?? \"\";\n\n const read = async () =>\n (await readFreshNavigationBuild({ cacheDir: config.cacheDir }))?.navigationIndex;\n\n let navigationIndex = await read();\n let diagnostics: string | undefined;\n if (!navigationIndex) {\n // Stale or cold: refresh through the canonical bin, then read again. A bin\n // that could not run throws, and this hook's bin reports that on stderr\n // and exits 1 — the same answer SessionStart gives to the same DSL error.\n const output = await runEnsureNavigationIndexBin(config.ensureBin);\n // `config.ensureBin` is the single-component bin, which reports one\n // diagnostics list for the one index it builds. The workspace shape's\n // per-member lists belong to the handler that knows the members.\n if (output && \"diagnostics\" in output) {\n diagnostics = renderNavigationDiagnostics(output.diagnostics);\n }\n navigationIndex = await read();\n }\n\n if (!navigationIndex) {\n throw navigationIndexUnavailable(DEFAULT_CACHE_KEY);\n }\n\n const sections: string[] = [\n // renderNavigationIndexPrompt already emits the \"## Project Navigation\n // Index\" heading — don't duplicate it here.\n renderNavigationIndexPrompt(navigationIndex),\n \"\",\n \"> Use `analyzer.getContextMap` with candidate paths/artifacts from the index\",\n \"> when you need structured dependency and read-target guidance.\",\n ];\n\n const candidates = renderCandidateArtifacts(prompt, navigationIndex);\n if (candidates) {\n sections.push(candidates);\n }\n if (diagnostics) {\n sections.push(\"\", diagnostics);\n }\n\n return buildContextResponse(\"UserPromptSubmit\", sections.join(\"\\n\"));\n };\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\ninterface CandidateArtifact {\n artifactId: string;\n artifact: ReturnType<typeof listArtifacts>[number][\"artifact\"];\n}\n\n/**\n * Render the prompt-keyword candidate section, or undefined when nothing matched.\n * Shared with the workspace handler, which renders one section per member.\n */\nexport function renderCandidateArtifacts(\n prompt: string,\n navigationIndex: Record<string, unknown>,\n heading = \"## Candidate Artifacts (from prompt keywords)\",\n): string | undefined {\n const candidates = extractCandidateArtifacts(prompt, navigationIndex);\n if (candidates.length === 0) return undefined;\n\n const lines = candidates.map((c) => {\n const props = c.artifact.properties ?? {};\n const tags = [props.type, props.authority, props.manual_edit ? `edit:${props.manual_edit}` : \"\"]\n .filter(Boolean)\n .join(\", \");\n return `- ${c.artifactId} [${tags}]`;\n });\n return `${heading}\\n${lines.join(\"\\n\")}`;\n}\n\nfunction extractCandidateArtifacts(\n prompt: string,\n navigationIndex: Record<string, unknown>,\n): CandidateArtifact[] {\n if (!prompt.trim()) return [];\n\n const artifacts = listArtifacts(navigationIndex);\n const lowerPrompt = prompt.toLowerCase();\n const matches: CandidateArtifact[] = [];\n const seen = new Set<string>();\n\n for (const { id, artifact } of artifacts) {\n if (lowerPrompt.includes(id.toLowerCase()) && !seen.has(id)) {\n seen.add(id);\n matches.push({ artifactId: id, artifact });\n continue;\n }\n\n const patterns = artifact.files?.path_patterns ?? [];\n for (const pattern of patterns) {\n if (typeof pattern !== \"string\") continue;\n const literal = pattern.replace(/[*?]/g, \"\").replace(/\\{.*\\}/g, \"\");\n if (literal.length > 3 && lowerPrompt.includes(literal.toLowerCase()) && !seen.has(id)) {\n seen.add(id);\n matches.push({ artifactId: id, artifact });\n break;\n }\n }\n }\n\n return matches;\n}\n","/**\n * Workspace member navigation — the shared warm-up + rendering used by every\n * workspace hook that needs per-member navigation indices (SessionStart and\n * UserPromptSubmit). One member = one navigation-index cache entry.\n *\n * LEAN module: it reads and renders, never builds. The heavy per-member warm-up\n * (`ensureMemberIndices`) lives with its only caller, the SessionStart handler,\n * so that importing member rendering does not drag `navigation-context` and the\n * `agent-contracts` DSL loader into the per-interaction hooks. Only types are\n * taken from `ensure-navigation-index`, and type imports are erased at build.\n */\n\nimport { renderNavigationIndexPrompt } from \"../navigation-index-prompt.js\";\nimport type {\n EnsureNavigationIndexOptions,\n NavigationIndexResult,\n} from \"./ensure-navigation-index.js\";\nimport { renderNavigationDiagnostics } from \"./navigation-cache.js\";\nimport { readFreshNavigationBuild } from \"./navigation-freshness.js\";\n\n/**\n * What a member needs to be READ from cache and rendered. Deliberately without\n * `navigationOptions`: the per-interaction hooks never build, so requiring build\n * options there would force them to resolve — and therefore parse — the embedded\n * DSL they exist to avoid.\n */\nexport interface WorkspaceMemberCacheConfig {\n /** Human-readable member name (e.g. `\"aaac\"`). */\n name: string;\n /**\n * Unique cache key for this member's navigation-index JSON.\n * Format: `navigation-index.<name>`.\n */\n cacheKey: string;\n}\n\n/** A member the SessionStart warm-up can also BUILD. */\nexport interface WorkspaceMemberNavConfig extends WorkspaceMemberCacheConfig {\n /** Absolute path to member root directory. */\n root: string;\n /** Source files for mtime-based cache invalidation. */\n sourceFiles: string[];\n /** Options passed to `buildNavigationContext()` on cache miss. */\n navigationOptions: EnsureNavigationIndexOptions[\"navigationOptions\"];\n}\n\nexport interface WorkspaceMemberNavResult {\n member: WorkspaceMemberCacheConfig;\n result: NavigationIndexResult;\n}\n\n/** One member's context section: index summary + freshness + build diagnostics. */\nexport function renderMemberSection({ member, result }: WorkspaceMemberNavResult): string {\n const summary = renderNavigationIndexPrompt(result.navigationIndex);\n const cacheNote = result.fromCache ? \"(loaded from cache)\" : \"(freshly built)\";\n const diagnostics = renderNavigationDiagnostics(\n result.diagnostics,\n `${member.name} navigation-index`,\n );\n return (\n `### Member: ${member.name} ${cacheNote}\\n${summary}` +\n (diagnostics ? `\\n\\n${diagnostics}` : \"\")\n );\n}\n\n/**\n * Lean read of every member's cached index.\n *\n * Members whose cache is missing or stale come back as `undefined`, so the\n * caller can run the workspace `ensure-navigation-index` bin ONCE — it warms\n * every member — and read again, instead of rebuilding per member in-process.\n */\nexport async function readFreshMemberIndices(\n cacheDir: string,\n members: WorkspaceMemberCacheConfig[],\n): Promise<\n Array<{ member: WorkspaceMemberCacheConfig; navigationIndex?: Record<string, unknown> }>\n> {\n return Promise.all(\n members.map(async (member) => ({\n member,\n navigationIndex: (\n await readFreshNavigationBuild({ cacheDir, cacheKey: member.cacheKey })\n )?.navigationIndex,\n })),\n );\n}\n","/**\n * Workspace UserPromptSubmit Hook Handler — per-member navigation context.\n *\n * The workspace hook set previously emitted the SINGLE-component ContextPack bin\n * at the workspace root (#263): SessionStart and PreToolUse were member-aware\n * while prompt submission saw only the root manifest, so no member's artifacts\n * reached the prompt. This mirrors the SessionStart handler — one index per\n * member — and adds prompt-keyword candidates per member.\n *\n * Hot path: this fires on every prompt submission, so it stays lean — it reads\n * each member's cached index and, when any is stale, runs the workspace\n * `ensure-navigation-index` bin ONCE (that bin warms every member) before\n * reading again. It never imports the DSL loader.\n */\n\nimport {\n readFreshMemberIndices,\n renderMemberSection,\n type WorkspaceMemberCacheConfig,\n} from \"./workspace-members.js\";\nimport {\n navigationIndexUnavailable,\n runEnsureNavigationIndexBin,\n type NavigationDiagnostic,\n} from \"./navigation-cache.js\";\nimport { renderCandidateArtifacts } from \"./user-prompt-submit.js\";\nimport {\n buildContextResponse,\n type HookOutput,\n type UserPromptSubmitInput,\n} from \"./hook-protocol.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface WorkspaceUserPromptSubmitConfig {\n /** Absolute path to the shared `.claude/cache/` directory. */\n cacheDir: string;\n /** Workspace members whose indices feed the prompt context. */\n members: WorkspaceMemberCacheConfig[];\n /**\n * Absolute path to this workspace's `.claude/bin/ensure-navigation-index`,\n * the single rebuild implementation. Run at most once per invocation, however\n * many members are stale, because that bin warms all of them.\n */\n ensureBin: string;\n}\n\n// ---------------------------------------------------------------------------\n// Handler\n// ---------------------------------------------------------------------------\n\nexport function createWorkspaceUserPromptSubmitHandler(\n config: WorkspaceUserPromptSubmitConfig,\n) {\n return async function handleWorkspaceUserPromptSubmit(\n input: UserPromptSubmitInput,\n ): Promise<HookOutput> {\n const prompt = input.prompt ?? \"\";\n\n let read = await readFreshMemberIndices(config.cacheDir, config.members);\n // Per-member diagnostics from a rebuild, keyed by member name.\n const rebuildDiagnostics = new Map<string, NavigationDiagnostic[]>();\n if (read.some((entry) => !entry.navigationIndex)) {\n const output = await runEnsureNavigationIndexBin(config.ensureBin);\n // `config.ensureBin` is the workspace bin, so `results` is the shape it\n // prints; a member reports `diagnostics` only when its build found any.\n if (output && \"results\" in output) {\n for (const result of output.results) {\n if (result.diagnostics) rebuildDiagnostics.set(result.member, result.diagnostics);\n }\n }\n read = await readFreshMemberIndices(config.cacheDir, config.members);\n }\n\n const sections: string[] = [];\n for (const entry of read) {\n // A member the rebuild did not leave an index for is a build failure, and\n // dropping its section renders context that LOOKS complete — the member is\n // simply not there. The workspace SessionStart handler already fails the\n // whole hook when any member cannot be built (`ensureMemberIndices` is a\n // `Promise.all`), so this reports it the same way (#310).\n if (!entry.navigationIndex) {\n throw navigationIndexUnavailable(entry.member.cacheKey);\n }\n\n sections.push(\n renderMemberSection({\n member: entry.member,\n result: {\n navigationIndex: entry.navigationIndex,\n fromCache: true,\n ...(rebuildDiagnostics.has(entry.member.name)\n ? { diagnostics: rebuildDiagnostics.get(entry.member.name) }\n : {}),\n },\n }),\n );\n const candidates = renderCandidateArtifacts(\n prompt,\n entry.navigationIndex,\n `#### Candidate Artifacts in ${entry.member.name} (from prompt keywords)`,\n );\n if (candidates) {\n sections.push(candidates);\n }\n }\n\n // Every member that IS declared rendered a section above or threw, so this is\n // reachable only for a workspace that declares no members at all: nothing to\n // inject, which is what an empty response means.\n if (sections.length === 0) {\n return {};\n }\n\n const additionalContext = [\n sections.join(\"\\n\\n\"),\n \"\",\n \"> Use `analyzer.getContextMap` with candidate paths/artifacts from a member's index\",\n \"> when you need structured dependency and read-target guidance.\",\n ].join(\"\\n\");\n\n return build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AiB;AAAA,EACnE;AACF;","names":[]}
@@ -5,7 +5,7 @@ import {
5
5
  PROJECT_CONFIG_FILENAME,
6
6
  buildGuardrailContext,
7
7
  loadProjectConfig
8
- } from "./chunk-Y7NORFFM.js";
8
+ } from "./chunk-5ZDW4RP7.js";
9
9
 
10
10
  // src/lib/artifact-resolver.ts
11
11
  import { readFile } from "fs/promises";
@@ -597,6 +597,13 @@ function getGuardrailRulesForAgent(component, agentId) {
597
597
  // src/lib/navigation-context.ts
598
598
  import { findMisspelledDslExtensions } from "@aaac/contracts";
599
599
  async function resolveNavigationDsl(options) {
600
+ return resolveArtifacts({
601
+ dsl: await overlaidDsl(options),
602
+ artifactBinding: options.artifactBinding,
603
+ paths: options.paths
604
+ });
605
+ }
606
+ async function overlaidDsl(options) {
600
607
  if (options.embeddedDsl != null) {
601
608
  if (options.projectDslPath) {
602
609
  const ctx = await loadDslContext({
@@ -616,16 +623,9 @@ async function resolveNavigationDsl(options) {
616
623
  }
617
624
  async function buildNavigationContext(options) {
618
625
  const diagnostics = [];
619
- let dsl = await resolveNavigationDsl(options);
620
- if (options.artifactBinding) {
621
- const bound = await resolveArtifacts({
622
- dsl,
623
- artifactBinding: options.artifactBinding,
624
- paths: options.paths
625
- });
626
- dsl = bound.dsl;
627
- diagnostics.push(...bound.diagnostics);
628
- }
626
+ const resolved = await resolveNavigationDsl(options);
627
+ const dsl = resolved.dsl;
628
+ diagnostics.push(...resolved.diagnostics);
629
629
  const { validateSchema, buildNavigationIndex } = await import("agent-contracts");
630
630
  const validation = validateSchema(dsl);
631
631
  const schemaDiagnostics = validation.diagnostics.map((d) => ({
@@ -721,4 +721,4 @@ export {
721
721
  buildNavigationContext,
722
722
  resolveNavigationSources
723
723
  };
724
- //# sourceMappingURL=chunk-CJLKKDKN.js.map
724
+ //# sourceMappingURL=chunk-N2EA3TGS.js.map