@aaac/runtime 0.2.8 → 0.2.10

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 (49) 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-CPSXQCNA.js → chunk-N2EA3TGS.js} +42 -14
  20. package/dist/chunk-N2EA3TGS.js.map +1 -0
  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 +157 -157
  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-BHlvPqIp.d.ts} +3 -1
  31. package/dist/index.d.ts +13 -5
  32. package/dist/index.js +230 -64
  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-CPSXQCNA.js.map +0 -1
  45. package/dist/chunk-D2UXESPT.js.map +0 -1
  46. package/dist/chunk-GWNXNSGL.js.map +0 -1
  47. package/dist/chunk-HR2Q64AO.js.map +0 -1
  48. package/dist/chunk-MG7WSWJU.js.map +0 -1
  49. /package/dist/{chunk-Y7NORFFM.js.map → chunk-5ZDW4RP7.js.map} +0 -0
@@ -1,3 +1,3 @@
1
1
  export { a as HookEventName, b as HookInput, H as HookOutput, P as PermissionDecision, c as PreToolUseInput, S as SessionStartInput, U as UserPromptSubmitInput, f as buildContextResponse, e as emitHookOutput, r as readHookInput } from '../../hook-protocol-BH86kCQB.js';
2
- export { A as ArtifactMatch, C as CacheEntry, a as CacheStore, b as CacheStoreOptions, D as DEFAULT_CACHE_KEY, d as FreshNavigationBuild, N as NavigationArtifact, P as PreToolUseHandlerConfig, W as WorkspaceFileSuggestionMember, f as WorkspaceMemberPreToolUseConfig, g as WorkspacePreToolUseConfig, j as createCacheStore, k as createPreToolUseHandler, l as createWorkspacePreToolUseHandler, o as handleFileSuggestion, p as handleWorkspaceFileSuggestion, q as isCachedRecord, s as listArtifacts, t as readFreshNavigationBuild } from '../../hooks-lite-DvZu9Jhx.js';
3
- import '../../guardrail-hooks-B-qe4ebW.js';
2
+ export { A as ArtifactMatch, C as CacheEntry, a as CacheStore, b as CacheStoreOptions, D as DEFAULT_CACHE_KEY, d as FreshNavigationBuild, N as NavigationArtifact, P as PreToolUseHandlerConfig, W as WorkspaceFileSuggestionMember, f as WorkspaceMemberPreToolUseConfig, g as WorkspacePreToolUseConfig, j as createCacheStore, k as createPreToolUseHandler, l as createWorkspacePreToolUseHandler, o as handleFileSuggestion, p as handleWorkspaceFileSuggestion, q as isCachedRecord, s as listArtifacts, t as readFreshNavigationBuild } from '../../hooks-lite-BtOGc2F_.js';
3
+ import '../../guardrail-hooks-BgHe8PrP.js';
@@ -3,18 +3,20 @@ import {
3
3
  createWorkspacePreToolUseHandler,
4
4
  handleFileSuggestion,
5
5
  handleWorkspaceFileSuggestion
6
- } from "../../chunk-GWNXNSGL.js";
6
+ } from "../../chunk-BHTHXGA3.js";
7
7
  import {
8
8
  DEFAULT_CACHE_KEY,
9
9
  buildContextResponse,
10
10
  createCacheStore,
11
11
  emitHookOutput,
12
12
  isCachedRecord,
13
- listArtifacts,
14
13
  readFreshNavigationBuild,
15
14
  readHookInput
16
- } from "../../chunk-D2UXESPT.js";
17
- import "../../chunk-HR2Q64AO.js";
15
+ } from "../../chunk-2SG3TBI3.js";
16
+ import {
17
+ listArtifacts
18
+ } from "../../chunk-EBMQHLXY.js";
19
+ import "../../chunk-EA4V5DVD.js";
18
20
  import "../../chunk-BJ7B4R26.js";
19
21
  export {
20
22
  DEFAULT_CACHE_KEY,
@@ -1,5 +1,5 @@
1
1
  export { H as HookOutput, U as UserPromptSubmitInput, e as emitHookOutput, r as readHookInput } from '../../hook-protocol-BH86kCQB.js';
2
- export { E as EnsureBinOutput, N as NavigationDiagnostic, U as UserPromptSubmitHandlerConfig, W as WorkspaceMemberCacheConfig, a as WorkspaceMemberNavResult, b as WorkspaceUserPromptSubmitConfig, c as createUserPromptSubmitHandler, d as createWorkspaceUserPromptSubmitHandler, r as readFreshMemberIndices, e as renderCandidateArtifacts, f as renderMemberSection, g as renderNavigationDiagnostics, h as runEnsureNavigationIndexBin } from '../../workspace-user-prompt-submit-aErGPoX4.js';
2
+ export { E as EnsureBinOutput, N as NavigationDiagnostic, U as UserPromptSubmitHandlerConfig, W as WorkspaceMemberCacheConfig, a as WorkspaceMemberNavResult, b as WorkspaceUserPromptSubmitConfig, c as createUserPromptSubmitHandler, d as createWorkspaceUserPromptSubmitHandler, r as readFreshMemberIndices, e as renderCandidateArtifacts, f as renderMemberSection, g as renderNavigationDiagnostics, h as runEnsureNavigationIndexBin } from '../../workspace-user-prompt-submit-GZwUKUHi.js';
3
3
  export { N as NavigationArtifactNode, i as isNavigationIndex, r as renderNavigationIndexPrompt } from '../../navigation-index-prompt-CbrS5laO.js';
4
- import '../../navigation-context-D1NbiipT.js';
5
- import '../../guardrail-hooks-B-qe4ebW.js';
4
+ import '../../navigation-context-DJjCkrcj.js';
5
+ import '../../guardrail-hooks-BgHe8PrP.js';
@@ -6,7 +6,7 @@ import {
6
6
  renderMemberSection,
7
7
  renderNavigationDiagnostics,
8
8
  runEnsureNavigationIndexBin
9
- } from "../../chunk-QVMLALPF.js";
9
+ } from "../../chunk-GGBNVCPV.js";
10
10
  import {
11
11
  isNavigationIndex,
12
12
  renderNavigationIndexPrompt
@@ -14,8 +14,9 @@ import {
14
14
  import {
15
15
  emitHookOutput,
16
16
  readHookInput
17
- } from "../../chunk-D2UXESPT.js";
18
- import "../../chunk-HR2Q64AO.js";
17
+ } from "../../chunk-2SG3TBI3.js";
18
+ import "../../chunk-EBMQHLXY.js";
19
+ import "../../chunk-EA4V5DVD.js";
19
20
  import "../../chunk-BJ7B4R26.js";
20
21
  export {
21
22
  createUserPromptSubmitHandler,
@@ -1,10 +1,10 @@
1
1
  import { S as SessionStartInput, H as HookOutput } from '../../hook-protocol-BH86kCQB.js';
2
2
  export { a as HookEventName, b as HookInput, P as PermissionDecision, c as PreToolUseInput, U as UserPromptSubmitInput, d as buildAllowResponse, f as buildContextResponse, g as buildDenyResponse, e as emitHookOutput, p as parseHookInput, r as readHookInput } from '../../hook-protocol-BH86kCQB.js';
3
- export { A as ArtifactMatch, C as CacheEntry, a as CacheStore, b as CacheStoreOptions, D as DEFAULT_CACHE_KEY, F as FileSuggestionCandidate, c as FileSuggestionOptions, d as FreshNavigationBuild, N as NavigationArtifact, P as PreToolUseHandlerConfig, W as WorkspaceFileSuggestionMember, e as WorkspaceMember, f as WorkspaceMemberPreToolUseConfig, g as WorkspacePreToolUseConfig, h as computeCurrentHash, i as computeSourceHash, j as createCacheStore, k as createPreToolUseHandler, l as createWorkspacePreToolUseHandler, m as formatNdjson, n as generateCandidates, o as handleFileSuggestion, p as handleWorkspaceFileSuggestion, q as isCachedRecord, r as isProtectedArtifact, s as listArtifacts, t as readFreshNavigationBuild, u as resolvePathToArtifacts, v as routePathToMember, w as stripMemberPrefix } from '../../hooks-lite-DvZu9Jhx.js';
4
- import { N as NavigationContextOptions } from '../../navigation-context-D1NbiipT.js';
5
- import { i as EnsureNavigationIndexOptions, j as WorkspaceMemberNavConfig, a as WorkspaceMemberNavResult } from '../../workspace-user-prompt-submit-aErGPoX4.js';
6
- export { E as EnsureBinOutput, N as NavigationDiagnostic, k as NavigationIndexResult, U as UserPromptSubmitHandlerConfig, W as WorkspaceMemberCacheConfig, b as WorkspaceUserPromptSubmitConfig, c as createUserPromptSubmitHandler, d as createWorkspaceUserPromptSubmitHandler, l as ensureNavigationIndex, r as readFreshMemberIndices, f as renderMemberSection, g as renderNavigationDiagnostics, h as runEnsureNavigationIndexBin } from '../../workspace-user-prompt-submit-aErGPoX4.js';
7
- import '../../guardrail-hooks-B-qe4ebW.js';
3
+ export { A as ArtifactMatch, C as CacheEntry, a as CacheStore, b as CacheStoreOptions, D as DEFAULT_CACHE_KEY, F as FileSuggestionCandidate, c as FileSuggestionOptions, d as FreshNavigationBuild, N as NavigationArtifact, P as PreToolUseHandlerConfig, W as WorkspaceFileSuggestionMember, e as WorkspaceMember, f as WorkspaceMemberPreToolUseConfig, g as WorkspacePreToolUseConfig, h as computeCurrentHash, i as computeSourceHash, j as createCacheStore, k as createPreToolUseHandler, l as createWorkspacePreToolUseHandler, m as formatNdjson, n as generateCandidates, o as handleFileSuggestion, p as handleWorkspaceFileSuggestion, q as isCachedRecord, r as isProtectedArtifact, s as listArtifacts, t as readFreshNavigationBuild, u as resolvePathToArtifacts, v as routePathToMember, w as stripMemberPrefix } from '../../hooks-lite-BtOGc2F_.js';
4
+ import { N as NavigationContextOptions } from '../../navigation-context-DJjCkrcj.js';
5
+ import { i as EnsureNavigationIndexOptions, j as WorkspaceMemberNavConfig, a as WorkspaceMemberNavResult } from '../../workspace-user-prompt-submit-GZwUKUHi.js';
6
+ export { E as EnsureBinOutput, N as NavigationDiagnostic, k as NavigationIndexResult, U as UserPromptSubmitHandlerConfig, W as WorkspaceMemberCacheConfig, b as WorkspaceUserPromptSubmitConfig, c as createUserPromptSubmitHandler, d as createWorkspaceUserPromptSubmitHandler, l as ensureNavigationIndex, r as readFreshMemberIndices, f as renderMemberSection, g as renderNavigationDiagnostics, h as runEnsureNavigationIndexBin } from '../../workspace-user-prompt-submit-GZwUKUHi.js';
7
+ import '../../guardrail-hooks-BgHe8PrP.js';
8
8
 
9
9
  /**
10
10
  * Latency utilities — timeout wrapper, graph build exclusion, degrade policy.
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  buildNavigationContext,
3
3
  resolveNavigationSources
4
- } from "../../chunk-CPSXQCNA.js";
4
+ } from "../../chunk-N2EA3TGS.js";
5
5
  import "../../chunk-ET6TGQRT.js";
6
- import "../../chunk-Y7NORFFM.js";
6
+ import "../../chunk-5ZDW4RP7.js";
7
7
  import {
8
8
  createPreToolUseHandler,
9
9
  createWorkspacePreToolUseHandler,
@@ -13,7 +13,7 @@ import {
13
13
  handleWorkspaceFileSuggestion,
14
14
  routePathToMember,
15
15
  stripMemberPrefix
16
- } from "../../chunk-GWNXNSGL.js";
16
+ } from "../../chunk-BHTHXGA3.js";
17
17
  import {
18
18
  createUserPromptSubmitHandler,
19
19
  createWorkspaceUserPromptSubmitHandler,
@@ -21,7 +21,7 @@ import {
21
21
  renderMemberSection,
22
22
  renderNavigationDiagnostics,
23
23
  runEnsureNavigationIndexBin
24
- } from "../../chunk-QVMLALPF.js";
24
+ } from "../../chunk-GGBNVCPV.js";
25
25
  import {
26
26
  renderNavigationIndexPrompt
27
27
  } from "../../chunk-3CLWG72V.js";
@@ -36,14 +36,16 @@ import {
36
36
  emitHookOutput,
37
37
  guardrailCacheKey,
38
38
  isCachedRecord,
39
- isProtectedArtifact,
40
- listArtifacts,
41
39
  parseHookInput,
42
40
  readFreshNavigationBuild,
43
- readHookInput,
41
+ readHookInput
42
+ } from "../../chunk-2SG3TBI3.js";
43
+ import {
44
+ isProtectedArtifact,
45
+ listArtifacts,
44
46
  resolvePathToArtifacts
45
- } from "../../chunk-D2UXESPT.js";
46
- import "../../chunk-HR2Q64AO.js";
47
+ } from "../../chunk-EBMQHLXY.js";
48
+ import "../../chunk-EA4V5DVD.js";
47
49
  import "../../chunk-BJ7B4R26.js";
48
50
 
49
51
  // src/lib/claude-native/latency.ts
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/lib/claude-native/latency.ts","../../../src/lib/claude-native/ensure-navigation-index.ts","../../../src/lib/claude-native/session-start.ts","../../../src/lib/claude-native/workspace-session-start.ts"],"sourcesContent":["/**\n * Latency utilities — timeout wrapper, graph build exclusion, degrade policy.\n *\n * Mirrors the Promise-sharing pattern from analyzer-bridge.ts for concurrent\n * graph build exclusion.\n */\n\n// ---------------------------------------------------------------------------\n// Timeout wrapper\n// ---------------------------------------------------------------------------\n\nexport class TimeoutError extends Error {\n constructor(ms: number) {\n super(`Operation timed out after ${ms}ms`);\n this.name = \"TimeoutError\";\n }\n}\n\n/**\n * Race a promise against a timeout. Resolves with the promise result or\n * rejects with TimeoutError.\n */\nexport async function withTimeout<T>(\n promise: Promise<T>,\n timeoutMs: number,\n): Promise<T> {\n if (timeoutMs <= 0) return promise;\n\n let timer: ReturnType<typeof setTimeout>;\n const timeout = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => reject(new TimeoutError(timeoutMs)), timeoutMs);\n });\n\n try {\n return await Promise.race([promise, timeout]);\n } finally {\n clearTimeout(timer!);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Exclusive lock (Promise sharing)\n// ---------------------------------------------------------------------------\n\n/**\n * Creates an exclusive async lock that ensures only one invocation runs at a\n * time. Subsequent callers await the same Promise (analyzer-bridge pattern).\n */\nexport function createExclusiveLock<T>(): {\n run: (fn: () => Promise<T>) => Promise<T>;\n} {\n let pending: Promise<T> | null = null;\n\n return {\n async run(fn: () => Promise<T>): Promise<T> {\n if (pending) return pending;\n pending = fn().finally(() => {\n pending = null;\n });\n return pending;\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Degrade policy\n// ---------------------------------------------------------------------------\n\nexport interface DegradeResult<T> {\n value: T;\n degraded: boolean;\n reason?: string;\n}\n\n/**\n * Attempt an operation with timeout; if it fails or times out, return the\n * fallback value with `degraded: true`.\n */\nexport async function withDegrade<T>(\n operation: () => Promise<T>,\n fallback: T,\n timeoutMs: number,\n): Promise<DegradeResult<T>> {\n try {\n const value = await withTimeout(operation(), timeoutMs);\n return { value, degraded: false };\n } catch (err) {\n const reason =\n err instanceof TimeoutError\n ? err.message\n : err instanceof Error\n ? err.message\n : String(err);\n return { value: fallback, degraded: true, reason };\n }\n}\n","/**\n * Ensure Navigation Index — cache warm / invalidation.\n *\n * Checks cache freshness via source file mtime comparison. If stale,\n * calls buildNavigationContext() and writes to .claude/cache/.\n * If fresh, returns cached data immediately.\n *\n * This is the performance-critical path for SessionStart hooks.\n */\n\nimport { buildNavigationContext, type NavigationContextOptions } from \"../navigation-context.js\";\nimport { createCacheStore, type CacheStore } from \"./cache-store.js\";\nimport { createExclusiveLock } from \"./latency.js\";\nimport { guardrailCacheKey } from \"./ensure-navigation-index-keys.js\";\nimport type { NavigationDiagnostic } from \"./navigation-cache.js\";\nimport {\n computeCurrentHash,\n readFreshNavigationBuild,\n DEFAULT_CACHE_KEY,\n} from \"./navigation-freshness.js\";\n\nexport { GUARDRAIL_CACHE_SUFFIX, guardrailCacheKey } from \"./ensure-navigation-index-keys.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface EnsureNavigationIndexOptions {\n /** Absolute path to .claude/cache/ directory. */\n cacheDir: string;\n /** Paths to source files whose mtime drives cache invalidation. */\n sourceFiles: string[];\n /** Options for buildNavigationContext() when cache is stale. */\n navigationOptions: NavigationContextOptions;\n /**\n * Cache key for the stored JSON file (default: `\"navigation-index\"`).\n *\n * In workspace mode each member uses its own key, e.g.\n * `\"navigation-index.aaac\"`, so their caches remain isolated.\n * Single-component callers omit this field and the default preserves\n * byte-identical behaviour with previous versions.\n */\n cacheKey?: string;\n}\n\nexport interface NavigationIndexResult {\n navigationIndex: Record<string, unknown>;\n /** Whether the result was loaded from cache (true) or freshly built (false). */\n fromCache: boolean;\n /**\n * Diagnostics from the build that produced this index — artifact-binding\n * findings (`unbound-artifact` / `orphan-binding` / `type-mismatch`) and\n * schema validation issues. Present only on a fresh build: they describe the\n * DSL/registry the index was built from, so a caller that hit the cache has\n * already been told once. Callers MUST surface them (a dropped\n * `orphan-binding` is exactly how a project's artifact registry silently\n * fails to reach the hooks — #260).\n */\n diagnostics?: NavigationDiagnostic[];\n}\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\n/**\n * Per-key exclusive locks so concurrent session-start calls for distinct\n * workspace members can build their indices in parallel, while duplicate calls\n * for the same key are deduplicated (share the in-flight promise).\n */\nconst buildLocks = new Map<string, ReturnType<typeof createExclusiveLock<NavigationIndexResult>>>();\n\nfunction getBuildLock(key: string): ReturnType<typeof createExclusiveLock<NavigationIndexResult>> {\n let lock = buildLocks.get(key);\n if (!lock) {\n lock = createExclusiveLock<NavigationIndexResult>();\n buildLocks.set(key, lock);\n }\n return lock;\n}\n\n/**\n * Ensure the navigation index is available and fresh. Returns the index\n * data, building + caching if necessary.\n *\n * In workspace mode, pass a unique `cacheKey` per member (e.g.\n * `\"navigation-index.aaac\"`) so each member's index is stored and\n * invalidated independently.\n */\nexport async function ensureNavigationIndex(\n options: EnsureNavigationIndexOptions,\n): Promise<NavigationIndexResult> {\n const cacheKey = options.cacheKey ?? DEFAULT_CACHE_KEY;\n\n return getBuildLock(cacheKey).run(async () => {\n const store: CacheStore = createCacheStore({ cacheDir: options.cacheDir });\n const currentHash = await computeCurrentHash(options.sourceFiles);\n\n // Try cache first — through the SAME predicate the lean hooks read with.\n // If this asked a weaker question (say, hash only), an entry the reader\n // rejects could be one the builder accepts, and the rebuild that was\n // supposed to repair it would return the untouched entry instead. The\n // per-prompt hook would then re-run this on every prompt and still get\n // nothing back.\n const cached = await readFreshNavigationBuild({\n cacheDir: options.cacheDir,\n cacheKey,\n });\n if (cached) {\n return { navigationIndex: cached.navigationIndex, fromCache: true };\n }\n\n // Cache miss or stale — rebuild\n const context = await buildNavigationContext(options.navigationOptions);\n const navigationIndex = context.navigationIndex;\n\n // Write to cache (non-blocking error handling)\n try {\n await store.write(cacheKey, navigationIndex, currentHash, options.sourceFiles);\n } catch {\n // Cache write failure is non-fatal\n }\n\n // Persist the member's DSL guardrail rules in a companion cache entry so\n // the lean PreToolUse hook can wire Bash guardrails without importing the\n // heavy agent-contracts DSL loader (#238 / C5). We always write, even when\n // there are no rules, so a stale non-empty entry cannot survive a DSL edit\n // that removed all guardrails.\n try {\n await store.write(\n guardrailCacheKey(cacheKey),\n context.guardrailRules ?? { commandRules: [], fileRules: [], contentRules: [] },\n currentHash,\n );\n } catch {\n // Cache write failure is non-fatal\n }\n\n return {\n navigationIndex,\n fromCache: false,\n ...(context.diagnostics.length > 0 ? { diagnostics: context.diagnostics } : {}),\n };\n });\n}\n","/**\n * SessionStart Hook Handler — cache warm + navigation-index summary injection.\n *\n * Executed on session new/resume/clear/compact events. Warms the navigation-index\n * cache and returns a rendered summary as additionalContext.\n *\n * Latency constraint: NO AST analysis or ContextPack generation.\n */\n\nimport { renderNavigationIndexPrompt } from \"../navigation-index-prompt.js\";\nimport {\n ensureNavigationIndex,\n type EnsureNavigationIndexOptions,\n} from \"./ensure-navigation-index.js\";\nimport { renderNavigationDiagnostics } from \"./navigation-cache.js\";\nimport {\n buildContextResponse,\n type HookOutput,\n type SessionStartInput,\n} from \"./hook-protocol.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface SessionStartHandlerConfig {\n /** Absolute path to .claude/cache/ directory. */\n cacheDir: string;\n /** Source files for cache invalidation (component.yaml, agent-contracts.yaml, etc.). */\n sourceFiles: string[];\n /** Options for buildNavigationContext(). */\n navigationOptions: EnsureNavigationIndexOptions[\"navigationOptions\"];\n}\n\n// ---------------------------------------------------------------------------\n// Handler\n// ---------------------------------------------------------------------------\n\n/**\n * Create a SessionStart hook handler.\n */\nexport function createSessionStartHandler(config: SessionStartHandlerConfig) {\n return async function handleSessionStart(\n _input: SessionStartInput,\n ): Promise<HookOutput> {\n const result = await ensureNavigationIndex({\n cacheDir: config.cacheDir,\n sourceFiles: config.sourceFiles,\n navigationOptions: config.navigationOptions,\n });\n\n const summary = renderNavigationIndexPrompt(result.navigationIndex);\n const cacheNote = result.fromCache\n ? \"(loaded from cache)\"\n : \"(freshly built)\";\n\n const diagnostics = renderNavigationDiagnostics(result.diagnostics);\n\n const additionalContext = [\n summary,\n \"\",\n `Navigation index ${cacheNote}. Use analyzer MCP tools for deep investigation.`,\n ...(diagnostics ? [\"\", diagnostics] : []),\n ].join(\"\\n\");\n\n return buildContextResponse(\"SessionStart\", additionalContext);\n };\n}\n","/**\n * Workspace SessionStart Hook Handler — per-member navigation-index warm-up.\n *\n * Builds (or validates) a cached navigation-index for each declared workspace\n * member in parallel, then returns a combined summary as `additionalContext`.\n *\n * This module is in the **heavy** path (imports ensureNavigationIndex →\n * navigation-context → agent-contracts) and is therefore NOT included in the\n * lean hooks-lite entry point. SessionStart fires only once per session, so\n * the higher import cost is acceptable.\n */\n\nimport {\n renderMemberSection,\n type WorkspaceMemberNavConfig,\n type WorkspaceMemberNavResult,\n} from \"./workspace-members.js\";\nimport { ensureNavigationIndex } from \"./ensure-navigation-index.js\";\nimport {\n buildContextResponse,\n type HookOutput,\n type SessionStartInput,\n} from \"./hook-protocol.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface WorkspaceSessionStartConfig {\n /** Absolute path to the shared `.claude/cache/` directory. */\n cacheDir: string;\n /** Workspace members to build/validate indices for. */\n members: WorkspaceMemberNavConfig[];\n}\n\n// ---------------------------------------------------------------------------\n// Warm-up\n// ---------------------------------------------------------------------------\n\n/**\n * Build (or validate) every member's navigation-index in **parallel** — each\n * cache key has its own exclusive lock, so concurrent calls for the same member\n * deduplicate rather than queue behind other members.\n *\n * This is the heavy path, and it lives here because SessionStart is the only\n * hook that may pay for it: it fires once per session. The per-interaction hooks\n * read the cache instead and run the `ensure-navigation-index` bin when it is\n * stale, which reaches this same builder in a child process.\n */\nexport async function ensureMemberIndices(\n cacheDir: string,\n members: WorkspaceMemberNavConfig[],\n): Promise<WorkspaceMemberNavResult[]> {\n return Promise.all(\n members.map(async (member) => ({\n member,\n result: await ensureNavigationIndex({\n cacheDir,\n sourceFiles: member.sourceFiles,\n navigationOptions: member.navigationOptions,\n cacheKey: member.cacheKey,\n }),\n })),\n );\n}\n\n// ---------------------------------------------------------------------------\n// Handler\n// ---------------------------------------------------------------------------\n\n/**\n * Create a workspace-aware SessionStart hook handler.\n */\nexport function createWorkspaceSessionStartHandler(\n config: WorkspaceSessionStartConfig,\n) {\n return async function handleWorkspaceSessionStart(\n _input: SessionStartInput,\n ): Promise<HookOutput> {\n const results = await ensureMemberIndices(config.cacheDir, config.members);\n\n const additionalContext = [\n results.map(renderMemberSection).join(\"\\n\\n\"),\n \"\",\n \"Workspace navigation indices ready. Use analyzer MCP tools for deep investigation.\",\n ].join(\"\\n\");\n\n return buildContextResponse(\"SessionStart\", additionalContext);\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWO,IAAM,eAAN,cAA2B,MAAM;AAAA,EACtC,YAAY,IAAY;AACtB,UAAM,6BAA6B,EAAE,IAAI;AACzC,SAAK,OAAO;AAAA,EACd;AACF;AAMA,eAAsB,YACpB,SACA,WACY;AACZ,MAAI,aAAa,EAAG,QAAO;AAE3B,MAAI;AACJ,QAAM,UAAU,IAAI,QAAe,CAAC,UAAU,WAAW;AACvD,YAAQ,WAAW,MAAM,OAAO,IAAI,aAAa,SAAS,CAAC,GAAG,SAAS;AAAA,EACzE,CAAC;AAED,MAAI;AACF,WAAO,MAAM,QAAQ,KAAK,CAAC,SAAS,OAAO,CAAC;AAAA,EAC9C,UAAE;AACA,iBAAa,KAAM;AAAA,EACrB;AACF;AAUO,SAAS,sBAEd;AACA,MAAI,UAA6B;AAEjC,SAAO;AAAA,IACL,MAAM,IAAI,IAAkC;AAC1C,UAAI,QAAS,QAAO;AACpB,gBAAU,GAAG,EAAE,QAAQ,MAAM;AAC3B,kBAAU;AAAA,MACZ,CAAC;AACD,aAAO;AAAA,IACT;AAAA,EACF;AACF;AAgBA,eAAsB,YACpB,WACA,UACA,WAC2B;AAC3B,MAAI;AACF,UAAM,QAAQ,MAAM,YAAY,UAAU,GAAG,SAAS;AACtD,WAAO,EAAE,OAAO,UAAU,MAAM;AAAA,EAClC,SAAS,KAAK;AACZ,UAAM,SACJ,eAAe,eACX,IAAI,UACJ,eAAe,QACb,IAAI,UACJ,OAAO,GAAG;AAClB,WAAO,EAAE,O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S,MAAM,sBAAsB;AAAA,MACzC,UAAU,OAAO;AAAA,MACjB,aAAa,OAAO;AAAA,MACpB,mBAAmB,OAAO;AAAA,IAC5B,CAAC;AAED,UAAM,UAAU,4BAA4B,OAAO,eAAe;AAClE,UAAM,YAAY,OAAO,YACrB,wBACA;AAEJ,UAAM,cAAc,4BAA4B,OAAO,WAAW;AAElE,UAAM,oBAAoB;AAAA,MACxB;AAAA,MACA;AAAA,MACA,oBAAoB,SAAS;AAAA,MAC7B,GAAI,cAAc,CAAC,IAAI,WAAW,IAAI,CAAC;AAAA,IACzC,EAAE,KAAK,IAAI;AAEX,WAAO,qBAAqB,gBAAgB,iBAAiB;AAAA,EAC/D;AACF;;;AClBA,eAAsB,oBACpB,UACA,SACqC;AACrC,SAAO,QAAQ;AAAA,IACb,QAAQ,IAAI,OAAO,YAAY;AAAA,MAC7B;AAAA,MACA,QAAQ,MAAM,sBAAsB;AAAA,QAClC;AAAA,QACA,aAAa,OAAO;AAAA,QACpB,mBAAmB,OAAO;AAAA,QAC1B,UAAU,OAAO;AAAA,MACnB,CAAC;AAAA,IACH,EAAE;AAAA,EACJ;AACF;AASO,SAAS,mCACd,QACA;AACA,SAAO,eAAe,4BACpB,QACqB;AACrB,UAAM,UAAU,MAAM,oBAAoB,OAAO,UAAU,OAAO,OAAO;AAEzE,UAAM,oBAAoB;AAAA,MACxB,QAAQ,IAAI,mBAAmB,EAAE,KAAK,MAAM;AAAA,MAC5C;AAAA,MACA;AAAA,IACF,EAAE,KAAK,IAAI;AAEX,WAAO,qBAAqB,gBAAgB,iBAAiB;AAAA,EAC/D;AACF;","names":[]}
1
+ {"version":3,"sources":["../../../src/lib/claude-native/latency.ts","../../../src/lib/claude-native/ensure-navigation-index.ts","../../../src/lib/claude-native/session-start.ts","../../../src/lib/claude-native/workspace-session-start.ts"],"sourcesContent":["/**\n * Latency utilities — timeout wrapper, graph build exclusion, degrade policy.\n *\n * Mirrors the Promise-sharing pattern from analyzer-bridge.ts for concurrent\n * graph build exclusion.\n */\n\n// ---------------------------------------------------------------------------\n// Timeout wrapper\n// ---------------------------------------------------------------------------\n\nexport class TimeoutError extends Error {\n constructor(ms: number) {\n super(`Operation timed out after ${ms}ms`);\n this.name = \"TimeoutError\";\n }\n}\n\n/**\n * Race a promise against a timeout. Resolves with the promise result or\n * rejects with TimeoutError.\n */\nexport async function withTimeout<T>(\n promise: Promise<T>,\n timeoutMs: number,\n): Promise<T> {\n if (timeoutMs <= 0) return promise;\n\n let timer: ReturnType<typeof setTimeout>;\n const timeout = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => reject(new TimeoutError(timeoutMs)), timeoutMs);\n });\n\n try {\n return await Promise.race([promise, timeout]);\n } finally {\n clearTimeout(timer!);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Exclusive lock (Promise sharing)\n// ---------------------------------------------------------------------------\n\n/**\n * Creates an exclusive async lock that ensures only one invocation runs at a\n * time. Subsequent callers await the same Promise (analyzer-bridge pattern).\n */\nexport function createExclusiveLock<T>(): {\n run: (fn: () => Promise<T>) => Promise<T>;\n} {\n let pending: Promise<T> | null = null;\n\n return {\n async run(fn: () => Promise<T>): Promise<T> {\n if (pending) return pending;\n pending = fn().finally(() => {\n pending = null;\n });\n return pending;\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Degrade policy\n// ---------------------------------------------------------------------------\n\nexport interface DegradeResult<T> {\n value: T;\n degraded: boolean;\n reason?: string;\n}\n\n/**\n * Attempt an operation with timeout; if it fails or times out, return the\n * fallback value with `degraded: true`.\n */\nexport async function withDegrade<T>(\n operation: () => Promise<T>,\n fallback: T,\n timeoutMs: number,\n): Promise<DegradeResult<T>> {\n try {\n const value = await withTimeout(operation(), timeoutMs);\n return { value, degraded: false };\n } catch (err) {\n const reason =\n err instanceof TimeoutError\n ? err.message\n : err instanceof Error\n ? err.message\n : String(err);\n return { value: fallback, degraded: true, reason };\n }\n}\n","/**\n * Ensure Navigation Index — cache warm / invalidation.\n *\n * Checks cache freshness via source file mtime comparison. If stale,\n * calls buildNavigationContext() and writes to .claude/cache/.\n * If fresh, returns cached data immediately.\n *\n * This is the performance-critical path for SessionStart hooks.\n */\n\nimport { buildNavigationContext, type NavigationContextOptions } from \"../navigation-context.js\";\nimport { createCacheStore, type CacheStore } from \"./cache-store.js\";\nimport { createExclusiveLock } from \"./latency.js\";\nimport { guardrailCacheKey } from \"./ensure-navigation-index-keys.js\";\nimport type { NavigationDiagnostic } from \"./navigation-cache.js\";\nimport {\n computeCurrentHash,\n readFreshNavigationBuild,\n DEFAULT_CACHE_KEY,\n} from \"./navigation-freshness.js\";\n\nexport { GUARDRAIL_CACHE_SUFFIX, guardrailCacheKey } from \"./ensure-navigation-index-keys.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface EnsureNavigationIndexOptions {\n /** Absolute path to .claude/cache/ directory. */\n cacheDir: string;\n /** Paths to source files whose mtime drives cache invalidation. */\n sourceFiles: string[];\n /** Options for buildNavigationContext() when cache is stale. */\n navigationOptions: NavigationContextOptions;\n /**\n * Cache key for the stored JSON file (default: `\"navigation-index\"`).\n *\n * In workspace mode each member uses its own key, e.g.\n * `\"navigation-index.aaac\"`, so their caches remain isolated.\n * Single-component callers omit this field and the default preserves\n * byte-identical behaviour with previous versions.\n */\n cacheKey?: string;\n}\n\nexport interface NavigationIndexResult {\n navigationIndex: Record<string, unknown>;\n /** Whether the result was loaded from cache (true) or freshly built (false). */\n fromCache: boolean;\n /**\n * Diagnostics from the build that produced this index — artifact-binding\n * findings (`unbound-artifact` / `orphan-binding` / `type-mismatch`) and\n * schema validation issues. Present only on a fresh build: they describe the\n * DSL/registry the index was built from, so a caller that hit the cache has\n * already been told once. Callers MUST surface them (a dropped\n * `orphan-binding` is exactly how a project's artifact registry silently\n * fails to reach the hooks — #260).\n */\n diagnostics?: NavigationDiagnostic[];\n}\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\n/**\n * Per-key exclusive locks so concurrent session-start calls for distinct\n * workspace members can build their indices in parallel, while duplicate calls\n * for the same key are deduplicated (share the in-flight promise).\n */\nconst buildLocks = new Map<string, ReturnType<typeof createExclusiveLock<NavigationIndexResult>>>();\n\nfunction getBuildLock(key: string): ReturnType<typeof createExclusiveLock<NavigationIndexResult>> {\n let lock = buildLocks.get(key);\n if (!lock) {\n lock = createExclusiveLock<NavigationIndexResult>();\n buildLocks.set(key, lock);\n }\n return lock;\n}\n\n/**\n * Ensure the navigation index is available and fresh. Returns the index\n * data, building + caching if necessary.\n *\n * In workspace mode, pass a unique `cacheKey` per member (e.g.\n * `\"navigation-index.aaac\"`) so each member's index is stored and\n * invalidated independently.\n */\nexport async function ensureNavigationIndex(\n options: EnsureNavigationIndexOptions,\n): Promise<NavigationIndexResult> {\n const cacheKey = options.cacheKey ?? DEFAULT_CACHE_KEY;\n\n return getBuildLock(cacheKey).run(async () => {\n const store: CacheStore = createCacheStore({ cacheDir: options.cacheDir });\n const currentHash = await computeCurrentHash(options.sourceFiles);\n\n // Try cache first — through the SAME predicate the lean hooks read with.\n // If this asked a weaker question (say, hash only), an entry the reader\n // rejects could be one the builder accepts, and the rebuild that was\n // supposed to repair it would return the untouched entry instead. The\n // per-prompt hook would then re-run this on every prompt and still get\n // nothing back.\n const cached = await readFreshNavigationBuild({\n cacheDir: options.cacheDir,\n cacheKey,\n });\n if (cached) {\n return { navigationIndex: cached.navigationIndex, fromCache: true };\n }\n\n // Cache miss or stale — rebuild\n const context = await buildNavigationContext(options.navigationOptions);\n const navigationIndex = context.navigationIndex;\n\n // Write to cache (non-blocking error handling)\n try {\n await store.write(cacheKey, navigationIndex, currentHash, options.sourceFiles);\n } catch {\n // Cache write failure is non-fatal\n }\n\n // Persist the member's DSL guardrail rules in a companion cache entry so\n // the lean PreToolUse hook can wire Bash guardrails without importing the\n // heavy agent-contracts DSL loader (#238 / C5). We always write, even when\n // there are no rules, so a stale non-empty entry cannot survive a DSL edit\n // that removed all guardrails.\n try {\n await store.write(\n guardrailCacheKey(cacheKey),\n context.guardrailRules ?? { commandRules: [], fileRules: [], contentRules: [] },\n currentHash,\n );\n } catch {\n // Cache write failure is non-fatal\n }\n\n return {\n navigationIndex,\n fromCache: false,\n ...(context.diagnostics.length > 0 ? { diagnostics: context.diagnostics } : {}),\n };\n });\n}\n","/**\n * SessionStart Hook Handler — cache warm + navigation-index summary injection.\n *\n * Executed on session new/resume/clear/compact events. Warms the navigation-index\n * cache and returns a rendered summary as additionalContext.\n *\n * Latency constraint: NO AST analysis or ContextPack generation.\n */\n\nimport { renderNavigationIndexPrompt } from \"../navigation-index-prompt.js\";\nimport {\n ensureNavigationIndex,\n type EnsureNavigationIndexOptions,\n} from \"./ensure-navigation-index.js\";\nimport { renderNavigationDiagnostics } from \"./navigation-cache.js\";\nimport {\n buildContextResponse,\n type HookOutput,\n type SessionStartInput,\n} from \"./hook-protocol.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface SessionStartHandlerConfig {\n /** Absolute path to .claude/cache/ directory. */\n cacheDir: string;\n /** Source files for cache invalidation (component.yaml, agent-contracts.yaml, etc.). */\n sourceFiles: string[];\n /** Options for buildNavigationContext(). */\n navigationOptions: EnsureNavigationIndexOptions[\"navigationOptions\"];\n}\n\n// ---------------------------------------------------------------------------\n// Handler\n// ---------------------------------------------------------------------------\n\n/**\n * Create a SessionStart hook handler.\n */\nexport function createSessionStartHandler(config: SessionStartHandlerConfig) {\n return async function handleSessionStart(\n _input: SessionStartInput,\n ): Promise<HookOutput> {\n const result = await ensureNavigationIndex({\n cacheDir: config.cacheDir,\n sourceFiles: config.sourceFiles,\n navigationOptions: config.navigationOptions,\n });\n\n const summary = renderNavigationIndexPrompt(result.navigationIndex);\n const cacheNote = result.fromCache\n ? \"(loaded from cache)\"\n : \"(freshly built)\";\n\n const diagnostics = renderNavigationDiagnostics(result.diagnostics);\n\n const additionalContext = [\n summary,\n \"\",\n `Navigation index ${cacheNote}. Use analyzer MCP tools for deep investigation.`,\n ...(diagnostics ? [\"\", diagnostics] : []),\n ].join(\"\\n\");\n\n return buildContextResponse(\"SessionStart\", additionalContext);\n };\n}\n","/**\n * Workspace SessionStart Hook Handler — per-member navigation-index warm-up.\n *\n * Builds (or validates) a cached navigation-index for each declared workspace\n * member in parallel, then returns a combined summary as `additionalContext`.\n *\n * This module is in the **heavy** path (imports ensureNavigationIndex →\n * navigation-context → agent-contracts) and is therefore NOT included in the\n * lean hooks-lite entry point. SessionStart fires only once per session, so\n * the higher import cost is acceptable.\n */\n\nimport {\n renderMemberSection,\n type WorkspaceMemberNavConfig,\n type WorkspaceMemberNavResult,\n} from \"./workspace-members.js\";\nimport { ensureNavigationIndex } from \"./ensure-navigation-index.js\";\nimport {\n buildContextResponse,\n type HookOutput,\n type SessionStartInput,\n} from \"./hook-protocol.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface WorkspaceSessionStartConfig {\n /** Absolute path to the shared `.claude/cache/` directory. */\n cacheDir: string;\n /** Workspace members to build/validate indices for. */\n members: WorkspaceMemberNavConfig[];\n}\n\n// ---------------------------------------------------------------------------\n// Warm-up\n// ---------------------------------------------------------------------------\n\n/**\n * Build (or validate) every member's navigation-index in **parallel** — each\n * cache key has its own exclusive lock, so concurrent calls for the same member\n * deduplicate rather than queue behind other members.\n *\n * This is the heavy path, and it lives here because SessionStart is the only\n * hook that may pay for it: it fires once per session. The per-interaction hooks\n * read the cache instead and run the `ensure-navigation-index` bin when it is\n * stale, which reaches this same builder in a child process.\n */\nexport async function ensureMemberIndices(\n cacheDir: string,\n members: WorkspaceMemberNavConfig[],\n): Promise<WorkspaceMemberNavResult[]> {\n return Promise.all(\n members.map(async (member) => ({\n member,\n result: await ensureNavigationIndex({\n cacheDir,\n sourceFiles: member.sourceFiles,\n navigationOptions: member.navigationOptions,\n cacheKey: member.cacheKey,\n }),\n })),\n );\n}\n\n// ---------------------------------------------------------------------------\n// Handler\n// ---------------------------------------------------------------------------\n\n/**\n * Create a workspace-aware SessionStart hook handler.\n */\nexport function createWorkspaceSessionStartHandler(\n config: WorkspaceSessionStartConfig,\n) {\n return async function handleWorkspaceSessionStart(\n _input: SessionStartInput,\n ): Promise<HookOutput> {\n const results = await ensureMemberIndices(config.cacheDir, config.members);\n\n const additionalContext = [\n results.map(renderMemberSection).join(\"\\n\\n\"),\n \"\",\n \"Workspace navigation indices ready. Use analyzer MCP tools for deep investigation.\",\n ].join(\"\\n\");\n\n return buildContextResponse(\"SessionStart\", additionalContext);\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWO,IAAM,eAAN,cAA2B,MAAM;AAAA,EACtC,YAAY,IAAY;AACtB,UAAM,6BAA6B,EAAE,IAAI;AACzC,SAAK,OAAO;AAAA,EACd;AACF;AAMA,eAAsB,YACpB,SACA,WACY;AACZ,MAAI,aAAa,EAAG,QAAO;AAE3B,MAAI;AACJ,QAAM,UAAU,IAAI,QAAe,CAAC,UAAU,WAAW;AACvD,YAAQ,WAAW,MAAM,OAAO,IAAI,aAAa,SAAS,CAAC,GAAG,SAAS;AAAA,EACzE,CAAC;AAED,MAAI;AACF,WAAO,MAAM,QAAQ,KAAK,CAAC,SAAS,OAAO,CAAC;AAAA,EAC9C,UAAE;AACA,iBAAa,KAAM;AAAA,EACrB;AACF;AAUO,SAAS,sBAEd;AACA,MAAI,UAA6B;AAEjC,SAAO;AAAA,IACL,MAAM,IAAI,IAAkC;AAC1C,UAAI,QAAS,QAAO;AACpB,gBAAU,GAAG,EAAE,QAAQ,MAAM;AAC3B,kBAAU;AAAA,MACZ,CAAC;AACD,aAAO;AAAA,IACT;AAAA,EACF;AACF;AAgBA,eAAsB,YACpB,WACA,UACA,WAC2B;AAC3B,MAAI;AACF,UAAM,QAAQ,MAAM,YAAY,UAAU,GAAG,SAAS;AACtD,WAAO,EAAE,OAAO,UAAU,MAAM;AAAA,EAClC,SA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/E;AAAA,EACF,CAAC;AACH;;;ACvGO,SAAS,0BAA0B,QAAmC;AAC3E,SAAO,eAAe,mBACpB,QACqB;AACrB,UAAM,SAAS,MAAM,sBAAsB;AAAA,MACzC,UAAU,OAAO;AAAA,MACjB,aAAa,OAAO;AAAA,MACpB,mBAAmB,OAAO;AAAA,IAC5B,CAAC;AAED,UAAM,UAAU,4BAA4B,OAAO,eAAe;AAClE,UAAM,YAAY,OAAO,YACrB,wBACA;AAEJ,UAAM,cAAc,4BAA4B,OAAO,WAAW;AAElE,UAAM,oBAAoB;AAAA,MACxB;AAAA,MACA;AAAA,MACA,oBAAoB,SAAS;AAAA,MAC7B,GAAI,cAAc,CAAC,IAAI,WAAW,IAAI,CAAC;AAAA,IACzC,EAAE,KAAK,IAAI;AAEX,WAAO,qBAAqB,gBAAgB,iBAAiB;AAAA,EAC/D;AACF;;;AClBA,eAAsB,oBACpB,UACA,SACqC;AACrC,SAAO,QAAQ;AAAA,IACb,QAAQ,IAAI,OAAO,YAAY;AAAA,MAC7B;AAAA,MACA,QAAQ,MAAM,sBAAsB;AAAA,QAClC;AAAA,QACA,aAAa,OAAO;AAAA,QACpB,mBAAmB,OAAO;AAAA,QAC1B,UAAU,OAAO;AAAA,MACnB,CAAC;AAAA,IACH,EAAE;AAAA,EACJ;AACF;AASO,SAAS,mCACd,QACA;AACA,SAAO,eAAe,4BACpB,QACqB;AACrB,UAAM,UAAU,MAAM,oBAAoB,OAAO,UAAU,OAAO,OAAO;AAEzE,UAAM,oBAAoB;AAAA,MACxB,QAAQ,IAAI,mBAAmB,EAAE,KAAK,MAAM;AAAA,MAC5C;AAAA,MACA;AAAA,IACF,EAAE,KAAK,IAAI;AAEX,WAAO,qBAAqB,gBAAgB,iBAAiB;AAAA,EAC/D;AACF;","names":[]}
@@ -1,4 +1,4 @@
1
- import { a as GuardrailRuleData } from './guardrail-hooks-B-qe4ebW.js';
1
+ import { a as GuardrailRuleData } from './guardrail-hooks-BgHe8PrP.js';
2
2
 
3
3
  interface NavigationContextOptions {
4
4
  configPath?: string;
@@ -1,5 +1,5 @@
1
1
  import { U as UserPromptSubmitInput, H as HookOutput } from './hook-protocol-BH86kCQB.js';
2
- import { N as NavigationContextOptions } from './navigation-context-D1NbiipT.js';
2
+ import { N as NavigationContextOptions } from './navigation-context-DJjCkrcj.js';
3
3
 
4
4
  /**
5
5
  * UserPromptSubmit Hook Handler — navigation-index summary injection.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aaac/runtime",
3
- "version": "0.2.8",
3
+ "version": "0.2.10",
4
4
  "description": "Runtime SDK for the AaaC toolchain",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -68,9 +68,9 @@
68
68
  "node": ">=22.0.0"
69
69
  },
70
70
  "dependencies": {
71
- "@aaac/contracts": "^0.2.8",
72
- "@aaac/observability": "^0.2.8",
73
- "@aaac/toolchain": "^0.2.8",
71
+ "@aaac/contracts": "^0.2.10",
72
+ "@aaac/observability": "^0.2.10",
73
+ "@aaac/toolchain": "^0.2.10",
74
74
  "agent-contracts": "^0.35.9",
75
75
  "commander": "^12.1.0",
76
76
  "dotenv": "^17.4.2",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/artifact-resolver.ts","../src/lib/dsl-context.ts","../src/lib/bound-resolver.ts","../src/lib/navigation-context.ts","../src/lib/claude-native/navigation-sources.ts"],"sourcesContent":["/**\n * Project artifact composition — the ONE place where the project manifest's\n * `artifacts:` contract (an artifact-contracts registry) is composed onto a\n * resolved agents DSL. Both the execution path (BoundResolver) and the\n * navigation-index path consume this; neither resolves the registry itself.\n *\n * Composition, not intersection (`docs/governance-layer-spec.md` §2.2: the\n * runtime joins every declared contract into one static DSL, and the\n * navigation-index is built from that join):\n *\n * - DSL artifact whose id the registry declares → the registry's concrete\n * data is merged over the component's default (upstream binding semantics).\n * - DSL artifact the registry does not declare → keeps its component default;\n * upstream reports `unbound-artifact`.\n * - Registry artifact no DSL artifact maps to → STILL a project artifact. It is\n * declared here so the binder merges and path-substitutes it exactly like the\n * mapped ones. Dropping it (the previous behaviour) meant an artifact the\n * project governs — including `authority: generated` ones — was invisible to\n * `@` completion and unprotected by the PreToolUse edit guard. This mirrors\n * `toolchains:`, whose registry entries are all composed in (bound-resolver).\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport YAML from \"yaml\";\n\nexport interface ArtifactResolveOptions {\n dsl: Record<string, unknown>;\n artifactBinding?: {\n source: string;\n mappings?: Record<string, string>;\n };\n paths?: Record<string, string>;\n}\n\nexport interface ArtifactResolveResult {\n dsl: Record<string, unknown>;\n diagnostics: Array<{ path: string; message: string; severity: string }>;\n}\n\n/**\n * Read the `artifacts:` map from an artifact-contracts registry. Read/parse\n * failures are loud: the manifest named this file, so silently continuing would\n * present a component-default index as if it were the project's.\n */\nasync function loadArtifactRegistry(\n source: string,\n): Promise<Record<string, unknown>> {\n let content: string;\n try {\n content = await readFile(source, \"utf8\");\n } catch {\n throw new Error(\n `Failed to read artifact registry: ${source} ` +\n \"(declared by the project manifest's `artifacts:`).\",\n );\n }\n\n let parsed: unknown;\n try {\n parsed = YAML.parse(content);\n } catch (err) {\n throw new Error(\n `Invalid YAML in artifact registry ${source}: ${(err as Error).message}`,\n );\n }\n\n const document =\n typeof parsed === \"object\" && parsed !== null && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : undefined;\n const artifacts = document?.artifacts;\n if (artifacts && typeof artifacts === \"object\" && !Array.isArray(artifacts)) {\n return artifacts as Record<string, unknown>;\n }\n return {};\n}\n\nexport async function resolveArtifacts(\n options: ArtifactResolveOptions,\n): Promise<ArtifactResolveResult> {\n if (!options.artifactBinding) {\n return { dsl: options.dsl, diagnostics: [] };\n }\n\n const { resolveArtifactBinding } = await import(\"agent-contracts\");\n const registry = await loadArtifactRegistry(options.artifactBinding.source);\n const dslArtifacts = (options.dsl.artifacts ?? {}) as Record<string, unknown>;\n const mappings = options.artifactBinding.mappings;\n\n // Registry ids that no DSL artifact resolves to (directly or via `mappings`)\n // are declared as empty artifacts so the binder produces them from the\n // registry — one code path for every artifact, mapped or composed. Ids that ARE\n // claimed by a DSL artifact are left alone, so a mapping collision still\n // surfaces upstream's `orphan-binding` instead of vanishing.\n const claimed = new Set(\n Object.keys(dslArtifacts).map((id) => mappings?.[id] ?? id),\n );\n const composed = Object.keys(registry).filter(\n (id) => !claimed.has(id) && !(id in dslArtifacts),\n );\n\n const bound = resolveArtifactBinding(\n {\n ...Object.fromEntries(composed.map((id) => [id, {}])),\n ...dslArtifacts,\n },\n { artifacts: registry },\n mappings,\n options.paths,\n );\n\n return {\n dsl: { ...options.dsl, artifacts: bound.artifacts },\n diagnostics: bound.diagnostics.map((d) => ({\n path: d.rule,\n message: d.message,\n severity: d.severity,\n })),\n };\n}\n","/**\n * Runtime DSL Context — builds WorkflowRegistries from embedded DSL data,\n * optionally merging with project-level DSL extensions.\n *\n * Default flow:\n * CLI binary embeds resolved DSL data (from code generation) →\n * loadDslContext() builds registries from it.\n *\n * Extended flow:\n * Project provides a DSL that extends/overrides the embedded base →\n * loadDslContext() merges via agent-contracts' mergeDsl() →\n * builds registries from the merged result.\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport type { z } from \"zod\";\nimport YAML from \"yaml\";\nimport {\n expandDslSection,\n readDslExtension,\n type DslSectionLike,\n type ExpandedDslSection,\n} from \"@aaac/contracts\";\nimport type { WorkflowRegistries, WorkflowContractLike, WorkflowStep, DelegateStep } from \"./workflow-runner.js\";\nimport type { AgentContractLike, TaskContractLike } from \"./task-runner.js\";\nimport type { ModelClass } from \"./model-resolver.js\";\nimport { jsonSchemaToZod } from \"./schema-converter.js\";\nimport type { GuardrailRule, GuardrailRuleData } from \"./guardrail-hooks.js\";\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\nexport interface LoadDslOptions {\n /**\n * Pre-resolved DSL data embedded in the CLI binary.\n * Produced by the code generator alongside TypeScript contracts.\n * This is the default DSL — used as-is when no project extension exists.\n */\n embeddedDsl: Record<string, unknown>;\n\n /**\n * Path to a project-level DSL file that extends/overrides the embedded DSL.\n * When provided, the project DSL is resolved (including its own extends chain)\n * and merged with embeddedDsl via mergeDsl().\n */\n projectDslPath?: string;\n\n /** Entities the CLI depends on — validated after merge. */\n requiredEntities?: RequiredEntities;\n}\n\nexport interface RequiredEntities {\n workflows?: string[];\n tasks?: string[];\n}\n\nexport interface DslContext {\n readonly registries: WorkflowRegistries;\n readonly dsl: Record<string, unknown>;\n}\n\n// ---------------------------------------------------------------------------\n// Errors\n// ---------------------------------------------------------------------------\n\nexport class DslValidationError extends Error {\n readonly missing: string[];\n constructor(missing: string[]) {\n super(\n \"Required entities missing after DSL merge:\\n\" +\n missing.map((m) => ` - ${m}`).join(\"\\n\"),\n );\n this.name = \"DslValidationError\";\n this.missing = missing;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Internal: build registries from resolved DSL\n// ---------------------------------------------------------------------------\n\n/**\n * Resolved DSL → the runtime's agent contracts.\n *\n * The single normalization point for a DSL agent, shared by the execution path\n * (`loadDslContext`) and every generator that has to reason about agents:\n * `claude-materialize/workflow-render.ts` (delegate prompts) and\n * `claude-materialize/agent-render.ts` (`.claude/agents/*.md`, #272).\n *\n * Being the single point makes it the single place a declaration can be dropped,\n * and five were: `anti_patterns`, `escalation_criteria`, `x-authority`,\n * `x-audit-checklist` and `sections` were read by nothing here, so every Claude\n * surface — the in-process system prompt, the SDK candidate agents, the\n * `.claude/agents/*.md` files — was structurally unable to carry them however\n * its renderer was written, while the Cursor binding rendered all five (#349).\n *\n * It takes the WHOLE DSL, not the `agents:` map: a `sections[]` entry may name a\n * list the document holds (`list: agents`, `list: workflow`) instead of carrying\n * prose, so expanding one needs the document. Required rather than optional so\n * that expansion cannot be half-done depending on the caller.\n *\n * `mode` normalization is fail-safe on purpose: only the exact string\n * `read-write` yields `read-write`, so an undeclared, unknown or misspelled mode\n * degrades to `read-only` and can never widen an agent's tool grant\n * (see `claude-tool-grants.ts`). `mode` is therefore also independent of\n * `dispatch_only`: an agent declaring only the latter is a `read-only` agent\n * that dispatches, and both facts survive on their own.\n *\n * The two `x-` prefixed declarations go through `readDslExtension`\n * (@aaac/contracts) rather than a subscript, so the unprefixed spelling an author\n * reaches for is read here instead of being dropped in silence — which is how an\n * agent set authored with `audit_checklist` rendered, exit 0 and stderr empty,\n * missing every checklist it declared (#357). That module owns why the prefix is\n * required at all; the contract fields it populates stay plain.\n */\nexport function buildAgentRegistry(\n dsl: Record<string, unknown>,\n): Record<string, AgentContractLike> {\n const agents = (dsl.agents as Record<string, Record<string, unknown>>) ?? {};\n const registry: Record<string, AgentContractLike> = {};\n for (const [id, agent] of Object.entries(agents)) {\n const rawMode = (agent.mode as string) ?? \"read-only\";\n const mode: \"read-write\" | \"read-only\" = rawMode === \"read-write\" ? \"read-write\" : \"read-only\";\n const authority = readDslExtension(agent, \"x-authority\") as\n | { can_decide?: string[]; cannot_decide?: string[] }\n | undefined;\n registry[id] = {\n id,\n role_name: (agent.role_name as string) ?? id,\n purpose: (agent.purpose as string) ?? \"\",\n description: readDslExtension(agent, \"x-description\") as string | undefined,\n mode,\n responsibilities: (agent.responsibilities as string[]) ?? [],\n constraints: (agent.constraints as string[]) ?? [],\n rules: (agent.rules as Array<{ id: string; description: string; severity: string }>) ?? [],\n can_invoke_agents: (agent.can_invoke_agents as string[]) ?? undefined,\n can_execute_tools: (agent.can_execute_tools as string[]) ?? undefined,\n dispatch_only: (agent.dispatch_only as boolean) ?? undefined,\n can_read_artifacts: (agent.can_read_artifacts as string[]) ?? [],\n can_write_artifacts: (agent.can_write_artifacts as string[]) ?? [],\n can_return_handoffs: (agent.can_return_handoffs as string[]) ?? [],\n can_perform_validations: (agent.can_perform_validations as string[]) ?? [],\n anti_patterns: (agent.anti_patterns as string[]) ?? [],\n escalation_criteria:\n (agent.escalation_criteria as Array<{ condition: string; action: string }>) ?? [],\n authority,\n audit_checklist:\n (readDslExtension(agent, \"x-audit-checklist\") as Array<{\n section: string;\n checks: string[];\n }>) ?? [],\n sections: ((agent.sections as DslSectionLike[]) ?? [])\n .map((section) => expandDslSection(section, dsl))\n .filter((section): section is ExpandedDslSection => section !== undefined),\n };\n }\n return registry;\n}\n\nfunction buildTaskRegistry(\n tasks: Record<string, Record<string, unknown>>,\n): Record<string, TaskContractLike> {\n const registry: Record<string, TaskContractLike> = {};\n for (const [id, task] of Object.entries(tasks)) {\n registry[id] = {\n id,\n description: (task.description as string) ?? \"\",\n target_agent: (task.target_agent as string) ?? \"\",\n result_handoff: (task.result_handoff as string) ?? \"\",\n completion_criteria: (task.completion_criteria as string[]) ?? [],\n model_class: task.model_class as ModelClass | undefined,\n };\n }\n return registry;\n}\n\n/**\n * Raw DSL workflow step → the runtime's step types. The single point where a\n * step's DSL spelling is read, so it is also where this runtime's own step\n * vocabulary is named.\n *\n * `x-optional`, `x-instruction` and `x-receives` are that vocabulary: nothing in\n * `agent-contracts`' `WorkflowStepSchema` declares them, and its validator\n * reports every undeclared property that is not `x-` prefixed as a blocking\n * `unknown-property` diagnostic — the mechanism that tells a project's own\n * extension apart from a misspelled schema field. Spelled without the prefix\n * they worked (the schema is passthrough) while making the DSL that used them\n * fail its own validation: the example shipped 14 such diagnostics (#324).\n *\n * The `DelegateStep` fields they populate keep their plain names — the prefix is\n * a fact about the DSL document, not about this runtime's interfaces. Which\n * spellings of a step's declaration reach those fields is `readDslExtension`'s\n * one answer (@aaac/contracts), shared with the agent registry above and with\n * the Cursor binding: #324 named the prefix but left the unprefixed spelling\n * silently discarded rather than read and reported (#357).\n */\nfunction buildWorkflowStep(step: Record<string, unknown>): WorkflowStep {\n if (step.type === \"gate\") {\n return {\n type: \"gate\" as const,\n gate_kind: (step.gate_kind as string) ?? \"\",\n description: (step.description as string) ?? \"\",\n model_class: step.model_class as ModelClass | undefined,\n depends_on: step.depends_on as readonly string[] | undefined,\n };\n }\n if (step.type === \"evaluate\") {\n return {\n type: \"evaluate\" as const,\n task: (step.task as string) ?? \"\",\n from_agent: (step.from_agent as string) ?? \"\",\n evaluator_agent: step.evaluator_agent as string | undefined,\n description: step.description as string | undefined,\n loop_to: (step.loop_to as string) ?? \"\",\n max_iterations: (step.max_iterations as number) ?? 1,\n inject_as: step.inject_as as string | undefined,\n on_exhausted: step.on_exhausted as \"abort\" | \"fail_partial\" | \"escalate\" | undefined,\n depends_on: step.depends_on as readonly string[] | undefined,\n };\n }\n return {\n type: \"delegate\" as const,\n task: (step.task as string) ?? \"\",\n from_agent: (step.from_agent as string) ?? \"\",\n description: (step.description as string) ?? \"\",\n optional: (readDslExtension(step, \"x-optional\") as boolean) ?? false,\n max_retries: (step.max_retries as number) ?? 0,\n max_follow_ups: step.max_follow_ups as number | undefined,\n depends_on: step.depends_on as readonly string[] | undefined,\n instruction: readDslExtension(step, \"x-instruction\") as string | undefined,\n receives: readDslExtension(step, \"x-receives\") as DelegateStep[\"receives\"],\n retry: step.retry as { condition: string; fix_task: string; revalidate_task?: string } | undefined,\n };\n}\n\nfunction buildWorkflowRegistry(\n workflows: Record<string, Record<string, unknown>>,\n): Record<string, WorkflowContractLike> {\n const registry: Record<string, WorkflowContractLike> = {};\n for (const [id, wf] of Object.entries(workflows)) {\n const steps = ((wf.steps as Record<string, unknown>[]) ?? []).map(buildWorkflowStep);\n registry[id] = { id, description: (wf.description as string) ?? \"\", steps };\n }\n return registry;\n}\n\nfunction buildHandoffSchemas(\n handoffTypes: Record<string, Record<string, unknown>>,\n): Record<string, z.ZodType> {\n const schemas: Record<string, z.ZodType> = {};\n for (const [id, ht] of Object.entries(handoffTypes)) {\n const schema = ht.schema as Record<string, unknown> | undefined;\n if (schema) {\n schemas[id] = jsonSchemaToZod(schema);\n }\n }\n return schemas;\n}\n\n// ---------------------------------------------------------------------------\n// Build registries from a resolved DSL object\n// ---------------------------------------------------------------------------\n\nexport function buildRegistriesFromDsl(\n dsl: Record<string, unknown>,\n): WorkflowRegistries {\n const tasks = (dsl.tasks as Record<string, Record<string, unknown>>) ?? {};\n const workflows = (dsl.workflow as Record<string, Record<string, unknown>>) ?? {};\n const handoffTypes = (dsl.handoff_types as Record<string, Record<string, unknown>>) ?? {};\n\n return {\n agentRegistry: buildAgentRegistry(dsl),\n taskRegistry: buildTaskRegistry(tasks),\n workflowRegistry: buildWorkflowRegistry(workflows),\n handoffSchemas: buildHandoffSchemas(handoffTypes),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Validation\n// ---------------------------------------------------------------------------\n\nfunction validateRequiredEntities(\n dsl: Record<string, unknown>,\n required: RequiredEntities,\n): void {\n const missing: string[] = [];\n\n const workflows = (dsl.workflow as Record<string, unknown>) ?? {};\n const tasks = (dsl.tasks as Record<string, unknown>) ?? {};\n const handoffTypes = (dsl.handoff_types as Record<string, unknown>) ?? {};\n\n if (required.workflows) {\n for (const wfId of required.workflows) {\n if (!(wfId in workflows)) {\n missing.push(`workflow \"${wfId}\" is required by the CLI but not found in the resolved DSL`);\n }\n }\n }\n\n if (required.tasks) {\n for (const taskId of required.tasks) {\n if (!(taskId in tasks)) {\n missing.push(`task \"${taskId}\" is required by the CLI but not found in the resolved DSL`);\n continue;\n }\n const task = tasks[taskId] as Record<string, unknown>;\n const invHandoff = task.invocation_handoff as string | undefined;\n const resHandoff = task.result_handoff as string | undefined;\n if (invHandoff && !(invHandoff in handoffTypes)) {\n missing.push(`handoff_type \"${invHandoff}\" (invocation_handoff of task \"${taskId}\") not found`);\n }\n if (resHandoff && !(resHandoff in handoffTypes)) {\n missing.push(`handoff_type \"${resHandoff}\" (result_handoff of task \"${taskId}\") not found`);\n }\n }\n }\n\n if (required.workflows) {\n for (const wfId of required.workflows) {\n if (!(wfId in workflows)) continue;\n const wf = workflows[wfId] as Record<string, unknown>;\n const steps = (wf.steps as Array<Record<string, unknown>>) ?? [];\n for (const step of steps) {\n if (step.type !== \"delegate\") continue;\n const taskId = step.task as string;\n if (taskId && taskId in tasks) {\n const task = tasks[taskId] as Record<string, unknown>;\n const resHandoff = task.result_handoff as string | undefined;\n if (resHandoff && !(resHandoff in handoffTypes)) {\n missing.push(`handoff_type \"${resHandoff}\" (result of task \"${taskId}\" in workflow \"${wfId}\") not found`);\n }\n }\n }\n }\n }\n\n if (missing.length > 0) {\n throw new DslValidationError(missing);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Main API\n// ---------------------------------------------------------------------------\n\n/**\n * Build a DslContext from embedded DSL data, optionally merging with\n * a project-level DSL extension.\n *\n * Default (no projectDslPath):\n * Builds registries directly from embeddedDsl — no filesystem access.\n *\n * Extended (with projectDslPath):\n * Resolves the project DSL from filesystem, merges it over embeddedDsl\n * via agent-contracts' mergeDsl(), then builds registries from the result.\n */\nexport async function loadDslContext(\n options: LoadDslOptions,\n): Promise<DslContext> {\n let dsl: Record<string, unknown>;\n\n if (options.projectDslPath) {\n const { resolve: resolveDsl, mergeDsl, expandDefaults } = await import(\"agent-contracts\");\n const raw = await readFile(options.projectDslPath, \"utf8\");\n const document: unknown = YAML.parse(raw);\n if (typeof document !== \"object\" || document === null || Array.isArray(document)) {\n throw new Error(`${options.projectDslPath} is not a DSL document (expected a YAML mapping)`);\n }\n const projectData = document as Record<string, unknown>;\n\n if (projectData.extends === \"/$embedded/\") {\n const { extends: _extends, ...projectOverrides } = projectData;\n const merged = mergeDsl(options.embeddedDsl, projectOverrides);\n dsl = expandDefaults(merged);\n } else {\n const projectResult = await resolveDsl(options.projectDslPath);\n const merged = mergeDsl(options.embeddedDsl, projectResult.data);\n dsl = expandDefaults(merged);\n }\n } else {\n dsl = options.embeddedDsl;\n }\n\n if (options.requiredEntities) {\n validateRequiredEntities(dsl, options.requiredEntities);\n }\n\n const registries = buildRegistriesFromDsl(dsl);\n\n return { registries, dsl };\n}\n","/**\n * BoundResolver — runtime binding + policy resolution with per-agent isolation.\n *\n * Resolves artifact composition and guardrail/policy in one pass at runtime,\n * producing a per-agent scoped ResolvedComponent. Reuses existing\n * resolveArtifacts(), buildGuardrailContext(), and agent scope resolution.\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport { dirname, resolve as resolvePath } from \"node:path\";\nimport { parseComponentFile } from \"@aaac/contracts\";\nimport YAML from \"yaml\";\nimport { buildGuardrailContext, type GuardrailCheckEntry, type GuardrailContext } from \"../generator/context.js\";\nimport { resolveArtifacts } from \"./artifact-resolver.js\";\nimport { buildRegistriesFromDsl } from \"./dsl-context.js\";\nimport type { GuardrailRuleData } from \"./guardrail-hooks.js\";\nimport type { WorkflowRegistries } from \"./workflow-runner.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface ArtifactBindingConfig {\n source: string;\n mappings?: Record<string, string>;\n}\n\nexport interface BoundResolveOptions {\n /** Component identifier — used for cache keying. */\n id: string;\n /** Pre-resolved DSL (e.g. embedded from codegen). */\n embeddedDsl?: Record<string, unknown>;\n /** Path to DSL file — resolved via agent-contracts when no embeddedDsl. */\n dslPath?: string;\n /** Paths to software binding YAML files (guardrail_impl, etc.). */\n bindingPaths?: string[];\n /** Active guardrail policy name from DSL guardrail_policies. */\n activeGuardrailPolicy?: string;\n /** Artifact binding config — composed via resolveArtifacts() (lib/artifact-resolver). */\n artifactBinding?: ArtifactBindingConfig;\n /** Path substitutions for artifact binding. */\n paths?: Record<string, string>;\n /** Path to toolchain-contracts.yaml. */\n toolchainContractsPath?: string;\n}\n\nexport interface ResolvedToolchain {\n id: string;\n kind: \"library\" | \"cli\" | \"component\";\n description?: string;\n module?: string;\n command?: string;\n cli_contract?: string;\n component_contract?: string;\n /**\n * `info.id` of the component `component_contract` names, or undefined when\n * the toolchain names no component.\n *\n * `component_contract` is a path relative to the toolchain-contracts file, so\n * this is the only layer that can turn it into an identity — and the identity\n * is what says whose namespace `operations` is written in (see\n * `component-scope.ts`).\n */\n componentId?: string;\n artifacts: { consumes: string[]; produces: string[] };\n operations?: string[];\n source: \"toolchain-contracts\" | \"agent-contracts\" | \"merged\";\n}\n\nexport interface ResolvedComponent {\n id: string;\n dsl: Record<string, unknown>;\n registries: WorkflowRegistries;\n guardrails: {\n perAgent: Map<string, GuardrailRuleData>;\n };\n diagnostics: Array<{ path?: string; message: string; severity?: string }>;\n toolchains?: Record<string, ResolvedToolchain>;\n toolchainsByAgent?: Map<string, ResolvedToolchain[]>;\n}\n\n// ---------------------------------------------------------------------------\n// Guardrail scope helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Effective guardrail IDs for an agent: entity-side bindings ∪ scope-side bindings.\n */\nexport function getEffectiveGuardrailIds(\n dsl: Record<string, unknown>,\n agentId: string,\n): Set<string> {\n const ids = new Set<string>();\n\n const agents = (dsl.agents ?? {}) as Record<string, Record<string, unknown>>;\n const agent = agents[agentId];\n if (agent) {\n for (const ref of (agent.guardrails as string[]) ?? []) {\n ids.add(ref);\n }\n }\n\n const guardrails = (dsl.guardrails ?? {}) as Record<\n string,\n { scope?: { agents?: string[] } }\n >;\n for (const [guardrailId, guardrail] of Object.entries(guardrails)) {\n if (guardrail.scope?.agents?.includes(agentId)) {\n ids.add(guardrailId);\n }\n }\n\n return ids;\n}\n\nfunction guardrailCheckToCommandRule(c: GuardrailCheckEntry) {\n return {\n guardrail_id: c.guardrail_id,\n pattern: c.pattern,\n action: c.action as GuardrailRuleData[\"commandRules\"][number][\"action\"],\n message: c.message,\n };\n}\n\nfunction guardrailCheckToFileRule(c: GuardrailCheckEntry) {\n return {\n guardrail_id: c.guardrail_id,\n pattern: c.pattern,\n action: c.action as GuardrailRuleData[\"fileRules\"][number][\"action\"],\n message: c.message,\n ...(c.exclude_glob ? { exclude_glob: c.exclude_glob } : {}),\n };\n}\n\nfunction guardrailCheckToContentRule(c: GuardrailCheckEntry) {\n return {\n guardrail_id: c.guardrail_id,\n pattern: c.pattern,\n action: c.action as GuardrailRuleData[\"contentRules\"][number][\"action\"],\n message: c.message,\n ...(c.file_glob ? { file_glob: c.file_glob } : {}),\n ...(c.exclude_glob ? { exclude_glob: c.exclude_glob } : {}),\n };\n}\n\nexport function guardrailContextToRuleData(\n ctx: GuardrailContext,\n effectiveIds?: Set<string>,\n): GuardrailRuleData {\n const filter = (checks: GuardrailCheckEntry[]) =>\n effectiveIds ? checks.filter((c) => effectiveIds.has(c.guardrail_id)) : checks;\n\n return {\n commandRules: filter(ctx.commandChecks).map(guardrailCheckToCommandRule),\n fileRules: filter(ctx.fileChecks).map(guardrailCheckToFileRule),\n contentRules: filter(ctx.contentChecks).map(guardrailCheckToContentRule),\n };\n}\n\nexport function buildPerAgentGuardrails(\n dsl: Record<string, unknown>,\n guardrailCtx: GuardrailContext,\n): Map<string, GuardrailRuleData> {\n const perAgent = new Map<string, GuardrailRuleData>();\n const agents = (dsl.agents ?? {}) as Record<string, unknown>;\n\n for (const agentId of Object.keys(agents)) {\n const effectiveIds = getEffectiveGuardrailIds(dsl, agentId);\n const rules = guardrailContextToRuleData(guardrailCtx, effectiveIds);\n if (hasGuardrailRules(rules)) {\n perAgent.set(agentId, rules);\n }\n }\n\n return perAgent;\n}\n\nconst EMPTY_GUARDRAIL_CONTEXT: GuardrailContext = {\n commandChecks: [],\n fileChecks: [],\n contentChecks: [],\n allChecks: [],\n hasGuardrails: false,\n diagnostics: [],\n};\n\n/**\n * Resolve the guardrail context from a DSL + its software bindings — the ONE\n * place `guardrail_impl` matchers become checks. The CLI execution path and the\n * navigation-index/hook path both call this, so the hooks enforce exactly what\n * `dev-team guard list` reports (#267).\n *\n * Checks from EVERY binding file are merged: `bindings.guardrail` is a list, and\n * overwriting per file silently dropped all but the last one (#268).\n */\nexport async function resolveGuardrailContext(\n dsl: Record<string, unknown>,\n bindingPaths?: string[],\n activeGuardrailPolicy?: string,\n options?: {\n /**\n * Ignore binding paths that do not exist. The `guard` CLI commands report on\n * whatever is present (a not-yet-created binding is not a failure); the\n * execution path wants the missing file to surface.\n */\n skipMissing?: boolean;\n },\n): Promise<GuardrailContext> {\n if (!bindingPaths || bindingPaths.length === 0) {\n return EMPTY_GUARDRAIL_CONTEXT;\n }\n\n const merged: GuardrailContext = {\n commandChecks: [],\n fileChecks: [],\n contentChecks: [],\n allChecks: [],\n hasGuardrails: false,\n diagnostics: [],\n };\n\n // Policy findings are project-level, so every binding file reports the same\n // ones; keep one copy of each.\n const seenDiagnostics = new Set<string>();\n\n for (const bindingPath of bindingPaths) {\n let raw: string;\n try {\n raw = await readFile(bindingPath, \"utf8\");\n } catch (err) {\n if (options?.skipMissing && (err as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw err;\n }\n const document: unknown = YAML.parse(raw);\n if (typeof document !== \"object\" || document === null || Array.isArray(document)) {\n throw new Error(`${bindingPath} is not a binding document (expected a YAML mapping)`);\n }\n const binding = document as Record<string, unknown>;\n const ctx = buildGuardrailContext(dsl, binding, activeGuardrailPolicy);\n merged.commandChecks.push(...ctx.commandChecks);\n merged.fileChecks.push(...ctx.fileChecks);\n merged.contentChecks.push(...ctx.contentChecks);\n merged.allChecks.push(...ctx.allChecks);\n merged.hasGuardrails = merged.hasGuardrails || ctx.hasGuardrails;\n for (const diagnostic of ctx.diagnostics) {\n const key = `${diagnostic.path} :: ${diagnostic.message}`;\n if (seenDiagnostics.has(key)) continue;\n seenDiagnostics.add(key);\n merged.diagnostics.push(diagnostic);\n }\n }\n\n return merged;\n}\n\nfunction hasGuardrailRules(rules: GuardrailRuleData): boolean {\n return (\n rules.commandRules.length > 0 ||\n rules.fileRules.length > 0 ||\n rules.contentRules.length > 0\n );\n}\n\n// ---------------------------------------------------------------------------\n// Toolchain derivation — types for dynamic import from @aaac/toolchain\n// ---------------------------------------------------------------------------\n\ninterface ToolchainDSLEntry {\n kind: \"library\" | \"cli\" | \"component\";\n description?: string;\n module?: string;\n command?: string;\n cli_contract?: string;\n component_contract?: string;\n artifacts: { consumes: string[]; produces: string[] };\n operations?: string[];\n}\n\ninterface ToolchainContractsDSLShape {\n toolchains: Record<string, ToolchainDSLEntry>;\n}\n\ninterface ToolchainModule {\n loadToolchainContracts(filePath: string): Promise<ToolchainContractsDSLShape>;\n}\n\n/**\n * Identity of the component a toolchain names — read with the contracts\n * package's own reader, so a `component_contract` is parsed here exactly as it\n * is everywhere else.\n *\n * A path that names nothing readable is a broken declaration and says so. The\n * field had no reader at all before #335, which is why one could point anywhere\n * (two fixtures pointed at files that were never written) and stay green.\n */\nasync function readComponentId(\n componentPath: string,\n toolchainId: string,\n): Promise<string> {\n try {\n return (await parseComponentFile(componentPath)).info.id;\n } catch (err) {\n throw new Error(\n `Toolchain \"${toolchainId}\" declares component_contract \"${componentPath}\", ` +\n `which cannot be read as a component contract: ${(err as Error).message}`,\n { cause: err },\n );\n }\n}\n\nfunction mergeDerivedWithAgentTools(\n derivedTools: ResolvedToolchain[],\n agentToolIds: string[],\n allToolchains: Record<string, ResolvedToolchain>,\n): ResolvedToolchain[] {\n const merged = new Map<string, ResolvedToolchain>();\n\n for (const tc of derivedTools) {\n merged.set(tc.id, tc);\n }\n\n for (const toolId of agentToolIds) {\n if (!merged.has(toolId)) {\n if (allToolchains[toolId]) {\n merged.set(toolId, { ...allToolchains[toolId], source: \"merged\" });\n }\n } else {\n const existing = merged.get(toolId)!;\n merged.set(toolId, { ...existing, source: \"merged\" });\n }\n }\n\n return Array.from(merged.values());\n}\n\nexport function deriveToolchainsForAgents(\n dsl: Record<string, unknown>,\n toolchains: Record<string, ResolvedToolchain>,\n): Map<string, ResolvedToolchain[]> {\n const result = new Map<string, ResolvedToolchain[]>();\n const agents = (dsl.agents ?? {}) as Record<string, Record<string, unknown>>;\n\n for (const [agentId, agent] of Object.entries(agents)) {\n const derivedTools: ResolvedToolchain[] = [];\n\n const canReadArtifacts = (agent.can_read_artifacts ?? []) as string[];\n const canWriteArtifacts = (agent.can_write_artifacts ?? []) as string[];\n const agentArtifacts = agent.artifacts as\n | { produces?: string[]; consumes?: string[] }\n | undefined;\n const readArtifacts = new Set([\n ...canReadArtifacts,\n ...(agentArtifacts?.consumes ?? []),\n ]);\n const writeArtifacts = new Set([\n ...canWriteArtifacts,\n ...(agentArtifacts?.produces ?? []),\n ]);\n\n for (const tc of Object.values(toolchains)) {\n let matched = false;\n\n for (const artifactId of tc.artifacts.consumes) {\n if (readArtifacts.has(artifactId) || writeArtifacts.has(artifactId)) {\n matched = true;\n break;\n }\n }\n\n if (!matched) {\n for (const artifactId of tc.artifacts.produces) {\n if (writeArtifacts.has(artifactId)) {\n matched = true;\n break;\n }\n }\n }\n\n if (matched) {\n derivedTools.push(tc);\n }\n }\n\n if (derivedTools.length > 0) {\n const agentTools = (agent.can_execute_tools ?? []) as string[];\n const mergedTools = mergeDerivedWithAgentTools(\n derivedTools,\n agentTools,\n toolchains,\n );\n result.set(agentId, mergedTools);\n }\n }\n\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// BoundResolver\n// ---------------------------------------------------------------------------\n\nexport class BoundResolver {\n private readonly cache = new Map<string, ResolvedComponent>();\n\n /**\n * Resolve binding + policy in one pass. Results are cached by component id.\n */\n async resolve(opts: BoundResolveOptions): Promise<ResolvedComponent> {\n const cached = this.cache.get(opts.id);\n if (cached) return cached;\n\n const diagnostics: ResolvedComponent[\"diagnostics\"] = [];\n let dsl: Record<string, unknown>;\n\n if (opts.embeddedDsl) {\n dsl = opts.embeddedDsl;\n } else if (opts.dslPath) {\n const { resolve: resolveDsl } = await import(\"agent-contracts\");\n const result = await resolveDsl(opts.dslPath);\n dsl = result.data;\n } else {\n throw new Error(\"BoundResolver.resolve requires embeddedDsl or dslPath\");\n }\n\n // Artifact composition (the shared seam — see lib/artifact-resolver.ts)\n if (opts.artifactBinding) {\n const bound = await resolveArtifacts({\n dsl,\n artifactBinding: opts.artifactBinding,\n paths: opts.paths,\n });\n dsl = bound.dsl;\n diagnostics.push(...bound.diagnostics);\n }\n\n // Guardrail + policy from bindings\n let guardrailCtx: GuardrailContext;\n\n guardrailCtx = await resolveGuardrailContext(\n dsl,\n opts.bindingPaths,\n opts.activeGuardrailPolicy,\n );\n diagnostics.push(...guardrailCtx.diagnostics);\n\n const perAgent = guardrailCtx.hasGuardrails\n ? buildPerAgentGuardrails(dsl, guardrailCtx)\n : new Map<string, GuardrailRuleData>();\n\n let toolchains: Record<string, ResolvedToolchain> | undefined;\n let toolchainsByAgent: Map<string, ResolvedToolchain[]> | undefined;\n\n if (opts.toolchainContractsPath) {\n const toolchainPkg = \"@aaac/toolchain\";\n const mod = (await import(/* webpackIgnore: true */ toolchainPkg)) as ToolchainModule;\n const tcDoc = await mod.loadToolchainContracts(opts.toolchainContractsPath);\n const toolchainDir = dirname(resolvePath(opts.toolchainContractsPath));\n\n toolchains = {};\n for (const [id, tc] of Object.entries(tcDoc.toolchains) as Array<[string, ToolchainDSLEntry]>) {\n toolchains[id] = {\n id,\n kind: tc.kind,\n description: tc.description,\n module: tc.module,\n command: tc.command,\n cli_contract: tc.cli_contract,\n component_contract: tc.component_contract,\n ...(tc.component_contract\n ? {\n componentId: await readComponentId(\n resolvePath(toolchainDir, tc.component_contract),\n id,\n ),\n }\n : {}),\n artifacts: {\n consumes: [...tc.artifacts.consumes],\n produces: [...tc.artifacts.produces],\n },\n operations: tc.operations ? [...tc.operations] : undefined,\n source: \"toolchain-contracts\",\n };\n }\n\n toolchainsByAgent = deriveToolchainsForAgents(dsl, toolchains);\n }\n\n const component: ResolvedComponent = {\n id: opts.id,\n dsl,\n registries: buildRegistriesFromDsl(dsl),\n guardrails: { perAgent },\n diagnostics,\n ...(toolchains ? { toolchains } : {}),\n ...(toolchainsByAgent ? { toolchainsByAgent } : {}),\n };\n\n this.cache.set(opts.id, component);\n return component;\n }\n\n /** Clear cached components (e.g. for testing). */\n clearCache(): void {\n this.cache.clear();\n }\n}\n\n/** Get guardrail rules for a specific agent from a ResolvedComponent. */\nexport function getGuardrailRulesForAgent(\n component: ResolvedComponent,\n agentId: string,\n): GuardrailRuleData | undefined {\n const perAgent = component.guardrails.perAgent.get(agentId);\n return perAgent && hasGuardrailRules(perAgent) ? perAgent : undefined;\n}\n","import { findMisspelledDslExtensions } from \"@aaac/contracts\";\nimport { resolveArtifacts } from \"./artifact-resolver.js\";\nimport {\n guardrailContextToRuleData,\n resolveGuardrailContext,\n} from \"./bound-resolver.js\";\nimport { loadDslContext } from \"./dsl-context.js\";\nimport type { GuardrailRuleData } from \"./guardrail-hooks.js\";\n\nexport interface NavigationContextOptions {\n configPath?: string;\n embeddedDsl?: Record<string, unknown>;\n projectDslPath?: string;\n artifactBinding?: {\n source: string;\n mappings?: Record<string, string>;\n };\n paths?: Record<string, string>;\n /**\n * Software binding files (`guardrail_impl`) from the project manifest's\n * `bindings.guardrail`. Without them the hooks enforce NO Bash guardrails\n * while the CLI enforces the project's — the asymmetry behind #267.\n */\n bindingPaths?: string[];\n /** Active guardrail policy name from the manifest. */\n activeGuardrailPolicy?: string;\n}\n\nexport interface NavigationContext {\n dsl: Record<string, unknown>;\n navigationIndex: Record<string, unknown>;\n /**\n * Guardrail rules resolved from the DSL + the project's software bindings.\n *\n * The navigation-index does not carry guardrail rules (it is an\n * artifact/tool graph), so they are surfaced separately here for the\n * PreToolUse Bash guardrail path (#238 / C5). `undefined` when the project\n * declares no guardrail binding.\n */\n guardrailRules?: GuardrailRuleData;\n diagnostics: Array<{ path: string; message: string; severity: string }>;\n}\n\n/**\n * Resolve the navigation sources of ONE project root into its effective DSL:\n * the component's bundled `/$embedded/` DSL overlaid with the project's\n * `agents:` DSL when the manifest declares one.\n *\n * Split out of `buildNavigationContext` because the `.claude/agents/*.md`\n * emitter needs exactly this — per workspace member — without building a\n * navigation index or resolving guardrails (#272). One definition, two callers.\n */\nexport async function resolveNavigationDsl(\n options: Pick<NavigationContextOptions, \"embeddedDsl\" | \"projectDslPath\">,\n): Promise<Record<string, unknown>> {\n if (options.embeddedDsl != null) {\n if (options.projectDslPath) {\n const ctx = await loadDslContext({\n embeddedDsl: options.embeddedDsl,\n projectDslPath: options.projectDslPath,\n });\n return ctx.dsl;\n }\n return options.embeddedDsl;\n }\n if (options.projectDslPath) {\n // No embedded DSL: resolve the project DSL file directly\n const { resolve } = await import(\"agent-contracts\");\n const result = await resolve(options.projectDslPath);\n return result.data;\n }\n throw new Error(\"resolveNavigationDsl requires embeddedDsl or projectDslPath\");\n}\n\nexport async function buildNavigationContext(\n options: NavigationContextOptions,\n): Promise<NavigationContext> {\n const diagnostics: NavigationContext[\"diagnostics\"] = [];\n let dsl = await resolveNavigationDsl(options);\n\n if (options.artifactBinding) {\n const bound = await resolveArtifacts({\n dsl,\n artifactBinding: options.artifactBinding,\n paths: options.paths,\n });\n dsl = bound.dsl;\n diagnostics.push(...bound.diagnostics);\n }\n\n const { validateSchema, buildNavigationIndex } = await import(\"agent-contracts\");\n const validation = validateSchema(dsl);\n const schemaDiagnostics = validation.diagnostics.map((d) => ({\n path: d.path,\n message: d.message,\n severity: d.severity ?? \"error\",\n }));\n diagnostics.push(...schemaDiagnostics);\n\n // Why an extension spelled without its `x-` prefix is reported HERE, on top of\n // the `unknown-property` upstream already returns for the same key: upstream\n // says the prefix is missing, which is true of any undeclared key, while this\n // says WHICH declaration was written and that a reader was looking for the\n // other spelling — the part that was missing when an agent set authored with\n // `audit_checklist` rendered clean and checklist-less (#357).\n //\n // `error`, matching the verdict upstream already reached: every key\n // `findMisspelledDslExtensions` reports is one `checkCustomPropsRecursive`\n // reports as blocking, so this can add a reason to a document that is already\n // failing and can never turn a passing one red — pinned against the real\n // validator in `@aaac/contracts`' `__tests__/dsl-extensions.test.ts`.\n diagnostics.push(\n ...findMisspelledDslExtensions(dsl).map((m) => ({\n path: m.path,\n message: m.message,\n severity: \"error\",\n })),\n );\n\n // `buildNavigationIndex` takes a POST-PARSE `Dsl`: `tools`, `agents`,\n // `artifacts` and `tasks` are schema defaults, so parsing guarantees they are\n // objects and the builder walks them without asking. A DSL the parser\n // rejected carries no such guarantee, and pushing it through anyway crashed\n // with `Cannot convert undefined or null to object` for every project that\n // omitted one of those keys — a message naming nothing about the DSL (#317).\n //\n // `validation.data` is present whenever the parse succeeded, INCLUDING when a\n // later blocking check set `success: false`; those projects still get their\n // index plus the diagnostics above. Only a failed parse lands here, and it has\n // no recovery: `expandDefaults` returns its input untouched when the parse\n // fails, so an index simply cannot be built. Naming the schema errors and\n // stopping is the answer — the hooks turn a throw into `exit 1` + stderr,\n // which is this harness's one failure report (#310).\n if (!validation.data) {\n throw new Error(\n [\n \"DSL schema validation failed — a navigation index cannot be built from it:\",\n ...schemaDiagnostics.map((d) => ` - [${d.severity}] ${d.path}: ${d.message}`),\n ].join(\"\\n\"),\n );\n }\n const navigationIndex = buildNavigationIndex(validation.data) as Record<string, unknown>;\n\n // Same resolver the CLI execution path uses, so `dev-team guard list` and the\n // PreToolUse Bash guard agree (#267).\n const guardrailCtx = await resolveGuardrailContext(\n dsl,\n options.bindingPaths,\n options.activeGuardrailPolicy,\n );\n // Policy-resolution findings ride the same channel the SessionStart hook\n // renders (claude-native/ensure-navigation-index.ts), so a project whose\n // guardrails cannot be given an enforcement action says so out loud (#293).\n diagnostics.push(...guardrailCtx.diagnostics);\n const guardrailRules = guardrailCtx.hasGuardrails\n ? guardrailContextToRuleData(guardrailCtx)\n : undefined;\n\n return { dsl, navigationIndex, guardrailRules, diagnostics };\n}\n","/**\n * Navigation sources — resolve the project manifest into the inputs the\n * navigation-index hooks need (which DSL to overlay, which artifact registry to\n * bind, which files invalidate the cache).\n *\n * The generated `.claude/bin/*` nav hooks bake only what cannot be read from\n * disk at hook time: the component's bundled `/$embedded/` DSL. Everything the\n * project manifest declares (`agents:`, `artifacts:`) is resolved HERE, at hook\n * runtime, through the same `loadProjectConfig` loader the CLI uses — so a\n * manifest edit takes effect without re-running `claude sync`, and the hooks\n * cannot drift from the CLI's view of the project\n * (docs/proposal/workspace-subproject-guardrail.md §3.2).\n */\n\nimport { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport {\n loadProjectConfig,\n PROJECT_CONFIG_FILENAME,\n} from \"../../generator/config.js\";\nimport type { NavigationContextOptions } from \"../navigation-context.js\";\n\nexport interface ResolveNavigationSourcesOptions {\n /**\n * Root of the project whose navigation-index is being built: the directory\n * that owns `project.yaml` (in workspace mode, the member root).\n */\n projectRoot: string;\n /**\n * The component's bundled `/$embedded/` DSL, baked into the hook bin by\n * `claude sync` — the only writer of `.claude/bin/*` (#273). Undefined for a\n * component whose contract declares no embedded DSL, where the bin resolves\n * `dslPath` directly.\n */\n embeddedDsl?: Record<string, unknown>;\n /**\n * Project-root-relative agents DSL path used ONLY when `projectRoot` has no\n * `project.yaml` (a bare component checkout), and only when the file is\n * actually there — it is a convention, not a declaration. With a manifest\n * present the manifest's `agents:` wins.\n */\n dslPath: string;\n}\n\nexport interface NavigationSources {\n navigationOptions: NavigationContextOptions;\n /** Files whose mtime invalidates the navigation-index cache. */\n sourceFiles: string[];\n}\n\n/**\n * Resolve the navigation-index inputs for one project root.\n *\n * With a `project.yaml` present, the manifest is authoritative:\n * - `agents:` → the DSL overlaid on `embeddedDsl` (omitted = embedded as-is),\n * - `artifacts:` → the artifact-contracts registry bound onto the DSL\n * artifacts, so path_patterns / authority / manual_edit reflect the project\n * rather than the component's built-in defaults,\n * - `bindings.guardrail` + `active_guardrail_policy` → the guardrail checks the\n * PreToolUse hook enforces, resolved by the same code as the CLI (#267).\n * All resolved files feed `sourceFiles`, so editing any of them rebuilds the\n * index on the next hook invocation.\n */\nexport async function resolveNavigationSources(\n options: ResolveNavigationSourcesOptions,\n): Promise<NavigationSources> {\n const manifestPath = resolve(options.projectRoot, PROJECT_CONFIG_FILENAME);\n\n if (!existsSync(manifestPath)) {\n const projectDslPath = resolve(options.projectRoot, options.dslPath);\n // With no manifest, `dslPath` is a CONVENTION, not a declaration: nothing in\n // this root asked for it. So it is an overlay only when it is actually\n // there, exactly as an undeclared `agents:` is treated below — otherwise the\n // root simply has no overlay and the embedded DSL stands as-is.\n //\n // Without an embedded DSL (`aaac generate` output) the path is not an\n // overlay but the ONLY source, so it is kept regardless and its absence\n // fails loudly at load with the missing filename.\n const isSource = options.embeddedDsl === undefined || existsSync(projectDslPath);\n return {\n navigationOptions: {\n ...(isSource ? { projectDslPath } : {}),\n embeddedDsl: options.embeddedDsl,\n },\n // Both paths are watched even when neither exists yet: the manifest is the\n // file that DECIDES the rest of this set, and the conventional DSL path\n // becomes an overlay the moment it appears. `computeCurrentHash` records an\n // absent file as `missing:<path>`, so the hash changes when either is\n // created.\n sourceFiles: [manifestPath, projectDslPath],\n };\n }\n\n const config = await loadProjectConfig(manifestPath);\n const sourceFiles = [manifestPath];\n\n // An undeclared `agents:` means \"no overlay\" — `config.dslPath` is then just\n // the schema default and pointing the loader at it would be a hard failure.\n const projectDslPath = config.dslDeclared ? config.dslPath : undefined;\n if (projectDslPath) {\n sourceFiles.push(projectDslPath);\n }\n\n if (config.artifactsPath) {\n sourceFiles.push(config.artifactsPath);\n }\n\n // Guardrail bindings feed the PreToolUse Bash guard, and edits to them must\n // rebuild the index (#267).\n sourceFiles.push(...config.bindingPaths);\n\n return {\n navigationOptions: {\n ...(projectDslPath ? { projectDslPath } : {}),\n embeddedDsl: options.embeddedDsl,\n ...(config.artifactsPath\n ? { artifactBinding: { source: config.artifactsPath } }\n : {}),\n bindingPaths: config.bindingPaths,\n ...(config.active_guardrail_policy\n ? { activeGuardrailPolicy: config.active_guardrail_policy }\n : {}),\n },\n sourceFiles,\n };\n}\n"],"mappings":";;;;;;;;;;AAsBA,SAAS,gBAAgB;AACzB,OAAO,UAAU;AAqBjB,eAAe,qBACb,QACkC;AAClC,MAAI;AACJ,MAAI;AACF,cAAU,MAAM,SAAS,QAAQ,MAAM;AAAA,EACzC,QAAQ;AACN,UAAM,IAAI;AAAA,MACR,qCAAqC,MAAM;AAAA,IAE7C;AAAA,EACF;AAEA,MAAI;AACJ,MAAI;AACF,aAAS,KAAK,MAAM,OAAO;AAAA,EAC7B,SAAS,KAAK;AACZ,UAAM,IAAI;AAAA,MACR,qCAAqC,MAAM,KAAM,IAAc,OAAO;AAAA,IACxE;AAAA,EACF;AAEA,QAAM,WACJ,OAAO,WAAW,YAAY,WAAW,QAAQ,CAAC,MAAM,QAAQ,MAAM,IACjE,SACD;AACN,QAAM,YAAY,UAAU;AAC5B,MAAI,aAAa,OAAO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AAe;AAgDxB,eAAsB,yBACpB,SAC4B;AAC5B,QAAM,eAAe,QAAQ,QAAQ,aAAa,uBAAuB;AAEzE,MAAI,CAAC,WAAW,YAAY,GAAG;AAC7B,UAAMC,kBAAiB,QAAQ,QAAQ,aAAa,QAAQ,OAAO;AASnE,UAAM,WAAW,QAAQ,gBAAgB,UAAa,WAAWA,eAAc;AAC/E,WAAO;AAAA,MACL,mBAAmB;AAAA,QACjB,GAAI,WAAW,EAAE,gBAAAA,gBAAe,IAAI,CAAC;AAAA,QACrC,aAAa,QAAQ;AAAA,MACvB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAMA,aAAa,CAAC,cAAcA,eAAc;AAAA,IAC5C;AAAA,EACF;AAEA,QAAM,SAAS,MAAM,kBAAkB,YAAY;AACnD,QAAM,cAAc,CAAC,YAAY;AAIjC,QAAM,iBAAiB,OAAO,cAAc,OAAO,UAAU;AAC7D,MAAI,gBAAgB;AAClB,gBAAY,KAAK,cAAc;AAAA,EACjC;AAEA,MAAI,OAAO,eAAe;AACxB,gBAAY,KAAK,OAAO,aAAa;AAAA,EACvC;AAIA,cAAY,KAAK,GAAG,OAAO,YAAY;AAEvC,SAAO;AAAA,IACL,mBAAmB;AAAA,MACjB,GAAI,iBAAiB,EAAE,eAAe,IAAI,CAAC;AAAA,MAC3C,aAAa,QAAQ;AAAA,MACrB,GAAI,OAAO,gBACP,EAAE,iBAAiB,EAAE,QAAQ,OAAO,cAAc,EAAE,IACpD,CAAC;AAAA,MACL,cAAc,OAAO;AAAA,MACrB,GAAI,OAAO,0BACP,EAAE,uBAAuB,OAAO,wBAAwB,IACxD,CAAC;AAAA,IACP;AAAA,IACA;AAAA,EACF;AACF;","names":["readFile","YAML","readFile","YAML","readFile","YAML","readFile","YAML","resolve","projectDslPath"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/claude-native/hook-protocol.ts","../src/lib/claude-native/cache-store.ts","../src/lib/claude-native/navigation-freshness.ts","../src/lib/claude-native/ensure-navigation-index-keys.ts","../src/lib/claude-native/artifact-resolver.ts"],"sourcesContent":["/**\n * Claude Code Hook Protocol — parse stdin JSON input and emit hook response JSON.\n *\n * Implements the protocol defined at https://code.claude.com/docs/en/hooks\n * for SessionStart, UserPromptSubmit, and PreToolUse hook events.\n */\n\n// ---------------------------------------------------------------------------\n// Hook Event Types\n// ---------------------------------------------------------------------------\n\n/**\n * One declaration for the events this harness models, so the type and the check\n * `parseHookInput` performs cannot name different sets.\n */\nconst MODELLED_EVENTS = [\"SessionStart\", \"UserPromptSubmit\", \"PreToolUse\"] as const;\n\nexport type HookEventName = (typeof MODELLED_EVENTS)[number];\n\nexport interface SessionStartInput {\n hookEventName: \"SessionStart\";\n session_id?: string;\n type?: \"new\" | \"resume\" | \"clear\" | \"compact\";\n}\n\nexport interface UserPromptSubmitInput {\n hookEventName: \"UserPromptSubmit\";\n session_id?: string;\n prompt?: string;\n}\n\nexport interface PreToolUseInput {\n hookEventName: \"PreToolUse\";\n session_id?: string;\n /** The session's working directory, where a Bash command runs. */\n cwd?: string;\n tool_name?: string;\n tool_input?: {\n file_path?: string;\n path?: string;\n command?: string;\n content?: string;\n [key: string]: unknown;\n };\n}\n\nexport type HookInput = SessionStartInput | UserPromptSubmitInput | PreToolUseInput;\n\n// ---------------------------------------------------------------------------\n// Hook Response Types\n// ---------------------------------------------------------------------------\n\nexport type PermissionDecision = \"allow\" | \"deny\" | \"ask\";\n\nexport interface HookOutput {\n /** Hook-specific output envelope. */\n hookSpecificOutput?: {\n hookEventName: HookEventName;\n /** Additional context injected into the session. */\n additionalContext?: string;\n /** Permission decision for PreToolUse hooks. */\n permissionDecision?: PermissionDecision;\n /** Reason for the permission decision. */\n permissionDecisionReason?: string;\n };\n}\n\n// ---------------------------------------------------------------------------\n// Parse / Emit\n// ---------------------------------------------------------------------------\n\n/** One wording for \"these bytes are not a hook payload\"; `raw` is the diagnosis. */\nconst notAHookPayload = (raw: string): Error =>\n new Error(`Not a hook payload: ${raw.slice(0, 100)}`);\n\nconst optionalString = (value: unknown): boolean =>\n value === undefined || typeof value === \"string\";\n\n/** The `tool_input` bag: four named strings, everything else `unknown`. */\nfunction isToolInput(value: unknown): boolean {\n if (value === undefined) return true;\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const input = value as Record<string, unknown>;\n return (\n optionalString(input.file_path) &&\n optionalString(input.path) &&\n optionalString(input.command) &&\n optionalString(input.content)\n );\n}\n\n/**\n * The single gate between stdin and {@link HookInput}.\n *\n * Every field of the member the discriminant names is checked. `prompt` is one\n * of them and reads like a field nothing would get wrong, which is the reason to\n * check it: `renderCandidateArtifacts` calls `prompt.trim()`, so a non-string\n * there is a `TypeError` two frames from the parse that let it through.\n */\nfunction isHookInput(value: Record<string, unknown>): value is HookInput & Record<string, unknown> {\n if (!optionalString(value.session_id)) return false;\n switch (value.hookEventName) {\n case \"SessionStart\":\n return (\n value.type === undefined ||\n (typeof value.type === \"string\" &&\n [\"new\", \"resume\", \"clear\", \"compact\"].includes(value.type))\n );\n case \"UserPromptSubmit\":\n return optionalString(value.prompt);\n case \"PreToolUse\":\n return optionalString(value.tool_name) && isToolInput(value.tool_input);\n default:\n return false;\n }\n}\n\n/**\n * Parse hook input from a raw JSON string (typically from stdin).\n *\n * Three answers, and the difference between the last two is load-bearing:\n *\n * • a {@link HookInput} — the payload names an event this harness models and\n * carries the fields that member declares;\n * • THROWS — the bytes are not a hook payload at all (not a JSON object, no\n * event name, or a modelled event whose fields are not what it declares).\n * `null` stdin used to reach `parsed.hook_event_name` and answer\n * `TypeError: … reading 'hook_event_name'`;\n * • `undefined` — a well-formed payload for an event this harness does not\n * model. NOT a throw, and that is not a nicety. `pre-tool-use.sh` turns any\n * non-zero bin exit into `exit 2`, which is the one code that BLOCKS a tool\n * call — deliberately, because a guard that could not run must refuse rather\n * than allow (#304). Refusing input we simply do not handle would spend that\n * on every tool call after a version skew, or on a user who registered the\n * launcher under another event, which `settings-merge.ts` explicitly\n * contemplates. Measured end to end: `pre-tool-use.sh` exits 2 on a bin\n * throw, `session-start.sh` and `user-prompt-submit.sh` exit 1 (non-blocking\n * per the protocol — only exit 2 blocks).\n *\n * Routing between the three modelled events stays with each bin's own guard,\n * which spends exit 0 on \"not mine\".\n */\nexport function parseHookInput(raw: string): HookInput | undefined {\n const parsed: unknown = JSON.parse(raw);\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw notAHookPayload(raw);\n }\n const record = parsed as Record<string, unknown>;\n // Claude Code's hook INPUT wire protocol sends the event name as snake_case\n // `hook_event_name` (sibling fields session_id / tool_name / tool_input are\n // likewise snake_case). The internal HookInput union — and every hook bin's\n // event guard — reads `hookEventName`. Normalize once here, at the single\n // stdin parse boundary, so the guards match real payloads (#252). Output\n // stays camelCase `hookSpecificOutput.hookEventName`, which the wire expects.\n if (typeof record.hook_event_name === \"string\" && record.hookEventName === undefined) {\n record.hookEventName = record.hook_event_name;\n }\n if (!MODELLED_EVENTS.includes(record.hookEventName as HookEventName)) {\n // A name we do not model is `undefined`; no name at all is not a payload.\n if (typeof record.hookEventName === \"string\") return undefined;\n throw notAHookPayload(raw);\n }\n if (!isHookInput(record)) throw notAHookPayload(raw);\n return record;\n}\n\n/**\n * Read all of stdin and parse as hook input JSON.\n */\nexport async function readHookInput(): Promise<HookInput | undefined> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string));\n }\n const raw = Buffer.concat(chunks).toString(\"utf-8\").trim();\n if (!raw) {\n throw new Error(\"Empty stdin — no hook input received\");\n }\n return parseHookInput(raw);\n}\n\n/**\n * Emit a hook response as JSON to stdout.\n */\nexport function emitHookOutput(output: HookOutput): void {\n process.stdout.write(JSON.stringify(output) + \"\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Response Builders\n// ---------------------------------------------------------------------------\n\n/**\n * Build a response that injects additional context into the session.\n */\nexport function buildContextResponse(\n eventName: HookEventName,\n additionalContext: string,\n): HookOutput {\n return {\n hookSpecificOutput: {\n hookEventName: eventName,\n additionalContext,\n },\n };\n}\n\n/**\n * Build a deny response for PreToolUse hooks.\n */\nexport function buildDenyResponse(reason: string): HookOutput {\n return {\n hookSpecificOutput: {\n hookEventName: \"PreToolUse\",\n permissionDecision: \"deny\",\n permissionDecisionReason: reason,\n },\n };\n}\n\n/**\n * Build an allow response (empty output = allow by default).\n */\nexport function buildAllowResponse(): HookOutput {\n return {};\n}\n","/**\n * Cache Store — read/write `.claude/cache/` directory.\n *\n * Stores navigation-index.json and metadata for graph cache invalidation.\n * Uses atomic write (write-to-temp + rename) for concurrent-access safety.\n */\n\nimport { readFile, writeFile, rename, stat, mkdir } from \"node:fs/promises\";\nimport { join, dirname } from \"node:path\";\nimport { randomBytes } from \"node:crypto\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * Deciding whether an entry is fresh is deliberately NOT a method here.\n * `navigation-cache.ts` owns that question, and owning it in one place is what\n * keeps the hook that READS the index and the builder that WRITES it from\n * disagreeing about the same file.\n */\nexport interface CacheEntry<T = unknown> {\n data: T;\n /** ISO timestamp of when the cache was written. */\n writtenAt: string;\n /** Hash of source inputs used for invalidation. */\n sourceHash: string;\n /**\n * The files `sourceHash` was computed over.\n *\n * Recorded with the hash, in the same record and the same atomic write, so a\n * reader can re-check freshness without being able to resolve that list\n * itself. Resolving it means parsing the project manifest, which is what the\n * interactive hooks must not pay for; the builder already knows the answer, so\n * it writes it down (#278).\n */\n sourceFiles?: string[];\n}\n\nexport interface CacheStoreOptions {\n /** Absolute path to the `.claude/cache/` directory. */\n cacheDir: string;\n}\n\n// ---------------------------------------------------------------------------\n// Cache Store\n// ---------------------------------------------------------------------------\n\n/**\n * What a caller knows about `data` and this module does not.\n *\n * `read` is generic over `T`, so the only thing here that could establish `T` is\n * the caller's own predicate — `as CacheEntry<T>` promised whatever the call\n * site asked for and delivered whatever was on disk, which is how a cache file\n * written by another process (or an older build) reached `computeCurrentHash`\n * as `sourceFiles: 5` and threw `TypeError: sourceFiles is not iterable`.\n */\nexport type DataPredicate<T> = (value: unknown) => value is T;\n\n/**\n * The shape of an entry whose `data` is declared no more precisely than \"an\n * object\" — what both navigation-index readers ask for. It checks exactly that\n * and no more: a predicate that demanded the index's own keys would promise more\n * than {@link FreshNavigationBuild} declares, and reject builds the type admits.\n */\nexport const isCachedRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nexport interface CacheStore {\n /**\n * The entry under `key` if the file holds one whose `data` satisfies `isData`,\n * else `null` — the same answer an absent or unparseable file gets, because a\n * record this reader cannot use is not one, however it came to be that way.\n */\n read<T>(key: string, isData: DataPredicate<T>): Promise<CacheEntry<T> | null>;\n write<T = unknown>(\n key: string,\n data: T,\n sourceHash: string,\n sourceFiles?: string[],\n ): Promise<void>;\n /** Get the mtime of a file (for invalidation checks). */\n getFileMtime(filePath: string): Promise<number | null>;\n}\n\n/**\n * The single gate between a cache file's bytes and {@link CacheEntry}.\n *\n * Every declared field is checked, `sourceFiles` included — that one is what\n * `readFreshNavigationBuild` iterates, and it is optional in the type, so\n * \"absent\" and \"present but not a list of strings\" are different answers and\n * only the first is an entry.\n */\nfunction isCacheEntry<T>(value: unknown, isData: DataPredicate<T>): value is CacheEntry<T> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const entry = value as Record<string, unknown>;\n return (\n typeof entry.writtenAt === \"string\" &&\n typeof entry.sourceHash === \"string\" &&\n (entry.sourceFiles === undefined ||\n (Array.isArray(entry.sourceFiles) &&\n entry.sourceFiles.every((f) => typeof f === \"string\"))) &&\n isData(entry.data)\n );\n}\n\nexport function createCacheStore(options: CacheStoreOptions): CacheStore {\n const { cacheDir } = options;\n\n function cacheFilePath(key: string): string {\n return join(cacheDir, `${key}.json`);\n }\n\n async function ensureDir(): Promise<void> {\n await mkdir(cacheDir, { recursive: true });\n }\n\n const store: CacheStore = {\n async read<T>(key: string, isData: DataPredicate<T>): Promise<CacheEntry<T> | null> {\n let parsed: unknown;\n try {\n parsed = JSON.parse(await readFile(cacheFilePath(key), \"utf-8\"));\n } catch {\n return null;\n }\n return isCacheEntry(parsed, isData) ? parsed : null;\n },\n\n async write<T = unknown>(\n key: string,\n data: T,\n sourceHash: string,\n sourceFiles?: string[],\n ): Promise<void> {\n await ensureDir();\n const entry: CacheEntry<T> = {\n data,\n writtenAt: new Date().toISOString(),\n sourceHash,\n ...(sourceFiles ? { sourceFiles } : {}),\n };\n const content = JSON.stringify(entry, null, 2);\n const target = cacheFilePath(key);\n const tmpPath = `${target}.${randomBytes(4).toString(\"hex\")}.tmp`;\n\n // Atomic write: write to temp file then rename\n await writeFile(tmpPath, content, \"utf-8\");\n try {\n await rename(tmpPath, target);\n } catch {\n // Fallback: direct write if rename fails (cross-device)\n await writeFile(target, content, \"utf-8\");\n }\n },\n\n async getFileMtime(filePath: string): Promise<number | null> {\n try {\n const s = await stat(filePath);\n return s.mtimeMs;\n } catch {\n return null;\n }\n },\n };\n\n return store;\n}\n\n/**\n * Compute a simple hash string from an array of file mtimes and content strings.\n * Not cryptographic — used only for cache invalidation.\n */\nexport function computeSourceHash(inputs: Array<string | number>): string {\n return inputs.map(String).join(\":\");\n}\n","/**\n * Is the cached navigation build still the one this project's sources describe?\n *\n * THE freshness predicate — there is deliberately no other. `cache-store` offers\n * no freshness method, and `ensureNavigationIndex` decides whether to rebuild by\n * asking this, so the hooks that READ a build and the builder that WRITES it\n * cannot answer differently about the same files.\n *\n * ITS OWN MODULE, and that is load-bearing rather than tidiness. The bundler\n * layers chunks by MODULE (`layerOnto` in scripts/build-claude-bundles.mjs), so\n * everything in one file lands on one side of the #278 split. Freshness is\n * needed on BOTH sides — by `build-contextpack`, which escalates a stale cache\n * to a rebuild, and by `check-artifact-edit`, which must not judge from one —\n * while the escalation itself (`runEnsureNavigationIndexBin`, a `spawn`) must\n * never be reachable from the PreToolUse guard: that hook fires on every tool\n * call and has no business starting the DSL loader. Splitting the file is what\n * makes \"the guard can ask, and cannot rebuild\" a fact about the chunk graph\n * instead of a convention.\n */\n\nimport { stat } from \"node:fs/promises\";\nimport { createCacheStore, computeSourceHash, isCachedRecord } from \"./cache-store.js\";\nimport { guardrailCacheKey } from \"./ensure-navigation-index-keys.js\";\nimport { isGuardrailRuleData, type GuardrailRuleData } from \"../guardrail-hooks.js\";\n\nexport const DEFAULT_CACHE_KEY = \"navigation-index\";\n\n/**\n * Cache hash for a set of source files: their mtimes, in order.\n *\n * There is no TTL — the index is stale exactly when one of the files it was\n * built from has been touched. Callers must pass the same `sourceFiles` the\n * build used, or the hash will never match.\n */\nexport async function computeCurrentHash(sourceFiles: string[]): Promise<string> {\n const mtimes: Array<string | number> = [];\n for (const file of sourceFiles) {\n try {\n const s = await stat(file);\n mtimes.push(s.mtimeMs);\n } catch {\n // File not found — include a sentinel so hash changes if file appears\n mtimes.push(`missing:${file}`);\n }\n }\n return computeSourceHash(mtimes);\n}\n\n/**\n * What one `ensureNavigationIndex` run produced: the navigation index and the\n * DSL guardrail rules resolved alongside it.\n *\n * Returned together because they were WRITTEN together, under one hash. A\n * caller that could take one without the other would be free to pair a current\n * artifact registry with a superseded rule set.\n */\nexport interface FreshNavigationBuild {\n navigationIndex: Record<string, unknown>;\n guardrailRules: GuardrailRuleData;\n}\n\n/**\n * The cached build if it is still fresh, else undefined. Never builds.\n *\n * The file list the hash is checked against comes from the CACHE ENTRY, not from\n * re-resolving the project manifest. That is what keeps this readable from the\n * lean graph: resolving the list means loading the manifest parser (zod + yaml),\n * which every per-interaction hook would then carry. The builder resolved it\n * already and wrote it down, so the reader just re-stats it.\n *\n * An entry with no recorded list is treated as stale. It was written by an older\n * build, and rebuilding is exactly what upgrades it — the alternative, assuming\n * it is fresh, would pin a stale index forever.\n *\n * FRESH MEANS THE WHOLE BUILD, not just the index. One run writes both entries,\n * so an index sitting next to no companion is the same \"written by an older\n * build\" case and has to be answered the same way. Asking only about the index\n * is not merely incomplete: `ensureNavigationIndex` returns early on this\n * predicate, so it would keep returning the untouched index and the companion\n * the PreToolUse guard reads could never come back (#304).\n */\nexport async function readFreshNavigationBuild(options: {\n cacheDir: string;\n cacheKey?: string;\n}): Promise<FreshNavigationBuild | undefined> {\n const cacheKey = options.cacheKey ?? DEFAULT_CACHE_KEY;\n const store = createCacheStore({ cacheDir: options.cacheDir });\n const entry = await store.read(cacheKey, isCachedRecord);\n if (!entry?.sourceFiles) return undefined;\n const current = await computeCurrentHash(entry.sourceFiles);\n if (current !== entry.sourceHash) return undefined;\n // Written in the same run, from the same hash — no second stat pass needed.\n const companion = await store.read(guardrailCacheKey(cacheKey), isGuardrailRuleData);\n if (companion?.sourceHash !== entry.sourceHash) return undefined;\n return { navigationIndex: entry.data, guardrailRules: companion.data };\n}\n","/**\n * Cache-key helpers shared between the heavy navigation-index warm path\n * (`ensure-navigation-index.ts`) and the lean PreToolUse hot path\n * (`workspace-pre-tool-use.ts`).\n *\n * This module is intentionally dependency-free (no `navigation-context` /\n * `agent-contracts` imports) so it is safe to include in the lean\n * `hooks-lite` entry point without pulling the heavy DSL loader.\n */\n\n/**\n * Cache-key suffix under which a member's DSL guardrail rules are persisted\n * alongside its navigation-index (#238 / C5).\n *\n * The navigation-index cache stays byte-identical to previous versions; the\n * guardrail rules live in a companion entry (e.g.\n * `navigation-index.aaac.guardrails.json`) so the lean PreToolUse hook can\n * read them without importing the heavy `agent-contracts` DSL loader.\n */\nexport const GUARDRAIL_CACHE_SUFFIX = \".guardrails\";\n\n/** Companion cache key for a navigation-index cache key's guardrail rules. */\nexport function guardrailCacheKey(navigationCacheKey: string): string {\n return `${navigationCacheKey}${GUARDRAIL_CACHE_SUFFIX}`;\n}\n","/**\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 { 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 */\nexport function resolvePathToArtifacts(\n filePath: string,\n navigationIndex: Record<string, unknown>,\n): ArtifactMatch[] {\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 * 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 props = match.artifact.properties ?? {};\n\n if (props.authority === \"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 (props.manual_edit === \"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":";;;;;;AAeA,IAAM,kBAAkB,CAAC,gBAAgB,oBAAoB,YAAY;AAyDzE,IAAM,kBAAkB,CAAC,QACvB,IAAI,MAAM,uBAAuB,IAAI,MAAM,GAAG,GAAG,CAAC,EAAE;AAEtD,IAAM,iBAAiB,CAAC,UACtB,UAAU,UAAa,OAAO,UAAU;AAG1C,SAAS,YAAY,OAAyB;AAC5C,MAAI,UAAU,OAAW,QAAO;AAChC,MAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,EAAG,QAAO;AAChF,QAAM,QAAQ;AACd,SACE,eAAe,MAAM,SAAS,KAC9B,eAAe,MAAM,IAAI,KACzB,eAAe,MAAM,OAAO,KAC5B,eAAe,MAAM,OAAO;AAEhC;AAUA,SAAS,YAAY,OAA8E;AACjG,MAAI,CAAC,eAAe,MAAM,UAAU,EAAG,QAAO;AAC9C,UAAQ,MAAM,eAAe;AAAA,IAC3B,KAAK;AACH,aACE,MAAM,SAAS,UACd,OAAO,MAAM,SAAS,YACrB,CAAC,OAAO,UAAU,SAAS,SAAS,EAAE,SAAS,MAAM,IAAI;AAAA,IAE/D,KAAK;AACH,aAAO,eAAe,MAAM,MAAM;AAAA,IACpC,KAAK;AACH,aAAO,eAAe,MAAM,SAAS,KAAK,YAAY,MAAM,UAAU;AAAA,IACxE;AACE,aAAO;AAAA,EACX;AACF;AA2BO,SAAS,eAAe,KAAoC;AACjE,QAAM,S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{"version":3,"sources":["../src/lib/claude-native/pre-tool-use.ts","../src/lib/claude-native/file-suggestion.ts","../src/lib/claude-native/workspace-router.ts","../src/lib/claude-native/workspace-pre-tool-use.ts"],"sourcesContent":["/**\n * PreToolUse Hook Handler — artifact guardrail + DSL guardrail enforcement.\n *\n * Executed before EVERY tool use — `.claude/settings.json` registers this hook\n * with no matcher, so which guard covers a call is decided here. Two guards:\n * 1. the ARTIFACT guard: file path → artifact reverse lookup → deny if protected\n * 2. the DSL GUARDRAIL guard: every rule the project declares — `command_regex`\n * over the command, `file_glob` over the file the call names, `content_regex`\n * over the text it is about to write — through `GuardrailHooks`. This hook is\n * Claude Code's ONLY refusal point, so a rule kind that is not consulted here\n * is a rule kind the session does not enforce (#316).\n *\n * Both read an input the SessionStart / UserPromptSubmit hooks materialize into\n * `.claude/cache/`. An input that is not there is not the same as an input that\n * says nothing — see `unmaterializedGuardReason`.\n *\n * The two guards are independent — `commandGuardCovers` and\n * `artifactGuardTarget` are asked separately, so one payload can answer to\n * both — and the artifact side defaults to COVERED: an enumeration of the tools\n * to guard is an enumeration that goes stale every time Claude Code grows one\n * (#309).\n */\n\nimport {\n createGuardrailHooksFromRules,\n toolWriteTarget,\n type GuardrailRuleData,\n} from \"../guardrail-hooks.js\";\nimport {\n resolvePathToArtifacts,\n isProtectedArtifact,\n} from \"./artifact-resolver.js\";\nimport {\n buildDenyResponse,\n buildAllowResponse,\n type HookOutput,\n type PreToolUseInput,\n} from \"./hook-protocol.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface PreToolUseHandlerConfig {\n /**\n * Navigation index read from the cache, or `undefined` when that cache entry\n * was not there to read. Pass what the read returned — do NOT substitute an\n * empty index, which reads as \"this project protects no artifact\".\n */\n navigationIndex?: Record<string, unknown>;\n /**\n * DSL guardrail rules read from the companion cache entry, or `undefined`\n * when that entry was not there to read. A project with no guardrails still\n * HAS the entry (the builder writes it empty), so `undefined` means the guard\n * has no rules to consult, never that there are none.\n */\n guardrailRules?: GuardrailRuleData;\n}\n\n/**\n * Does the command guard cover this call?\n *\n * A call that carries a `command` is a command about to be executed, whatever\n * the tool is called; `Bash` and `PowerShell` are both built-ins today and a\n * third spelling costs nothing. Reading the payload rather than the tool name\n * is also what `guard evaluate` already does (`guard-commands.ts`), so the CLI\n * evaluator and the hook classify a payload the same way.\n */\nexport function commandGuardCovers(input: PreToolUseInput): boolean {\n return input.tool_input?.command !== undefined;\n}\n\n/**\n * The file the artifact guard must judge for this call, or `\"\"` when there is\n * none — a PreToolUse-payload adapter over `toolWriteTarget`, which is where the\n * answer lives.\n *\n * It lives THERE and not here because the DSL file guardrails ask the identical\n * question, and the moment the two asked it separately they answered\n * differently: the workspace route excused a read-only tool and the\n * single-component route refused the same `Read` (#316). The artifact guard and\n * the `file_glob` guard now cover exactly the same operations because there is\n * one function to change.\n *\n * The two guard CLASSES are still independent, not alternatives. Classifying a\n * call into one of them let a payload carrying both a `command` and a path skip\n * the artifact check entirely; no built-in carries both today, which is exactly\n * the kind of \"no tool does that yet\" that #309 exists to stop relying on.\n */\nexport function artifactGuardTarget(input: PreToolUseInput): string {\n return toolWriteTarget(input.tool_name, input.tool_input);\n}\n\n/** A `.claude/cache/` input the PreToolUse guard cannot reach a verdict without. */\nexport type PreToolUseGuardInput = \"navigation-index\" | \"guardrail-rules\";\n\n/** Which cache entry backs which guard, and what refusing it protects. */\nconst GUARD_INPUT_DESCRIPTION: Record<PreToolUseGuardInput, string> = {\n \"navigation-index\": \"the artifact edit guard\",\n // Every rule kind the DSL declares — command, file and content — comes out of\n // this one entry, so naming only the command half here would tell a refused\n // edit that the guard it tripped is about something else (#316).\n \"guardrail-rules\": \"the DSL guardrails\",\n};\n\n/**\n * Refusal message for a guard with no build it may judge from.\n *\n * This is the #293 rule applied one level further out. There, a guardrail whose\n * policy declares no action denies, because an unknowable verdict must not come\n * out permissive. Here the rules (or the artifact index) cannot be consulted at\n * all, so the verdict is unknowable for the same reason — and the previous\n * behaviour, allowing, is exactly how `git commit --no-verify` ran through\n * Claude Code with the guard saying nothing (#304). Only the operations the\n * missing guard covers are refused; a Read or a Grep is not one of them.\n *\n * ONE state, not two. \"Never materialized\" and \"materialized from sources that\n * have since changed\" differ only in how the cache got that way; both leave the\n * guard unable to answer for the project as it stands NOW, and both are repaired\n * by the same rebuild. Telling them apart here would mean two messages for one\n * decision — and the second one was the silent case: a warm cache whose DSL no\n * longer parses kept the guard judging by rules the project had already stopped\n * declaring, so a newly added rule was simply never enforced (#316).\n *\n * The message names the repair, because the repair is automatic: SessionStart\n * and every UserPromptSubmit run `ensure-navigation-index`, which writes the\n * whole build. Seeing this means that has not happened yet — or cannot, in which\n * case the per-prompt hook is already reporting why on stderr (#310).\n */\nexport function unmaterializedGuardReason(\n input: PreToolUseGuardInput,\n scope?: string,\n): string {\n const where = scope ? ` for ${scope}` : \"\";\n return (\n `[guard-unavailable] ${GUARD_INPUT_DESCRIPTION[input]} cannot run: the ` +\n `\\`${input}\\` cache entry${where} is absent or was built from sources that ` +\n `have since changed, so this operation gets no verdict and is refused rather ` +\n `than judged by superseded rules or silently allowed. ` +\n `Run \\`.claude/bin/ensure-navigation-index\\` (SessionStart and every prompt ` +\n `submission do this automatically — if it keeps failing, that failure is the bug).`\n );\n}\n\n// ---------------------------------------------------------------------------\n// Handler\n// ---------------------------------------------------------------------------\n\n/**\n * Create a PreToolUse hook handler.\n *\n * The caller passes the cache reads verbatim; deciding what an absent read\n * means is this handler's job, not the calling bin's.\n */\nexport function createPreToolUseHandler(config: PreToolUseHandlerConfig) {\n // Pre-compiled once; `null` means the rules were never materialized, which is\n // a refusal below — not a quiet skip of the command guard.\n const guardrailHooks = config.guardrailRules\n ? createGuardrailHooksFromRules(config.guardrailRules)\n : null;\n\n return async function handlePreToolUse(\n input: PreToolUseInput,\n ): Promise<HookOutput> {\n const target = artifactGuardTarget(input);\n\n // The DSL guardrails cover both classes of operation, so a rule set that was\n // never materialized refuses both — not just the command half, which is how\n // `file_glob` rules stayed unenforced with nothing said (#316).\n if (!guardrailHooks && (commandGuardCovers(input) || target)) {\n return buildDenyResponse(unmaterializedGuardReason(\"guardrail-rules\"));\n }\n\n if (guardrailHooks) {\n // --- Shell command: DSL command guardrails ---\n if (commandGuardCovers(input)) {\n const verdict = guardrailHooks.beforeShellExecution({\n command: input.tool_input?.command,\n cwd: input.cwd,\n });\n if (verdict.permission === \"deny\") {\n return buildDenyResponse(verdict.user_message);\n }\n }\n\n // --- DSL file + content guardrails ---\n //\n // The payload goes to the evaluator VERBATIM. It reads the target and the\n // pending content out of the tool input itself and answers `{}` for a call\n // that names no file, so which calls are covered is decided once, there —\n // exactly as `guard evaluate` and the SDK adapter already ask it, which is\n // what keeps the three routes on one verdict.\n const verdict = guardrailHooks.preToolUse({\n tool_name: input.tool_name,\n tool_input: input.tool_input,\n });\n if (verdict.permission === \"deny\") {\n return buildDenyResponse(verdict.user_message);\n }\n }\n\n // --- Candidate file write: artifact protection ---\n if (target) {\n if (!config.navigationIndex) {\n return buildDenyResponse(unmaterializedGuardReason(\"navigation-index\"));\n }\n for (const match of resolvePathToArtifacts(target, config.navigationIndex)) {\n const check = isProtectedArtifact(match);\n if (check.protected) {\n return buildDenyResponse(check.reason);\n }\n }\n }\n\n // --- Default: allow ---\n return buildAllowResponse();\n };\n}\n","/**\n * File Suggestion Handler — artifact-aware @ completion for Claude Code.\n *\n * Reads stdin prefix, filters navigation-index artifacts, and emits NDJSON\n * candidates sorted by relevance score.\n */\n\nimport { listArtifacts, type NavigationArtifact } from \"./artifact-resolver.js\";\nimport { createCacheStore, isCachedRecord } from \"./cache-store.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface FileSuggestionCandidate {\n label: string;\n path: string;\n kind: \"artifact\" | \"file\";\n /** Artifact ID this file/pattern belongs to. */\n artifact?: string;\n /** Authority of the artifact (canonical, generated, etc.). */\n authority?: string;\n /** Manual edit policy for the artifact. */\n manual_edit?: string;\n /** Relevance score (higher = more relevant). */\n score: number;\n}\n\nexport interface FileSuggestionOptions {\n /** The navigation index to search. */\n navigationIndex: Record<string, unknown>;\n /** Maximum number of candidates to return. */\n maxCandidates?: number;\n /**\n * Prefix prepended to every emitted path (#266). Artifact `path_patterns` are\n * project-root relative, so in a workspace — where Claude Code's cwd is the\n * workspace root — a member's candidates must be re-rooted under the member\n * directory. The mirror image of `stripMemberPrefix` on the PreToolUse side.\n */\n pathPrefix?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\nconst DEFAULT_MAX_CANDIDATES = 100;\n\n/**\n * Generate file suggestion candidates from the navigation index.\n * Filters by prefix if provided, then returns NDJSON-formatted candidates.\n */\nexport function generateCandidates(\n prefix: string,\n options: FileSuggestionOptions,\n): FileSuggestionCandidate[] {\n const { navigationIndex, maxCandidates = DEFAULT_MAX_CANDIDATES } = options;\n const artifacts = listArtifacts(navigationIndex);\n const candidates: FileSuggestionCandidate[] = [];\n const lowerPrefix = prefix.toLowerCase();\n const rootPath = (path: string) => joinPathPrefix(options.pathPrefix, path);\n\n for (const { id, artifact } of artifacts) {\n const props = artifact.properties ?? {};\n const patterns = artifact.files?.path_patterns ?? [];\n\n // Artifact-level candidate\n if (!prefix || id.toLowerCase().includes(lowerPrefix)) {\n candidates.push({\n label: id,\n path: rootPath(patterns.length > 0 ? String(patterns[0]) : id),\n kind: \"artifact\",\n authority: props.authority as string | undefined,\n manual_edit: props.manual_edit as string | undefined,\n score: computeArtifactScore(id, artifact, prefix),\n });\n }\n\n // File-level candidates from path patterns\n for (const pattern of patterns) {\n if (typeof pattern !== \"string\") continue;\n // Skip pure glob patterns for file-level suggestions (they're covered by artifact-level)\n if (pattern.includes(\"*\") || pattern.includes(\"?\")) continue;\n\n if (!prefix || pattern.toLowerCase().includes(lowerPrefix)) {\n candidates.push({\n label: pattern,\n path: rootPath(pattern),\n kind: \"file\",\n artifact: id,\n authority: props.authority as string | undefined,\n manual_edit: props.manual_edit as string | undefined,\n score: computeFileScore(pattern, prefix),\n });\n }\n }\n }\n\n // Sort by score descending, then by label\n candidates.sort((a, b) => {\n if (b.score !== a.score) return b.score - a.score;\n return a.label.localeCompare(b.label);\n });\n\n return candidates.slice(0, maxCandidates);\n}\n\n/** Join a member path prefix with a project-relative path. */\nfunction joinPathPrefix(prefix: string | undefined, path: string): string {\n if (!prefix) return path;\n const normalized = prefix.replace(/^\\.\\//, \"\").replace(/\\/+$/, \"\");\n return normalized ? `${normalized}/${path}` : path;\n}\n\n/**\n * Format candidates as NDJSON (one JSON object per line).\n */\nexport function formatNdjson(candidates: FileSuggestionCandidate[]): string {\n return candidates.map((c) => JSON.stringify(c)).join(\"\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Scoring helpers\n// ---------------------------------------------------------------------------\n\nfunction computeArtifactScore(\n id: string,\n artifact: NavigationArtifact,\n prefix: string,\n): number {\n let score = 50;\n const props = artifact.properties ?? {};\n\n // Boost canonical, editable artifacts\n if (props.authority === \"canonical\") score += 20;\n if (props.manual_edit === \"allowed\") score += 10;\n\n // Boost source artifacts\n if (props.type === \"source\") score += 15;\n\n // Penalize generated artifacts\n if (props.authority === \"generated\") score -= 20;\n if (props.manual_edit === \"forbidden\") score -= 10;\n\n // Boost exact prefix match\n if (prefix && id.toLowerCase().startsWith(prefix.toLowerCase())) {\n score += 20;\n }\n\n return score;\n}\n\nfunction computeFileScore(path: string, prefix: string): number {\n let score = 40;\n\n // Boost exact prefix match\n if (prefix && path.toLowerCase().startsWith(prefix.toLowerCase())) {\n score += 30;\n }\n\n // Boost shorter paths (more specific)\n score += Math.max(0, 20 - path.split(\"/\").length * 2);\n\n return score;\n}\n\n/**\n * Main handler for file-suggestion bin script.\n * Reads prefix from stdin, returns NDJSON candidates to stdout.\n */\nexport async function handleFileSuggestion(\n navigationIndex: Record<string, unknown>,\n stdinData: string,\n): Promise<string> {\n const prefix = stdinData.trim();\n const candidates = generateCandidates(prefix, { navigationIndex });\n return formatNdjson(candidates);\n}\n\n/** One workspace member's cached index, as the file-suggestion bin knows it. */\nexport interface WorkspaceFileSuggestionMember {\n /** Member name (for diagnostics only). */\n name: string;\n /** Workspace-relative member path — prepended to every candidate path. */\n memberPath: string;\n /** Cache key of this member's navigation-index. */\n cacheKey: string;\n}\n\n/**\n * Workspace variant (#266): merge candidates from every member's own index.\n *\n * The single-component handler reads the lone `navigation-index` cache entry,\n * which workspace mode never writes (each member has its own key) — so `@`\n * completion returned nothing at all. Members whose index has not been built yet\n * are skipped rather than failing the hook: SessionStart warms them.\n */\nexport async function handleWorkspaceFileSuggestion(\n cacheDir: string,\n members: WorkspaceFileSuggestionMember[],\n stdinData: string,\n maxCandidates = DEFAULT_MAX_CANDIDATES,\n): Promise<string> {\n const prefix = stdinData.trim();\n const store = createCacheStore({ cacheDir });\n const merged: FileSuggestionCandidate[] = [];\n\n for (const member of members) {\n const entry = await store.read(member.cacheKey, isCachedRecord);\n if (!entry) continue;\n merged.push(\n ...generateCandidates(prefix, {\n navigationIndex: entry.data,\n pathPrefix: member.memberPath,\n maxCandidates: Number.POSITIVE_INFINITY,\n }),\n );\n }\n\n merged.sort((a, b) => (b.score !== a.score ? b.score - a.score : a.label.localeCompare(b.label)));\n return formatNdjson(merged.slice(0, maxCandidates));\n}\n","/**\n * Workspace Router — route a file path to the owning workspace member.\n *\n * Pure path-manipulation module. No imports from navigation-context,\n * agent-contracts, or any heavy dependency — safe for the lean hooks-lite\n * entry point.\n *\n * Algorithm: longest-prefix match among member absolute root paths.\n *\n * C4 resolution: stripMemberPrefix converts a workspace-relative path\n * (`aaac/packages/runtime/x.ts`) into a repo-relative path\n * (`packages/runtime/x.ts`) so existing member DSL path_patterns work\n * without modification.\n */\n\nimport { resolve } from \"node:path\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface WorkspaceMember {\n /** Human-readable member name (e.g. `\"aaac\"`). */\n name: string;\n /** Absolute path to the member root directory. */\n root: string;\n}\n\n// ---------------------------------------------------------------------------\n// Router\n// ---------------------------------------------------------------------------\n\n/**\n * Route a file path to the workspace member whose root is the longest\n * matching prefix of that path.\n *\n * Generic over `T extends WorkspaceMember` so callers that pass a richer\n * member type (e.g. `WorkspaceMemberPreToolUseConfig`) get back that type\n * without a cast.\n *\n * @param filePath - Absolute or workspace-root-relative file path (as\n * received from Claude Code's `tool_input.file_path`).\n * @param members - Workspace members with **absolute** root paths.\n * @param workspaceRoot - Absolute path to the workspace root directory.\n * Used to resolve relative `filePath` values.\n * @returns The owning member, or `null` when no member claims this path.\n */\nexport function routePathToMember<T extends WorkspaceMember>(\n filePath: string,\n members: T[],\n workspaceRoot: string,\n): T | null {\n if (!filePath) return null;\n\n // Normalise to absolute path\n const absPath = filePath.startsWith(\"/\")\n ? filePath\n : resolve(workspaceRoot, filePath);\n\n let best: T | null = null;\n let bestPrefixLen = 0;\n\n for (const member of members) {\n const memberRoot = member.root;\n // Ensure the prefix ends with \"/\" so \"aaac-extra\" doesn't match \"aaac\"\n const prefix = memberRoot.endsWith(\"/\") ? memberRoot : memberRoot + \"/\";\n\n if (absPath.startsWith(prefix) && prefix.length > bestPrefixLen) {\n best = member;\n bestPrefixLen = prefix.length;\n }\n }\n\n return best;\n}\n\n/**\n * Strip the member root prefix from `filePath` to obtain a repo-relative\n * path that member DSL `path_patterns` can match against unchanged (C4).\n *\n * Example:\n * filePath = \"aaac/packages/runtime/x.ts\" (workspace-relative)\n * memberRoot = \"/abs/workspace/aaac\"\n * workspaceRoot = \"/abs/workspace\"\n * → returns \"packages/runtime/x.ts\"\n *\n * @param filePath - Absolute or workspace-root-relative path.\n * @param memberRoot - Absolute path to the member root.\n * @param workspaceRoot - Absolute path to the workspace root.\n * @returns Repo-relative path (no leading slash/dot).\n * Falls back to the original `filePath` when stripping is not possible.\n */\nexport function stripMemberPrefix(\n filePath: string,\n memberRoot: string,\n workspaceRoot: string,\n): string {\n const absPath = filePath.startsWith(\"/\")\n ? filePath\n : resolve(workspaceRoot, filePath);\n\n const prefix = memberRoot.endsWith(\"/\") ? memberRoot : memberRoot + \"/\";\n if (absPath.startsWith(prefix)) {\n return absPath.slice(prefix.length);\n }\n\n return filePath;\n}\n","/**\n * Workspace PreToolUse Hook Handler — routes edits to the owning member\n * and enforces that member's artifact guardrails.\n *\n * Hot-path module. Does NOT import navigation-context or agent-contracts —\n * it only reads an already-built navigation index from the cache. Suitable\n * for inclusion in the lean hooks-lite entry point.\n *\n * Flow (per PreToolUse invocation, once `artifactGuardTarget` names a file the\n * file guards have to judge):\n * 1. Extract file path from tool input.\n * 2. Route to owning member via longest-prefix match (workspace-router).\n * 3. Read the member's fresh build — navigation-index + guardrail rules.\n * 4. Strip member-root prefix → repo-relative path (C4 resolution).\n * 5. Apply the member's file + content guardrails to that path.\n * 6. Resolve path to artifacts; deny if protected.\n */\n\nimport {\n createGuardrailHooksFromRules,\n toolPendingContent,\n type GuardrailHooks,\n} from \"../guardrail-hooks.js\";\nimport {\n resolvePathToArtifacts,\n isProtectedArtifact,\n} from \"./artifact-resolver.js\";\nimport {\n readFreshNavigationBuild,\n type FreshNavigationBuild,\n} from \"./navigation-freshness.js\";\nimport {\n buildDenyResponse,\n buildAllowResponse,\n type HookOutput,\n type PreToolUseInput,\n} from \"./hook-protocol.js\";\n// The guard classification and the unavailable-guard refusal come from the\n// single-component handler, which is where both are defined (#304). Two copies\n// would let the workspace route admit what the single-component route refuses;\n// the same direction already carries `renderCandidateArtifacts` from\n// user-prompt-submit.\nimport {\n artifactGuardTarget,\n commandGuardCovers,\n unmaterializedGuardReason,\n} from \"./pre-tool-use.js\";\nimport {\n routePathToMember,\n stripMemberPrefix,\n type WorkspaceMember,\n} from \"./workspace-router.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface WorkspaceMemberPreToolUseConfig extends WorkspaceMember {\n /**\n * Cache key for this member's navigation-index JSON.\n * Format: `navigation-index.<name>` (e.g. `navigation-index.aaac`).\n *\n * The member's DSL guardrail rules live in the companion entry this key\n * implies. There is no override for that: `ensureNavigationIndex` — the only\n * writer — derives the companion key from this one, so a reader free to name\n * a different entry could only ever name one nothing writes (#316).\n */\n cacheKey: string;\n}\n\nexport interface WorkspacePreToolUseConfig {\n /** Absolute path to the workspace root directory. */\n workspaceRoot: string;\n /** Absolute path to the shared `.claude/cache/` directory. */\n cacheDir: string;\n /** Workspace members to route edits to. */\n members: WorkspaceMemberPreToolUseConfig[];\n}\n\n// ---------------------------------------------------------------------------\n// Handler\n// ---------------------------------------------------------------------------\n\n/**\n * Extract path-like tokens from a shell command so a Bash invocation can be\n * routed to the owning workspace member (#238 / C5).\n *\n * Whitespace-split, strips common shell quoting; keeps only tokens that look\n * like paths (contain a `/` or `\\`). This is a best-effort heuristic — command\n * guardrails that fail to route to a specific member fall back to evaluating\n * against every member's rules (safety-preserving union).\n */\nfunction extractCommandPathTokens(command: string): string[] {\n const tokens: string[] = [];\n for (const raw of command.split(/\\s+/)) {\n const t = raw.replace(/^['\"]+|['\"]+$/g, \"\");\n if (t && (t.includes(\"/\") || t.includes(\"\\\\\"))) {\n tokens.push(t);\n }\n }\n return tokens;\n}\n\n/**\n * Create a workspace-aware PreToolUse hook handler.\n *\n * On each invocation both guards are asked — independently, so one payload can\n * answer to both — and the handler:\n * - file guards, over the file `artifactGuardTarget` names:\n * - Routes the target path to the owning member by longest-prefix match.\n * - Reads the member's fresh build (refuses if it has none).\n * - Strips the member-root prefix so the member's `path_patterns` and\n * `file_glob` patterns both receive the repo-relative path they are written\n * against (C4).\n * - Denies a blocking `file_glob` / `content_regex` violation, then denies if\n * any matched artifact is protected (Phase 1).\n * - command guard, when the call carries one (#238 / C5, Phase 3):\n * - Routes the command to the owning member via a path token in the command\n * (longest-prefix match); when no member path is present, evaluates the\n * command against every member's rules so safety guardrails are never\n * silently skipped.\n * - Denies blocking command violations from that member's rules.\n *\n * Artifact protection (Phase 1) and DSL guardrails (Phase 3) are independent and\n * coexist: a member with only artifact rules keeps working unchanged, and a\n * member with only guardrail rules still enforces command and file safety.\n *\n * A member with no usable build refuses the operations its guards cover, rather\n * than admitting them — see `unmaterializedGuardReason`.\n */\nexport function createWorkspacePreToolUseHandler(\n config: WorkspacePreToolUseConfig,\n) {\n /**\n * One member's fresh build plus its compiled hooks, memoised for the life of\n * this hook invocation. `undefined` means the member has no build this guard\n * may judge from — absent, or superseded by an edit to the member's sources.\n *\n * Both entries come from ONE freshness answer. Read separately, a member's\n * artifact registry and its rule set could be paired across two builds.\n */\n const buildByMember = new Map<\n string,\n (FreshNavigationBuild & { hooks: GuardrailHooks }) | undefined\n >();\n\n async function loadMemberBuild(member: WorkspaceMemberPreToolUseConfig) {\n if (buildByMember.has(member.name)) {\n return buildByMember.get(member.name);\n }\n const build = await readFreshNavigationBuild({\n cacheDir: config.cacheDir,\n cacheKey: member.cacheKey,\n });\n // A member that declares no guardrail still HAS a rule set — the builder\n // writes it empty — so an empty one is an answer (\"nothing matches\") and is\n // compiled like any other. Treating empty as \"no hooks\" made the two\n // indistinguishable (#304).\n const loaded = build\n ? { ...build, hooks: createGuardrailHooksFromRules(build.guardrailRules) }\n : undefined;\n buildByMember.set(member.name, loaded);\n return loaded;\n }\n\n /**\n * Route a Bash command to the member(s) whose guardrail rules apply. Returns\n * a single owning member when a member-prefixed path is present in the\n * command; otherwise returns every member (safety-preserving union).\n */\n function membersForCommand(\n command: string,\n ): WorkspaceMemberPreToolUseConfig[] {\n for (const token of extractCommandPathTokens(command)) {\n const owner = routePathToMember(\n token,\n config.members,\n config.workspaceRoot,\n );\n if (owner) return [owner];\n }\n return config.members;\n }\n\n return async function handleWorkspacePreToolUse(\n input: PreToolUseInput,\n ): Promise<HookOutput> {\n // --- Shell command: member-scoped DSL guardrail enforcement (Phase 3 / C5) ---\n if (commandGuardCovers(input)) {\n const command = input.tool_input?.command ?? \"\";\n for (const member of membersForCommand(command)) {\n const build = await loadMemberBuild(member);\n if (!build) {\n return buildDenyResponse(\n unmaterializedGuardReason(\"guardrail-rules\", `member \"${member.name}\"`),\n );\n }\n const verdict = build.hooks.beforeShellExecution({ command, cwd: input.cwd });\n if (verdict.permission === \"deny\") {\n return buildDenyResponse(verdict.user_message);\n }\n }\n }\n\n // The file guards run on the same call, not instead of it: a payload\n // carrying both a command and a path is judged by both.\n const filePath = artifactGuardTarget(input);\n if (!filePath) {\n return buildAllowResponse();\n }\n\n // Step 1: Route to owning member\n const member = routePathToMember(\n filePath,\n config.members,\n config.workspaceRoot,\n );\n if (!member) {\n // Path does not belong to any declared member — allow\n return buildAllowResponse();\n }\n\n // Step 2: Load the member's build — index and rules, one freshness answer\n const build = await loadMemberBuild(member);\n if (!build) {\n return buildDenyResponse(\n unmaterializedGuardReason(\"navigation-index\", `member \"${member.name}\"`),\n );\n }\n\n // Step 3: Strip member-root prefix → repo-relative path (C4)\n const repoRelPath = stripMemberPrefix(\n filePath,\n member.root,\n config.workspaceRoot,\n );\n\n // Step 4: The member's DSL file + content guardrails.\n //\n // Asked through the ALREADY-EXTRACTED gate, not the tool-input one the\n // single-component route uses, because the path this member's `file_glob`\n // patterns are written against is the repo-relative one Step 3 produced —\n // not the workspace-scoped path the tool named. Handing the tool input over\n // instead would make the evaluator re-read that path and judge the wrong\n // string; rewriting the payload would put the \"which key names the file\"\n // decision back in a caller, which is what #309 removed. The verdict is the\n // same one `preToolUse` reaches — one evaluator, two payload shapes.\n const fileVerdict = build.hooks.afterFileEdit({\n file_path: repoRelPath,\n content: toolPendingContent(input.tool_input),\n });\n if (fileVerdict.permission === \"deny\") {\n return buildDenyResponse(fileVerdict.user_message);\n }\n\n // Step 5: Resolve path to artifacts and check protection\n for (const match of resolvePathToArtifacts(repoRelPath, build.navigationIndex)) {\n const check = isProtectedArtifact(match);\n if (check.protected) {\n return buildDenyResponse(check.reason);\n }\n }\n\n return buildAllowResponse();\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAoEO,SAAS,mBAAmB,OAAiC;AAClE,SAAO,MAAM,YAAY,YAAY;AACvC;AAmBO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