@aaac/runtime 0.1.52 → 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-C6XCN33A.js → chunk-N4KNGDYY.js} +344 -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-4OMCAGNY.js → chunk-QVH5KKBR.js} +57 -2
  15. package/dist/{chunk-4OMCAGNY.js.map → chunk-QVH5KKBR.js.map} +1 -1
  16. package/dist/claude-bundles/full.js +223 -217
  17. package/dist/claude-bundles/lean.js +6 -6
  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 -412
  23. package/dist/index.js.map +1 -1
  24. package/dist/lib/claude-native/hooks-lite.d.ts +18 -306
  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 +170 -36
  28. package/dist/lib/claude-native/index.js.map +1 -1
  29. package/dist/navigation-context-D_E1NIUf.d.ts +41 -0
  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 +2 -1
  33. package/dist/chunk-C6XCN33A.js.map +0 -1
  34. package/dist/chunk-EH5VFZYJ.js.map +0 -1
  35. package/dist/chunk-YZQRSVDZ.js.map +0 -1
  36. package/dist/navigation-context-BE1KHJ_8.d.ts +0 -22
@@ -1 +1 @@
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/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 * 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 resolvePathToArtifacts,\n isProtectedArtifact,\n} from \"./artifact-resolver.js\";\nimport {\n createCacheStore,\n} from \"./cache-store.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\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// ---------------------------------------------------------------------------\n// Handler\n// ---------------------------------------------------------------------------\n\n/**\n * Create a workspace-aware PreToolUse hook handler.\n *\n * On each invocation the handler:\n * - Skips non-edit tools (allow).\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.\n */\nexport function createWorkspacePreToolUseHandler(\n config: WorkspacePreToolUseConfig,\n) {\n const store = createCacheStore({ cacheDir: config.cacheDir });\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 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,KAAK,IAAI,QAAQ,OAAO,KAAK,KAAe,CAAC;AAAA,EAC3E;AACA,QAAM,MAAM,OAAO,OAAO,MAAM,EAAE,SAAS,OAAO,EAAE,KAAK;AACzD,MAAI,CAAC,KAAK;AACR,UAAM,IAAI,MAAM,2CAAsC;AAAA,EACxD;AACA,SAAO,eAAe,GAAG;AAC3B;AAKO,SAAS,eAAe,QAA0B;AACvD,UAAQ,OAAO,MAAM,KAAK,UAAU,MAAM,IAAI,IAAI;AACpD;AASO,SAAS,qBACd,WACA,mBAC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AGA,UAAM,UAAU,uBAAuB,aAAa,MAAM,IAAI;AAE9D,eAAW,SAAS,SAAS;AAC3B,YAAM,QAAQ,oBAAoB,KAAK;AACvC,UAAI,MAAM,WAAW;AACnB,eAAO,kBAAkB,MAAM,MAAM;AAAA,MACvC;AAAA,IACF;AAEA,WAAO,mBAAmB;AAAA,EAC5B;AACF;","names":["EDIT_TOOLS"]}
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/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 * 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,KAAK,IAAI,QAAQ,OAAO,KAAK,KAAe,CAAC;AAAA,EAC3E;AACA,QAAM,MAAM,OAAO,OAAO,MAAM,EAAE,SAAS,OAAO,EAAE,KAAK;AACzD,MAAI,CAAC,KAAK;AACR,UAAM,IAAI,MAAM,2CAAsC;AAAA,EACxD;AACA,SAAO,eAAe,GAAG;AAC3B;AAKO,SAAS,eAAe,QAA0B;AACvD,UAAQ,OAAO,MAAM,KAAK,UAAU,MAAM,IAAI,IAAI;AACpD;AASO,SAAS,qBACd,WACA,mBACY;AACZ,SAAO;AAAA,IACL,oBAAoB;AAAA,MAClB,eAAe;AAAA,MACf;AAAA,IACF;AAAA,EACF;AACF;AAKO,SAAS,kBAAkB,QAA4B;AAC5D,SAAO;AAAA,IACL,oBAAoB;AAAA,MAClB,eAAe;AAAA,MACf,oBAAoB;AAAA,MACpB,0BAA0B;AAAA,IAC5B;AAAA,EACF;AACF;AAKO,SAAS,qBAAiC;AAC/C,SAAO,CAAC;AACV;;;ACvIA,SAAS,UAAU,WAAW,QAAQ,MAAM,aAAa;AACzD,SAAS,YAAqB;AAC9B,SAAS,mBAAmB;AAmCrB,SAAS,iBAAiB,SAAwC;AACvE,Q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