@aaac/runtime 0.1.38 → 0.1.40

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.
@@ -287,13 +287,13 @@ interface SessionStartHandlerConfig {
287
287
  declare function createSessionStartHandler(config: SessionStartHandlerConfig): (_input: SessionStartInput) => Promise<HookOutput>;
288
288
 
289
289
  /**
290
- * UserPromptSubmit Hook Handler — ContextPack + candidate metadata injection.
290
+ * UserPromptSubmit Hook Handler — navigation-index summary injection.
291
291
  *
292
- * Executed after prompt submission, before Claude processes it. Extracts
293
- * artifact candidates from the prompt, generates a ContextPack via the
294
- * analyzer bridge, and composes additionalContext.
292
+ * Executed after prompt submission, before Claude processes it. Provides a
293
+ * compact navigation-index summary so the LLM can pick candidates and delegate
294
+ * deep exploration to `analyzer.getContextMap` (Level 2).
295
295
  *
296
- * Hard timeout with fallback to navigation-index summary only.
296
+ * ContextPack is NOT pre-injected by default (#206 Phase D).
297
297
  */
298
298
 
299
299
  interface UserPromptSubmitHandlerConfig {
@@ -305,10 +305,6 @@ interface UserPromptSubmitHandlerConfig {
305
305
  sourceFiles: string[];
306
306
  /** Options for buildNavigationContext(). */
307
307
  navigationOptions: EnsureNavigationIndexOptions["navigationOptions"];
308
- /** Hard timeout for the entire handler in ms. */
309
- timeoutMs?: number;
310
- /** Token budget for ContextPack generation. */
311
- budgetTokens?: number;
312
308
  }
313
309
  /**
314
310
  * Create a UserPromptSubmit hook handler.
@@ -1,9 +1,7 @@
1
1
  import {
2
2
  buildNavigationContext,
3
- createAnalyzerBridge,
4
- renderContextPackPrompt,
5
3
  renderNavigationIndexPrompt
6
- } from "../../chunk-63RFYS7F.js";
4
+ } from "../../chunk-WFIXO3GQ.js";
7
5
  import {
8
6
  createGuardrailHooksFromRules,
9
7
  matchGlob
@@ -323,11 +321,7 @@ function createSessionStartHandler(config) {
323
321
  }
324
322
 
325
323
  // src/lib/claude-native/user-prompt-submit.ts
326
- var DEFAULT_TIMEOUT_MS = 5e3;
327
- var DEFAULT_BUDGET_TOKENS = 3e4;
328
324
  function createUserPromptSubmitHandler(config) {
329
- const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
330
- const budgetTokens = config.budgetTokens ?? DEFAULT_BUDGET_TOKENS;
331
325
  return async function handleUserPromptSubmit(input) {
332
326
  const prompt = input.prompt ?? "";
333
327
  const navResult = await ensureNavigationIndex({
@@ -336,29 +330,15 @@ function createUserPromptSubmitHandler(config) {
336
330
  navigationOptions: config.navigationOptions
337
331
  });
338
332
  const navigationIndex = navResult.navigationIndex;
339
- const fallbackSummary = renderNavigationIndexPrompt(navigationIndex);
333
+ const navigationSummary = renderNavigationIndexPrompt(navigationIndex);
334
+ const sections = [
335
+ "## Project Navigation Index",
336
+ navigationSummary,
337
+ "",
338
+ "> Use `analyzer.getContextMap` with candidate paths/artifacts from the index",
339
+ "> when you need structured dependency and read-target guidance."
340
+ ];
340
341
  const candidates = extractCandidateArtifacts(prompt, navigationIndex);
341
- const candidateFiles = candidates.flatMap((c) => {
342
- const patterns = c.artifact.files?.path_patterns ?? [];
343
- return patterns.filter(
344
- (p) => typeof p === "string" && !p.includes("*")
345
- );
346
- });
347
- const contextPackResult = await withDegrade(
348
- async () => {
349
- if (candidateFiles.length === 0) return null;
350
- const bridge = createAnalyzerBridge({
351
- projectRoot: config.projectRoot,
352
- navigationIndex
353
- });
354
- return bridge.generateContextPack(candidateFiles, {
355
- budgetTokens
356
- });
357
- },
358
- null,
359
- timeoutMs
360
- );
361
- const sections = [];
362
342
  if (candidates.length > 0) {
363
343
  const candidateLines = candidates.map((c) => {
364
344
  const props = c.artifact.properties ?? {};
@@ -366,21 +346,10 @@ function createUserPromptSubmitHandler(config) {
366
346
  return `- ${c.artifactId} [${tags}]`;
367
347
  });
368
348
  sections.push(
369
- "## Candidate Artifacts\n" + candidateLines.join("\n")
370
- );
371
- }
372
- if (contextPackResult.value && contextPackResult.value.entries.length > 0) {
373
- sections.push(renderContextPackPrompt(contextPackResult.value));
374
- }
375
- if (contextPackResult.degraded) {
376
- sections.push(
377
- `> Note: Context generation degraded (${contextPackResult.reason ?? "unknown"}). Using navigation-index summary as fallback.`
349
+ "## Candidate Artifacts (from prompt keywords)\n" + candidateLines.join("\n")
378
350
  );
379
- sections.push(fallbackSummary);
380
- } else if (sections.length === 0) {
381
- sections.push(fallbackSummary);
382
351
  }
383
- const additionalContext = sections.join("\n\n");
352
+ const additionalContext = sections.join("\n");
384
353
  return buildContextResponse("UserPromptSubmit", additionalContext);
385
354
  };
386
355
  }
@@ -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/ensure-navigation-index.ts","../../../src/lib/claude-native/file-suggestion.ts","../../../src/lib/claude-native/session-start.ts","../../../src/lib/claude-native/user-prompt-submit.ts","../../../src/lib/claude-native/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 HookInput;\n return parsed;\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 * Ensure Navigation Index — cache warm / invalidation.\n *\n * Checks cache freshness via source file mtime comparison. If stale,\n * calls buildNavigationContext() and writes to .claude/cache/.\n * If fresh, returns cached data immediately.\n *\n * This is the performance-critical path for SessionStart hooks.\n */\n\nimport { stat } from \"node:fs/promises\";\nimport { buildNavigationContext, type NavigationContextOptions } from \"../navigation-context.js\";\nimport {\n createCacheStore,\n computeSourceHash,\n type CacheStore,\n} from \"./cache-store.js\";\nimport { createExclusiveLock } from \"./latency.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface EnsureNavigationIndexOptions {\n /** Absolute path to .claude/cache/ directory. */\n cacheDir: string;\n /** Paths to source files whose mtime drives cache invalidation. */\n sourceFiles: string[];\n /** Options for buildNavigationContext() when cache is stale. */\n navigationOptions: NavigationContextOptions;\n}\n\nexport interface NavigationIndexResult {\n navigationIndex: Record<string, unknown>;\n /** Whether the result was loaded from cache (true) or freshly built (false). */\n fromCache: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\nconst CACHE_KEY = \"navigation-index\";\n\n/** Shared lock to prevent concurrent navigation-index builds. */\nconst buildLock = createExclusiveLock<NavigationIndexResult>();\n\n/**\n * Collect mtimes for source files and produce a cache hash.\n */\nasync function computeCurrentHash(sourceFiles: string[]): Promise<string> {\n const mtimes: Array<string | number> = [];\n for (const file of sourceFiles) {\n try {\n const s = await stat(file);\n mtimes.push(s.mtimeMs);\n } catch {\n // File not found — include a sentinel so hash changes if file appears\n mtimes.push(`missing:${file}`);\n }\n }\n return computeSourceHash(mtimes);\n}\n\n/**\n * Ensure the navigation index is available and fresh. Returns the index\n * data, building + caching if necessary.\n */\nexport async function ensureNavigationIndex(\n options: EnsureNavigationIndexOptions,\n): Promise<NavigationIndexResult> {\n return buildLock.run(async () => {\n const store: CacheStore = createCacheStore({ cacheDir: options.cacheDir });\n const currentHash = await computeCurrentHash(options.sourceFiles);\n\n // Try cache first\n const cached = await store.readIfFresh<Record<string, unknown>>(\n CACHE_KEY,\n currentHash,\n );\n if (cached) {\n return { navigationIndex: cached, fromCache: true };\n }\n\n // Cache miss or stale — rebuild\n const context = await buildNavigationContext(options.navigationOptions);\n const navigationIndex = context.navigationIndex;\n\n // Write to cache (non-blocking error handling)\n try {\n await store.write(CACHE_KEY, navigationIndex, currentHash);\n } catch {\n // Cache write failure is non-fatal\n }\n\n return { navigationIndex, fromCache: false };\n });\n}\n","/**\n * File Suggestion Handler — artifact-aware @ completion for Claude Code.\n *\n * Reads stdin prefix, filters navigation-index artifacts, and emits NDJSON\n * candidates sorted by relevance score.\n */\n\nimport { listArtifacts, type NavigationArtifact } from \"./artifact-resolver.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface FileSuggestionCandidate {\n label: string;\n path: string;\n kind: \"artifact\" | \"file\";\n /** Artifact ID this file/pattern belongs to. */\n artifact?: string;\n /** Authority of the artifact (canonical, generated, etc.). */\n authority?: string;\n /** Manual edit policy for the artifact. */\n manual_edit?: string;\n /** Relevance score (higher = more relevant). */\n score: number;\n}\n\nexport interface FileSuggestionOptions {\n /** The navigation index to search. */\n navigationIndex: Record<string, unknown>;\n /** Maximum number of candidates to return. */\n maxCandidates?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\nconst DEFAULT_MAX_CANDIDATES = 100;\n\n/**\n * Generate file suggestion candidates from the navigation index.\n * Filters by prefix if provided, then returns NDJSON-formatted candidates.\n */\nexport function generateCandidates(\n prefix: string,\n options: FileSuggestionOptions,\n): FileSuggestionCandidate[] {\n const { navigationIndex, maxCandidates = DEFAULT_MAX_CANDIDATES } = options;\n const artifacts = listArtifacts(navigationIndex);\n const candidates: FileSuggestionCandidate[] = [];\n const lowerPrefix = prefix.toLowerCase();\n\n for (const { id, artifact } of artifacts) {\n const props = artifact.properties ?? {};\n const patterns = artifact.files?.path_patterns ?? [];\n\n // Artifact-level candidate\n if (!prefix || id.toLowerCase().includes(lowerPrefix)) {\n candidates.push({\n label: id,\n path: patterns.length > 0 ? String(patterns[0]) : id,\n kind: \"artifact\",\n authority: props.authority as string | undefined,\n manual_edit: props.manual_edit as string | undefined,\n score: computeArtifactScore(id, artifact, prefix),\n });\n }\n\n // File-level candidates from path patterns\n for (const pattern of patterns) {\n if (typeof pattern !== \"string\") continue;\n // Skip pure glob patterns for file-level suggestions (they're covered by artifact-level)\n if (pattern.includes(\"*\") || pattern.includes(\"?\")) continue;\n\n if (!prefix || pattern.toLowerCase().includes(lowerPrefix)) {\n candidates.push({\n label: pattern,\n path: pattern,\n kind: \"file\",\n artifact: id,\n authority: props.authority as string | undefined,\n manual_edit: props.manual_edit as string | undefined,\n score: computeFileScore(pattern, prefix),\n });\n }\n }\n }\n\n // Sort by score descending, then by label\n candidates.sort((a, b) => {\n if (b.score !== a.score) return b.score - a.score;\n return a.label.localeCompare(b.label);\n });\n\n return candidates.slice(0, maxCandidates);\n}\n\n/**\n * Format candidates as NDJSON (one JSON object per line).\n */\nexport function formatNdjson(candidates: FileSuggestionCandidate[]): string {\n return candidates.map((c) => JSON.stringify(c)).join(\"\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Scoring helpers\n// ---------------------------------------------------------------------------\n\nfunction computeArtifactScore(\n id: string,\n artifact: NavigationArtifact,\n prefix: string,\n): number {\n let score = 50;\n const props = artifact.properties ?? {};\n\n // Boost canonical, editable artifacts\n if (props.authority === \"canonical\") score += 20;\n if (props.manual_edit === \"allowed\") score += 10;\n\n // Boost source artifacts\n if (props.type === \"source\") score += 15;\n\n // Penalize generated artifacts\n if (props.authority === \"generated\") score -= 20;\n if (props.manual_edit === \"forbidden\") score -= 10;\n\n // Boost exact prefix match\n if (prefix && id.toLowerCase().startsWith(prefix.toLowerCase())) {\n score += 20;\n }\n\n return score;\n}\n\nfunction computeFileScore(path: string, prefix: string): number {\n let score = 40;\n\n // Boost exact prefix match\n if (prefix && path.toLowerCase().startsWith(prefix.toLowerCase())) {\n score += 30;\n }\n\n // Boost shorter paths (more specific)\n score += Math.max(0, 20 - path.split(\"/\").length * 2);\n\n return score;\n}\n\n/**\n * Main handler for file-suggestion bin script.\n * Reads prefix from stdin, returns NDJSON candidates to stdout.\n */\nexport async function handleFileSuggestion(\n navigationIndex: Record<string, unknown>,\n stdinData: string,\n): Promise<string> {\n const prefix = stdinData.trim();\n const candidates = generateCandidates(prefix, { navigationIndex });\n return formatNdjson(candidates);\n}\n","/**\n * SessionStart Hook Handler — cache warm + navigation-index summary injection.\n *\n * Executed on session new/resume/clear/compact events. Warms the navigation-index\n * cache and returns a rendered summary as additionalContext.\n *\n * Latency constraint: NO AST analysis or ContextPack generation.\n */\n\nimport { renderNavigationIndexPrompt } from \"../task-runner.js\";\nimport {\n ensureNavigationIndex,\n type EnsureNavigationIndexOptions,\n} from \"./ensure-navigation-index.js\";\nimport {\n buildContextResponse,\n type HookOutput,\n type SessionStartInput,\n} from \"./hook-protocol.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface SessionStartHandlerConfig {\n /** Absolute path to .claude/cache/ directory. */\n cacheDir: string;\n /** Source files for cache invalidation (component.yaml, agent-contracts.yaml, etc.). */\n sourceFiles: string[];\n /** Options for buildNavigationContext(). */\n navigationOptions: EnsureNavigationIndexOptions[\"navigationOptions\"];\n}\n\n// ---------------------------------------------------------------------------\n// Handler\n// ---------------------------------------------------------------------------\n\n/**\n * Create a SessionStart hook handler.\n */\nexport function createSessionStartHandler(config: SessionStartHandlerConfig) {\n return async function handleSessionStart(\n _input: SessionStartInput,\n ): Promise<HookOutput> {\n const result = await ensureNavigationIndex({\n cacheDir: config.cacheDir,\n sourceFiles: config.sourceFiles,\n navigationOptions: config.navigationOptions,\n });\n\n const summary = renderNavigationIndexPrompt(result.navigationIndex);\n const cacheNote = result.fromCache\n ? \"(loaded from cache)\"\n : \"(freshly built)\";\n\n const additionalContext = [\n summary,\n \"\",\n `Navigation index ${cacheNote}. Use analyzer MCP tools for deep investigation.`,\n ].join(\"\\n\");\n\n return buildContextResponse(\"SessionStart\", additionalContext);\n };\n}\n","/**\n * UserPromptSubmit Hook Handler — ContextPack + candidate metadata injection.\n *\n * Executed after prompt submission, before Claude processes it. Extracts\n * artifact candidates from the prompt, generates a ContextPack via the\n * analyzer bridge, and composes additionalContext.\n *\n * Hard timeout with fallback to navigation-index summary only.\n */\n\nimport { renderNavigationIndexPrompt } from \"../task-runner.js\";\nimport {\n createAnalyzerBridge,\n renderContextPackPrompt,\n type ContextPack,\n} from \"../analyzer-bridge.js\";\nimport {\n ensureNavigationIndex,\n type EnsureNavigationIndexOptions,\n} from \"./ensure-navigation-index.js\";\nimport {\n resolvePathToArtifacts,\n listArtifacts,\n} from \"./artifact-resolver.js\";\nimport {\n buildContextResponse,\n type HookOutput,\n type UserPromptSubmitInput,\n} from \"./hook-protocol.js\";\nimport { withDegrade } from \"./latency.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface UserPromptSubmitHandlerConfig {\n /** Absolute path to the project root. */\n projectRoot: string;\n /** Absolute path to .claude/cache/ directory. */\n cacheDir: string;\n /** Source files for cache invalidation. */\n sourceFiles: string[];\n /** Options for buildNavigationContext(). */\n navigationOptions: EnsureNavigationIndexOptions[\"navigationOptions\"];\n /** Hard timeout for the entire handler in ms. */\n timeoutMs?: number;\n /** Token budget for ContextPack generation. */\n budgetTokens?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst DEFAULT_TIMEOUT_MS = 5_000;\nconst DEFAULT_BUDGET_TOKENS = 30_000;\n\n// ---------------------------------------------------------------------------\n// Handler\n// ---------------------------------------------------------------------------\n\n/**\n * Create a UserPromptSubmit hook handler.\n */\nexport function createUserPromptSubmitHandler(\n config: UserPromptSubmitHandlerConfig,\n) {\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const budgetTokens = config.budgetTokens ?? DEFAULT_BUDGET_TOKENS;\n\n return async function handleUserPromptSubmit(\n input: UserPromptSubmitInput,\n ): Promise<HookOutput> {\n const prompt = input.prompt ?? \"\";\n\n // Step 1: Ensure navigation index is available\n const navResult = await ensureNavigationIndex({\n cacheDir: config.cacheDir,\n sourceFiles: config.sourceFiles,\n navigationOptions: config.navigationOptions,\n });\n const navigationIndex = navResult.navigationIndex;\n\n // Build fallback summary for degrade path\n const fallbackSummary = renderNavigationIndexPrompt(navigationIndex);\n\n // Step 2: Extract candidate artifacts from prompt\n const candidates = extractCandidateArtifacts(prompt, navigationIndex);\n const candidateFiles = candidates.flatMap((c) => {\n const patterns = c.artifact.files?.path_patterns ?? [];\n return patterns.filter(\n (p): p is string => typeof p === \"string\" && !p.includes(\"*\"),\n );\n });\n\n // Step 3: Generate ContextPack with timeout + degrade\n const contextPackResult = await withDegrade(\n async () => {\n if (candidateFiles.length === 0) return null;\n\n const bridge = createAnalyzerBridge({\n projectRoot: config.projectRoot,\n navigationIndex,\n });\n\n return bridge.generateContextPack(candidateFiles, {\n budgetTokens,\n });\n },\n null as ContextPack | null,\n timeoutMs,\n );\n\n // Step 4: Compose additionalContext\n const sections: string[] = [];\n\n // Candidate metadata\n if (candidates.length > 0) {\n const candidateLines = candidates.map((c) => {\n const props = c.artifact.properties ?? {};\n const tags = [props.type, props.authority, props.manual_edit ? `edit:${props.manual_edit}` : \"\"]\n .filter(Boolean)\n .join(\", \");\n return `- ${c.artifactId} [${tags}]`;\n });\n sections.push(\n \"## Candidate Artifacts\\n\" + candidateLines.join(\"\\n\"),\n );\n }\n\n // ContextPack content\n if (contextPackResult.value && contextPackResult.value.entries.length > 0) {\n sections.push(renderContextPackPrompt(contextPackResult.value));\n }\n\n // Degrade note\n if (contextPackResult.degraded) {\n sections.push(\n `> Note: Context generation degraded (${contextPackResult.reason ?? \"unknown\"}). ` +\n \"Using navigation-index summary as fallback.\",\n );\n sections.push(fallbackSummary);\n } else if (sections.length === 0) {\n // No candidates found — provide navigation summary as baseline context\n sections.push(fallbackSummary);\n }\n\n const additionalContext = sections.join(\"\\n\\n\");\n return buildContextResponse(\"UserPromptSubmit\", additionalContext);\n };\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\ninterface CandidateArtifact {\n artifactId: string;\n artifact: ReturnType<typeof listArtifacts>[number][\"artifact\"];\n}\n\n/**\n * Extract candidate artifacts from prompt text by keyword matching\n * against artifact IDs and path patterns.\n */\nfunction extractCandidateArtifacts(\n prompt: string,\n navigationIndex: Record<string, unknown>,\n): CandidateArtifact[] {\n if (!prompt.trim()) return [];\n\n const artifacts = listArtifacts(navigationIndex);\n const lowerPrompt = prompt.toLowerCase();\n const matches: CandidateArtifact[] = [];\n const seen = new Set<string>();\n\n for (const { id, artifact } of artifacts) {\n // Match artifact ID in prompt\n if (lowerPrompt.includes(id.toLowerCase()) && !seen.has(id)) {\n seen.add(id);\n matches.push({ artifactId: id, artifact });\n continue;\n }\n\n // Match path patterns in prompt\n const patterns = artifact.files?.path_patterns ?? [];\n for (const pattern of patterns) {\n if (typeof pattern !== \"string\") continue;\n // Strip glob wildcards for matching\n const literal = pattern.replace(/[*?]/g, \"\").replace(/\\{.*\\}/g, \"\");\n if (literal.length > 3 && lowerPrompt.includes(literal.toLowerCase()) && !seen.has(id)) {\n seen.add(id);\n matches.push({ artifactId: id, artifact });\n break;\n }\n }\n }\n\n return matches;\n}\n","/**\n * 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"],"mappings":";;;;;;;;;;;;;;AAmEO,SAAS,eAAe,KAAwB;AACrD,QAAM,SAAS,KAAK,MAAM,GAAG;AAC7B,SAAO;AACT;AAKA,eAAsB,gBAAoC;AACxD,QAAM,SA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ook-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/ensure-navigation-index.ts","../../../src/lib/claude-native/file-suggestion.ts","../../../src/lib/claude-native/session-start.ts","../../../src/lib/claude-native/user-prompt-submit.ts","../../../src/lib/claude-native/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 HookInput;\n return parsed;\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 * Ensure Navigation Index — cache warm / invalidation.\n *\n * Checks cache freshness via source file mtime comparison. If stale,\n * calls buildNavigationContext() and writes to .claude/cache/.\n * If fresh, returns cached data immediately.\n *\n * This is the performance-critical path for SessionStart hooks.\n */\n\nimport { stat } from \"node:fs/promises\";\nimport { buildNavigationContext, type NavigationContextOptions } from \"../navigation-context.js\";\nimport {\n createCacheStore,\n computeSourceHash,\n type CacheStore,\n} from \"./cache-store.js\";\nimport { createExclusiveLock } from \"./latency.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface EnsureNavigationIndexOptions {\n /** Absolute path to .claude/cache/ directory. */\n cacheDir: string;\n /** Paths to source files whose mtime drives cache invalidation. */\n sourceFiles: string[];\n /** Options for buildNavigationContext() when cache is stale. */\n navigationOptions: NavigationContextOptions;\n}\n\nexport interface NavigationIndexResult {\n navigationIndex: Record<string, unknown>;\n /** Whether the result was loaded from cache (true) or freshly built (false). */\n fromCache: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\nconst CACHE_KEY = \"navigation-index\";\n\n/** Shared lock to prevent concurrent navigation-index builds. */\nconst buildLock = createExclusiveLock<NavigationIndexResult>();\n\n/**\n * Collect mtimes for source files and produce a cache hash.\n */\nasync function computeCurrentHash(sourceFiles: string[]): Promise<string> {\n const mtimes: Array<string | number> = [];\n for (const file of sourceFiles) {\n try {\n const s = await stat(file);\n mtimes.push(s.mtimeMs);\n } catch {\n // File not found — include a sentinel so hash changes if file appears\n mtimes.push(`missing:${file}`);\n }\n }\n return computeSourceHash(mtimes);\n}\n\n/**\n * Ensure the navigation index is available and fresh. Returns the index\n * data, building + caching if necessary.\n */\nexport async function ensureNavigationIndex(\n options: EnsureNavigationIndexOptions,\n): Promise<NavigationIndexResult> {\n return buildLock.run(async () => {\n const store: CacheStore = createCacheStore({ cacheDir: options.cacheDir });\n const currentHash = await computeCurrentHash(options.sourceFiles);\n\n // Try cache first\n const cached = await store.readIfFresh<Record<string, unknown>>(\n CACHE_KEY,\n currentHash,\n );\n if (cached) {\n return { navigationIndex: cached, fromCache: true };\n }\n\n // Cache miss or stale — rebuild\n const context = await buildNavigationContext(options.navigationOptions);\n const navigationIndex = context.navigationIndex;\n\n // Write to cache (non-blocking error handling)\n try {\n await store.write(CACHE_KEY, navigationIndex, currentHash);\n } catch {\n // Cache write failure is non-fatal\n }\n\n return { navigationIndex, fromCache: false };\n });\n}\n","/**\n * File Suggestion Handler — artifact-aware @ completion for Claude Code.\n *\n * Reads stdin prefix, filters navigation-index artifacts, and emits NDJSON\n * candidates sorted by relevance score.\n */\n\nimport { listArtifacts, type NavigationArtifact } from \"./artifact-resolver.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface FileSuggestionCandidate {\n label: string;\n path: string;\n kind: \"artifact\" | \"file\";\n /** Artifact ID this file/pattern belongs to. */\n artifact?: string;\n /** Authority of the artifact (canonical, generated, etc.). */\n authority?: string;\n /** Manual edit policy for the artifact. */\n manual_edit?: string;\n /** Relevance score (higher = more relevant). */\n score: number;\n}\n\nexport interface FileSuggestionOptions {\n /** The navigation index to search. */\n navigationIndex: Record<string, unknown>;\n /** Maximum number of candidates to return. */\n maxCandidates?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\nconst DEFAULT_MAX_CANDIDATES = 100;\n\n/**\n * Generate file suggestion candidates from the navigation index.\n * Filters by prefix if provided, then returns NDJSON-formatted candidates.\n */\nexport function generateCandidates(\n prefix: string,\n options: FileSuggestionOptions,\n): FileSuggestionCandidate[] {\n const { navigationIndex, maxCandidates = DEFAULT_MAX_CANDIDATES } = options;\n const artifacts = listArtifacts(navigationIndex);\n const candidates: FileSuggestionCandidate[] = [];\n const lowerPrefix = prefix.toLowerCase();\n\n for (const { id, artifact } of artifacts) {\n const props = artifact.properties ?? {};\n const patterns = artifact.files?.path_patterns ?? [];\n\n // Artifact-level candidate\n if (!prefix || id.toLowerCase().includes(lowerPrefix)) {\n candidates.push({\n label: id,\n path: patterns.length > 0 ? String(patterns[0]) : id,\n kind: \"artifact\",\n authority: props.authority as string | undefined,\n manual_edit: props.manual_edit as string | undefined,\n score: computeArtifactScore(id, artifact, prefix),\n });\n }\n\n // File-level candidates from path patterns\n for (const pattern of patterns) {\n if (typeof pattern !== \"string\") continue;\n // Skip pure glob patterns for file-level suggestions (they're covered by artifact-level)\n if (pattern.includes(\"*\") || pattern.includes(\"?\")) continue;\n\n if (!prefix || pattern.toLowerCase().includes(lowerPrefix)) {\n candidates.push({\n label: pattern,\n path: pattern,\n kind: \"file\",\n artifact: id,\n authority: props.authority as string | undefined,\n manual_edit: props.manual_edit as string | undefined,\n score: computeFileScore(pattern, prefix),\n });\n }\n }\n }\n\n // Sort by score descending, then by label\n candidates.sort((a, b) => {\n if (b.score !== a.score) return b.score - a.score;\n return a.label.localeCompare(b.label);\n });\n\n return candidates.slice(0, maxCandidates);\n}\n\n/**\n * Format candidates as NDJSON (one JSON object per line).\n */\nexport function formatNdjson(candidates: FileSuggestionCandidate[]): string {\n return candidates.map((c) => JSON.stringify(c)).join(\"\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Scoring helpers\n// ---------------------------------------------------------------------------\n\nfunction computeArtifactScore(\n id: string,\n artifact: NavigationArtifact,\n prefix: string,\n): number {\n let score = 50;\n const props = artifact.properties ?? {};\n\n // Boost canonical, editable artifacts\n if (props.authority === \"canonical\") score += 20;\n if (props.manual_edit === \"allowed\") score += 10;\n\n // Boost source artifacts\n if (props.type === \"source\") score += 15;\n\n // Penalize generated artifacts\n if (props.authority === \"generated\") score -= 20;\n if (props.manual_edit === \"forbidden\") score -= 10;\n\n // Boost exact prefix match\n if (prefix && id.toLowerCase().startsWith(prefix.toLowerCase())) {\n score += 20;\n }\n\n return score;\n}\n\nfunction computeFileScore(path: string, prefix: string): number {\n let score = 40;\n\n // Boost exact prefix match\n if (prefix && path.toLowerCase().startsWith(prefix.toLowerCase())) {\n score += 30;\n }\n\n // Boost shorter paths (more specific)\n score += Math.max(0, 20 - path.split(\"/\").length * 2);\n\n return score;\n}\n\n/**\n * Main handler for file-suggestion bin script.\n * Reads prefix from stdin, returns NDJSON candidates to stdout.\n */\nexport async function handleFileSuggestion(\n navigationIndex: Record<string, unknown>,\n stdinData: string,\n): Promise<string> {\n const prefix = stdinData.trim();\n const candidates = generateCandidates(prefix, { navigationIndex });\n return formatNdjson(candidates);\n}\n","/**\n * SessionStart Hook Handler — cache warm + navigation-index summary injection.\n *\n * Executed on session new/resume/clear/compact events. Warms the navigation-index\n * cache and returns a rendered summary as additionalContext.\n *\n * Latency constraint: NO AST analysis or ContextPack generation.\n */\n\nimport { renderNavigationIndexPrompt } from \"../task-runner.js\";\nimport {\n ensureNavigationIndex,\n type EnsureNavigationIndexOptions,\n} from \"./ensure-navigation-index.js\";\nimport {\n buildContextResponse,\n type HookOutput,\n type SessionStartInput,\n} from \"./hook-protocol.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface SessionStartHandlerConfig {\n /** Absolute path to .claude/cache/ directory. */\n cacheDir: string;\n /** Source files for cache invalidation (component.yaml, agent-contracts.yaml, etc.). */\n sourceFiles: string[];\n /** Options for buildNavigationContext(). */\n navigationOptions: EnsureNavigationIndexOptions[\"navigationOptions\"];\n}\n\n// ---------------------------------------------------------------------------\n// Handler\n// ---------------------------------------------------------------------------\n\n/**\n * Create a SessionStart hook handler.\n */\nexport function createSessionStartHandler(config: SessionStartHandlerConfig) {\n return async function handleSessionStart(\n _input: SessionStartInput,\n ): Promise<HookOutput> {\n const result = await ensureNavigationIndex({\n cacheDir: config.cacheDir,\n sourceFiles: config.sourceFiles,\n navigationOptions: config.navigationOptions,\n });\n\n const summary = renderNavigationIndexPrompt(result.navigationIndex);\n const cacheNote = result.fromCache\n ? \"(loaded from cache)\"\n : \"(freshly built)\";\n\n const additionalContext = [\n summary,\n \"\",\n `Navigation index ${cacheNote}. Use analyzer MCP tools for deep investigation.`,\n ].join(\"\\n\");\n\n return buildContextResponse(\"SessionStart\", additionalContext);\n };\n}\n","/**\n * UserPromptSubmit Hook Handler — navigation-index summary injection.\n *\n * Executed after prompt submission, before Claude processes it. Provides a\n * compact navigation-index summary so the LLM can pick candidates and delegate\n * deep exploration to `analyzer.getContextMap` (Level 2).\n *\n * ContextPack is NOT pre-injected by default (#206 Phase D).\n */\n\nimport { renderNavigationIndexPrompt } from \"../task-runner.js\";\nimport {\n ensureNavigationIndex,\n type EnsureNavigationIndexOptions,\n} from \"./ensure-navigation-index.js\";\nimport {\n listArtifacts,\n} from \"./artifact-resolver.js\";\nimport {\n buildContextResponse,\n type HookOutput,\n type UserPromptSubmitInput,\n} from \"./hook-protocol.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface UserPromptSubmitHandlerConfig {\n /** Absolute path to the project root. */\n projectRoot: string;\n /** Absolute path to .claude/cache/ directory. */\n cacheDir: string;\n /** Source files for cache invalidation. */\n sourceFiles: string[];\n /** Options for buildNavigationContext(). */\n navigationOptions: EnsureNavigationIndexOptions[\"navigationOptions\"];\n}\n\n// ---------------------------------------------------------------------------\n// Handler\n// ---------------------------------------------------------------------------\n\n/**\n * Create a UserPromptSubmit hook handler.\n */\nexport function createUserPromptSubmitHandler(\n config: UserPromptSubmitHandlerConfig,\n) {\n return async function handleUserPromptSubmit(\n input: UserPromptSubmitInput,\n ): Promise<HookOutput> {\n const prompt = input.prompt ?? \"\";\n\n const navResult = await ensureNavigationIndex({\n cacheDir: config.cacheDir,\n sourceFiles: config.sourceFiles,\n navigationOptions: config.navigationOptions,\n });\n const navigationIndex = navResult.navigationIndex;\n const navigationSummary = renderNavigationIndexPrompt(navigationIndex);\n\n const sections: string[] = [\n \"## Project Navigation Index\",\n navigationSummary,\n \"\",\n \"> Use `analyzer.getContextMap` with candidate paths/artifacts from the index\",\n \"> when you need structured dependency and read-target guidance.\",\n ];\n\n const candidates = extractCandidateArtifacts(prompt, navigationIndex);\n if (candidates.length > 0) {\n const candidateLines = candidates.map((c) => {\n const props = c.artifact.properties ?? {};\n const tags = [props.type, props.authority, props.manual_edit ? `edit:${props.manual_edit}` : \"\"]\n .filter(Boolean)\n .join(\", \");\n return `- ${c.artifactId} [${tags}]`;\n });\n sections.push(\n \"## Candidate Artifacts (from prompt keywords)\\n\" + candidateLines.join(\"\\n\"),\n );\n }\n\n const additionalContext = sections.join(\"\\n\");\n return buildContextResponse(\"UserPromptSubmit\", additionalContext);\n };\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\ninterface CandidateArtifact {\n artifactId: string;\n artifact: ReturnType<typeof listArtifacts>[number][\"artifact\"];\n}\n\nfunction extractCandidateArtifacts(\n prompt: string,\n navigationIndex: Record<string, unknown>,\n): CandidateArtifact[] {\n if (!prompt.trim()) return [];\n\n const artifacts = listArtifacts(navigationIndex);\n const lowerPrompt = prompt.toLowerCase();\n const matches: CandidateArtifact[] = [];\n const seen = new Set<string>();\n\n for (const { id, artifact } of artifacts) {\n if (lowerPrompt.includes(id.toLowerCase()) && !seen.has(id)) {\n seen.add(id);\n matches.push({ artifactId: id, artifact });\n continue;\n }\n\n const patterns = artifact.files?.path_patterns ?? [];\n for (const pattern of patterns) {\n if (typeof pattern !== \"string\") continue;\n const literal = pattern.replace(/[*?]/g, \"\").replace(/\\{.*\\}/g, \"\");\n if (literal.length > 3 && lowerPrompt.includes(literal.toLowerCase()) && !seen.has(id)) {\n seen.add(id);\n matches.push({ artifactId: id, artifact });\n break;\n }\n }\n }\n\n return matches;\n}\n","/**\n * 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"],"mappings":";;;;;;;;;;;;AAmEO,SAAS,eAAe,KAAwB;AACrD,QAAM,SAAS,KAAK,MAAM,GAAG;AAC7B,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;A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,UAC7B;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAGA,WAAO,mBAAmB;AAAA,EAC5B;AACF;","names":["stat","stat"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aaac/runtime",
3
- "version": "0.1.38",
3
+ "version": "0.1.40",
4
4
  "description": "Runtime SDK for the AaaC toolchain",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -59,9 +59,9 @@
59
59
  "node": ">=22.0.0"
60
60
  },
61
61
  "dependencies": {
62
- "@aaac/contracts": "^0.1.17",
63
- "@aaac/toolchain": "^0.1.2",
62
+ "@aaac/contracts": "^0.1.20",
64
63
  "@aaac/observability": "^0.1.15",
64
+ "@aaac/toolchain": "^0.1.2",
65
65
  "agent-contracts": "^0.35.1",
66
66
  "commander": "^12.1.0",
67
67
  "dotenv": "^17.4.2",
@@ -73,7 +73,7 @@
73
73
  "@anthropic-ai/claude-agent-sdk": ">=0.2.0",
74
74
  "@google/adk": ">=1.2.0",
75
75
  "@openai/agents": ">=0.10.0",
76
- "artifact-contracts-analyzer": ">=0.3.0"
76
+ "artifact-contracts-analyzer": ">=0.3.3"
77
77
  },
78
78
  "peerDependenciesMeta": {
79
79
  "@google/adk": {
@@ -88,5 +88,8 @@
88
88
  "artifact-contracts-analyzer": {
89
89
  "optional": true
90
90
  }
91
+ },
92
+ "devDependencies": {
93
+ "artifact-contracts-analyzer": "file:../../../artifact-contracts-analyzer"
91
94
  }
92
95
  }