@aaac/runtime 0.1.53 → 0.1.55

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/adapters/adk-sdk.d.ts +1 -1
  2. package/dist/adapters/adk-sdk.js +1 -1
  3. package/dist/adapters/claude-agent-sdk.d.ts +1 -1
  4. package/dist/adapters/mock.d.ts +1 -1
  5. package/dist/adapters/openai-agents-sdk.d.ts +1 -1
  6. package/dist/{chunk-YZQRSVDZ.js → chunk-3H3PVPPF.js} +198 -4
  7. package/dist/chunk-3H3PVPPF.js.map +1 -0
  8. package/dist/chunk-LDCQZPDG.js +11 -0
  9. package/dist/chunk-LDCQZPDG.js.map +1 -0
  10. package/dist/{chunk-M3GJAHLX.js → chunk-N4KNGDYY.js} +343 -28
  11. package/dist/chunk-N4KNGDYY.js.map +1 -0
  12. package/dist/{chunk-EH5VFZYJ.js → chunk-NMX4C6LC.js} +6 -2
  13. package/dist/chunk-NMX4C6LC.js.map +1 -0
  14. package/dist/{chunk-KNYJV2Q6.js → chunk-QVH5KKBR.js} +5 -9
  15. package/dist/chunk-QVH5KKBR.js.map +1 -0
  16. package/dist/claude-bundles/full.js +223 -217
  17. package/dist/claude-bundles/lean.js +5 -5
  18. package/dist/generator/index.d.ts +2 -286
  19. package/dist/generator/index.js +1 -1
  20. package/dist/index-LqEvaRk-.d.ts +299 -0
  21. package/dist/index.d.ts +29 -17
  22. package/dist/index.js +118 -436
  23. package/dist/index.js.map +1 -1
  24. package/dist/lib/claude-native/hooks-lite.d.ts +18 -325
  25. package/dist/lib/claude-native/hooks-lite.js +8 -2
  26. package/dist/lib/claude-native/index.d.ts +153 -20
  27. package/dist/lib/claude-native/index.js +162 -37
  28. package/dist/lib/claude-native/index.js.map +1 -1
  29. package/dist/{navigation-context-xrReMkTn.d.ts → navigation-context-D_E1NIUf.d.ts} +11 -3
  30. package/dist/{task-runner-Sez_CXcD.d.ts → task-runner-DfIEorkU.d.ts} +21 -9
  31. package/dist/workspace-pre-tool-use-C6nidc0q.d.ts +333 -0
  32. package/package.json +1 -1
  33. package/dist/chunk-EH5VFZYJ.js.map +0 -1
  34. package/dist/chunk-KNYJV2Q6.js.map +0 -1
  35. package/dist/chunk-M3GJAHLX.js.map +0 -1
  36. package/dist/chunk-YZQRSVDZ.js.map +0 -1
@@ -1,9 +1,13 @@
1
1
  import {
2
2
  buildNavigationContext,
3
3
  renderNavigationIndexPrompt
4
- } from "../../chunk-M3GJAHLX.js";
4
+ } from "../../chunk-N4KNGDYY.js";
5
5
  import "../../chunk-ET6TGQRT.js";
6
6
  import "../../chunk-KXGUWBGK.js";
7
+ import {
8
+ PROJECT_CONFIG_FILENAME,
9
+ loadProjectConfig
10
+ } from "../../chunk-3H3PVPPF.js";
7
11
  import {
8
12
  TimeoutError,
9
13
  buildAllowResponse,
@@ -15,7 +19,6 @@ import {
15
19
  createPreToolUseHandler,
16
20
  createWorkspacePreToolUseHandler,
17
21
  emitHookOutput,
18
- guardrailCacheKey,
19
22
  isProtectedArtifact,
20
23
  listArtifacts,
21
24
  parseHookInput,
@@ -25,12 +28,59 @@ import {
25
28
  stripMemberPrefix,
26
29
  withDegrade,
27
30
  withTimeout
28
- } from "../../chunk-KNYJV2Q6.js";
29
- import "../../chunk-EH5VFZYJ.js";
31
+ } from "../../chunk-QVH5KKBR.js";
32
+ import {
33
+ guardrailCacheKey
34
+ } from "../../chunk-LDCQZPDG.js";
35
+ import "../../chunk-NMX4C6LC.js";
30
36
  import "../../chunk-BJ7B4R26.js";
31
37
 
38
+ // src/lib/claude-native/navigation-sources.ts
39
+ import { existsSync } from "fs";
40
+ import { resolve } from "path";
41
+ async function resolveNavigationSources(options) {
42
+ const manifestPath = resolve(options.projectRoot, PROJECT_CONFIG_FILENAME);
43
+ if (!existsSync(manifestPath)) {
44
+ const projectDslPath2 = resolve(options.projectRoot, options.dslPath);
45
+ return {
46
+ navigationOptions: { projectDslPath: projectDslPath2, embeddedDsl: options.embeddedDsl },
47
+ sourceFiles: [projectDslPath2]
48
+ };
49
+ }
50
+ const config = await loadProjectConfig(manifestPath);
51
+ const sourceFiles = [manifestPath];
52
+ const projectDslPath = config.dslDeclared ? config.dslPath : void 0;
53
+ if (projectDslPath) {
54
+ sourceFiles.push(projectDslPath);
55
+ }
56
+ if (config.artifactsPath) {
57
+ sourceFiles.push(config.artifactsPath);
58
+ }
59
+ sourceFiles.push(...config.bindingPaths);
60
+ return {
61
+ navigationOptions: {
62
+ ...projectDslPath ? { projectDslPath } : {},
63
+ embeddedDsl: options.embeddedDsl,
64
+ ...config.artifactsPath ? { artifactBinding: { source: config.artifactsPath } } : {},
65
+ bindingPaths: config.bindingPaths,
66
+ ...config.active_guardrail_policy ? { activeGuardrailPolicy: config.active_guardrail_policy } : {}
67
+ },
68
+ sourceFiles
69
+ };
70
+ }
71
+
32
72
  // src/lib/claude-native/ensure-navigation-index.ts
33
73
  import { stat } from "fs/promises";
74
+ var MAX_RENDERED_DIAGNOSTICS = 20;
75
+ function renderNavigationDiagnostics(diagnostics, label = "navigation-index") {
76
+ if (!diagnostics || diagnostics.length === 0) return void 0;
77
+ const lines = diagnostics.slice(0, MAX_RENDERED_DIAGNOSTICS).map((d) => ` - [${d.severity}] ${d.path}: ${d.message}`);
78
+ const hidden = diagnostics.length - lines.length;
79
+ if (hidden > 0) {
80
+ lines.push(` - \u2026 ${hidden} more`);
81
+ }
82
+ return [`${label} diagnostics (${diagnostics.length}):`, ...lines].join("\n");
83
+ }
34
84
  var DEFAULT_CACHE_KEY = "navigation-index";
35
85
  var buildLocks = /* @__PURE__ */ new Map();
36
86
  function getBuildLock(key) {
@@ -79,7 +129,11 @@ async function ensureNavigationIndex(options) {
79
129
  );
80
130
  } catch {
81
131
  }
82
- return { navigationIndex, fromCache: false };
132
+ return {
133
+ navigationIndex,
134
+ fromCache: false,
135
+ ...context.diagnostics.length > 0 ? { diagnostics: context.diagnostics } : {}
136
+ };
83
137
  });
84
138
  }
85
139
 
@@ -90,13 +144,14 @@ function generateCandidates(prefix, options) {
90
144
  const artifacts = listArtifacts(navigationIndex);
91
145
  const candidates = [];
92
146
  const lowerPrefix = prefix.toLowerCase();
147
+ const rootPath = (path) => joinPathPrefix(options.pathPrefix, path);
93
148
  for (const { id, artifact } of artifacts) {
94
149
  const props = artifact.properties ?? {};
95
150
  const patterns = artifact.files?.path_patterns ?? [];
96
151
  if (!prefix || id.toLowerCase().includes(lowerPrefix)) {
97
152
  candidates.push({
98
153
  label: id,
99
- path: patterns.length > 0 ? String(patterns[0]) : id,
154
+ path: rootPath(patterns.length > 0 ? String(patterns[0]) : id),
100
155
  kind: "artifact",
101
156
  authority: props.authority,
102
157
  manual_edit: props.manual_edit,
@@ -109,7 +164,7 @@ function generateCandidates(prefix, options) {
109
164
  if (!prefix || pattern.toLowerCase().includes(lowerPrefix)) {
110
165
  candidates.push({
111
166
  label: pattern,
112
- path: pattern,
167
+ path: rootPath(pattern),
113
168
  kind: "file",
114
169
  artifact: id,
115
170
  authority: props.authority,
@@ -125,6 +180,11 @@ function generateCandidates(prefix, options) {
125
180
  });
126
181
  return candidates.slice(0, maxCandidates);
127
182
  }
183
+ function joinPathPrefix(prefix, path) {
184
+ if (!prefix) return path;
185
+ const normalized = prefix.replace(/^\.\//, "").replace(/\/+$/, "");
186
+ return normalized ? `${normalized}/${path}` : path;
187
+ }
128
188
  function formatNdjson(candidates) {
129
189
  return candidates.map((c) => JSON.stringify(c)).join("\n");
130
190
  }
@@ -154,6 +214,24 @@ async function handleFileSuggestion(navigationIndex, stdinData) {
154
214
  const candidates = generateCandidates(prefix, { navigationIndex });
155
215
  return formatNdjson(candidates);
156
216
  }
217
+ async function handleWorkspaceFileSuggestion(cacheDir, members, stdinData, maxCandidates = DEFAULT_MAX_CANDIDATES) {
218
+ const prefix = stdinData.trim();
219
+ const store = createCacheStore({ cacheDir });
220
+ const merged = [];
221
+ for (const member of members) {
222
+ const entry = await store.read(member.cacheKey);
223
+ if (!entry) continue;
224
+ merged.push(
225
+ ...generateCandidates(prefix, {
226
+ navigationIndex: entry.data,
227
+ pathPrefix: member.memberPath,
228
+ maxCandidates: Number.POSITIVE_INFINITY
229
+ })
230
+ );
231
+ }
232
+ merged.sort((a, b) => b.score !== a.score ? b.score - a.score : a.label.localeCompare(b.label));
233
+ return formatNdjson(merged.slice(0, maxCandidates));
234
+ }
157
235
 
158
236
  // src/lib/claude-native/session-start.ts
159
237
  function createSessionStartHandler(config) {
@@ -165,10 +243,12 @@ function createSessionStartHandler(config) {
165
243
  });
166
244
  const summary = renderNavigationIndexPrompt(result.navigationIndex);
167
245
  const cacheNote = result.fromCache ? "(loaded from cache)" : "(freshly built)";
246
+ const diagnostics = renderNavigationDiagnostics(result.diagnostics);
168
247
  const additionalContext = [
169
248
  summary,
170
249
  "",
171
- `Navigation index ${cacheNote}. Use analyzer MCP tools for deep investigation.`
250
+ `Navigation index ${cacheNote}. Use analyzer MCP tools for deep investigation.`,
251
+ ...diagnostics ? ["", diagnostics] : []
172
252
  ].join("\n");
173
253
  return buildContextResponse("SessionStart", additionalContext);
174
254
  };
@@ -193,21 +273,25 @@ function createUserPromptSubmitHandler(config) {
193
273
  "> Use `analyzer.getContextMap` with candidate paths/artifacts from the index",
194
274
  "> when you need structured dependency and read-target guidance."
195
275
  ];
196
- const candidates = extractCandidateArtifacts(prompt, navigationIndex);
197
- if (candidates.length > 0) {
198
- const candidateLines = candidates.map((c) => {
199
- const props = c.artifact.properties ?? {};
200
- const tags = [props.type, props.authority, props.manual_edit ? `edit:${props.manual_edit}` : ""].filter(Boolean).join(", ");
201
- return `- ${c.artifactId} [${tags}]`;
202
- });
203
- sections.push(
204
- "## Candidate Artifacts (from prompt keywords)\n" + candidateLines.join("\n")
205
- );
276
+ const candidates = renderCandidateArtifacts(prompt, navigationIndex);
277
+ if (candidates) {
278
+ sections.push(candidates);
206
279
  }
207
280
  const additionalContext = sections.join("\n");
208
281
  return buildContextResponse("UserPromptSubmit", additionalContext);
209
282
  };
210
283
  }
284
+ function renderCandidateArtifacts(prompt, navigationIndex, heading = "## Candidate Artifacts (from prompt keywords)") {
285
+ const candidates = extractCandidateArtifacts(prompt, navigationIndex);
286
+ if (candidates.length === 0) return void 0;
287
+ const lines = candidates.map((c) => {
288
+ const props = c.artifact.properties ?? {};
289
+ const tags = [props.type, props.authority, props.manual_edit ? `edit:${props.manual_edit}` : ""].filter(Boolean).join(", ");
290
+ return `- ${c.artifactId} [${tags}]`;
291
+ });
292
+ return `${heading}
293
+ ${lines.join("\n")}`;
294
+ }
211
295
  function extractCandidateArtifacts(prompt, navigationIndex) {
212
296
  if (!prompt.trim()) return [];
213
297
  const artifacts = listArtifacts(navigationIndex);
@@ -234,35 +318,70 @@ function extractCandidateArtifacts(prompt, navigationIndex) {
234
318
  return matches;
235
319
  }
236
320
 
321
+ // src/lib/claude-native/workspace-members.ts
322
+ async function ensureMemberIndices(cacheDir, members) {
323
+ return Promise.all(
324
+ members.map(async (member) => ({
325
+ member,
326
+ result: await ensureNavigationIndex({
327
+ cacheDir,
328
+ sourceFiles: member.sourceFiles,
329
+ navigationOptions: member.navigationOptions,
330
+ cacheKey: member.cacheKey
331
+ })
332
+ }))
333
+ );
334
+ }
335
+ function renderMemberSection({ member, result }) {
336
+ const summary = renderNavigationIndexPrompt(result.navigationIndex);
337
+ const cacheNote = result.fromCache ? "(loaded from cache)" : "(freshly built)";
338
+ const diagnostics = renderNavigationDiagnostics(
339
+ result.diagnostics,
340
+ `${member.name} navigation-index`
341
+ );
342
+ return `### Member: ${member.name} ${cacheNote}
343
+ ${summary}` + (diagnostics ? `
344
+
345
+ ${diagnostics}` : "");
346
+ }
347
+
237
348
  // src/lib/claude-native/workspace-session-start.ts
238
349
  function createWorkspaceSessionStartHandler(config) {
239
350
  return async function handleWorkspaceSessionStart(_input) {
240
- const results = await Promise.all(
241
- config.members.map(async (member) => {
242
- const result = await ensureNavigationIndex({
243
- cacheDir: config.cacheDir,
244
- sourceFiles: member.sourceFiles,
245
- navigationOptions: member.navigationOptions,
246
- cacheKey: member.cacheKey
247
- });
248
- return { member, result };
249
- })
250
- );
351
+ const results = await ensureMemberIndices(config.cacheDir, config.members);
352
+ const additionalContext = [
353
+ results.map(renderMemberSection).join("\n\n"),
354
+ "",
355
+ "Workspace navigation indices ready. Use analyzer MCP tools for deep investigation."
356
+ ].join("\n");
357
+ return buildContextResponse("SessionStart", additionalContext);
358
+ };
359
+ }
360
+
361
+ // src/lib/claude-native/workspace-user-prompt-submit.ts
362
+ function createWorkspaceUserPromptSubmitHandler(config) {
363
+ return async function handleWorkspaceUserPromptSubmit(input) {
364
+ const prompt = input.prompt ?? "";
365
+ const results = await ensureMemberIndices(config.cacheDir, config.members);
251
366
  const sections = [];
252
- for (const { member, result } of results) {
253
- const summary = renderNavigationIndexPrompt(result.navigationIndex);
254
- const cacheNote = result.fromCache ? "(loaded from cache)" : "(freshly built)";
255
- sections.push(
256
- `### Member: ${member.name} ${cacheNote}
257
- ${summary}`
367
+ for (const entry of results) {
368
+ sections.push(renderMemberSection(entry));
369
+ const candidates = renderCandidateArtifacts(
370
+ prompt,
371
+ entry.result.navigationIndex,
372
+ `#### Candidate Artifacts in ${entry.member.name} (from prompt keywords)`
258
373
  );
374
+ if (candidates) {
375
+ sections.push(candidates);
376
+ }
259
377
  }
260
378
  const additionalContext = [
261
379
  sections.join("\n\n"),
262
380
  "",
263
- "Workspace navigation indices ready. Use analyzer MCP tools for deep investigation."
381
+ "> Use `analyzer.getContextMap` with candidate paths/artifacts from a member's index",
382
+ "> when you need structured dependency and read-target guidance."
264
383
  ].join("\n");
265
- return buildContextResponse("SessionStart", additionalContext);
384
+ return buildContextResponse("UserPromptSubmit", additionalContext);
266
385
  };
267
386
  }
268
387
  export {
@@ -278,15 +397,21 @@ export {
278
397
  createUserPromptSubmitHandler,
279
398
  createWorkspacePreToolUseHandler,
280
399
  createWorkspaceSessionStartHandler,
400
+ createWorkspaceUserPromptSubmitHandler,
281
401
  emitHookOutput,
402
+ ensureMemberIndices,
282
403
  ensureNavigationIndex,
283
404
  formatNdjson,
284
405
  generateCandidates,
285
406
  handleFileSuggestion,
407
+ handleWorkspaceFileSuggestion,
286
408
  isProtectedArtifact,
287
409
  listArtifacts,
288
410
  parseHookInput,
289
411
  readHookInput,
412
+ renderMemberSection,
413
+ renderNavigationDiagnostics,
414
+ resolveNavigationSources,
290
415
  resolvePathToArtifacts,
291
416
  routePathToMember,
292
417
  stripMemberPrefix,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../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/workspace-session-start.ts"],"sourcesContent":["/**\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\";\nimport { guardrailCacheKey } from \"./ensure-navigation-index-keys.js\";\n\nexport { GUARDRAIL_CACHE_SUFFIX, guardrailCacheKey } from \"./ensure-navigation-index-keys.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface EnsureNavigationIndexOptions {\n /** Absolute path to .claude/cache/ directory. */\n cacheDir: string;\n /** Paths to source files whose mtime drives cache invalidation. */\n sourceFiles: string[];\n /** Options for buildNavigationContext() when cache is stale. */\n navigationOptions: NavigationContextOptions;\n /**\n * Cache key for the stored JSON file (default: `\"navigation-index\"`).\n *\n * In workspace mode each member uses its own key, e.g.\n * `\"navigation-index.aaac\"`, so their caches remain isolated.\n * Single-component callers omit this field and the default preserves\n * byte-identical behaviour with previous versions.\n */\n cacheKey?: string;\n}\n\nexport interface NavigationIndexResult {\n navigationIndex: Record<string, unknown>;\n /** Whether the result was loaded from cache (true) or freshly built (false). */\n fromCache: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\nconst DEFAULT_CACHE_KEY = \"navigation-index\";\n\n/**\n * Per-key exclusive locks so concurrent session-start calls for distinct\n * workspace members can build their indices in parallel, while duplicate calls\n * for the same key are deduplicated (share the in-flight promise).\n */\nconst buildLocks = new Map<string, ReturnType<typeof createExclusiveLock<NavigationIndexResult>>>();\n\nfunction getBuildLock(key: string): ReturnType<typeof createExclusiveLock<NavigationIndexResult>> {\n let lock = buildLocks.get(key);\n if (!lock) {\n lock = createExclusiveLock<NavigationIndexResult>();\n buildLocks.set(key, lock);\n }\n return lock;\n}\n\n/**\n * 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 *\n * In workspace mode, pass a unique `cacheKey` per member (e.g.\n * `\"navigation-index.aaac\"`) so each member's index is stored and\n * invalidated independently.\n */\nexport async function ensureNavigationIndex(\n options: EnsureNavigationIndexOptions,\n): Promise<NavigationIndexResult> {\n const cacheKey = options.cacheKey ?? DEFAULT_CACHE_KEY;\n\n return getBuildLock(cacheKey).run(async () => {\n const store: CacheStore = createCacheStore({ cacheDir: options.cacheDir });\n const currentHash = await computeCurrentHash(options.sourceFiles);\n\n // Try cache first\n const cached = await store.readIfFresh<Record<string, unknown>>(\n cacheKey,\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(cacheKey, navigationIndex, currentHash);\n } catch {\n // Cache write failure is non-fatal\n }\n\n // Persist the member's DSL guardrail rules in a companion cache entry so\n // the lean PreToolUse hook can wire Bash guardrails without importing the\n // heavy agent-contracts DSL loader (#238 / C5). We always write, even when\n // there are no rules, so a stale non-empty entry cannot survive a DSL edit\n // that removed all guardrails.\n try {\n await store.write(\n guardrailCacheKey(cacheKey),\n context.guardrailRules ?? { commandRules: [], fileRules: [], contentRules: [] },\n currentHash,\n );\n } catch {\n // Cache write failure is non-fatal\n }\n\n return { 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 // renderNavigationIndexPrompt already emits the \"## Project Navigation\n // Index\" heading — don't duplicate it here.\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 * Workspace SessionStart Hook Handler — per-member navigation-index warm-up.\n *\n * Builds (or validates) a cached navigation-index for each declared workspace\n * member in parallel, then returns a combined summary as `additionalContext`.\n *\n * This module is in the **heavy** path (imports ensureNavigationIndex →\n * navigation-context → agent-contracts) and is therefore NOT included in the\n * lean hooks-lite entry point. SessionStart fires only once per session, so\n * the higher import cost is acceptable.\n */\n\nimport { 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 WorkspaceMemberSessionConfig {\n /** Human-readable member name (e.g. `\"aaac\"`). */\n name: string;\n /** Absolute path to member root directory. */\n root: string;\n /**\n * Unique cache key for this member's navigation-index JSON.\n * Format: `navigation-index.<name>`.\n */\n cacheKey: string;\n /** Source files for mtime-based cache invalidation. */\n sourceFiles: string[];\n /** Options passed to `buildNavigationContext()` on cache miss. */\n navigationOptions: EnsureNavigationIndexOptions[\"navigationOptions\"];\n}\n\nexport interface WorkspaceSessionStartConfig {\n /** Absolute path to the shared `.claude/cache/` directory. */\n cacheDir: string;\n /** Workspace members to build/validate indices for. */\n members: WorkspaceMemberSessionConfig[];\n}\n\n// ---------------------------------------------------------------------------\n// Handler\n// ---------------------------------------------------------------------------\n\n/**\n * Create a workspace-aware SessionStart hook handler.\n *\n * All member navigation-indices are built in **parallel** (each key has its\n * own exclusive lock so concurrent calls for the same member deduplicate\n * rather than queue behind other members).\n */\nexport function createWorkspaceSessionStartHandler(\n config: WorkspaceSessionStartConfig,\n) {\n return async function handleWorkspaceSessionStart(\n _input: SessionStartInput,\n ): Promise<HookOutput> {\n // Build all member indices concurrently\n const results = await Promise.all(\n config.members.map(async (member) => {\n const result = await ensureNavigationIndex({\n cacheDir: config.cacheDir,\n sourceFiles: member.sourceFiles,\n navigationOptions: member.navigationOptions,\n cacheKey: member.cacheKey,\n });\n return { member, result };\n }),\n );\n\n // Aggregate summaries\n const sections: string[] = [];\n for (const { member, result } of results) {\n const summary = renderNavigationIndexPrompt(result.navigationIndex);\n const cacheNote = result.fromCache ? \"(loaded from cache)\" : \"(freshly built)\";\n sections.push(\n `### Member: ${member.name} ${cacheNote}\\n${summary}`,\n );\n }\n\n const additionalContext = [\n sections.join(\"\\n\\n\"),\n \"\",\n \"Workspace navigation indices ready. Use analyzer MCP tools for deep investigation.\",\n ].join(\"\\n\");\n\n return buildContextResponse(\"SessionStart\", additionalContext);\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA,SAAS,YAAY;AA4CrB,IAAM,oBAAoB;AAO1B,IAAM,aAAa,oBAAI,IAA2E;AAElG,SAAS,aAAa,KAA4E;AAChG,MAAI,OAAO,WAAW,IAAI,GAAG;AAC7B,MAAI,CAAC,MAAM;AACT,WAAO,oBAA2C;AAClD,eAAW,IAAI,KAAK,IAAI;AAAA,EAC1B;AACA,SAAO;AACT;AAKA,eAAe,mBAAmB,aAAwC;AACxE,QAAM,SAAiC,CAAC;AACxC,aAAW,QAAQ,aAAa;AAC9B,QAAI;AACF,YAAM,IAAI,MAAM,KAAK,IAAI;AACzB,aAAO,KAAK,EAAE,OAAO;AAAA,IACvB,QAAQ;AAEN,aAAO,KAAK,WAAW,IAAI,EAAE;AAAA,IAC/B;AAAA,EACF;AACA,SAAO,kBAAkB,MAAM;AACjC;AAUA,eAAsB,sBACpB,SACgC;AAChC,QAAM,WAAW,QAAQ,YAAY;AAErC,SAAO,aAAa,QAAQ,EAAE,IAAI,YAAY;AAC5C,UAAM,QAAoB,iBAAiB,EAAE,UAAU,QAAQ,SAAS,CAAC;AACzE,UAAM,cAAc,MAAM,mBAAmB,QAAQ,WAAW;AAGhE,UAAM,SAAS,MAAM,MAAM;AAAA,MACzB;AAAA,MACA;AAAA,IACF;AACA,QAAI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AmB,OAAO;AAAA,UAC1B,UAAU,OAAO;AAAA,QACnB,CAAC;AACD,eAAO,EAAE,QAAQ,OAAO;AAAA,MAC1B,CAAC;AAAA,IACH;AAGA,UAAM,WAAqB,CAAC;AAC5B,eAAW,EAAE,QAAQ,OAAO,KAAK,SAAS;AACxC,YAAM,UAAU,4BAA4B,OAAO,eAAe;AAClE,YAAM,YAAY,OAAO,YAAY,wBAAwB;AAC7D,eAAS;AAAA,QACP,eAAe,OAAO,IAAI,IAAI,SAAS;AAAA,EAAK,OAAO;AAAA,MACrD;AAAA,IACF;AAEA,UAAM,oBAAoB;AAAA,MACxB,SAAS,KAAK,MAAM;AAAA,MACpB;AAAA,MACA;AAAA,IACF,EAAE,KAAK,IAAI;AAEX,WAAO,qBAAqB,gBAAgB,iBAAiB;AAAA,EAC/D;AACF;","names":[]}
1
+ {"version":3,"sources":["../../../src/lib/claude-native/navigation-sources.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/workspace-members.ts","../../../src/lib/claude-native/workspace-session-start.ts","../../../src/lib/claude-native/workspace-user-prompt-submit.ts"],"sourcesContent":["/**\n * Navigation sources — resolve the project manifest into the inputs the\n * navigation-index hooks need (which DSL to overlay, which artifact registry to\n * bind, which files invalidate the cache).\n *\n * The generated `.claude/bin/*` nav hooks bake only what cannot be read from\n * disk at hook time: the component's bundled `/$embedded/` DSL. Everything the\n * project manifest declares (`agents:`, `artifacts:`) is resolved HERE, at hook\n * runtime, through the same `loadProjectConfig` loader the CLI uses — so a\n * manifest edit takes effect without re-running `claude sync`, and the hooks\n * cannot drift from the CLI's view of the project\n * (docs/proposal/workspace-subproject-guardrail.md §3.2).\n */\n\nimport { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport {\n loadProjectConfig,\n PROJECT_CONFIG_FILENAME,\n} from \"../../generator/config.js\";\nimport type { NavigationContextOptions } from \"../navigation-context.js\";\n\nexport interface ResolveNavigationSourcesOptions {\n /**\n * Root of the project whose navigation-index is being built: the directory\n * that owns `project.yaml` (in workspace mode, the member root).\n */\n projectRoot: string;\n /**\n * The component's bundled `/$embedded/` DSL, baked into the hook bin by\n * `claude sync`. Undefined for `aaac generate` output, where the bin resolves\n * `dslPath` directly.\n */\n embeddedDsl?: Record<string, unknown>;\n /**\n * Project-root-relative agents DSL path used ONLY when `projectRoot` has no\n * `project.yaml` (a bare component checkout). With a manifest present the\n * manifest's `agents:` wins.\n */\n dslPath: string;\n}\n\nexport interface NavigationSources {\n navigationOptions: NavigationContextOptions;\n /** Files whose mtime invalidates the navigation-index cache. */\n sourceFiles: string[];\n}\n\n/**\n * Resolve the navigation-index inputs for one project root.\n *\n * With a `project.yaml` present, the manifest is authoritative:\n * - `agents:` → the DSL overlaid on `embeddedDsl` (omitted = embedded as-is),\n * - `artifacts:` → the artifact-contracts registry bound onto the DSL\n * artifacts, so path_patterns / authority / manual_edit reflect the project\n * rather than the component's built-in defaults,\n * - `bindings.guardrail` + `active_guardrail_policy` → the guardrail checks the\n * PreToolUse hook enforces, resolved by the same code as the CLI (#267).\n * All resolved files feed `sourceFiles`, so editing any of them rebuilds the\n * index on the next hook invocation.\n */\nexport async function resolveNavigationSources(\n options: ResolveNavigationSourcesOptions,\n): Promise<NavigationSources> {\n const manifestPath = resolve(options.projectRoot, PROJECT_CONFIG_FILENAME);\n\n if (!existsSync(manifestPath)) {\n const projectDslPath = resolve(options.projectRoot, options.dslPath);\n return {\n navigationOptions: { projectDslPath, embeddedDsl: options.embeddedDsl },\n sourceFiles: [projectDslPath],\n };\n }\n\n const config = await loadProjectConfig(manifestPath);\n const sourceFiles = [manifestPath];\n\n // An undeclared `agents:` means \"no overlay\" — `config.dslPath` is then just\n // the schema default and pointing the loader at it would be a hard failure.\n const projectDslPath = config.dslDeclared ? config.dslPath : undefined;\n if (projectDslPath) {\n sourceFiles.push(projectDslPath);\n }\n\n if (config.artifactsPath) {\n sourceFiles.push(config.artifactsPath);\n }\n\n // Guardrail bindings feed the PreToolUse Bash guard, and edits to them must\n // rebuild the index (#267).\n sourceFiles.push(...config.bindingPaths);\n\n return {\n navigationOptions: {\n ...(projectDslPath ? { projectDslPath } : {}),\n embeddedDsl: options.embeddedDsl,\n ...(config.artifactsPath\n ? { artifactBinding: { source: config.artifactsPath } }\n : {}),\n bindingPaths: config.bindingPaths,\n ...(config.active_guardrail_policy\n ? { activeGuardrailPolicy: config.active_guardrail_policy }\n : {}),\n },\n sourceFiles,\n };\n}\n","/**\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\";\nimport { guardrailCacheKey } from \"./ensure-navigation-index-keys.js\";\n\nexport { GUARDRAIL_CACHE_SUFFIX, guardrailCacheKey } from \"./ensure-navigation-index-keys.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface EnsureNavigationIndexOptions {\n /** Absolute path to .claude/cache/ directory. */\n cacheDir: string;\n /** Paths to source files whose mtime drives cache invalidation. */\n sourceFiles: string[];\n /** Options for buildNavigationContext() when cache is stale. */\n navigationOptions: NavigationContextOptions;\n /**\n * Cache key for the stored JSON file (default: `\"navigation-index\"`).\n *\n * In workspace mode each member uses its own key, e.g.\n * `\"navigation-index.aaac\"`, so their caches remain isolated.\n * Single-component callers omit this field and the default preserves\n * byte-identical behaviour with previous versions.\n */\n cacheKey?: string;\n}\n\nexport interface NavigationIndexResult {\n navigationIndex: Record<string, unknown>;\n /** Whether the result was loaded from cache (true) or freshly built (false). */\n fromCache: boolean;\n /**\n * Diagnostics from the build that produced this index — artifact-binding\n * findings (`unbound-artifact` / `orphan-binding` / `type-mismatch`) and\n * schema validation issues. Present only on a fresh build: they describe the\n * DSL/registry the index was built from, so a caller that hit the cache has\n * already been told once. Callers MUST surface them (a dropped\n * `orphan-binding` is exactly how a project's artifact registry silently\n * fails to reach the hooks — #260).\n */\n diagnostics?: Array<{ path: string; message: string; severity: string }>;\n}\n\n// ---------------------------------------------------------------------------\n// Diagnostics rendering\n// ---------------------------------------------------------------------------\n\n/**\n * How many diagnostics are spelled out before collapsing into a count. Sized to\n * show a whole artifact registry's binding findings (unbound + orphan) for a\n * typical project rather than truncating the picture the reader needs.\n */\nconst MAX_RENDERED_DIAGNOSTICS = 20;\n\n/**\n * Render build diagnostics as hook context lines. Returns undefined when there\n * is nothing to report, so callers can skip the section entirely.\n */\nexport function renderNavigationDiagnostics(\n diagnostics: NavigationIndexResult[\"diagnostics\"],\n label = \"navigation-index\",\n): string | undefined {\n if (!diagnostics || diagnostics.length === 0) return undefined;\n\n const lines = diagnostics\n .slice(0, MAX_RENDERED_DIAGNOSTICS)\n .map((d) => ` - [${d.severity}] ${d.path}: ${d.message}`);\n const hidden = diagnostics.length - lines.length;\n if (hidden > 0) {\n lines.push(` - … ${hidden} more`);\n }\n\n return [`${label} diagnostics (${diagnostics.length}):`, ...lines].join(\"\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\nconst DEFAULT_CACHE_KEY = \"navigation-index\";\n\n/**\n * Per-key exclusive locks so concurrent session-start calls for distinct\n * workspace members can build their indices in parallel, while duplicate calls\n * for the same key are deduplicated (share the in-flight promise).\n */\nconst buildLocks = new Map<string, ReturnType<typeof createExclusiveLock<NavigationIndexResult>>>();\n\nfunction getBuildLock(key: string): ReturnType<typeof createExclusiveLock<NavigationIndexResult>> {\n let lock = buildLocks.get(key);\n if (!lock) {\n lock = createExclusiveLock<NavigationIndexResult>();\n buildLocks.set(key, lock);\n }\n return lock;\n}\n\n/**\n * 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 *\n * In workspace mode, pass a unique `cacheKey` per member (e.g.\n * `\"navigation-index.aaac\"`) so each member's index is stored and\n * invalidated independently.\n */\nexport async function ensureNavigationIndex(\n options: EnsureNavigationIndexOptions,\n): Promise<NavigationIndexResult> {\n const cacheKey = options.cacheKey ?? DEFAULT_CACHE_KEY;\n\n return getBuildLock(cacheKey).run(async () => {\n const store: CacheStore = createCacheStore({ cacheDir: options.cacheDir });\n const currentHash = await computeCurrentHash(options.sourceFiles);\n\n // Try cache first\n const cached = await store.readIfFresh<Record<string, unknown>>(\n cacheKey,\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(cacheKey, navigationIndex, currentHash);\n } catch {\n // Cache write failure is non-fatal\n }\n\n // Persist the member's DSL guardrail rules in a companion cache entry so\n // the lean PreToolUse hook can wire Bash guardrails without importing the\n // heavy agent-contracts DSL loader (#238 / C5). We always write, even when\n // there are no rules, so a stale non-empty entry cannot survive a DSL edit\n // that removed all guardrails.\n try {\n await store.write(\n guardrailCacheKey(cacheKey),\n context.guardrailRules ?? { commandRules: [], fileRules: [], contentRules: [] },\n currentHash,\n );\n } catch {\n // Cache write failure is non-fatal\n }\n\n return {\n navigationIndex,\n fromCache: false,\n ...(context.diagnostics.length > 0 ? { diagnostics: context.diagnostics } : {}),\n };\n });\n}\n","/**\n * File Suggestion Handler — artifact-aware @ completion for Claude Code.\n *\n * Reads stdin prefix, filters navigation-index artifacts, and emits NDJSON\n * candidates sorted by relevance score.\n */\n\nimport { listArtifacts, type NavigationArtifact } from \"./artifact-resolver.js\";\nimport { createCacheStore } from \"./cache-store.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface FileSuggestionCandidate {\n label: string;\n path: string;\n kind: \"artifact\" | \"file\";\n /** Artifact ID this file/pattern belongs to. */\n artifact?: string;\n /** Authority of the artifact (canonical, generated, etc.). */\n authority?: string;\n /** Manual edit policy for the artifact. */\n manual_edit?: string;\n /** Relevance score (higher = more relevant). */\n score: number;\n}\n\nexport interface FileSuggestionOptions {\n /** The navigation index to search. */\n navigationIndex: Record<string, unknown>;\n /** Maximum number of candidates to return. */\n maxCandidates?: number;\n /**\n * Prefix prepended to every emitted path (#266). Artifact `path_patterns` are\n * project-root relative, so in a workspace — where Claude Code's cwd is the\n * workspace root — a member's candidates must be re-rooted under the member\n * directory. The mirror image of `stripMemberPrefix` on the PreToolUse side.\n */\n pathPrefix?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\nconst DEFAULT_MAX_CANDIDATES = 100;\n\n/**\n * Generate file suggestion candidates from the navigation index.\n * Filters by prefix if provided, then returns NDJSON-formatted candidates.\n */\nexport function generateCandidates(\n prefix: string,\n options: FileSuggestionOptions,\n): FileSuggestionCandidate[] {\n const { navigationIndex, maxCandidates = DEFAULT_MAX_CANDIDATES } = options;\n const artifacts = listArtifacts(navigationIndex);\n const candidates: FileSuggestionCandidate[] = [];\n const lowerPrefix = prefix.toLowerCase();\n const rootPath = (path: string) => joinPathPrefix(options.pathPrefix, path);\n\n for (const { id, artifact } of artifacts) {\n const props = artifact.properties ?? {};\n const patterns = artifact.files?.path_patterns ?? [];\n\n // Artifact-level candidate\n if (!prefix || id.toLowerCase().includes(lowerPrefix)) {\n candidates.push({\n label: id,\n path: rootPath(patterns.length > 0 ? String(patterns[0]) : id),\n kind: \"artifact\",\n authority: props.authority as string | undefined,\n manual_edit: props.manual_edit as string | undefined,\n score: computeArtifactScore(id, artifact, prefix),\n });\n }\n\n // File-level candidates from path patterns\n for (const pattern of patterns) {\n if (typeof pattern !== \"string\") continue;\n // Skip pure glob patterns for file-level suggestions (they're covered by artifact-level)\n if (pattern.includes(\"*\") || pattern.includes(\"?\")) continue;\n\n if (!prefix || pattern.toLowerCase().includes(lowerPrefix)) {\n candidates.push({\n label: pattern,\n path: rootPath(pattern),\n kind: \"file\",\n artifact: id,\n authority: props.authority as string | undefined,\n manual_edit: props.manual_edit as string | undefined,\n score: computeFileScore(pattern, prefix),\n });\n }\n }\n }\n\n // Sort by score descending, then by label\n candidates.sort((a, b) => {\n if (b.score !== a.score) return b.score - a.score;\n return a.label.localeCompare(b.label);\n });\n\n return candidates.slice(0, maxCandidates);\n}\n\n/** Join a member path prefix with a project-relative path. */\nfunction joinPathPrefix(prefix: string | undefined, path: string): string {\n if (!prefix) return path;\n const normalized = prefix.replace(/^\\.\\//, \"\").replace(/\\/+$/, \"\");\n return normalized ? `${normalized}/${path}` : path;\n}\n\n/**\n * Format candidates as NDJSON (one JSON object per line).\n */\nexport function formatNdjson(candidates: FileSuggestionCandidate[]): string {\n return candidates.map((c) => JSON.stringify(c)).join(\"\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Scoring helpers\n// ---------------------------------------------------------------------------\n\nfunction computeArtifactScore(\n id: string,\n artifact: NavigationArtifact,\n prefix: string,\n): number {\n let score = 50;\n const props = artifact.properties ?? {};\n\n // Boost canonical, editable artifacts\n if (props.authority === \"canonical\") score += 20;\n if (props.manual_edit === \"allowed\") score += 10;\n\n // Boost source artifacts\n if (props.type === \"source\") score += 15;\n\n // Penalize generated artifacts\n if (props.authority === \"generated\") score -= 20;\n if (props.manual_edit === \"forbidden\") score -= 10;\n\n // Boost exact prefix match\n if (prefix && id.toLowerCase().startsWith(prefix.toLowerCase())) {\n score += 20;\n }\n\n return score;\n}\n\nfunction computeFileScore(path: string, prefix: string): number {\n let score = 40;\n\n // Boost exact prefix match\n if (prefix && path.toLowerCase().startsWith(prefix.toLowerCase())) {\n score += 30;\n }\n\n // Boost shorter paths (more specific)\n score += Math.max(0, 20 - path.split(\"/\").length * 2);\n\n return score;\n}\n\n/**\n * Main handler for file-suggestion bin script.\n * Reads prefix from stdin, returns NDJSON candidates to stdout.\n */\nexport async function handleFileSuggestion(\n navigationIndex: Record<string, unknown>,\n stdinData: string,\n): Promise<string> {\n const prefix = stdinData.trim();\n const candidates = generateCandidates(prefix, { navigationIndex });\n return formatNdjson(candidates);\n}\n\n/** One workspace member's cached index, as the file-suggestion bin knows it. */\nexport interface WorkspaceFileSuggestionMember {\n /** Member name (for diagnostics only). */\n name: string;\n /** Workspace-relative member path — prepended to every candidate path. */\n memberPath: string;\n /** Cache key of this member's navigation-index. */\n cacheKey: string;\n}\n\n/**\n * Workspace variant (#266): merge candidates from every member's own index.\n *\n * The single-component handler reads the lone `navigation-index` cache entry,\n * which workspace mode never writes (each member has its own key) — so `@`\n * completion returned nothing at all. Members whose index has not been built yet\n * are skipped rather than failing the hook: SessionStart warms them.\n */\nexport async function handleWorkspaceFileSuggestion(\n cacheDir: string,\n members: WorkspaceFileSuggestionMember[],\n stdinData: string,\n maxCandidates = DEFAULT_MAX_CANDIDATES,\n): Promise<string> {\n const prefix = stdinData.trim();\n const store = createCacheStore({ cacheDir });\n const merged: FileSuggestionCandidate[] = [];\n\n for (const member of members) {\n const entry = await store.read<Record<string, unknown>>(member.cacheKey);\n if (!entry) continue;\n merged.push(\n ...generateCandidates(prefix, {\n navigationIndex: entry.data,\n pathPrefix: member.memberPath,\n maxCandidates: Number.POSITIVE_INFINITY,\n }),\n );\n }\n\n merged.sort((a, b) => (b.score !== a.score ? b.score - a.score : a.label.localeCompare(b.label)));\n return formatNdjson(merged.slice(0, maxCandidates));\n}\n","/**\n * 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 renderNavigationDiagnostics,\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 diagnostics = renderNavigationDiagnostics(result.diagnostics);\n\n const additionalContext = [\n summary,\n \"\",\n `Navigation index ${cacheNote}. Use analyzer MCP tools for deep investigation.`,\n ...(diagnostics ? [\"\", diagnostics] : []),\n ].join(\"\\n\");\n\n return buildContextResponse(\"SessionStart\", additionalContext);\n };\n}\n","/**\n * 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 .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 // renderNavigationIndexPrompt already emits the \"## Project Navigation\n // Index\" heading — don't duplicate it here.\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 = renderCandidateArtifacts(prompt, navigationIndex);\n if (candidates) {\n sections.push(candidates);\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\n/**\n * Render the prompt-keyword candidate section, or undefined when nothing matched.\n * Shared with the workspace handler, which renders one section per member.\n */\nexport function renderCandidateArtifacts(\n prompt: string,\n navigationIndex: Record<string, unknown>,\n heading = \"## Candidate Artifacts (from prompt keywords)\",\n): string | undefined {\n const candidates = extractCandidateArtifacts(prompt, navigationIndex);\n if (candidates.length === 0) return undefined;\n\n const lines = 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 return `${heading}\\n${lines.join(\"\\n\")}`;\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 * Workspace member navigation — the shared warm-up + rendering used by every\n * workspace hook that needs per-member navigation indices (SessionStart and\n * UserPromptSubmit). One member = one navigation-index cache entry.\n *\n * Heavy path (pulls ensureNavigationIndex → navigation-context → agent-contracts);\n * never import from the lean `hooks-lite` entry.\n */\n\nimport { renderNavigationIndexPrompt } from \"../task-runner.js\";\nimport {\n ensureNavigationIndex,\n renderNavigationDiagnostics,\n type EnsureNavigationIndexOptions,\n type NavigationIndexResult,\n} from \"./ensure-navigation-index.js\";\n\nexport interface WorkspaceMemberNavConfig {\n /** Human-readable member name (e.g. `\"aaac\"`). */\n name: string;\n /** Absolute path to member root directory. */\n root: string;\n /**\n * Unique cache key for this member's navigation-index JSON.\n * Format: `navigation-index.<name>`.\n */\n cacheKey: string;\n /** Source files for mtime-based cache invalidation. */\n sourceFiles: string[];\n /** Options passed to `buildNavigationContext()` on cache miss. */\n navigationOptions: EnsureNavigationIndexOptions[\"navigationOptions\"];\n}\n\nexport interface WorkspaceMemberNavResult {\n member: WorkspaceMemberNavConfig;\n result: NavigationIndexResult;\n}\n\n/**\n * Build (or validate) every member's navigation-index in **parallel** — each\n * cache key has its own exclusive lock, so concurrent calls for the same member\n * deduplicate rather than queue behind other members.\n */\nexport async function ensureMemberIndices(\n cacheDir: string,\n members: WorkspaceMemberNavConfig[],\n): Promise<WorkspaceMemberNavResult[]> {\n return Promise.all(\n members.map(async (member) => ({\n member,\n result: await ensureNavigationIndex({\n cacheDir,\n sourceFiles: member.sourceFiles,\n navigationOptions: member.navigationOptions,\n cacheKey: member.cacheKey,\n }),\n })),\n );\n}\n\n/** One member's context section: index summary + freshness + build diagnostics. */\nexport function renderMemberSection({ member, result }: WorkspaceMemberNavResult): string {\n const summary = renderNavigationIndexPrompt(result.navigationIndex);\n const cacheNote = result.fromCache ? \"(loaded from cache)\" : \"(freshly built)\";\n const diagnostics = renderNavigationDiagnostics(\n result.diagnostics,\n `${member.name} navigation-index`,\n );\n return (\n `### Member: ${member.name} ${cacheNote}\\n${summary}` +\n (diagnostics ? `\\n\\n${diagnostics}` : \"\")\n );\n}\n","/**\n * Workspace SessionStart Hook Handler — per-member navigation-index warm-up.\n *\n * Builds (or validates) a cached navigation-index for each declared workspace\n * member in parallel, then returns a combined summary as `additionalContext`.\n *\n * This module is in the **heavy** path (imports ensureNavigationIndex →\n * navigation-context → agent-contracts) and is therefore NOT included in the\n * lean hooks-lite entry point. SessionStart fires only once per session, so\n * the higher import cost is acceptable.\n */\n\nimport {\n ensureMemberIndices,\n renderMemberSection,\n type WorkspaceMemberNavConfig,\n} from \"./workspace-members.js\";\nimport {\n buildContextResponse,\n type HookOutput,\n type SessionStartInput,\n} from \"./hook-protocol.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface WorkspaceSessionStartConfig {\n /** Absolute path to the shared `.claude/cache/` directory. */\n cacheDir: string;\n /** Workspace members to build/validate indices for. */\n members: WorkspaceMemberNavConfig[];\n}\n\n// ---------------------------------------------------------------------------\n// Handler\n// ---------------------------------------------------------------------------\n\n/**\n * Create a workspace-aware SessionStart hook handler.\n */\nexport function createWorkspaceSessionStartHandler(\n config: WorkspaceSessionStartConfig,\n) {\n return async function handleWorkspaceSessionStart(\n _input: SessionStartInput,\n ): Promise<HookOutput> {\n const results = await ensureMemberIndices(config.cacheDir, config.members);\n\n const additionalContext = [\n results.map(renderMemberSection).join(\"\\n\\n\"),\n \"\",\n \"Workspace navigation indices ready. Use analyzer MCP tools for deep investigation.\",\n ].join(\"\\n\");\n\n return buildContextResponse(\"SessionStart\", additionalContext);\n };\n}\n","/**\n * Workspace UserPromptSubmit Hook Handler — per-member navigation context.\n *\n * The workspace hook set previously emitted the SINGLE-component ContextPack bin\n * at the workspace root (#263): SessionStart and PreToolUse were member-aware\n * while prompt submission saw only the root manifest, so no member's artifacts\n * reached the prompt. This mirrors the SessionStart handler — one index per\n * member — and adds prompt-keyword candidates per member.\n *\n * Heavy path (ensureNavigationIndex → agent-contracts); not part of hooks-lite.\n */\n\nimport {\n ensureMemberIndices,\n renderMemberSection,\n type WorkspaceMemberNavConfig,\n} from \"./workspace-members.js\";\nimport { renderCandidateArtifacts } from \"./user-prompt-submit.js\";\nimport {\n buildContextResponse,\n type HookOutput,\n type UserPromptSubmitInput,\n} from \"./hook-protocol.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface WorkspaceUserPromptSubmitConfig {\n /** Absolute path to the shared `.claude/cache/` directory. */\n cacheDir: string;\n /** Workspace members whose indices feed the prompt context. */\n members: WorkspaceMemberNavConfig[];\n}\n\n// ---------------------------------------------------------------------------\n// Handler\n// ---------------------------------------------------------------------------\n\nexport function createWorkspaceUserPromptSubmitHandler(\n config: WorkspaceUserPromptSubmitConfig,\n) {\n return async function handleWorkspaceUserPromptSubmit(\n input: UserPromptSubmitInput,\n ): Promise<HookOutput> {\n const prompt = input.prompt ?? \"\";\n const results = await ensureMemberIndices(config.cacheDir, config.members);\n\n const sections: string[] = [];\n for (const entry of results) {\n sections.push(renderMemberSection(entry));\n const candidates = renderCandidateArtifacts(\n prompt,\n entry.result.navigationIndex,\n `#### Candidate Artifacts in ${entry.member.name} (from prompt keywords)`,\n );\n if (candidates) {\n sections.push(candidates);\n }\n }\n\n const additionalContext = [\n sections.join(\"\\n\\n\"),\n \"\",\n \"> Use `analyzer.getContextMap` with candidate paths/artifacts from a member's index\",\n \"> when you need structured dependency and read-target guidance.\",\n ].join(\"\\n\");\n\n return buildContextResponse(\"UserPromptSubmit\", additionalContext);\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAcA,SAAS,kBAAkB;AAC3B,SAAS,eAAe;AA8CxB,eAAsB,yBACpB,SAC4B;AAC5B,QAAM,eAAe,QAAQ,QAAQ,aAAa,uBAAuB;AAEzE,MAAI,CAAC,WAAW,YAAY,GAAG;AAC7B,UAAMA,kBAAiB,QAAQ,QAAQ,aAAa,QAAQ,OAAO;AACnE,WAAO;AAAA,MACL,mBAAmB,EAAE,gBAAAA,iBAAgB,aAAa,QAAQ,YAAY;AAAA,MACtE,aAAa,CAACA,eAAc;AAAA,IAC9B;AAAA,EACF;AAEA,QAAM,SAAS,MAAM,kBAAkB,YAAY;AACnD,QAAM,cAAc,CAAC,YAAY;AAIjC,QAAM,iBAA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B,OAAO,UAAU,OAAO,OAAO;AAEzE,UAAM,WAAqB,CAAC;AAC5B,eAAW,SAAS,SAAS;AAC3B,eAAS,KAAK,oBAAoB,KAAK,CAAC;AACxC,YAAM,aAAa;AAAA,QACjB;AAAA,QACA,MAAM,OAAO;AAAA,QACb,+BAA+B,MAAM,OAAO,IAAI;AAAA,MAClD;AACA,UAAI,YAAY;AACd,iBAAS,KAAK,UAAU;AAAA,MAC1B;AAAA,IACF;AAEA,UAAM,oBAAoB;AAAA,MACxB,SAAS,KAAK,MAAM;AAAA,MACpB;AAAA,MACA;AAAA,MACA;AAAA,IACF,EAAE,KAAK,IAAI;AAEX,WAAO,qBAAqB,oBAAoB,iBAAiB;AAAA,EACnE;AACF;","names":["projectDslPath"]}
@@ -9,17 +9,25 @@ interface NavigationContextOptions {
9
9
  mappings?: Record<string, string>;
10
10
  };
11
11
  paths?: Record<string, string>;
12
+ /**
13
+ * Software binding files (`guardrail_impl`) from the project manifest's
14
+ * `bindings.guardrail`. Without them the hooks enforce NO Bash guardrails
15
+ * while the CLI enforces the project's — the asymmetry behind #267.
16
+ */
17
+ bindingPaths?: string[];
18
+ /** Active guardrail policy name from the manifest. */
19
+ activeGuardrailPolicy?: string;
12
20
  }
13
21
  interface NavigationContext {
14
22
  dsl: Record<string, unknown>;
15
23
  navigationIndex: Record<string, unknown>;
16
24
  /**
17
- * DSL guardrail rules (`_guardrailRules`) extracted from the resolved DSL.
25
+ * Guardrail rules resolved from the DSL + the project's software bindings.
18
26
  *
19
27
  * The navigation-index does not carry guardrail rules (it is an
20
28
  * artifact/tool graph), so they are surfaced separately here for the
21
- * PreToolUse Bash guardrail path (#238 / C5). `undefined` when the DSL
22
- * declares no guardrail rules.
29
+ * PreToolUse Bash guardrail path (#238 / C5). `undefined` when the project
30
+ * declares no guardrail binding.
23
31
  */
24
32
  guardrailRules?: GuardrailRuleData;
25
33
  diagnostics: Array<{
@@ -448,7 +448,13 @@ type SdkAdapterFactory = () => SdkAdapter;
448
448
  * Model-aware adapter factory. Accepts a model_class and returns an adapter
449
449
  * configured for that capability level (possibly a different provider/model).
450
450
  */
451
- type ModelAwareSdkAdapterFactory = (modelClass?: ModelClass) => SdkAdapter | Promise<SdkAdapter>;
451
+ type ModelAwareSdkAdapterFactory = (modelClass?: ModelClass,
452
+ /**
453
+ * Agent the step runs as (a task's `target_agent`). Guardrail hooks are fixed at
454
+ * adapter construction, so an agent-scoped factory returns a distinct adapter per
455
+ * agent (#269). Ignored by factories that do not scope guardrails.
456
+ */
457
+ agentId?: string) => SdkAdapter | Promise<SdkAdapter>;
452
458
  /** Accepts either a single adapter (serial/shared) or a factory (parallel-safe). */
453
459
  type AdapterOrFactory = SdkAdapter | SdkAdapterFactory | ModelAwareSdkAdapterFactory;
454
460
  /** Specification for what a step receives from a dependency. */
@@ -564,6 +570,13 @@ interface WorkflowRunOptions {
564
570
  * When undefined, envelopes omit adapter/model (observer spans lack gen_ai attrs).
565
571
  */
566
572
  resolveModelMeta?: (modelClass?: ModelClass) => ResolvedModel;
573
+ /**
574
+ * Request each step's adapter from the factory scoped to the step's agent, so
575
+ * per-agent guardrails apply to the agent actually doing the work (#269). Set by
576
+ * executeWorkflow when the resolved component has per-agent guardrail rules;
577
+ * without it, adapters are shared exactly as before.
578
+ */
579
+ perAgentAdapters?: boolean;
567
580
  }
568
581
  /** Typed handoff envelope for workflow input. */
569
582
  interface HandoffInput<TType extends string = string, TPayload = unknown> {
@@ -628,6 +641,8 @@ interface WorkflowInvocation<THandoffType extends string = string, TPayload = un
628
641
  * not typically set by external callers.
629
642
  */
630
643
  resolveModelMeta?: (modelClass?: ModelClass) => ResolvedModel;
644
+ /** See WorkflowRunOptions.perAgentAdapters (#269). Injected by executeWorkflow. */
645
+ perAgentAdapters?: boolean;
631
646
  }
632
647
  interface StepResult {
633
648
  step_index: number;
@@ -685,9 +700,9 @@ declare function parseGateEvaluationResponse(response: string): boolean;
685
700
  /**
686
701
  * BoundResolver — runtime binding + policy resolution with per-agent isolation.
687
702
  *
688
- * Resolves artifact binding and guardrail/policy in one pass at runtime,
703
+ * Resolves artifact composition and guardrail/policy in one pass at runtime,
689
704
  * producing a per-agent scoped ResolvedComponent. Reuses existing
690
- * resolveBound(), buildGuardrailContext(), and agent scope resolution.
705
+ * resolveArtifacts(), buildGuardrailContext(), and agent scope resolution.
691
706
  */
692
707
 
693
708
  interface ArtifactBindingConfig {
@@ -705,7 +720,7 @@ interface BoundResolveOptions {
705
720
  bindingPaths?: string[];
706
721
  /** Active guardrail policy name from DSL guardrail_policies. */
707
722
  activeGuardrailPolicy?: string;
708
- /** Artifact binding config — resolved via agent-contracts resolveBound(). */
723
+ /** Artifact binding config — composed via resolveArtifacts() (lib/artifact-resolver). */
709
724
  artifactBinding?: ArtifactBindingConfig;
710
725
  /** Path substitutions for artifact binding. */
711
726
  paths?: Record<string, string>;
@@ -758,11 +773,8 @@ declare class BoundResolver {
758
773
  /** Clear cached components (e.g. for testing). */
759
774
  clearCache(): void;
760
775
  }
761
- /**
762
- * Get guardrail rules for a specific agent from a ResolvedComponent.
763
- * Falls back to embedded _guardrailRules when no per-agent rules exist.
764
- */
765
- declare function getGuardrailRulesForAgent(component: ResolvedComponent, agentId: string, fallbackDsl?: Record<string, unknown>): GuardrailRuleData | undefined;
776
+ /** Get guardrail rules for a specific agent from a ResolvedComponent. */
777
+ declare function getGuardrailRulesForAgent(component: ResolvedComponent, agentId: string): GuardrailRuleData | undefined;
766
778
 
767
779
  /**
768
780
  * Candidate Agents — backend-neutral bridge for LLM-internal routing (model B)