@aaac/runtime 0.2.9 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/adapters/adk-sdk.d.ts +1 -1
  2. package/dist/adapters/adk-sdk.js +1 -1
  3. package/dist/adapters/claude-agent-sdk.d.ts +1 -1
  4. package/dist/adapters/claude-agent-sdk.js +5 -4
  5. package/dist/adapters/claude-agent-sdk.js.map +1 -1
  6. package/dist/adapters/openai-agents-sdk.d.ts +1 -1
  7. package/dist/adapters/openai-agents-sdk.js +1 -1
  8. package/dist/{chunk-D2UXESPT.js → chunk-2SG3TBI3.js} +4 -51
  9. package/dist/chunk-2SG3TBI3.js.map +1 -0
  10. package/dist/{chunk-Y7NORFFM.js → chunk-5ZDW4RP7.js} +2 -2
  11. package/dist/{chunk-GWNXNSGL.js → chunk-BHTHXGA3.js} +12 -9
  12. package/dist/chunk-BHTHXGA3.js.map +1 -0
  13. package/dist/{chunk-HR2Q64AO.js → chunk-EA4V5DVD.js} +29 -4
  14. package/dist/chunk-EA4V5DVD.js.map +1 -0
  15. package/dist/chunk-EBMQHLXY.js +61 -0
  16. package/dist/chunk-EBMQHLXY.js.map +1 -0
  17. package/dist/{chunk-QVMLALPF.js → chunk-GGBNVCPV.js} +5 -3
  18. package/dist/{chunk-QVMLALPF.js.map → chunk-GGBNVCPV.js.map} +1 -1
  19. package/dist/{chunk-CJLKKDKN.js → chunk-N2EA3TGS.js} +12 -12
  20. package/dist/{chunk-CJLKKDKN.js.map → chunk-N2EA3TGS.js.map} +1 -1
  21. package/dist/{chunk-MG7WSWJU.js → chunk-RTYJNZGT.js} +1 -1
  22. package/dist/chunk-RTYJNZGT.js.map +1 -0
  23. package/dist/claude-bundles/full.js +148 -148
  24. package/dist/claude-bundles/lean.js +5 -5
  25. package/dist/claude-bundles/prompt.js +2 -2
  26. package/dist/generator/index.d.ts +2 -2
  27. package/dist/generator/index.js +2 -2
  28. package/dist/{guardrail-hooks-B-qe4ebW.d.ts → guardrail-hooks-BgHe8PrP.d.ts} +6 -3
  29. package/dist/{hooks-lite-DvZu9Jhx.d.ts → hooks-lite-BtOGc2F_.d.ts} +12 -1
  30. package/dist/{index-C2DHitGz.d.ts → index-DeZsmlij.d.ts} +4 -1
  31. package/dist/index.d.ts +24 -5
  32. package/dist/index.js +144 -45
  33. package/dist/index.js.map +1 -1
  34. package/dist/lib/claude-native/hooks-lite.d.ts +2 -2
  35. package/dist/lib/claude-native/hooks-lite.js +6 -4
  36. package/dist/lib/claude-native/hooks-prompt.d.ts +3 -3
  37. package/dist/lib/claude-native/hooks-prompt.js +4 -3
  38. package/dist/lib/claude-native/index.d.ts +5 -5
  39. package/dist/lib/claude-native/index.js +11 -9
  40. package/dist/lib/claude-native/index.js.map +1 -1
  41. package/dist/{navigation-context-D1NbiipT.d.ts → navigation-context-DJjCkrcj.d.ts} +1 -1
  42. package/dist/{workspace-user-prompt-submit-aErGPoX4.d.ts → workspace-user-prompt-submit-GZwUKUHi.d.ts} +1 -1
  43. package/package.json +4 -4
  44. package/dist/chunk-D2UXESPT.js.map +0 -1
  45. package/dist/chunk-GWNXNSGL.js.map +0 -1
  46. package/dist/chunk-HR2Q64AO.js.map +0 -1
  47. package/dist/chunk-MG7WSWJU.js.map +0 -1
  48. /package/dist/{chunk-Y7NORFFM.js.map → chunk-5ZDW4RP7.js.map} +0 -0
@@ -1,3 +1,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-CJLKKDKN.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,OAAO,UAAU,UAA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B;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,SAAS,KAAK;AACZ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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.9",
3
+ "version": "0.3.0",
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.9",
72
- "@aaac/observability": "^0.2.9",
73
- "@aaac/toolchain": "^0.2.9",
71
+ "@aaac/contracts": "^0.3.0",
72
+ "@aaac/observability": "^0.3.0",
73
+ "@aaac/toolchain": "^0.3.0",
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/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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;AACjC,UAAI,UAAU,SAAS,QAAQ,GAAG;AAChC,gBAAQ,KAAK,EAAE,YAAY,IAAI,UAAU,gBAAgB,QAAQ,CAAC;AAClE;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;AAKO,SAAS,oBAAoB,OAGlC;AACA,QAAM,QAAQ,MAAM,SAAS,cAAc,CAAC;AAE5C,MAAI,MAAM,cAAc,aAAa;AACnC,UAAM,QAAQ,MAAM,SAAS,QAAQ;AACrC,UAAM,OAAO,QACT,SAAS,KAAK,qBACd;AACJ,WAAO;AAAA,MACL,WAAW;AAAA,MACX,QACE,uCAAuC,MAAM,UAAU,oCACrB,IAAI;AAAA,IAC1C;AAAA,EACF;AAEA,MAAI,MAAM,gBAAgB,aAAa;AACrC,WAAO;AAAA,MACL,WAAW;AAAA,MACX,QACE,6BAA6B,MAAM,UAAU;AAAA,IAEjD;AAAA,EACF;AAEA,SAAO,EAAE,WAAW,OAAO,QAAQ,GAAG;AACxC;AAKO,SAAS,cACd,iBACqD;AACrD,QAAM,YACH,gBAAgB,aAAoD,CAAC;AACxE,SAAO,OAAO,QAAQ,SAAS,EAAE,IAAI,CAAC,CAAC,IAAI,QAAQ,OAAO;AAAA,IACxD;AAAA,IACA;AAAA,EACF,EAAE;AACJ;","names":["stat","stat"]}
@@ -1 +0,0 @@
1
- {"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,SAAS,oBAAoB,OAAgC;AAClE,SAAO,gBAAgB,MAAM,WAAW,MAAM,UAAU;AAC1D;AAMA,IAAM,0BAAgE;AAAA,EACpE,oBAAoB;AAAA;AAAA;AAAA;AAAA,EAIpB,mBAAmB;AACrB;AA0BO,SAAS,0BACd,OACA,OACQ;AACR,QAAM,QAAQ,QAAQ,QAAQ,KAAK,KAAK;AACxC,SACE,uBAAuB,wBAAwB,KAAK,CAAC,sBAChD,KAAK,iBAAiB,KAAK;AAMpC;AAYO,SAAS,wBAAwB,QAAiC;AAGvE,QAAM,iBAAiB,OAAO,iBAC1B,8BAA8B,OAAO,cAAc,IACnD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,QAAI,CAAC,QAAQ;AAEX,aAAO,mBAAmB;AAAA,IAC5B;AAGA,UAAM,QAAQ,MAAM,gBAAgB,MAAM;AAC1C,QAAI,CAAC,OAAO;AACV,aAAO;AAAA,QACL,0BAA0B,oBAAoB,WAAW,OAAO,IAAI,GAAG;AAAA,MACzE;AAAA,IACF;AAGA,UAAM,cAAc;AAAA,MAClB;AAAA,MACA,OAAO;AAAA,MACP,OAAO;AAAA,IACT;AAYA,UAAM,cAAc,MAAM,MAAM,cAAc;AAAA,MAC5C,WAAW;AAAA,MACX,SAAS,mBAAmB,MAAM,UAAU;AAAA,IAC9C,CAAC;AACD,QAAI,YAAY,eAAe,QAAQ;AACrC,aAAO,kBAAkB,YAAY,YAAY;AAAA,IACnD;AAGA,eAAW,SAAS,uBAAuB,aAAa,MAAM,eAAe,GAAG;AAC9E,YAAM,QAAQ,oBAAoB,KAAK;AACvC,UAAI,MAAM,WAAW;AACnB,eAAO,kBAAkB,MAAM,MAAM;AAAA,MACvC;AAAA,IACF;AAEA,WAAO,mBAAmB;AAAA,EAC5B;AACF;","names":["verdict","member","build"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/command-body-files.ts","../src/lib/guardrail-hooks.ts"],"sourcesContent":["/**\n * The text a command guardrail scans for a shell command: the command itself,\n * plus the contents of any message body it passes by file.\n *\n * `gh pr create --body-file body.md`, `gh issue comment -F body.md`,\n * `gh release create --notes-file notes.md` and `git commit -F msg.txt` carry\n * the same text a heredoc would put on the command line. Scanning only the\n * command string let a rule that stops the heredoc form pass the file form.\n *\n * Only a plain path is resolved — bare, or wrapped whole in one pair of quotes.\n * `-` (stdin), a path built from a variable, and anything that is not a regular\n * file (a FIFO would block the hook) are left out, and the command string alone\n * is what gets scanned for them, as before. The file text is joined on a new\n * line, so a pattern's `.` never spans the command and the body, and a pattern\n * anchored at `^` still means the start of the command.\n */\nimport { readFileSync, statSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\n\nconst BODY_FILE_FLAG =\n /(?:^|\\s)(?:--body-file|--notes-file|--file|-F)(?:=|\\s+)(?:'([^']*)'|\"([^\"]*)\"|([^\\s;|&]+))/g;\n\nexport function commandScanText(command: string, cwd?: string): string {\n const bodies: string[] = [];\n for (const match of command.matchAll(BODY_FILE_FLAG)) {\n const path = match[1] ?? match[2] ?? match[3];\n if (!path || path === \"-\") continue;\n const absPath = resolve(cwd ?? process.cwd(), path);\n try {\n if (!statSync(absPath).isFile()) continue;\n bodies.push(readFileSync(absPath, \"utf8\"));\n } catch {\n continue;\n }\n }\n return bodies.length === 0 ? command : [command, ...bodies].join(\"\\n\");\n}\n","/**\n * SDK Guardrail Hook Bridge — generic adapter from guardrail check functions to\n * SDK-compatible hook responses.\n *\n * Embedded guardrail rules are converted via createGuardrailHooksFromRules(),\n * which delegates to createGuardrailHooks(). All hook logic lives here.\n *\n * Every check this module runs arrives as an ARGUMENT. It has no ambient\n * source: it does not know what a plugin is, and it reaches for no registry, so\n * what a route enforces is decided by that route and is readable at its call\n * site. This is also what keeps the module light enough to sit on the lean\n * hot-path graph — see `PluginRegistry.guardrailChecks` for the measurement and\n * for which layer supplies the plugin source.\n */\n\nimport { commandScanText } from \"./command-body-files.js\";\n\n/**\n * Enforcement action of a guardrail.\n *\n * `block` / `warn` / `shadow` / `info` are DECLARED by the active guardrail\n * policy. `unresolved` is not an enforcement level a policy can declare: it is\n * the state of a guardrail that has a binding implementation while the active\n * policy declares no action for it (no `active_guardrail_policy` in the project\n * manifest, an unknown policy name, or a policy with no rule for the guardrail).\n *\n * An unresolved guardrail DENIES — see `getBlockingViolations`. Substituting a\n * permissive default here is what turned every `action: block` guardrail in a\n * policy-less project into a no-op while the guardrail cache still listed it\n * (#293); the action is not knowable, so the operation the guardrail covers is\n * refused and the message says how to fix the manifest.\n *\n * ONE declaration for the set, so the type and the check `isGuardrailRuleData`\n * performs cannot name different ones — a bare union has nothing a predicate\n * can read, and the rules cross a process boundary as JSON.\n */\nexport const GUARDRAIL_ACTIONS = [\n \"block\",\n \"warn\",\n \"shadow\",\n \"info\",\n \"unresolved\",\n] as const;\n\nexport type GuardrailAction = (typeof GUARDRAIL_ACTIONS)[number];\n\n/** The action of a guardrail whose active policy declares none (see GuardrailAction). */\nexport const UNRESOLVED_GUARDRAIL_ACTION = \"unresolved\" as const;\n\nexport interface GuardrailCheckResult {\n guardrail_id: string;\n passed: boolean;\n action: GuardrailAction;\n message: string;\n}\n\n/**\n * What a guardrail hook answers.\n *\n * A refusal CARRIES ITS MESSAGE — one fact, not two independently optional\n * ones. Declared as separate optionals, every consumer had to supply a value\n * for a case no producer can reach (`beforeShellExecution`, `preToolUse` and\n * `afterFileEdit` all refuse through `denyResponse`, which always writes one),\n * and they supplied three different ones: two hand-written copies of \"Command\n * blocked by guardrail\" in the PreToolUse routes and a fall-back to\n * `agent_message` in the SDK adapter (#311). Nothing rejected a fourth, and\n * nothing noticed when one of them drifted, because a string literal that\n * disagrees with another string literal is not a type error.\n *\n * So the union states what the producer already guarantees, and the question\n * disappears instead of being answered in more places.\n */\nexport type HookResponse =\n | {\n permission: \"deny\";\n /** Every blocking violation, rendered. Never empty — a refusal has a cause. */\n user_message: string;\n agent_message: string;\n additionalContext?: undefined;\n }\n | {\n permission?: undefined;\n user_message?: undefined;\n agent_message?: undefined;\n /** Violations to surface to the agent without refusing. */\n additionalContext?: string;\n };\n\nexport interface GuardrailRule {\n guardrail_id: string;\n pattern: string;\n action: GuardrailAction;\n message: string;\n file_glob?: string;\n exclude_glob?: string;\n}\n\nexport interface GuardrailRuleData {\n commandRules: GuardrailRule[];\n fileRules: GuardrailRule[];\n contentRules: GuardrailRule[];\n}\n\nfunction isGuardrailRule(value: unknown): value is GuardrailRule {\n if (typeof value !== \"object\" || value === null) return false;\n const rule = value as Record<string, unknown>;\n return (\n typeof rule.guardrail_id === \"string\" &&\n typeof rule.pattern === \"string\" &&\n GUARDRAIL_ACTIONS.includes(rule.action as GuardrailAction) &&\n typeof rule.message === \"string\" &&\n (rule.file_glob === undefined || typeof rule.file_glob === \"string\") &&\n (rule.exclude_glob === undefined || typeof rule.exclude_glob === \"string\")\n );\n}\n\n/**\n * The single gate in front of {@link GuardrailRuleData}, next to the type it\n * grants — the rules are written to a cache file by one process and read back by\n * another, so the reader has only bytes and this predicate is what turns them\n * into rules the PreToolUse guard may run.\n *\n * Every declared field is checked, `action` against {@link GUARDRAIL_ACTIONS} —\n * the rules decide whether an operation is refused, so a rule carrying an action\n * the evaluator does not implement is not one this guard may run.\n */\nexport function isGuardrailRuleData(value: unknown): value is GuardrailRuleData {\n if (typeof value !== \"object\" || value === null) return false;\n const data = value as Record<string, unknown>;\n return (\n Array.isArray(data.commandRules) &&\n data.commandRules.every(isGuardrailRule) &&\n Array.isArray(data.fileRules) &&\n data.fileRules.every(isGuardrailRule) &&\n Array.isArray(data.contentRules) &&\n data.contentRules.every(isGuardrailRule)\n );\n}\n\nexport interface GuardrailCheckFunctions {\n checkCommand: (command: string) => GuardrailCheckResult[];\n checkFilePath: (filePath: string) => GuardrailCheckResult[];\n checkContent: (filePath: string, content: string) => GuardrailCheckResult[];\n}\n\nfunction globFragmentToRegex(fragment: string): string {\n let out = \"\";\n for (const ch of fragment) {\n if (ch === \"*\") out += \"[^/]*\";\n else if (ch === \"?\") out += \"[^/]\";\n else if (\".+^$|()[]\\\\\".includes(ch)) out += \"\\\\\" + ch;\n else out += ch;\n }\n return out;\n}\n\n/**\n * A pattern ending in `/` denotes a DIRECTORY and matches everything under it\n * (#262). This is the dominant style in artifact `path_patterns` — the embedded\n * dev-team DSL (`src/`, `lib/`, `tests/`, `.cursor/rules/`) and every\n * artifact-contracts registry rely on it. Without this, such a pattern compiles\n * to `^src/$`, which no file path can ever equal, so path → artifact reverse\n * lookup silently matched nothing and the artifact edit guard never fired.\n *\n * The rewrite is monotonic: file paths never end in `/`, so a pattern that\n * matched something before still matches exactly the same paths.\n */\nfunction expandDirectoryPattern(pattern: string): string {\n return pattern.endsWith(\"/\") ? `${pattern}**` : pattern;\n}\n\nexport function matchGlob(rawPattern: string, path: string): boolean {\n const pattern = expandDirectoryPattern(rawPattern);\n let regex = \"\";\n let i = 0;\n while (i < pattern.length) {\n if (pattern[i] === \"*\" && pattern[i + 1] === \"*\" && pattern[i + 2] === \"/\") {\n regex += \"(?:.+/)?\";\n i += 3;\n } else if (pattern[i] === \"*\" && pattern[i + 1] === \"*\") {\n regex += \".*\";\n i += 2;\n } else if (pattern[i] === \"*\") {\n regex += \"[^/]*\";\n i += 1;\n } else if (pattern[i] === \"?\") {\n regex += \"[^/]\";\n i += 1;\n } else if (pattern[i] === \"{\") {\n const end = pattern.indexOf(\"}\", i);\n if (end !== -1) {\n const alts = pattern.slice(i + 1, end).split(\",\").map(globFragmentToRegex);\n regex += \"(?:\" + alts.join(\"|\") + \")\";\n i = end + 1;\n } else {\n regex += \"\\\\{\";\n i += 1;\n }\n } else if (\".+^$|()[]\\\\\".includes(pattern[i])) {\n regex += \"\\\\\" + pattern[i];\n i += 1;\n } else {\n regex += pattern[i];\n i += 1;\n }\n }\n return new RegExp(\"^\" + regex + \"$\").test(path);\n}\n\n/**\n * Does this tool-input key name a file the call acts on?\n *\n * Derived from the naming convention rather than from a census of today's\n * tools. `NotebookEdit` calls its target `notebook_path`, so a reader that knew\n * only `file_path`/`path` classified that call correctly and then judged\n * nothing — the artifact guard was reached and found no path to protect (#309).\n * Every such key so far ends in `path`, so the rule follows the suffix and the\n * next tool to name an `output_path` is already covered.\n *\n * `file` / `filename` carry no suffix; they are the SDK progress-event\n * spellings the task runner reads, and are named for that reason.\n */\nfunction namesTargetFile(key: string): boolean {\n return (\n key === \"path\" || key === \"file\" || key === \"filename\" || key.endsWith(\"_path\")\n );\n}\n\n/**\n * Does this tool-input key carry text the call is about to WRITE?\n *\n * The same convention rule as `namesTargetFile`, over the other half of a file\n * edit. `Write` calls it `content`; `Edit` and `NotebookEdit` prefix the value\n * they are installing with `new_` (`new_string`, `new_source`), so the rule\n * follows the prefix and a tool that arrives naming a `new_text` is covered.\n *\n * The exclusions are the point. `old_string` is the text being REMOVED, and\n * scanning it would refuse the very edit that takes a forbidden string OUT of a\n * file — a content guardrail that fights its own repair. `file_path` and the\n * `cell_id` / `edit_mode` sort of parameter are neither. So \"everything the\n * payload happens to hold\" is not an available answer; the key has to say it is\n * the incoming value.\n */\nfunction namesPendingContent(key: string): boolean {\n return key === \"content\" || key.startsWith(\"new_\");\n}\n\n/**\n * The first non-empty string value under a key `names` accepts, or `\"\"`.\n *\n * Keys are scanned in sorted order, so the answer cannot depend on the order a\n * payload happened to serialize its properties in.\n *\n * Reads TOP-LEVEL string values only, and returns the first match: a payload\n * carrying its files in an array (`file_paths`) or nested (`edits[].new_string`)\n * is not covered, and no built-in has that shape today (#309).\n */\nfunction firstStringValue(\n toolInput: Record<string, unknown> | undefined | null,\n names: (key: string) => boolean,\n): string {\n if (!toolInput) return \"\";\n for (const key of Object.keys(toolInput).sort()) {\n if (!names(key)) continue;\n const value = toolInput[key];\n if (typeof value === \"string\" && value) return value;\n }\n return \"\";\n}\n\n/**\n * The file a tool call names as its target, or `\"\"` when it names none.\n *\n * ONE reader for every consumer that asks \"which file is this call about\": the\n * `preToolUse` file guardrails below, both Claude Code PreToolUse routes, the\n * `guard evaluate` CLI, the Claude SDK adapter and the task runner's\n * `process.edit` events. They had four spellings of it between them, agreeing\n * on `file_path` and diverging after — and a reader that knows fewer keys than\n * the tool writes turns a guard that runs into a guard that decides nothing.\n *\n * Scope is a TOOL INPUT. The after-file-edit payloads (`afterFileEdit` here,\n * the Cursor hook input in `guard-commands`) are not tool inputs: their\n * `file_path` is a top-level protocol field and is the whole interface.\n */\nexport function toolTargetPath(\n toolInput: Record<string, unknown> | undefined | null,\n): string {\n return firstStringValue(toolInput, namesTargetFile);\n}\n\n/**\n * Claude Code tools that cannot modify a file in the working tree — the ONLY\n * calls a `file_glob` / `content_regex` guardrail lets past unexamined.\n *\n * This list is inverted on purpose. Naming the tools to guard (`Edit`, `Write`,\n * `MultiEdit`) meant the guard covered exactly the tools that existed when it\n * was written, and `NotebookEdit` — a first-party file editor — walked through\n * a `manual_edit: forbidden` artifact for as long as it has existed (#309).\n * Every future tool would have arrived the same way, silently, because a name\n * that is missing from an allowlist looks identical to a name that is absent\n * for a reason.\n *\n * Naming the tools NOT to guard puts the staleness on the harmless side. An\n * unrecognised tool is judged instead of waved through, and being judged costs\n * it nothing unless it names a covered file: `toolTargetPath` reads the file out\n * of the call, so a tool that targets no file resolves to nothing and is\n * allowed. \"Deny by default\" here therefore means \"examined by default\", not\n * \"refused by default\" — a new Claude Code release does not lock the session\n * down.\n *\n * Every name is a Claude Code built-in, pinned against an independent\n * transcription of the tool reference in `__tests__/fixtures/`.\n */\nexport const NON_MUTATING_TOOLS: ReadonlySet<string> = new Set([\n // Name a path in their input and only ever read it.\n \"Read\",\n \"Glob\",\n \"Grep\",\n \"LSP\",\n // Load or delegate: whatever they set in motion arrives at the same guard as\n // its own tool call, and is guarded there.\n \"Task\",\n \"Agent\",\n \"Skill\",\n // Reach outside the working tree entirely.\n \"WebFetch\",\n \"WebSearch\",\n // Session-local state rather than files.\n \"TodoWrite\",\n \"AskUserQuestion\",\n \"ToolSearch\",\n \"EnterPlanMode\",\n \"ExitPlanMode\",\n]);\n\n/**\n * The file this call may WRITE, or `\"\"` when there is none.\n *\n * ONE answer to \"which operations do the file guards cover\", for every route:\n * the `preToolUse` gate below, both Claude Code PreToolUse routes (through\n * `artifactGuardTarget`), the `guard evaluate` CLI and the Claude SDK adapter.\n *\n * `file_glob` and `content_regex` guard WRITES. That is not a reading of what\n * the matcher could mean — it is what every rule declared against it says:\n * across `agents/bindings/runtime.yaml`, `examples/governance/bindings/runtime.yaml`\n * and the bindings `aaac init` bootstraps a new project with, all 19 messages\n * are \"Writing to … is blocked\", \"Generated files must not be hand-edited\" or\n * \"Do not write … at repo root\". None is about reading one. So a guard that\n * refused `Read` would refuse an operation no rule in this repo asks it to, and\n * `protect-generated-files` — `action: block` under the default policy — would\n * stop an agent reading the generated code it has to read to work.\n *\n * Answering it HERE rather than in the hook is what keeps the routes on one\n * verdict. Answered per-consumer, it went two ways immediately: the workspace\n * PreToolUse route filtered by this set and the single-component one did not, so\n * the same `Read secrets/prod.env` was allowed by one and refused by the other\n * (#316).\n */\nexport function toolWriteTarget(\n toolName: string | undefined,\n toolInput: Record<string, unknown> | undefined | null,\n): string {\n if (NON_MUTATING_TOOLS.has(toolName ?? \"\")) return \"\";\n return toolTargetPath(toolInput);\n}\n\n/**\n * The text a tool call is about to write into `toolTargetPath`, or `\"\"`.\n *\n * The companion reader, and the reason `content_regex` guardrails are decided\n * BEFORE the write rather than reported after it. Claude Code hands PreToolUse\n * the tool's parameters in full, so the pending content is already in the\n * payload; the only event that could carry it afterwards is PostToolUse, whose\n * `block` cannot un-write the file and would answer the same declared\n * `action: block` differently from every other route (#316).\n */\nexport function toolPendingContent(\n toolInput: Record<string, unknown> | undefined | null,\n): string {\n return firstStringValue(toolInput, namesPendingContent);\n}\n\n/**\n * What one check is asked about: a command, a path, or a path and the content\n * about to go into it. Nothing here names an AGENT.\n *\n * Which rules an agent is checked against is settled before an evaluator\n * exists, by the layer that knows where rules come from — see\n * `createAgentGuardrailHooks` in `execute.ts`, the one constructor of per-agent\n * hooks. An agent id travelling inside the context would mean that same\n * question could also be answered later, from in here, and it did: a second\n * per-agent constructor exported beside that one wrote `agentId` on every\n * context it forwarded, no gate read it, and the two disagreed on memoisation\n * and on what an agent with no rules gets (#333).\n *\n * So the field is gone, and an OBJECT LITERAL naming an agent is now TS2353 —\n * which is what makes that constructor un-pasteable verbatim.\n * `adapter-guardrail-hooks.test.ts` pins the absence with a `@ts-expect-error`\n * that turns into TS2578 if the field returns.\n *\n * That is the whole of what the type says, and it is less than it sounds.\n * Excess-property checking reaches object literals only: an `as HookContext`\n * cast, an interface that extends this one, a literal bound to a variable\n * first, and a plain `Record<string, unknown>` all compile — measured, not\n * assumed. And a second per-agent constructor that simply never writes an agent\n * id needs none of them and compiles as it is. What is removed here is the\n * AFFORDANCE the duplicate happened to use, not the possibility of another one.\n * The invariant — ONE constructor of per-agent hooks — is held by the\n * declaration on `createAgentGuardrailHooks` and by reading it, and nothing\n * mechanical will fail if it is broken.\n */\nexport interface HookContext {\n command?: string;\n filePath?: string;\n content?: string;\n}\n\n/**\n * The guardrail gates, one per payload SHAPE — not one per rule kind.\n *\n * Which gate a caller picks is decided by what it holds, never by which rules\n * it wants consulted: every gate runs every rule the context can answer. An\n * object with four methods hid the opposite for as long as this existed — the\n * Claude Code PreToolUse route called `beforeShellExecution` and nothing else,\n * so a project's `file_glob` and `content_regex` guardrails were enforced by\n * `guard evaluate` and by the SDK adapter while the session a person actually\n * works in never consulted them, and no type or single-route test could say so\n * (#316).\n */\n/**\n * A shell command about to run, and the directory it runs in — which resolves a\n * message body the command passes by file (`commandScanText`). Without `cwd`\n * the hook process's own directory is used.\n */\nexport interface ShellCommandInput {\n command?: string;\n cwd?: string;\n}\n\nexport interface GuardrailHooks {\n /** A command about to run. Claude Code PreToolUse (both routes), `guard evaluate`. */\n beforeShellExecution: (input: ShellCommandInput) => HookResponse;\n /**\n * The checks {@link GuardrailHooks.beforeShellExecution} decides on — the\n * command plus any body it passes by file. `guard evaluate` reports these, so\n * the list it prints is the one its verdict came from.\n */\n checkShellCommand: (input: ShellCommandInput) => GuardrailCheckResult[];\n /**\n * A TOOL INPUT, verbatim: `toolTargetPath` reads the file out of it and\n * `toolPendingContent` the text about to go in. The single-component Claude\n * Code PreToolUse route, `guard evaluate` and the Claude SDK adapter.\n */\n preToolUse: (input: {\n tool_name?: string;\n tool_input?: Record<string, unknown>;\n }) => HookResponse;\n /**\n * A file write whose path and content the caller has ALREADY extracted —\n * Cursor's after-file-edit event, where both are top-level protocol fields,\n * and the workspace Claude Code PreToolUse route, which must ask about the\n * member-repo-relative path (`stripMemberPrefix`) rather than the one the\n * tool named, because member guardrail patterns are written in that space.\n */\n afterFileEdit: (input: { file_path?: string; content?: string }) => HookResponse;\n /** The shared check runner. Not a gate: `getBlockingViolations` is what refuses. */\n runChecks: (ctx: HookContext) => GuardrailCheckResult[];\n}\n\n/**\n * Does this action refuse the operation? `block` because the policy says so,\n * `unresolved` because the policy says nothing and a guardrail whose action is\n * unknown must not be permissive (#293). Single definition — every deny gate\n * (shell / pre-tool-use / after-file-edit hooks, `guard evaluate`'s exit code,\n * the OpenAI Agents SDK tripwire) reads it through `getBlockingViolations`.\n */\nfunction isDenyAction(action: GuardrailAction): boolean {\n return action === \"block\" || action === UNRESOLVED_GUARDRAIL_ACTION;\n}\n\nexport function getBlockingViolations(results: GuardrailCheckResult[]): GuardrailCheckResult[] {\n return results.filter((r) => !r.passed && isDenyAction(r.action));\n}\n\nexport function getWarnings(results: GuardrailCheckResult[]): GuardrailCheckResult[] {\n return results.filter((r) => !r.passed && r.action === \"warn\");\n}\n\nexport function hasBlockingViolation(results: GuardrailCheckResult[]): boolean {\n return getBlockingViolations(results).length > 0;\n}\n\n/**\n * How a guardrail violation reads: `[guardrail-id] message`, one per line.\n *\n * Single definition — the shell, pre-tool-use and after-file-edit hooks all\n * refuse in the same words, a warning reads the same as the refusal it would\n * have been under a stricter policy, and the ADK adapter throws the same text\n * where it has no hook response to return. Exported for that last one only:\n * not re-exported from the package barrel, because no consumer outside this\n * runtime renders a violation.\n */\nexport function renderViolations(results: GuardrailCheckResult[]): string {\n return results.map((r) => `[${r.guardrail_id}] ${r.message}`).join(\"\\n\");\n}\n\n/**\n * The refusal every guardrail hook returns.\n *\n * The message is written HERE, once, rather than at each of the three hooks —\n * that is what makes `HookResponse`'s \"a denial carries its message\" a fact\n * about the code and not a convention. `user_message` and `agent_message` are\n * the same text on purpose: the agent is told exactly what the user is told.\n */\nfunction denyResponse(blocks: GuardrailCheckResult[]): HookResponse {\n const message = renderViolations(blocks);\n return { permission: \"deny\", user_message: message, agent_message: message };\n}\n\n/**\n * Create SDK hook functions from guardrail check functions.\n *\n * Returns hook functions in the format expected by the Claude SDK, plus a\n * generic runChecks() for programmatic use.\n *\n * Takes any number of check SOURCES and asks every one of them every question\n * the context can answer — which is the same rule `GuardrailHooks` states about\n * its gates, one level down. A source is not a rule kind and not a route: it is\n * one supplier of checks, and the hooks it produces cannot tell which supplier a\n * verdict came from. That is what lets a second supplier be added (the execution\n * layer adds the process's plugin guardrails, see\n * `PluginRegistry.guardrailChecks`) without there being a second EVALUATOR —\n * the property #304 and #316 exist to hold.\n *\n * Ordering is by question, then by source, so the sources a caller lists are\n * consulted in the order it listed them and a refusal reads the same way every\n * time (`renderViolations` joins in result order).\n *\n * Zero sources is a legitimate answer, not a degenerate one: it is what an agent\n * with no resolved rules and no plugins has, and the hooks it gets deny nothing.\n */\nexport function createGuardrailHooks(...sources: GuardrailCheckFunctions[]): GuardrailHooks {\n function runChecks(ctx: HookContext): GuardrailCheckResult[] {\n const results: GuardrailCheckResult[] = [];\n\n if (ctx.command) {\n for (const source of sources) results.push(...source.checkCommand(ctx.command));\n }\n\n if (ctx.filePath) {\n for (const source of sources) results.push(...source.checkFilePath(ctx.filePath));\n }\n\n if (ctx.filePath && ctx.content) {\n for (const source of sources) {\n results.push(...source.checkContent(ctx.filePath, ctx.content));\n }\n }\n\n return results;\n }\n\n function checkShellCommand(input: ShellCommandInput): GuardrailCheckResult[] {\n const command = input.command ?? \"\";\n if (!command) return [];\n return runChecks({ command: commandScanText(command, input.cwd) });\n }\n\n function beforeShellExecution(input: ShellCommandInput): HookResponse {\n const results = checkShellCommand(input);\n if (results.length === 0) return {};\n const blocks = getBlockingViolations(results);\n const warns = getWarnings(results);\n\n if (blocks.length > 0) {\n return denyResponse(blocks);\n }\n\n if (warns.length > 0) {\n return { additionalContext: renderViolations(warns) };\n }\n\n return {};\n }\n\n /**\n * The verdict on one file write — the ONE gate behind both file-shaped hooks\n * below, so `file_glob` and `content_regex` are decided together and cannot\n * be decided differently depending on which payload shape arrived.\n *\n * They diverged before: `preToolUse` asked `runChecks({ filePath })` and so\n * consulted `checkFilePath` alone, while `afterFileEdit` asked with the\n * content and got both. The rules a project declares are the same rules\n * either way (#316).\n */\n function fileWriteVerdict(filePath: string, content: string): HookResponse {\n if (!filePath) return {};\n\n const blocks = getBlockingViolations(runChecks({ filePath, content }));\n return blocks.length > 0 ? denyResponse(blocks) : {};\n }\n\n function preToolUse(input: {\n tool_name?: string;\n tool_input?: Record<string, unknown>;\n }): HookResponse {\n return fileWriteVerdict(\n toolWriteTarget(input.tool_name, input.tool_input),\n toolPendingContent(input.tool_input),\n );\n }\n\n function afterFileEdit(input: { file_path?: string; content?: string }): HookResponse {\n return fileWriteVerdict(input.file_path ?? \"\", input.content ?? \"\");\n }\n\n return { beforeShellExecution, checkShellCommand, preToolUse, afterFileEdit, runChecks };\n}\n\n/** Compile a guardrail regex pattern, supporting inline `(?i)` case-insensitivity prefix. */\nexport function compileGuardrailPattern(pattern: string): RegExp {\n if (pattern.startsWith(\"(?i)\")) {\n return new RegExp(pattern.slice(4), \"i\");\n }\n return new RegExp(pattern);\n}\n\n/**\n * Create SDK hook functions from embedded guardrail rule data.\n *\n * The rules are the first check source; `extraSources` are consulted after\n * them, on every question. This is the funnel every route reaches the evaluator\n * through — both Claude Code PreToolUse routes, `guard evaluate` and the\n * execution layer — so what distinguishes those routes is visible here as an\n * argument list and nowhere else.\n */\nexport function createGuardrailHooksFromRules(\n rules: GuardrailRuleData,\n ...extraSources: GuardrailCheckFunctions[]\n): GuardrailHooks {\n const commandChecks = rules.commandRules.map((rule) => ({\n guardrail_id: rule.guardrail_id,\n pattern: compileGuardrailPattern(rule.pattern),\n action: rule.action,\n message: rule.message,\n }));\n\n const fileChecks = rules.fileRules;\n\n const contentChecks = rules.contentRules.map((rule) => ({\n guardrail_id: rule.guardrail_id,\n pattern: compileGuardrailPattern(rule.pattern),\n action: rule.action,\n message: rule.message,\n file_glob: rule.file_glob,\n exclude_glob: rule.exclude_glob,\n }));\n\n return createGuardrailHooks({\n checkCommand(command: string): GuardrailCheckResult[] {\n const results: GuardrailCheckResult[] = [];\n for (const check of commandChecks) {\n const passed = !check.pattern.test(command);\n results.push({\n guardrail_id: check.guardrail_id,\n passed,\n action: check.action,\n message: passed ? \"\" : check.message,\n });\n }\n return results;\n },\n\n checkFilePath(filePath: string): GuardrailCheckResult[] {\n const results: GuardrailCheckResult[] = [];\n for (const check of fileChecks) {\n if (check.exclude_glob && matchGlob(check.exclude_glob, filePath)) {\n continue;\n }\n const matched = matchGlob(check.pattern, filePath);\n results.push({\n guardrail_id: check.guardrail_id,\n passed: !matched,\n action: check.action,\n message: matched ? check.message : \"\",\n });\n }\n return results;\n },\n\n checkContent(filePath: string, content: string): GuardrailCheckResult[] {\n const results: GuardrailCheckResult[] = [];\n for (const check of contentChecks) {\n if (check.file_glob && !matchGlob(check.file_glob, filePath)) {\n continue;\n }\n if (check.exclude_glob && matchGlob(check.exclude_glob, filePath)) {\n continue;\n }\n const matched = check.pattern.test(content);\n results.push({\n guardrail_id: check.guardrail_id,\n passed: !matched,\n action: check.action,\n message: matched ? check.message : \"\",\n });\n }\n return results;\n },\n }, ...extraSources);\n}\n"],"mappings":";AAgBA,SAAS,cAAc,gBAAgB;AACvC,SAAS,eAAe;AAExB,IAAM,iBACJ;AAEK,SAAS,gBAAgB,SAAiB,KAAsB;AACrE,QAAM,SAAmB,CAAC;AAC1B,aAAW,SAAS,QAAQ,SAAS,cAAc,GAAG;AACpD,UAAM,OAAO,MAAM,CAAC,KAAK,MAAM,CAAC,KAAK,MAAM,CAAC;AAC5C,QAAI,CAAC,QAAQ,SAAS,IAAK;AAC3B,UAAM,UAAU,QAAQ,OAAO,QAAQ,IAAI,GAAG,IAAI;AAClD,QAAI;AACF,UAAI,CAAC,SAAS,OAAO,EAAE,OAAO,EAAG;AACjC,aAAO,KAAK,aAAa,SAAS,MAAM,CAAC;AAAA,IAC3C,QAAQ;AACN;AAAA,IACF;AAAA,EACF;AACA,SAAO,OAAO,WAAW,IAAI,UAAU,CAAC,SAAS,GAAG,MAAM,EAAE,KAAK,IAAI;AACvE;;;ACAO,IAAM,oBAAoB;AAAA,EAC/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SAAS,QAAQ;AACjD,gBAAQ,KAAK;AAAA,UACX,cAAc,MAAM;AAAA,UACpB,QAAQ,CAAC;AAAA,UACT,QAAQ,MAAM;AAAA,UACd,SAAS,UAAU,MAAM,UAAU;AAAA,QACrC,CAAC;AAAA,MACH;AACA,aAAO;AAAA,IACT;AAAA,IAEA,aAAa,UAAkB,SAAyC;AACtE,YAAM,UAAkC,CAAC;AACzC,iBAAW,SAAS,eAAe;AACjC,YAAI,MAAM,aAAa,CAAC,UAAU,MAAM,WAAW,QAAQ,GAAG;AAC5D;AAAA,QACF;AACA,YAAI,MAAM,gBAAgB,UAAU,MAAM,cAAc,QAAQ,GAAG;AACjE;AAAA,QACF;AACA,cAAM,UAAU,MAAM,QAAQ,KAAK,OAAO;AAC1C,gBAAQ,KAAK;AAAA,UACX,cAAc,MAAM;AAAA,UACpB,QAAQ,CAAC;AAAA,UACT,QAAQ,MAAM;AAAA,UACd,SAAS,UAAU,MAAM,UAAU;AAAA,QACrC,CAAC;AAAA,MACH;AACA,aAAO;AAAA,IACT;AAAA,EACF,GAAG,GAAG,YAAY;AACpB;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/adapter-error.ts","../src/lib/claude-tool-grants.ts"],"sourcesContent":["/**\n * AdapterError — an SDK adapter call that failed, with what kind of failure it was.\n *\n * Callers decide what to do from `kind` (log in again, wait for the usage\n * limit, report a timeout) instead of reading the provider's message text.\n */\n\n/**\n * - `authentication`: the credentials were rejected (expired login, invalid key)\n * - `rate_limit`: a usage or rate limit was reached\n * - `aborted`: the caller's AbortSignal stopped the call\n * - `other`: any other failure\n */\nexport type AdapterErrorKind = \"authentication\" | \"rate_limit\" | \"aborted\" | \"other\";\n\nexport class AdapterError extends Error {\n readonly kind: AdapterErrorKind;\n\n constructor(kind: AdapterErrorKind, message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = \"AdapterError\";\n this.kind = kind;\n }\n}\n\n/** The kind of an error thrown by an adapter call; anything not an AdapterError is `other` */\nexport function adapterErrorKind(error: unknown): AdapterErrorKind {\n return error instanceof AdapterError ? error.kind : \"other\";\n}\n","/**\n * Claude Code built-in tool grant per agent `mode`.\n *\n * ONE definition of \"which Claude Code tools does a `read-only` / `read-write`\n * agent get\". Two consumers, one rule:\n *\n * - in-process: `task-runner.ts` derives `readonly` from `agentContract.mode`\n * and the Claude adapter turns it into the SDK `tools` option.\n * - on-disk: `claude-materialize/agent-render.ts` writes the same names\n * into the `tools:` frontmatter of a materialized `.claude/agents/*.md`\n * subagent (#272).\n *\n * Both must agree — a subagent that Claude Code launches from disk and the same\n * agent delegated to in-process are the same agent, so a divergent tool grant\n * would mean the DSL's `mode` means two different things.\n *\n * `mode` normalization itself lives in `dsl-context.ts` (`buildAgentRegistry`)\n * and is fail-safe: anything that is not exactly `read-write` becomes\n * `read-only`, so an unrecognized mode can never widen the grant.\n */\n\n/** Tools a `read-only` agent may use: inspection + command execution, no writes. */\nexport const READ_ONLY_TOOL_GRANT: readonly string[] = [\"Read\", \"Glob\", \"Grep\", \"Bash\"];\n\n/** Tools a `read-write` agent may use: the read-only set plus the write tools. */\nexport const READ_WRITE_TOOL_GRANT: readonly string[] = [\n \"Read\",\n \"Glob\",\n \"Grep\",\n \"Edit\",\n \"Write\",\n \"Bash\",\n];\n\n/** The Claude Code tool names that mutate the working tree. */\nexport const WRITE_TOOL_NAMES: readonly string[] = READ_WRITE_TOOL_GRANT.filter(\n (t) => !READ_ONLY_TOOL_GRANT.includes(t),\n);\n\n/** Claude Code tool grant for an agent mode. */\nexport function toolGrantForMode(mode: \"read-write\" | \"read-only\"): readonly string[] {\n return mode === \"read-write\" ? READ_WRITE_TOOL_GRANT : READ_ONLY_TOOL_GRANT;\n}\n\n/**\n * The sub-agent delegation tool, canonical spelling. An agent that declares\n * `can_invoke_agents` cannot delegate without it, because neither mode grant\n * includes it. Listing it in a subagent's `tools:` is also what lets that\n * subagent spawn subagents of its own.\n *\n * Claude Code renamed `Task` to `Agent` in 2.1.63; the SDK likewise documents\n * \"a custom subagent that can be invoked via the Agent tool\"\n * (`@anthropic-ai/claude-agent-sdk` sdk.d.ts:36).\n */\nexport const DELEGATION_TOOL_NAME = \"Agent\";\n\n/** Pre-2.1.63 spelling. Claude Code still resolves it as an alias. */\nexport const DELEGATION_TOOL_LEGACY_NAME = \"Task\";\n\n/**\n * Both delegation spellings, granted everywhere.\n *\n * `Agent` does not resolve before Claude Code 2.1.63 and `Task` is the alias\n * that does, so granting only one silently costs the agent its ability to\n * delegate on some installed versions. Granting both is free: a `tools:` list —\n * in a subagent file exactly as in the SDK `tools` option — is an **allowlist**\n * resolved against the available tool pool, and an entry that does not resolve\n * is simply not granted. Only a list where NOTHING resolves fails the launch.\n */\nexport const DELEGATION_TOOL_NAMES: readonly string[] = [\n DELEGATION_TOOL_LEGACY_NAME,\n DELEGATION_TOOL_NAME,\n];\n\n/**\n * The Claude Code tool grant for one agent: its mode grant, plus the delegation\n * tool when the DSL says it may invoke other agents.\n *\n * This is the grant an agent gets wherever it runs — the same rule the adapter\n * applies in-process — so a DSL agent does not gain or lose the ability to\n * delegate depending on whether Claude Code launched it from\n * `.claude/agents/<id>.md` or the runtime registered it as a candidate.\n */\nexport function toolGrantForAgent(agent: {\n mode: \"read-write\" | \"read-only\";\n can_invoke_agents?: readonly string[];\n}): readonly string[] {\n const grant = [...toolGrantForMode(agent.mode)];\n if (agent.can_invoke_agents && agent.can_invoke_agents.length > 0) {\n grant.push(...DELEGATION_TOOL_NAMES);\n }\n return grant;\n}\n"],"mappings":";AAeO,IAAM,eAAN,cAA2B,MAAM;AAAA,EAC7B;AAAA,EAET,YAAY,MAAwB,SAAiB,SAA+B;AAClF,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AAGO,SAAS,iBAAiB,OAAkC;AACjE,SAAO,iBAAiB,eAAe,MAAM,OAAO;AACtD;;;ACNO,IAAM,uBAA0C,CAAC,QAAQ,QAAQ,QAAQ,MAAM;AAG/E,IAAM,wBAA2C;AAAA,EACtD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAGO,IAAM,mBAAsC,sBAAsB;AAAA,EACvE,CAAC,MAAM,CAAC,qBAAqB,SAAS,CAAC;AACzC;AAGO,SAAS,iBAAiB,MAAqD;AACpF,SAAO,SAAS,eAAe,wBAAwB;AACzD;AAYO,IAAM,uBAAuB;AAG7B,IAAM,8BAA8B;AAYpC,IAAM,wBAA2C;AAAA,EACtD;AAAA,EACA;AACF;AAWO,SAAS,kBAAkB,OAGZ;AACpB,QAAM,QAAQ,CAAC,GAAG,iBAAiB,MAAM,IAAI,CAAC;AAC9C,MAAI,MAAM,qBAAqB,MAAM,kBAAkB,SAAS,GAAG;AACjE,UAAM,KAAK,GAAG,qBAAqB;AAAA,EACrC;AACA,SAAO;AACT;","names":[]}