@aaac/runtime 0.1.53 → 0.1.54

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 (36) 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/mock.d.ts +1 -1
  5. package/dist/adapters/openai-agents-sdk.d.ts +1 -1
  6. package/dist/{chunk-YZQRSVDZ.js → chunk-3H3PVPPF.js} +198 -4
  7. package/dist/chunk-3H3PVPPF.js.map +1 -0
  8. package/dist/chunk-LDCQZPDG.js +11 -0
  9. package/dist/chunk-LDCQZPDG.js.map +1 -0
  10. package/dist/{chunk-M3GJAHLX.js → chunk-N4KNGDYY.js} +343 -28
  11. package/dist/chunk-N4KNGDYY.js.map +1 -0
  12. package/dist/{chunk-EH5VFZYJ.js → chunk-NMX4C6LC.js} +6 -2
  13. package/dist/chunk-NMX4C6LC.js.map +1 -0
  14. package/dist/{chunk-KNYJV2Q6.js → chunk-QVH5KKBR.js} +5 -9
  15. package/dist/chunk-QVH5KKBR.js.map +1 -0
  16. package/dist/claude-bundles/full.js +223 -217
  17. package/dist/claude-bundles/lean.js +5 -5
  18. package/dist/generator/index.d.ts +2 -286
  19. package/dist/generator/index.js +1 -1
  20. package/dist/index-LqEvaRk-.d.ts +299 -0
  21. package/dist/index.d.ts +29 -17
  22. package/dist/index.js +75 -414
  23. package/dist/index.js.map +1 -1
  24. package/dist/lib/claude-native/hooks-lite.d.ts +18 -325
  25. package/dist/lib/claude-native/hooks-lite.js +8 -2
  26. package/dist/lib/claude-native/index.d.ts +153 -20
  27. package/dist/lib/claude-native/index.js +162 -37
  28. package/dist/lib/claude-native/index.js.map +1 -1
  29. package/dist/{navigation-context-xrReMkTn.d.ts → navigation-context-D_E1NIUf.d.ts} +11 -3
  30. package/dist/{task-runner-Sez_CXcD.d.ts → task-runner-CLc8iTzy.d.ts} +5 -8
  31. package/dist/workspace-pre-tool-use-C6nidc0q.d.ts +333 -0
  32. package/package.json +1 -1
  33. package/dist/chunk-EH5VFZYJ.js.map +0 -1
  34. package/dist/chunk-KNYJV2Q6.js.map +0 -1
  35. package/dist/chunk-M3GJAHLX.js.map +0 -1
  36. package/dist/chunk-YZQRSVDZ.js.map +0 -1
@@ -0,0 +1,333 @@
1
+ import { a as GuardrailRuleData } from './guardrail-hooks-slK-z0Dz.js';
2
+
3
+ /**
4
+ * Claude Code Hook Protocol — parse stdin JSON input and emit hook response JSON.
5
+ *
6
+ * Implements the protocol defined at https://code.claude.com/docs/en/hooks
7
+ * for SessionStart, UserPromptSubmit, and PreToolUse hook events.
8
+ */
9
+ type HookEventName = "SessionStart" | "UserPromptSubmit" | "PreToolUse";
10
+ interface SessionStartInput {
11
+ hookEventName: "SessionStart";
12
+ session_id?: string;
13
+ type?: "new" | "resume" | "clear" | "compact";
14
+ }
15
+ interface UserPromptSubmitInput {
16
+ hookEventName: "UserPromptSubmit";
17
+ session_id?: string;
18
+ prompt?: string;
19
+ }
20
+ interface PreToolUseInput {
21
+ hookEventName: "PreToolUse";
22
+ session_id?: string;
23
+ tool_name?: string;
24
+ tool_input?: {
25
+ file_path?: string;
26
+ path?: string;
27
+ command?: string;
28
+ content?: string;
29
+ [key: string]: unknown;
30
+ };
31
+ }
32
+ type HookInput = SessionStartInput | UserPromptSubmitInput | PreToolUseInput;
33
+ type PermissionDecision = "allow" | "deny" | "ask";
34
+ interface HookOutput {
35
+ /** Hook-specific output envelope. */
36
+ hookSpecificOutput?: {
37
+ hookEventName: HookEventName;
38
+ /** Additional context injected into the session. */
39
+ additionalContext?: string;
40
+ /** Permission decision for PreToolUse hooks. */
41
+ permissionDecision?: PermissionDecision;
42
+ /** Reason for the permission decision. */
43
+ permissionDecisionReason?: string;
44
+ };
45
+ }
46
+ /**
47
+ * Parse hook input from a raw JSON string (typically from stdin).
48
+ * Throws on invalid JSON but not on missing fields — callers handle defaults.
49
+ */
50
+ declare function parseHookInput(raw: string): HookInput;
51
+ /**
52
+ * Read all of stdin and parse as hook input JSON.
53
+ */
54
+ declare function readHookInput(): Promise<HookInput>;
55
+ /**
56
+ * Emit a hook response as JSON to stdout.
57
+ */
58
+ declare function emitHookOutput(output: HookOutput): void;
59
+ /**
60
+ * Build a response that injects additional context into the session.
61
+ */
62
+ declare function buildContextResponse(eventName: HookEventName, additionalContext: string): HookOutput;
63
+ /**
64
+ * Build a deny response for PreToolUse hooks.
65
+ */
66
+ declare function buildDenyResponse(reason: string): HookOutput;
67
+ /**
68
+ * Build an allow response (empty output = allow by default).
69
+ */
70
+ declare function buildAllowResponse(): HookOutput;
71
+
72
+ /**
73
+ * Cache Store — read/write `.claude/cache/` directory.
74
+ *
75
+ * Stores navigation-index.json and metadata for graph cache invalidation.
76
+ * Uses atomic write (write-to-temp + rename) for concurrent-access safety.
77
+ */
78
+ interface CacheEntry<T = unknown> {
79
+ data: T;
80
+ /** ISO timestamp of when the cache was written. */
81
+ writtenAt: string;
82
+ /** Hash of source inputs used for invalidation. */
83
+ sourceHash: string;
84
+ }
85
+ interface CacheStoreOptions {
86
+ /** Absolute path to the `.claude/cache/` directory. */
87
+ cacheDir: string;
88
+ }
89
+ interface CacheStore {
90
+ read<T = unknown>(key: string): Promise<CacheEntry<T> | null>;
91
+ write<T = unknown>(key: string, data: T, sourceHash: string): Promise<void>;
92
+ /**
93
+ * Check if a cache entry is fresh by comparing its sourceHash.
94
+ * Returns the cached data if fresh, null if stale or missing.
95
+ */
96
+ readIfFresh<T = unknown>(key: string, currentHash: string): Promise<T | null>;
97
+ /** Get the mtime of a file (for invalidation checks). */
98
+ getFileMtime(filePath: string): Promise<number | null>;
99
+ }
100
+ declare function createCacheStore(options: CacheStoreOptions): CacheStore;
101
+ /**
102
+ * Compute a simple hash string from an array of file mtimes and content strings.
103
+ * Not cryptographic — used only for cache invalidation.
104
+ */
105
+ declare function computeSourceHash(inputs: Array<string | number>): string;
106
+
107
+ /**
108
+ * Latency utilities — timeout wrapper, graph build exclusion, degrade policy.
109
+ *
110
+ * Mirrors the Promise-sharing pattern from analyzer-bridge.ts for concurrent
111
+ * graph build exclusion.
112
+ */
113
+ declare class TimeoutError extends Error {
114
+ constructor(ms: number);
115
+ }
116
+ /**
117
+ * Race a promise against a timeout. Resolves with the promise result or
118
+ * rejects with TimeoutError.
119
+ */
120
+ declare function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T>;
121
+ /**
122
+ * Creates an exclusive async lock that ensures only one invocation runs at a
123
+ * time. Subsequent callers await the same Promise (analyzer-bridge pattern).
124
+ */
125
+ declare function createExclusiveLock<T>(): {
126
+ run: (fn: () => Promise<T>) => Promise<T>;
127
+ };
128
+ interface DegradeResult<T> {
129
+ value: T;
130
+ degraded: boolean;
131
+ reason?: string;
132
+ }
133
+ /**
134
+ * Attempt an operation with timeout; if it fails or times out, return the
135
+ * fallback value with `degraded: true`.
136
+ */
137
+ declare function withDegrade<T>(operation: () => Promise<T>, fallback: T, timeoutMs: number): Promise<DegradeResult<T>>;
138
+
139
+ /**
140
+ * Artifact Resolver — reverse-lookup path to artifact_id using navigation-index.
141
+ *
142
+ * Uses glob matching from guardrail-hooks.ts to match file paths against
143
+ * artifact path_patterns defined in the navigation index.
144
+ */
145
+ /** Minimal shape of a navigation-index artifact node. */
146
+ interface NavigationArtifact {
147
+ properties?: {
148
+ type?: string;
149
+ authority?: string;
150
+ manual_edit?: string;
151
+ [key: string]: unknown;
152
+ };
153
+ files?: {
154
+ path_patterns?: string[];
155
+ [key: string]: unknown;
156
+ };
157
+ agents?: {
158
+ owners?: string[];
159
+ editors?: string[];
160
+ [key: string]: unknown;
161
+ };
162
+ routes?: {
163
+ regenerate?: string;
164
+ [key: string]: unknown;
165
+ };
166
+ relations?: {
167
+ derived_artifacts?: string[];
168
+ [key: string]: unknown;
169
+ };
170
+ }
171
+ interface ArtifactMatch {
172
+ artifactId: string;
173
+ artifact: NavigationArtifact;
174
+ /** The glob pattern that matched. */
175
+ matchedPattern: string;
176
+ }
177
+ /**
178
+ * Resolve a file path to its artifact(s) in the navigation index.
179
+ * Returns all matching artifacts (a file may belong to multiple artifacts).
180
+ */
181
+ declare function resolvePathToArtifacts(filePath: string, navigationIndex: Record<string, unknown>): ArtifactMatch[];
182
+ /**
183
+ * Check if a file path targets a protected artifact (generated or manual_edit: forbidden).
184
+ */
185
+ declare function isProtectedArtifact(match: ArtifactMatch): {
186
+ protected: boolean;
187
+ reason: string;
188
+ };
189
+ /**
190
+ * Get all artifact entries from a navigation index as a flat list.
191
+ */
192
+ declare function listArtifacts(navigationIndex: Record<string, unknown>): Array<{
193
+ id: string;
194
+ artifact: NavigationArtifact;
195
+ }>;
196
+
197
+ /**
198
+ * PreToolUse Hook Handler — artifact guardrail + DSL guardrail enforcement.
199
+ *
200
+ * Executed before tool use (Edit, Write, Bash, etc.). Checks:
201
+ * 1. Edit/Write tools: file path → artifact reverse lookup → deny if protected
202
+ * 2. Bash tool: apply DSL guardrail rules via GuardrailHooks
203
+ */
204
+
205
+ interface PreToolUseHandlerConfig {
206
+ /** Navigation index for artifact resolution. */
207
+ navigationIndex: Record<string, unknown>;
208
+ /** DSL guardrail rules for Bash command evaluation. */
209
+ guardrailRules?: GuardrailRuleData;
210
+ }
211
+ /**
212
+ * Create a PreToolUse hook handler.
213
+ */
214
+ declare function createPreToolUseHandler(config: PreToolUseHandlerConfig): (input: PreToolUseInput) => Promise<HookOutput>;
215
+
216
+ /**
217
+ * Workspace Router — route a file path to the owning workspace member.
218
+ *
219
+ * Pure path-manipulation module. No imports from navigation-context,
220
+ * agent-contracts, or any heavy dependency — safe for the lean hooks-lite
221
+ * entry point.
222
+ *
223
+ * Algorithm: longest-prefix match among member absolute root paths.
224
+ *
225
+ * C4 resolution: stripMemberPrefix converts a workspace-relative path
226
+ * (`aaac/packages/runtime/x.ts`) into a repo-relative path
227
+ * (`packages/runtime/x.ts`) so existing member DSL path_patterns work
228
+ * without modification.
229
+ */
230
+ interface WorkspaceMember {
231
+ /** Human-readable member name (e.g. `"aaac"`). */
232
+ name: string;
233
+ /** Absolute path to the member root directory. */
234
+ root: string;
235
+ }
236
+ /**
237
+ * Route a file path to the workspace member whose root is the longest
238
+ * matching prefix of that path.
239
+ *
240
+ * Generic over `T extends WorkspaceMember` so callers that pass a richer
241
+ * member type (e.g. `WorkspaceMemberPreToolUseConfig`) get back that type
242
+ * without a cast.
243
+ *
244
+ * @param filePath - Absolute or workspace-root-relative file path (as
245
+ * received from Claude Code's `tool_input.file_path`).
246
+ * @param members - Workspace members with **absolute** root paths.
247
+ * @param workspaceRoot - Absolute path to the workspace root directory.
248
+ * Used to resolve relative `filePath` values.
249
+ * @returns The owning member, or `null` when no member claims this path.
250
+ */
251
+ declare function routePathToMember<T extends WorkspaceMember>(filePath: string, members: T[], workspaceRoot: string): T | null;
252
+ /**
253
+ * Strip the member root prefix from `filePath` to obtain a repo-relative
254
+ * path that member DSL `path_patterns` can match against unchanged (C4).
255
+ *
256
+ * Example:
257
+ * filePath = "aaac/packages/runtime/x.ts" (workspace-relative)
258
+ * memberRoot = "/abs/workspace/aaac"
259
+ * workspaceRoot = "/abs/workspace"
260
+ * → returns "packages/runtime/x.ts"
261
+ *
262
+ * @param filePath - Absolute or workspace-root-relative path.
263
+ * @param memberRoot - Absolute path to the member root.
264
+ * @param workspaceRoot - Absolute path to the workspace root.
265
+ * @returns Repo-relative path (no leading slash/dot).
266
+ * Falls back to the original `filePath` when stripping is not possible.
267
+ */
268
+ declare function stripMemberPrefix(filePath: string, memberRoot: string, workspaceRoot: string): string;
269
+
270
+ /**
271
+ * Workspace PreToolUse Hook Handler — routes edits to the owning member
272
+ * and enforces that member's artifact guardrails.
273
+ *
274
+ * Hot-path module. Does NOT import navigation-context or agent-contracts —
275
+ * it only reads an already-built navigation index from the cache. Suitable
276
+ * for inclusion in the lean hooks-lite entry point.
277
+ *
278
+ * Flow (per PreToolUse invocation):
279
+ * 1. Extract file path from tool input.
280
+ * 2. Route to owning member via longest-prefix match (workspace-router).
281
+ * 3. Read member's navigation-index from cache (cache-store).
282
+ * 4. Strip member-root prefix → repo-relative path (C4 resolution).
283
+ * 5. Resolve path to artifacts; deny if protected.
284
+ */
285
+
286
+ interface WorkspaceMemberPreToolUseConfig extends WorkspaceMember {
287
+ /**
288
+ * Cache key for this member's navigation-index JSON.
289
+ * Format: `navigation-index.<name>` (e.g. `navigation-index.aaac`).
290
+ */
291
+ cacheKey: string;
292
+ /**
293
+ * Cache key for this member's DSL guardrail rules (#238 / C5).
294
+ *
295
+ * Defaults to `guardrailCacheKey(cacheKey)` (i.e. `<cacheKey>.guardrails`)
296
+ * when omitted, matching what `ensureNavigationIndex` persists during the
297
+ * SessionStart warm-up. Provided explicitly only for tests / custom layouts.
298
+ */
299
+ guardrailCacheKey?: string;
300
+ }
301
+ interface WorkspacePreToolUseConfig {
302
+ /** Absolute path to the workspace root directory. */
303
+ workspaceRoot: string;
304
+ /** Absolute path to the shared `.claude/cache/` directory. */
305
+ cacheDir: string;
306
+ /** Workspace members to route edits to. */
307
+ members: WorkspaceMemberPreToolUseConfig[];
308
+ }
309
+ /**
310
+ * Create a workspace-aware PreToolUse hook handler.
311
+ *
312
+ * On each invocation the handler:
313
+ * - Edit/Write tools:
314
+ * - Routes the target path to the owning member by longest-prefix match.
315
+ * - Reads the member's cached navigation-index (allows if no cache yet).
316
+ * - Strips the member-root prefix so `resolvePathToArtifacts` receives the
317
+ * same repo-relative path the member DSL's `path_patterns` expect (C4).
318
+ * - Denies if any matched artifact is protected (Phase 1).
319
+ * - Bash tools (#238 / C5, Phase 3):
320
+ * - Routes the command to the owning member via a path token in the command
321
+ * (longest-prefix match); when no member path is present, evaluates the
322
+ * command against every member's rules so safety guardrails are never
323
+ * silently skipped.
324
+ * - Loads that member's DSL guardrail rules from the companion cache entry
325
+ * and denies blocking command violations.
326
+ *
327
+ * Artifact protection (Phase 1) and Bash guardrails (Phase 3) are independent
328
+ * and coexist: a member with only artifact rules keeps working unchanged, and
329
+ * a member with only guardrail rules still enforces Bash safety.
330
+ */
331
+ declare function createWorkspacePreToolUseHandler(config: WorkspacePreToolUseConfig): (input: PreToolUseInput) => Promise<HookOutput>;
332
+
333
+ export { type ArtifactMatch as A, type CacheEntry as C, type DegradeResult as D, type HookEventName as H, type NavigationArtifact as N, type PermissionDecision as P, type SessionStartInput as S, TimeoutError as T, type UserPromptSubmitInput as U, type WorkspaceMember as W, type CacheStore as a, type CacheStoreOptions as b, type HookInput as c, type HookOutput as d, type PreToolUseHandlerConfig as e, type PreToolUseInput as f, type WorkspaceMemberPreToolUseConfig as g, type WorkspacePreToolUseConfig as h, buildAllowResponse as i, buildContextResponse as j, buildDenyResponse as k, computeSourceHash as l, createCacheStore as m, createExclusiveLock as n, createPreToolUseHandler as o, createWorkspacePreToolUseHandler as p, emitHookOutput as q, isProtectedArtifact as r, listArtifacts as s, parseHookInput as t, readHookInput as u, resolvePathToArtifacts as v, routePathToMember as w, stripMemberPrefix as x, withDegrade as y, withTimeout as z };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aaac/runtime",
3
- "version": "0.1.53",
3
+ "version": "0.1.54",
4
4
  "description": "Runtime SDK for the AaaC toolchain",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/plugin.ts","../src/lib/guardrail-hooks.ts"],"sourcesContent":["/**\n * Plugin Interface — extension points for user code injection\n */\n\nimport type { TaskContext, TaskOutcome, AgentContractLike, TaskContractLike, PromptBuilderOptions } from \"./task-runner.js\";\nimport type { WorkflowResult } from \"./workflow-runner.js\";\n\nexport interface GuardrailResult {\n matched: boolean;\n guardrail_id: string;\n severity: \"critical\" | \"mandatory\" | \"warning\" | \"info\";\n action: \"block\" | \"warn\" | \"shadow\" | \"info\";\n message: string;\n}\n\nexport interface PromptBuilderArgs {\n agent: AgentContractLike;\n task: TaskContractLike;\n context: TaskContext;\n options?: PromptBuilderOptions;\n}\n\nexport interface AgentPlugin {\n readonly id: string;\n beforeTask?(taskId: string, context: TaskContext): Promise<TaskContext | null>;\n afterTask?(taskId: string, outcome: TaskOutcome): Promise<TaskOutcome>;\n /**\n * Enrich the structured TaskContext before prompt generation.\n * Unlike beforeTask (which can skip a task by returning null),\n * this hook is purely for context augmentation.\n */\n contextEnhancer?(taskId: string, context: TaskContext): TaskContext;\n /**\n * Lightweight prompt post-processor. Applied after the prompt is built.\n * Use for appending instructions or modifying sections.\n */\n promptEnhancer?(taskId: string, prompt: string, context: TaskContext): string;\n /**\n * Full prompt builder override. If provided and returns a non-null string,\n * replaces the default buildTaskPrompt output entirely.\n * Receives the agent/task contracts and context so the plugin can build\n * a completely custom prompt.\n */\n promptBuilder?(args: PromptBuilderArgs): string | null;\n customGuardrails?: {\n evaluateCommand?(command: string): GuardrailResult[];\n evaluateFilePath?(filePath: string): GuardrailResult[];\n evaluateFileContent?(filePath: string, content: string): GuardrailResult[];\n };\n beforeWorkflow?(workflowId: string, userRequest: string): Promise<void>;\n afterWorkflow?(workflowId: string, result: WorkflowResult): Promise<void>;\n}\n\nexport class PluginRegistry {\n private plugins: AgentPlugin[] = [];\n\n register(plugin: AgentPlugin): void {\n if (this.plugins.some((p) => p.id === plugin.id)) {\n throw new Error(`Plugin \"${plugin.id}\" is already registered`);\n }\n this.plugins.push(plugin);\n }\n\n getAll(): readonly AgentPlugin[] {\n return this.plugins;\n }\n\n async runBeforeTask(taskId: string, context: TaskContext): Promise<TaskContext | null> {\n let ctx: TaskContext | null = context;\n for (const plugin of this.plugins) {\n if (!plugin.beforeTask || ctx === null) continue;\n ctx = await plugin.beforeTask(taskId, ctx);\n }\n return ctx;\n }\n\n async runAfterTask(taskId: string, outcome: TaskOutcome): Promise<TaskOutcome> {\n let result = outcome;\n for (const plugin of this.plugins) {\n if (!plugin.afterTask) continue;\n result = await plugin.afterTask(taskId, result);\n }\n return result;\n }\n\n applyContextEnhancers(taskId: string, context: TaskContext): TaskContext {\n let ctx = context;\n for (const plugin of this.plugins) {\n if (!plugin.contextEnhancer) continue;\n ctx = plugin.contextEnhancer(taskId, ctx);\n }\n return ctx;\n }\n\n /**\n * Try plugin promptBuilder hooks. Returns custom prompt if any plugin provides one,\n * or null to use the default buildTaskPrompt.\n */\n applyPromptBuilder(args: PromptBuilderArgs): string | null {\n for (const plugin of this.plugins) {\n if (!plugin.promptBuilder) continue;\n const result = plugin.promptBuilder(args);\n if (result !== null) return result;\n }\n return null;\n }\n\n applyPromptEnhancers(taskId: string, prompt: string, context: TaskContext): string {\n let enhanced = prompt;\n for (const plugin of this.plugins) {\n if (!plugin.promptEnhancer) continue;\n enhanced = plugin.promptEnhancer(taskId, enhanced, context);\n }\n return enhanced;\n }\n\n evaluateCommandGuardrails(command: string): GuardrailResult[] {\n const results: GuardrailResult[] = [];\n for (const plugin of this.plugins) {\n if (!plugin.customGuardrails?.evaluateCommand) continue;\n results.push(...plugin.customGuardrails.evaluateCommand(command));\n }\n return results;\n }\n\n evaluateFilePathGuardrails(filePath: string): GuardrailResult[] {\n const results: GuardrailResult[] = [];\n for (const plugin of this.plugins) {\n if (!plugin.customGuardrails?.evaluateFilePath) continue;\n results.push(...plugin.customGuardrails.evaluateFilePath(filePath));\n }\n return results;\n }\n\n evaluateFileContentGuardrails(filePath: string, content: string): GuardrailResult[] {\n const results: GuardrailResult[] = [];\n for (const plugin of this.plugins) {\n if (!plugin.customGuardrails?.evaluateFileContent) continue;\n results.push(...plugin.customGuardrails.evaluateFileContent(filePath, content));\n }\n return results;\n }\n\n async runBeforeWorkflow(workflowId: string, userRequest: string): Promise<void> {\n for (const plugin of this.plugins) {\n if (!plugin.beforeWorkflow) continue;\n await plugin.beforeWorkflow(workflowId, userRequest);\n }\n }\n\n async runAfterWorkflow(workflowId: string, result: WorkflowResult): Promise<void> {\n for (const plugin of this.plugins) {\n if (!plugin.afterWorkflow) continue;\n await plugin.afterWorkflow(workflowId, result);\n }\n }\n}\n\nexport const pluginRegistry = new PluginRegistry();\n","/**\n * SDK Guardrail Hook Bridge — generic adapter from guardrail check functions\n * + plugin guardrails to 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\nimport { pluginRegistry } from \"./plugin.js\";\n\nexport interface GuardrailCheckResult {\n guardrail_id: string;\n passed: boolean;\n action: \"block\" | \"warn\" | \"shadow\" | \"info\";\n message: string;\n}\n\nexport interface HookResponse {\n permission?: \"deny\";\n user_message?: string;\n agent_message?: string;\n additionalContext?: string;\n}\n\nexport interface GuardrailRule {\n guardrail_id: string;\n pattern: string;\n action: \"block\" | \"warn\" | \"shadow\" | \"info\";\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\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\nexport function matchGlob(pattern: string, path: string): boolean {\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\nexport interface HookContext {\n /** Agent id for per-agent guardrail filtering. */\n agentId?: string;\n command?: string;\n filePath?: string;\n content?: string;\n}\n\nexport interface GuardrailHooks {\n beforeShellExecution: (input: { command?: string }) => HookResponse;\n preToolUse: (input: {\n tool_name?: string;\n tool_input?: { file_path?: string; path?: string };\n }) => HookResponse;\n afterFileEdit: (input: { file_path?: string; content?: string }) => HookResponse;\n runChecks: (ctx: HookContext) => GuardrailCheckResult[];\n}\n\nexport function getBlockingViolations(results: GuardrailCheckResult[]): GuardrailCheckResult[] {\n return results.filter((r) => !r.passed && r.action === \"block\");\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 results.some((r) => !r.passed && r.action === \"block\");\n}\n\nfunction pluginResultToCheckResult(r: {\n matched: boolean;\n guardrail_id: string;\n action: string;\n message: string;\n}): GuardrailCheckResult {\n return {\n guardrail_id: r.guardrail_id,\n passed: !r.matched,\n action: r.action as GuardrailCheckResult[\"action\"],\n message: r.matched ? r.message : \"\",\n };\n}\n\n/**\n * Create SDK hook functions from generated guardrail check functions.\n *\n * Merges DSL-generated checks with plugin-registered guardrails and\n * returns hook functions in the format expected by the Claude SDK,\n * plus a generic runChecks() for programmatic use.\n */\nexport function createGuardrailHooks(checks: GuardrailCheckFunctions): GuardrailHooks {\n function runChecks(ctx: HookContext): GuardrailCheckResult[] {\n const results: GuardrailCheckResult[] = [];\n\n if (ctx.command) {\n results.push(...checks.checkCommand(ctx.command));\n results.push(\n ...pluginRegistry.evaluateCommandGuardrails(ctx.command).map(pluginResultToCheckResult),\n );\n }\n\n if (ctx.filePath) {\n results.push(...checks.checkFilePath(ctx.filePath));\n results.push(\n ...pluginRegistry.evaluateFilePathGuardrails(ctx.filePath).map(pluginResultToCheckResult),\n );\n }\n\n if (ctx.filePath && ctx.content) {\n results.push(...checks.checkContent(ctx.filePath, ctx.content));\n results.push(\n ...pluginRegistry\n .evaluateFileContentGuardrails(ctx.filePath, ctx.content)\n .map(pluginResultToCheckResult),\n );\n }\n\n return results;\n }\n\n function beforeShellExecution(input: { command?: string }): HookResponse {\n const command = input.command ?? \"\";\n if (!command) return {};\n\n const results = runChecks({ command });\n const blocks = getBlockingViolations(results);\n const warns = getWarnings(results);\n\n if (blocks.length > 0) {\n const msg = blocks.map((r) => `[${r.guardrail_id}] ${r.message}`).join(\"\\n\");\n return { permission: \"deny\", user_message: msg, agent_message: msg };\n }\n\n if (warns.length > 0) {\n return {\n additionalContext: warns.map((r) => `[${r.guardrail_id}] ${r.message}`).join(\"\\n\"),\n };\n }\n\n return {};\n }\n\n function preToolUse(input: {\n tool_name?: string;\n tool_input?: { file_path?: string; path?: string };\n }): HookResponse {\n const filePath = input.tool_input?.file_path ?? input.tool_input?.path ?? \"\";\n if (!filePath) return {};\n\n const results = runChecks({ filePath });\n const blocks = getBlockingViolations(results);\n\n if (blocks.length > 0) {\n const msg = blocks.map((r) => `[${r.guardrail_id}] ${r.message}`).join(\"\\n\");\n return { permission: \"deny\", user_message: msg, agent_message: msg };\n }\n\n return {};\n }\n\n function afterFileEdit(input: { file_path?: string; content?: string }): HookResponse {\n const filePath = input.file_path ?? \"\";\n const content = input.content ?? \"\";\n if (!filePath) return {};\n\n const results = runChecks({ filePath, content });\n const blocks = getBlockingViolations(results);\n\n if (blocks.length > 0) {\n const msg = blocks.map((r) => `[${r.guardrail_id}] ${r.message}`).join(\"\\n\");\n return { permission: \"deny\", user_message: msg, agent_message: msg };\n }\n\n return {};\n }\n\n return { beforeShellExecution, preToolUse, afterFileEdit, runChecks };\n}\n\n/**\n * Create SDK hook functions from embedded guardrail rule data.\n */\n/**\n * Create SDK hooks scoped to a single agent from a per-agent guardrail map.\n * Returns empty-passing hooks when the agent has no rules in the map.\n */\nexport function createGuardrailHooksForAgent(\n agentId: string,\n perAgent: Map<string, GuardrailRuleData>,\n): GuardrailHooks {\n const rules = perAgent.get(agentId);\n if (!rules) {\n return createGuardrailHooks({\n checkCommand: () => [],\n checkFilePath: () => [],\n checkContent: () => [],\n });\n }\n const hooks = createGuardrailHooksFromRules(rules);\n const baseRunChecks = hooks.runChecks;\n return {\n ...hooks,\n runChecks(ctx: HookContext) {\n return baseRunChecks({ ...ctx, agentId });\n },\n };\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\nexport function createGuardrailHooksFromRules(rules: GuardrailRuleData): 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 });\n}\n"],"mappings":";AAqDO,IAAM,iBAAN,MAAqB;AAAA,EAClB,UAAyB,CAAC;AAAA,EAElC,SAAS,QAA2B;AAClC,QAAI,KAAK,QAAQ,KAAK,CAAC,MAAM,EAAE,OAAO,OAAO,EAAE,GAAG;AAChD,YAAM,IAAI,MAAM,WAAW,OAAO,EAAE,yBAAyB;AAAA,IAC/D;AACA,SAAK,QAAQ,KAAK,MAAM;AAAA,EAC1B;AAAA,EAEA,SAAiC;AAC/B,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,MAAM,cAAc,QAAgB,SAAmD;AACrF,QAAI,MAA0B;AAC9B,eAAW,UAAU,KAAK,SAAS;AACjC,UAAI,CAAC,OAAO,cAAc,QAAQ,KAAM;AACxC,YAAM,MAAM,OAAO,WAAW,QAAQ,GAAG;AAAA,IAC3C;AACA,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,aAAa,QAAgB,SAA4C;AAC7E,QAAI,SAAS;AACb,eAAW,UAAU,KAAK,SAAS;AACjC,UAAI,CAAC,OAAO,UAAW;AACvB,eAAS,MAAM,OAAO,UAAU,QAAQ,MAAM;AAAA,IAChD;AACA,WAAO;AAAA,EACT;AAAA,EAEA,sBAAsB,QAAgB,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U,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,CAAC;AACH;","names":[]}
@@ -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/latency.ts","../src/lib/claude-native/artifact-resolver.ts","../src/lib/claude-native/pre-tool-use.ts","../src/lib/claude-native/workspace-router.ts","../src/lib/claude-native/ensure-navigation-index-keys.ts","../src/lib/claude-native/workspace-pre-tool-use.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\nexport type HookEventName = \"SessionStart\" | \"UserPromptSubmit\" | \"PreToolUse\";\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 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/**\n * Parse hook input from a raw JSON string (typically from stdin).\n * Throws on invalid JSON but not on missing fields — callers handle defaults.\n */\nexport function parseHookInput(raw: string): HookInput {\n const parsed = JSON.parse(raw) 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 parsed.hook_event_name === \"string\" && parsed.hookEventName === undefined) {\n parsed.hookEventName = parsed.hook_event_name;\n }\n // Boundary assertion: stdin JSON is inherently untyped, and HookInput models\n // the event name as required, so the normalized record is asserted here.\n return parsed as unknown as HookInput;\n}\n\n/**\n * Read all of stdin and parse as hook input JSON.\n */\nexport async function readHookInput(): Promise<HookInput> {\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\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\nexport interface CacheStoreOptions {\n /** Absolute path to the `.claude/cache/` directory. */\n cacheDir: string;\n}\n\n// ---------------------------------------------------------------------------\n// Cache Store\n// ---------------------------------------------------------------------------\n\nexport interface CacheStore {\n read<T = unknown>(key: string): Promise<CacheEntry<T> | null>;\n write<T = unknown>(key: string, data: T, sourceHash: string): Promise<void>;\n /**\n * Check if a cache entry is fresh by comparing its sourceHash.\n * Returns the cached data if fresh, null if stale or missing.\n */\n readIfFresh<T = unknown>(key: string, currentHash: string): Promise<T | null>;\n /** Get the mtime of a file (for invalidation checks). */\n getFileMtime(filePath: string): Promise<number | null>;\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 = unknown>(key: string): Promise<CacheEntry<T> | null> {\n try {\n const raw = await readFile(cacheFilePath(key), \"utf-8\");\n return JSON.parse(raw) as CacheEntry<T>;\n } catch {\n return null;\n }\n },\n\n async write<T = unknown>(key: string, data: T, sourceHash: string): Promise<void> {\n await ensureDir();\n const entry: CacheEntry<T> = {\n data,\n writtenAt: new Date().toISOString(),\n sourceHash,\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 readIfFresh<T = unknown>(key: string, currentHash: string): Promise<T | null> {\n const entry = await store.read<T>(key);\n if (!entry) return null;\n if (entry.sourceHash !== currentHash) return null;\n return entry.data;\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 * 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 * 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","/**\n * PreToolUse Hook Handler — artifact guardrail + DSL guardrail enforcement.\n *\n * Executed before tool use (Edit, Write, Bash, etc.). Checks:\n * 1. Edit/Write tools: file path → artifact reverse lookup → deny if protected\n * 2. Bash tool: apply DSL guardrail rules via GuardrailHooks\n */\n\nimport {\n createGuardrailHooksFromRules,\n getBlockingViolations,\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 /** Navigation index for artifact resolution. */\n navigationIndex: Record<string, unknown>;\n /** DSL guardrail rules for Bash command evaluation. */\n guardrailRules?: GuardrailRuleData;\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/** Tool names that perform file edits. */\nconst EDIT_TOOLS = new Set([\"Edit\", \"Write\", \"MultiEdit\", \"edit\", \"write\"]);\n\n/** Tool names that execute shell commands. */\nconst BASH_TOOLS = new Set([\"Bash\", \"bash\", \"Terminal\", \"terminal\"]);\n\n// ---------------------------------------------------------------------------\n// Handler\n// ---------------------------------------------------------------------------\n\n/**\n * Create a PreToolUse hook handler.\n */\nexport function createPreToolUseHandler(config: PreToolUseHandlerConfig) {\n // Pre-compile guardrail hooks if rules provided\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 toolName = input.tool_name ?? \"\";\n const toolInput = input.tool_input ?? {};\n\n // --- Edit/Write tool: artifact protection ---\n if (EDIT_TOOLS.has(toolName)) {\n const filePath = toolInput.file_path ?? toolInput.path ?? \"\";\n if (filePath) {\n const matches = resolvePathToArtifacts(\n filePath,\n config.navigationIndex,\n );\n\n for (const match of matches) {\n const check = isProtectedArtifact(match);\n if (check.protected) {\n return buildDenyResponse(check.reason);\n }\n }\n }\n }\n\n // --- Bash tool: DSL guardrail enforcement ---\n if (BASH_TOOLS.has(toolName) && guardrailHooks) {\n const command = toolInput.command ?? \"\";\n if (command) {\n const hookResult = guardrailHooks.beforeShellExecution({ command });\n if (hookResult.permission === \"deny\") {\n return buildDenyResponse(\n hookResult.user_message ?? \"Command blocked by guardrail\",\n );\n }\n }\n }\n\n // --- Default: allow ---\n return buildAllowResponse();\n };\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 * 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 * 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):\n * 1. Extract file path from tool input.\n * 2. Route to owning member via longest-prefix match (workspace-router).\n * 3. Read member's navigation-index from cache (cache-store).\n * 4. Strip member-root prefix → repo-relative path (C4 resolution).\n * 5. Resolve path to artifacts; deny if protected.\n */\n\nimport {\n createGuardrailHooksFromRules,\n type GuardrailHooks,\n type GuardrailRuleData,\n} from \"../guardrail-hooks.js\";\nimport {\n resolvePathToArtifacts,\n isProtectedArtifact,\n} from \"./artifact-resolver.js\";\nimport {\n createCacheStore,\n} from \"./cache-store.js\";\nimport { guardrailCacheKey } from \"./ensure-navigation-index-keys.js\";\nimport {\n buildDenyResponse,\n buildAllowResponse,\n type HookOutput,\n type PreToolUseInput,\n} from \"./hook-protocol.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 cacheKey: string;\n /**\n * Cache key for this member's DSL guardrail rules (#238 / C5).\n *\n * Defaults to `guardrailCacheKey(cacheKey)` (i.e. `<cacheKey>.guardrails`)\n * when omitted, matching what `ensureNavigationIndex` persists during the\n * SessionStart warm-up. Provided explicitly only for tests / custom layouts.\n */\n guardrailCacheKey?: 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// Constants\n// ---------------------------------------------------------------------------\n\n/** Tool names that perform file edits. */\nconst EDIT_TOOLS = new Set([\"Edit\", \"Write\", \"MultiEdit\", \"edit\", \"write\"]);\n\n/** Tool names that execute shell commands. */\nconst BASH_TOOLS = new Set([\"Bash\", \"bash\", \"Terminal\", \"terminal\"]);\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 the handler:\n * - Edit/Write tools:\n * - Routes the target path to the owning member by longest-prefix match.\n * - Reads the member's cached navigation-index (allows if no cache yet).\n * - Strips the member-root prefix so `resolvePathToArtifacts` receives the\n * same repo-relative path the member DSL's `path_patterns` expect (C4).\n * - Denies if any matched artifact is protected (Phase 1).\n * - Bash tools (#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 * - Loads that member's DSL guardrail rules from the companion cache entry\n * and denies blocking command violations.\n *\n * Artifact protection (Phase 1) and Bash guardrails (Phase 3) are independent\n * and coexist: a member with only artifact rules keeps working unchanged, and\n * a member with only guardrail rules still enforces Bash safety.\n */\nexport function createWorkspacePreToolUseHandler(\n config: WorkspacePreToolUseConfig,\n) {\n const store = createCacheStore({ cacheDir: config.cacheDir });\n\n // Per-member compiled guardrail hooks, memoised across invocations.\n const guardrailHooksByMember = new Map<string, GuardrailHooks | null>();\n\n async function loadGuardrailHooks(\n member: WorkspaceMemberPreToolUseConfig,\n ): Promise<GuardrailHooks | null> {\n const key = member.name;\n if (guardrailHooksByMember.has(key)) {\n return guardrailHooksByMember.get(key) ?? null;\n }\n const cacheKey = member.guardrailCacheKey ?? guardrailCacheKey(member.cacheKey);\n const entry = await store.read<GuardrailRuleData>(cacheKey);\n const rules = entry?.data;\n const hooks =\n rules &&\n (rules.commandRules.length > 0 ||\n rules.fileRules.length > 0 ||\n rules.contentRules.length > 0)\n ? createGuardrailHooksFromRules(rules)\n : null;\n guardrailHooksByMember.set(key, hooks);\n return hooks;\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 const toolName = input.tool_name ?? \"\";\n const toolInput = input.tool_input ?? {};\n\n // --- Bash tool: member-scoped DSL guardrail enforcement (Phase 3 / C5) ---\n if (BASH_TOOLS.has(toolName)) {\n const command = toolInput.command ?? \"\";\n if (!command) {\n return buildAllowResponse();\n }\n for (const member of membersForCommand(command)) {\n const hooks = await loadGuardrailHooks(member);\n if (!hooks) continue;\n const result = hooks.beforeShellExecution({ command });\n if (result.permission === \"deny\") {\n return buildDenyResponse(\n result.user_message ?? \"Command blocked by guardrail\",\n );\n }\n }\n return buildAllowResponse();\n }\n\n if (!EDIT_TOOLS.has(toolName)) {\n return buildAllowResponse();\n }\n\n const filePath = toolInput.file_path ?? toolInput.path ?? \"\";\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 member's navigation-index from cache\n const entry = await store.read<Record<string, unknown>>(member.cacheKey);\n if (!entry) {\n // No cache yet (session-start hasn't run) — fail-open\n return buildAllowResponse();\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: Resolve path to artifacts and check protection\n const matches = resolvePathToArtifacts(repoRelPath, entry.data);\n\n for (const match of matches) {\n const check = isProtectedArtifact(match);\n if (check.protected) {\n return buildDenyResponse(check.reason);\n }\n }\n\n return buildAllowResponse();\n };\n}\n"],"mappings":";;;;;;AAmEO,SAAS,eAAe,KAAwB;AACrD,QAAM,SAAS,KAAK,MAAM,GAAG;AAO7B,MAAI,OAAO,OAAO,oBAAoB,YAAY,OAAO,kBAAkB,QAAW;AACpF,WAAO,gBAAgB,OAAO;AAAA,EAChC;AAGA,SAAO;AACT;AAKA,eAAsB,gBAAoC;AACxD,QAAM,SAAmB,CAAC;AAC1B,mBAAiB,SAAS,QAAQ,OAAO;AACvC,WAAO,KAAK,OAAO,SAAS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