@aiwg/cli 2026.11.0 → 2026.11.2

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 (168) hide show
  1. package/agentic/code/addons/aiwg-hooks/canonical/aiwg-prompt-discovery.yaml +9 -0
  2. package/agentic/code/addons/aiwg-hooks/hooks/aiwg-prompt-discovery.cjs +136 -0
  3. package/agentic/code/providers/flue/README.md +2 -1
  4. package/agentic/code/providers/model-capabilities.v1.json +27 -23
  5. package/agentic/code/providers/model-catalog.v1.json +3 -3
  6. package/dist/src/artifacts/cli.js +13 -13
  7. package/dist/src/artifacts/discover-cli-help.js +25 -0
  8. package/dist/src/artifacts/discover-facets.js +2 -0
  9. package/dist/src/artifacts/discover-session-facets.js +15 -0
  10. package/dist/src/artifacts/fortemi-core-prebuilt-freshness.js +28 -0
  11. package/dist/src/artifacts/fortemi-core-query-adapter.js +4 -4
  12. package/dist/src/artifacts/fortemi-core-sync.js +3 -0
  13. package/dist/src/artifacts/framework-capabilities.js +11 -3
  14. package/dist/src/artifacts/framework-source-digest.js +1 -1
  15. package/dist/src/artifacts/index-builder.js +12 -13
  16. package/dist/src/artifacts/index-dependencies.js +72 -0
  17. package/dist/src/artifacts/query-engine-discover-output.js +13 -5
  18. package/dist/src/artifacts/query-engine-discover.js +103 -28
  19. package/dist/src/artifacts/query-engine-entries.js +107 -10
  20. package/dist/src/artifacts/query-engine-installation.js +27 -0
  21. package/dist/src/artifacts/query-engine-options.js +14 -1
  22. package/dist/src/artifacts/query-engine-rules.js +1 -2
  23. package/dist/src/artifacts/query-engine-scoring.js +38 -32
  24. package/dist/src/artifacts/query-engine-show-card.js +8 -2
  25. package/dist/src/artifacts/query-engine-show-load.js +1 -1
  26. package/dist/src/artifacts/query-engine-show.js +5 -3
  27. package/dist/src/artifacts/query-engine-templates.js +33 -0
  28. package/dist/src/artifacts/query-engine-verbose.js +25 -0
  29. package/dist/src/artifacts/relations-builder.js +49 -4
  30. package/dist/src/artifacts/relations.js +26 -10
  31. package/dist/src/artifacts/template-references.js +42 -0
  32. package/dist/src/artifacts/types.js +1 -1
  33. package/dist/src/cli/handlers/bundle-reconciliation.js +7 -3
  34. package/dist/src/cli/handlers/checkpoint-handoff.js +48 -0
  35. package/dist/src/cli/handlers/checkpoint-record.js +20 -0
  36. package/dist/src/cli/handlers/checkpoint.js +176 -0
  37. package/dist/src/cli/handlers/decision.js +1 -1
  38. package/dist/src/cli/handlers/doctor-args.js +3 -1
  39. package/dist/src/cli/handlers/doctor-help.js +2 -1
  40. package/dist/src/cli/handlers/help.js +1 -0
  41. package/dist/src/cli/handlers/index.js +4 -2
  42. package/dist/src/cli/handlers/models-resource-sample.js +7 -3
  43. package/dist/src/cli/handlers/ralph-launcher.js +1 -1
  44. package/dist/src/cli/handlers/refresh-bundles.js +2 -1
  45. package/dist/src/cli/handlers/refresh-managed-deployment.js +196 -0
  46. package/dist/src/cli/handlers/refresh.js +10 -2
  47. package/dist/src/cli/handlers/script-runner.js +2 -1
  48. package/dist/src/cli/handlers/steward-signing.js +44 -0
  49. package/dist/src/cli/handlers/steward.js +5 -0
  50. package/dist/src/cli/handlers/subcommands-discovery.js +8 -1
  51. package/dist/src/cli/handlers/use-provider-results.js +17 -0
  52. package/dist/src/cli/handlers/use.js +19 -18
  53. package/dist/src/cli/router.js +12 -2
  54. package/dist/src/cli/services/deployment-verification.js +11 -7
  55. package/dist/src/cli/user-scope-mirror.js +3 -1
  56. package/dist/src/config/aiwg-config.js +5 -1
  57. package/dist/src/config/cli.js +1 -0
  58. package/dist/src/config/delivery-validation.js +21 -0
  59. package/dist/src/config/host-resource-report.d.mts +1 -1
  60. package/dist/src/config/host-resource-report.mjs +23 -4
  61. package/dist/src/config/host-resource-runtime.d.mts +8 -0
  62. package/dist/src/config/host-resource-runtime.mjs +67 -24
  63. package/dist/src/config/index-graph-overrides.js +4 -0
  64. package/dist/src/config/worker-attribution.d.mts +7 -0
  65. package/dist/src/config/worker-attribution.mjs +44 -0
  66. package/dist/src/config/worker-write.js +4 -10
  67. package/dist/src/decision/ledger.js +15 -15
  68. package/dist/src/decision/offload.js +6 -7
  69. package/dist/src/delivery/git.js +62 -0
  70. package/dist/src/delivery/pr.js +151 -0
  71. package/dist/src/delivery/template-sections.js +56 -0
  72. package/dist/src/delivery/tracker.js +33 -0
  73. package/dist/src/discovery/interview.js +1 -1
  74. package/dist/src/extensions/claude-hooks-installer.js +62 -53
  75. package/dist/src/extensions/loader.js +2 -1
  76. package/dist/src/extensions/managed-hook-script-state.js +48 -0
  77. package/dist/src/extensions/muse-managed-hooks.js +49 -0
  78. package/dist/src/issues/cli.js +15 -3
  79. package/dist/src/issues/external-cli.js +79 -0
  80. package/dist/src/issues/live.js +26 -2
  81. package/dist/src/issues/local.js +5 -1
  82. package/dist/src/issues/tracker-policy.js +27 -0
  83. package/dist/src/mcp/json-document.d.mts +2 -0
  84. package/dist/src/mcp/tools/worker-invoke.mjs +2 -1
  85. package/dist/src/mcp/tools/worker-stdin-runtime.mjs +12 -0
  86. package/dist/src/models/conductor-data-policy.d.mts +3 -2
  87. package/dist/src/models/conductor-data-policy.mjs +94 -5
  88. package/dist/src/models/model-capabilities.v1.json +27 -23
  89. package/dist/src/models/model-catalog.v1.json +3 -3
  90. package/dist/src/models/provider-policy.js +8 -0
  91. package/dist/src/models/worker-health-readiness.js +20 -4
  92. package/dist/src/models/worker-health-snapshot.js +29 -0
  93. package/dist/src/models/worker-installation.d.mts +5 -1
  94. package/dist/src/models/worker-installation.mjs +11 -5
  95. package/dist/src/models/worker-plan.js +3 -3
  96. package/dist/src/models/worker-qualification-policy.js +54 -0
  97. package/dist/src/models/worker-selection-policy.js +2 -1
  98. package/dist/src/providers/deployment-lock.js +77 -0
  99. package/dist/src/providers/deployment-ownership.d.mts +12 -2
  100. package/dist/src/providers/deployment-ownership.mjs +115 -21
  101. package/dist/src/providers/deployment-preservation.d.mts +2 -1
  102. package/dist/src/providers/deployment-preservation.mjs +3 -0
  103. package/dist/src/providers/provider-definitions.js +4 -0
  104. package/dist/src/providers/skill-ownership.d.mts +1 -0
  105. package/dist/src/providers/transformation-receipt-integration.js +4 -2
  106. package/dist/src/providers/transformation-receipt.js +4 -2
  107. package/dist/src/serve/worker-invocation-preparation.js +3 -1
  108. package/dist/src/serve/worker-invocation.js +6 -2
  109. package/dist/src/skills/run.js +5 -0
  110. package/dist/src/smiths/context-pipeline/workspace-audit.js +34 -17
  111. package/dist/src/smiths/context-pipeline/workspace-context-shared.js +12 -6
  112. package/dist/src/smiths/context-pipeline/workspace-doctor.js +44 -4
  113. package/dist/src/smiths/context-pipeline/workspace-document.js +5 -2
  114. package/dist/src/smiths/context-pipeline/workspace-migration.js +2 -1
  115. package/dist/src/smiths/hook-bridge/codex-translator.js +150 -92
  116. package/dist/src/smiths/hook-bridge/codex-trust.js +50 -0
  117. package/dist/src/smiths/hook-bridge/factory-hook-config.js +132 -0
  118. package/dist/src/smiths/hook-bridge/factory-translator.js +88 -33
  119. package/dist/src/smiths/hook-bridge/hermes-translator.js +3 -1
  120. package/dist/src/smiths/hook-bridge/index.js +3 -3
  121. package/dist/src/smiths/hook-bridge/loader.js +10 -2
  122. package/dist/src/smiths/hook-bridge/prompt-discovery-gaps.js +5 -0
  123. package/dist/src/storage/workspace-permissions-health.js +64 -0
  124. package/dist/src/storage/workspace-permissions.js +51 -0
  125. package/package.json +9 -2
  126. package/schemas/models/model-config-compatibility.v1.schema.json +4 -0
  127. package/tools/agents/deploy-agents.mjs +15 -0
  128. package/tools/agents/providers/base-contract.mjs +7 -1
  129. package/tools/agents/providers/base-files.mjs +2 -1
  130. package/tools/agents/providers/base-flat-artifacts.mjs +6 -3
  131. package/tools/agents/providers/base-inventory.mjs +35 -13
  132. package/tools/agents/providers/base-models-platforms.mjs +3 -3
  133. package/tools/agents/providers/base-skill-copy.mjs +2 -0
  134. package/tools/agents/providers/base.mjs +1 -1
  135. package/tools/agents/providers/bound-rules-pointer.mjs +21 -0
  136. package/tools/agents/providers/claude-post-deploy.mjs +9 -5
  137. package/tools/agents/providers/codex-post-deploy.mjs +10 -0
  138. package/tools/agents/providers/conductor-data-guard.mjs +35 -11
  139. package/tools/agents/providers/factory-hooks.mjs +43 -0
  140. package/tools/agents/providers/factory.mjs +4 -91
  141. package/tools/agents/providers/muse-hooks.mjs +6 -41
  142. package/tools/agents/providers/muse-prompt-discovery.mjs +18 -0
  143. package/tools/agents/providers/packaged-codex-agents.mjs +48 -0
  144. package/tools/agents/providers/provider-prepare-coordinator.mjs +15 -10
  145. package/tools/agents/providers/rule-delivery-surface.mjs +10 -7
  146. package/tools/agents/providers/rule-deployment-commit.mjs +10 -0
  147. package/tools/agents/providers/rule-presentation.mjs +6 -5
  148. package/tools/agents/providers/rule-projection.mjs +10 -2
  149. package/tools/agents/providers/rule-startup.mjs +8 -1
  150. package/tools/agents/providers/stale-artifact-prune.mjs +9 -8
  151. package/tools/cli/decision-offload-report.mjs +7 -2
  152. package/tools/plugin/issue-template-copies.mjs +24 -0
  153. package/tools/plugin/package-plugins.mjs +11 -3
  154. package/tools/ralph-external/lib/factory-adapter.mjs +7 -8
  155. package/tools/ralph-external/lib/worker-artifacts.mjs +4 -2
  156. package/tools/ralph-external/lib/worker-capture.mjs +157 -0
  157. package/tools/ralph-external/lib/worker-final.mjs +43 -8
  158. package/tools/ralph-external/lib/worker-health.mjs +3 -0
  159. package/tools/ralph-external/lib/worker-invocation-processes.mjs +9 -6
  160. package/tools/ralph-external/lib/worker-launch-cli.mjs +20 -2
  161. package/tools/ralph-external/lib/worker-process-identity.mjs +30 -0
  162. package/tools/ralph-external/lib/worker-prompt.mjs +35 -0
  163. package/tools/ralph-external/lib/worker-retry-evidence.mjs +87 -6
  164. package/tools/ralph-external/lib/worker-run-directory-refusal.mjs +8 -0
  165. package/tools/ralph-external/lib/worker-termination.mjs +56 -6
  166. package/tools/ralph-external/process-monitor.mjs +12 -18
  167. package/tools/ralph-external/session-launcher.mjs +53 -36
  168. package/vscode-extension/schemas/aiwg.config.v1.json +15 -0
@@ -13,6 +13,7 @@ import fs from 'fs';
13
13
  import path from 'path';
14
14
  import { createHash } from 'crypto';
15
15
  import { load as loadYaml } from 'js-yaml';
16
+ import { normalizeNamedCaptures } from '../config/index-graph-overrides.js';
16
17
  import { validateDecisionDocument } from '../decision/validate.js';
17
18
  import { parseDecisionJson, parseDecisionYaml } from '../decision/entry.js';
18
19
  import { validateGateDocument } from '../gates/schema.js';
@@ -29,6 +30,8 @@ import { collectGraphIndexFiles, findArtifactFiles, indexPathFor } from './index
29
30
  import { acquireDirectoryLock } from './prebuilt-build-lock.js';
30
31
  import { graphIndexDigest, indexAdapterRegistry, recordIndexVerification } from './index-adapters.js';
31
32
  import { loadMemoryRecord } from '../memory/maintenance-record.js';
33
+ import { extractTemplateReferences, isTemplateReference } from './template-references.js';
34
+ import { createDependencyResolver, extractFlowDependencies } from './index-dependencies.js';
32
35
  function absoluteEntryPath(cwd, entryPath, graph) {
33
36
  if ((!graph || graph === 'project') && entryPath.startsWith(`${DEFAULT_PROJECT_AIWG_DIR}/`)) {
34
37
  return path.join(resolveProjectAiwgDir(cwd), entryPath.slice(DEFAULT_PROJECT_AIWG_DIR.length + 1));
@@ -96,9 +99,10 @@ export function extractMentions(content) {
96
99
  const pattern = /@(?:\$AIWG_ROOT\/)?(\.?aiwg\/[\w./-]+|[a-zA-Z][\w./-]+\.\w+)/g;
97
100
  let match;
98
101
  while ((match = pattern.exec(content)) !== null) {
99
- mentions.add(match[1]);
102
+ if (!isTemplateReference(match[1]))
103
+ mentions.add(match[1]);
100
104
  }
101
- return Array.from(mentions);
105
+ return [...new Set([...mentions, ...extractTemplateReferences(content)])];
102
106
  }
103
107
  /**
104
108
  * Extract relative Markdown links that may resolve to graph-local artifacts.
@@ -623,9 +627,7 @@ function computeChecksum(content) {
623
627
  /**
624
628
  * Convert Python-style named capture groups (?P<name>...) to JS-style (?<name>...)
625
629
  */
626
- export function normalizeNamedCaptures(pattern) {
627
- return pattern.replace(/\(\?P</g, '(?<');
628
- }
630
+ export { normalizeNamedCaptures } from '../config/index-graph-overrides.js';
629
631
  /**
630
632
  * Build a MetadataEntry from filename regex captures instead of file content.
631
633
  * Used when graphConfig.nodeStrategy === 'filename-metadata'.
@@ -813,6 +815,7 @@ export function parseFlowDoc(content, filePath) {
813
815
  capability,
814
816
  tags: labels,
815
817
  searchTerms: [...searchTerms],
818
+ dependencies: extractFlowDependencies(spec),
816
819
  };
817
820
  }
818
821
  /**
@@ -911,7 +914,7 @@ function extractIndexArtifact(job, bindingOnly, warnings = []) {
911
914
  } };
912
915
  const tags = flow?.tags ?? decision?.tags ?? gatePack?.tags ?? (Array.isArray(data.tags) ? data.tags.map(String) : []);
913
916
  const summary = flow?.description ?? decision?.description ?? gatePack?.description ?? schemaDoc?.capability ?? runbook?.capability ?? extractSummary(data, body);
914
- const dependencies = extractMentions(content);
917
+ const dependencies = [...new Set([...extractMentions(content), ...(flow?.dependencies ?? [])])];
915
918
  const markdownLinks = extractMarkdownLinks(content);
916
919
  // Discovery metadata (#1214, #1540, #1792) — meaningful for operational
917
920
  // AIWG artifact kinds. Kept undefined on document types so the index file
@@ -1369,6 +1372,7 @@ async function buildIndexSnapshot(cwd, options, preparePublication, observation)
1369
1372
  }
1370
1373
  // Build tag reverse index
1371
1374
  for (const entry of Object.values(entries)) {
1375
+ entry.dependents = []; // Recompute reverse edges even for reused incremental entries.
1372
1376
  for (const tag of entry.tags) {
1373
1377
  if (!tagIndex[tag])
1374
1378
  tagIndex[tag] = [];
@@ -1377,18 +1381,13 @@ async function buildIndexSnapshot(cwd, options, preparePublication, observation)
1377
1381
  }
1378
1382
  // Build dependency graph and compute dependents
1379
1383
  let markdownLinkEdgeCount = 0;
1380
- const entryPaths = Object.keys(entries);
1381
- const dependencyPaths = new Map();
1384
+ const resolveDependency = createDependencyResolver(entries);
1382
1385
  for (const entry of Object.values(entries)) {
1383
1386
  if (!depGraph[entry.path]) {
1384
1387
  depGraph[entry.path] = { upstream: [], downstream: [] };
1385
1388
  }
1386
1389
  for (const dep of entry.dependencies) {
1387
- // Normalize: check if referenced path exists in the index
1388
- if (!dependencyPaths.has(dep)) {
1389
- dependencyPaths.set(dep, entryPaths.find(p => p === dep || p.endsWith(dep)));
1390
- }
1391
- const normalizedDep = dependencyPaths.get(dep);
1390
+ const normalizedDep = resolveDependency(entry.path, dep);
1392
1391
  if (normalizedDep && normalizedDep !== entry.path) {
1393
1392
  addDependencyEdge(depGraph, entries, entry.path, normalizedDep, 'depends-on');
1394
1393
  }
@@ -0,0 +1,72 @@
1
+ // Resolve indexed file and declarative Flow references without per-edge scans.
2
+ import path from 'node:path';
3
+ import { isTemplateReference, sourceBundleRoot, templateReferenceCandidates } from './template-references.js';
4
+ export function extractFlowDependencies(spec) {
5
+ const result = new Set();
6
+ const pending = [spec];
7
+ const seen = new Set();
8
+ while (pending.length) {
9
+ const value = pending.pop();
10
+ if (!value || typeof value !== 'object' || seen.has(value))
11
+ continue;
12
+ seen.add(value);
13
+ for (const [key, child] of Object.entries(value)) {
14
+ if (['body', 'content', 'script', 'source', 'template'].includes(key))
15
+ continue;
16
+ const kind = key === 'agent' ? 'agent'
17
+ : /^(?:capability|rollback[_-]?capability|playbook|flow)$/.test(key) ? 'flow' : undefined;
18
+ if (kind && typeof child === 'string' && /^[\w.-]+$/.test(child))
19
+ result.add(`${kind}:${child}`);
20
+ else if (child && typeof child === 'object')
21
+ pending.push(child);
22
+ }
23
+ }
24
+ return [...result];
25
+ }
26
+ function register(map, key, value) {
27
+ if (!map.has(key))
28
+ map.set(key, value);
29
+ else if (map.get(key) !== value)
30
+ map.set(key, null);
31
+ }
32
+ export function createDependencyResolver(entries) {
33
+ const suffixes = new Map();
34
+ const names = new Map();
35
+ for (const entry of Object.values(entries)) {
36
+ const file = entry.path;
37
+ for (let offset = file.indexOf('/'); offset >= 0; offset = file.indexOf('/', offset + 1)) {
38
+ register(suffixes, file.slice(offset + 1), file);
39
+ }
40
+ if (['agent', 'flow', 'runbook'].includes(entry.type)) {
41
+ // Flow agent fields use file slugs even when frontmatter names are titles
42
+ // (for example, project-manager.md declares name: Project Manager).
43
+ const basename = path.posix.basename(file);
44
+ const slug = /^(AGENT|FLOW)\.md$/i.test(basename)
45
+ ? path.posix.basename(path.posix.dirname(file)) : basename.replace(/\.[^.]+$/, '');
46
+ for (const alias of new Set([entry.name, slug].filter(Boolean))) {
47
+ const name = `${entry.type === 'agent' ? 'agent' : 'flow'}:${alias}`;
48
+ register(names, name, file);
49
+ register(names, `${sourceBundleRoot(file) ?? ''}|${name}`, file);
50
+ }
51
+ }
52
+ }
53
+ return (source, dep) => {
54
+ if (isTemplateReference(dep)) {
55
+ return templateReferenceCandidates(source, dep).find(candidate => entries[candidate]);
56
+ }
57
+ if (/^(agent|flow):/.test(dep)) {
58
+ const local = `${sourceBundleRoot(source) ?? ''}|${dep}`;
59
+ return (names.has(local) ? names.get(local) : names.get(dep)) ?? undefined;
60
+ }
61
+ if (entries[dep])
62
+ return dep;
63
+ // A bare filename (`@CLAUDE.md`, `@AIWG.md`) names a project or sibling file, not
64
+ // any indexed file that happens to share the basename (for example a template).
65
+ if (!dep.includes('/')) {
66
+ const sibling = path.posix.join(path.posix.dirname(source), dep);
67
+ return entries[sibling] ? sibling : undefined;
68
+ }
69
+ return suffixes.get(dep) ?? undefined;
70
+ };
71
+ }
72
+ //# sourceMappingURL=index-dependencies.js.map
@@ -4,9 +4,11 @@ import { diagnoseFacetActivations } from './discover-facets.js';
4
4
  import { buildRunHint, DISCOVER_TYPE_ORDER, discoveryIdForEntry, normalizeIndexedPath, scopeRank, showHintForDiscoverResult, } from './query-engine-entries.js';
5
5
  import { boundRuleDescriptor, compoundGoverningRules, governingRuleFields, governingRuleStats, RULE_CHECK_OBLIGATION, statsText, } from './query-engine-rules.js';
6
6
  import { tokenize } from './query-engine-scoring.js';
7
- import { ensureRelations } from './relations.js';
7
+ import { ensureRelations, loadRelations } from './relations.js';
8
+ import { templateRelationFields } from './query-engine-templates.js';
8
9
  export async function emitDiscoverResults(context) {
9
- const { cwd, params, types, limit, aiwgRoot, entries, backend, resourceSource, resolvedWebRelease, prebuiltRelations, scored, relaxed, queryTimeMs, lexicalDiagnostics } = context;
10
+ const { cwd, params, types, limit, aiwgRoot, entries, backend, resourceSource, resolvedWebRelease, prebuiltRelations, prebuiltSelection, frameworkReconciled, indexStale, scored, relaxed, queryTimeMs, lexicalDiagnostics } = context;
11
+ const readOnly = Boolean(params.noBuild || indexStale);
10
12
  /**
11
13
  * Resolve a stored framework-graph path to an absolute AIWG_ROOT
12
14
  * path (#1217). Framework-graph entries are stored as paths relative
@@ -43,7 +45,8 @@ export async function emitDiscoverResults(context) {
43
45
  : `No capability matched "${params.phrase}" among ${entries.length} indexed capabilities. Try a broader phrase or a \`--type\` filter. If you just installed or authored capabilities, refresh discovery with \`aiwg use <framework>\` (or \`aiwg index build\`).`
44
46
  : null;
45
47
  const relations = resourceSource === 'local' && (!params.graph || params.graph === 'framework')
46
- ? prebuiltRelations ?? await ensureRelations(cwd) : undefined;
48
+ ? prebuiltRelations ?? (readOnly ? loadRelations(cwd, cwd, false)
49
+ : await ensureRelations(cwd, cwd, { verbose: params.verbose, selection: prebuiltSelection, reconciled: frameworkReconciled })) : undefined;
47
50
  const governing = scored.map(result => compoundGoverningRules(entries, result.entry, relations ?? undefined, params.phrase));
48
51
  const responseRules = new Map();
49
52
  for (const item of governing.flat()) {
@@ -89,8 +92,7 @@ export async function emitDiscoverResults(context) {
89
92
  },
90
93
  };
91
94
  };
92
- const { loadRelations } = await import('./relations.js');
93
- const ruleRelations = resourceSource === 'local' ? loadRelations(cwd) ?? (aiwgRoot ? loadRelations(aiwgRoot, cwd) : null) : null;
95
+ const ruleRelations = relations ?? (resourceSource === 'local' ? loadRelations(cwd, cwd, !readOnly) ?? (aiwgRoot ? loadRelations(aiwgRoot, cwd, !readOnly) : null) : null);
94
96
  if (params.json) {
95
97
  const jsonIndent = params.jsonPretty === false ? undefined : 2;
96
98
  console.log(JSON.stringify({
@@ -119,6 +121,7 @@ export async function emitDiscoverResults(context) {
119
121
  type: r.entry.type,
120
122
  name: r.entry.name,
121
123
  title: r.entry.title,
124
+ ...templateRelationFields(r.entry, ruleRelations, 3, includePaths),
122
125
  score: Math.round(r.score * 100) / 100,
123
126
  ranking: rankingDiagnostic(r.entry, r.score, r.facetDiagnostics),
124
127
  ...governingRuleFields(governing[resultIndex]),
@@ -146,6 +149,7 @@ export async function emitDiscoverResults(context) {
146
149
  rule_stats: responseRuleStats,
147
150
  ...(responseFields.required_rule_checks ? { required_rule_checks: responseFields.required_rule_checks, rule_check_obligation: RULE_CHECK_OBLIGATION } : {}),
148
151
  total: scored.length,
152
+ ...(indexStale ? { stale: true } : {}),
149
153
  query_time_ms: queryTimeMs,
150
154
  diagnostics: {
151
155
  content_tokens: tokenize(params.phrase),
@@ -210,6 +214,10 @@ export async function emitDiscoverResults(context) {
210
214
  `scope ${ranking.tie_breakers.scope}`,
211
215
  ].filter((part) => Boolean(part));
212
216
  console.log(` ranking: ${rankingParts.join('; ')}`);
217
+ for (const [key, items] of Object.entries(templateRelationFields(r.entry, ruleRelations, 3))) {
218
+ if (items?.length)
219
+ console.log(` ${key === 'templates' ? 'templates' : 'used by'}: ${items.map(item => `${item.name} (${item.show_command})`).join('; ')}`);
220
+ }
213
221
  if (governing[i].length) {
214
222
  console.log(` ${statsText(governingRuleStats(governing[i]))}`);
215
223
  console.log(` ${RULE_CHECK_OBLIGATION}`);
@@ -1,15 +1,21 @@
1
- import { applyFacetFusion } from './discover-facets.js';
2
- import { refreshFrameworkCapabilities, resolveFrameworkCorpusRoot } from './framework-capabilities.js';
1
+ // Load and rank capability discovery candidates.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { applyFacetFusion, diagnoseFacetActivations } from './discover-facets.js';
5
+ import { isIndexWritePermissionError, refreshFrameworkCapabilities, resolveFrameworkCorpusRoot } from './framework-capabilities.js';
3
6
  import { resolveFrameworkIndexRoot } from './framework-index-paths.js';
4
7
  import { loadGraphIndexFile, loadMetadataIndex } from './index-reader.js';
5
8
  import { emitDiscoverResults } from './query-engine-discover-output.js';
6
- import { compareDiscoverResults, dedupeDiscoverResults, DEFAULT_ARTIFACT_SEARCH_BACKEND, DEFAULT_DISCOVER_TYPES, defaultCapabilityGraphs, discoveryIdForEntry, isOrdinaryMemoryEntry, projectAllowsUserIndices, projectCapabilityFallback, withIndexProvenance, } from './query-engine-entries.js';
9
+ import { compareDiscoverResults, dedupeDiscoverResults, DEFAULT_ARTIFACT_SEARCH_BACKEND, DEFAULT_DISCOVER_TYPES, defaultCapabilityGraphs, discoveryIdForEntry, isOrdinaryMemoryEntry, projectAllowsUserIndices, projectCapabilityFallback, prepareProjectCapabilityIndex, withIndexProvenance, } from './query-engine-entries.js';
7
10
  import { scoreEntryDetailed } from './query-engine-scoring.js';
8
- import { emptyRuleStats, selectPrebuiltRelations } from './relations.js';
9
- import { loadGlobalGraphConfigs } from './types.js';
11
+ import { emptyRuleStats, selectPrebuiltRelations, loadBuiltRelations } from './relations.js';
12
+ import { templateRelationFields } from './query-engine-templates.js';
13
+ import { getGraphIndexDir, loadGlobalGraphConfigs } from './types.js';
10
14
  export async function discoverCapability(cwd, params) {
11
15
  loadGlobalGraphConfigs();
12
16
  const startTime = Date.now();
17
+ const readOnly = Boolean(params.promptContext || params.noBuild);
18
+ let indexWriteFailure;
13
19
  const types = params.typeFilter && params.typeFilter.length > 0
14
20
  ? params.typeFilter
15
21
  : DEFAULT_DISCOVER_TYPES;
@@ -25,24 +31,37 @@ export async function discoverCapability(cwd, params) {
25
31
  // Source: prefer `framework` graph (built post-deploy), fall back to
26
32
  // project / codebase / legacy depending on what's available.
27
33
  let entries = [];
28
- const backend = params.backend ?? DEFAULT_ARTIFACT_SEARCH_BACKEND;
34
+ let localFramework = null;
35
+ const backend = readOnly ? 'local' : params.backend ?? DEFAULT_ARTIFACT_SEARCH_BACKEND;
29
36
  let fortemiCoreDiscoveryScores = null;
30
- let resourceSource = params.resourceSource ?? 'local';
37
+ let resourceSource = readOnly ? 'local' : params.resourceSource ?? 'local';
31
38
  let resolvedWebRelease;
32
39
  let verifiedSourcePaths;
33
- const prebuiltRelations = resourceSource !== 'web' && (!params.graph || params.graph === 'framework')
34
- ? selectPrebuiltRelations(cwd).reader : null;
35
- if ((!prebuiltRelations || backend === 'local') && resourceSource !== 'web' && (!params.graph || params.graph === 'framework')) {
40
+ const prebuiltSelection = resourceSource !== 'web' && (!params.graph || params.graph === 'framework')
41
+ ? selectPrebuiltRelations(cwd, cwd, !readOnly) : undefined;
42
+ const prebuiltRelations = prebuiltSelection?.reader ?? null;
43
+ // A valid prebuilt relationship package means the shipped index is current:
44
+ // never build a per-root framework index beside it (#3308, #2069 test).
45
+ if (!readOnly && (!prebuiltRelations || backend === 'local') && resourceSource !== 'web' && (!params.graph || params.graph === 'framework')) {
36
46
  const root = resolveFrameworkCorpusRoot(cwd) ?? aiwgRoot;
37
47
  if (root) {
38
48
  try {
39
- await refreshFrameworkCapabilities(root, backend === 'fortemi-core');
49
+ await refreshFrameworkCapabilities(root, false, { sourceDigest: prebuiltSelection?.sourceDigest });
50
+ if (resolveFrameworkCorpusRoot(root))
51
+ localFramework = loadGraphIndexFile(cwd, 'metadata.json', 'framework');
40
52
  }
41
53
  catch (error) {
42
- console.error(`Warning: capability index refresh failed: ${error instanceof Error ? error.message : String(error)}`);
54
+ if (isIndexWritePermissionError(error))
55
+ indexWriteFailure = 'framework';
56
+ else
57
+ console.error(`Warning: capability index refresh failed: ${error instanceof Error ? error.message : String(error)}`);
43
58
  }
44
59
  }
45
60
  }
61
+ const projectBuildAttempted = !readOnly && !indexWriteFailure && resourceSource !== 'web' && (!params.graph || params.graph === 'project')
62
+ ? await prepareProjectCapabilityIndex(cwd, () => { indexWriteFailure = 'project'; }) : false;
63
+ if (indexWriteFailure && resourceSource === 'auto')
64
+ resourceSource = 'local';
46
65
  if (resourceSource === 'auto') {
47
66
  const { loadFortemiCoreMetadataEntries } = await import('./fortemi-core-query-adapter.js');
48
67
  const localGraphs = params.graph ? [params.graph] : defaultCapabilityGraphs(cwd);
@@ -85,18 +104,37 @@ export async function discoverCapability(cwd, params) {
85
104
  const graphs = resourceSource === 'web'
86
105
  ? ['framework']
87
106
  : params.graph ? [params.graph] : defaultCapabilityGraphs(cwd);
88
- const { loadFortemiCoreMetadataEntries, queryFortemiCoreAiwgDiscovery, } = await import('./fortemi-core-query-adapter.js');
89
107
  let unavailableReason;
90
108
  for (const graph of graphs) {
91
- const loaded = loadFortemiCoreMetadataEntries(cwd, graph, verifiedSourcePaths);
92
- if (loaded.reason && graph === 'project' && !params.graph) {
93
- const fallback = projectCapabilityFallback(cwd);
94
- if (fallback) {
95
- entries.push(...fallback);
109
+ if (indexWriteFailure) {
110
+ const index = loadGraphIndexFile(cwd, 'metadata.json', graph);
111
+ if (Object.keys(index?.entries ?? {}).length) {
112
+ entries.push(...Object.values(index.entries).map(entry => withIndexProvenance(entry, graph)));
113
+ continue;
114
+ }
115
+ }
116
+ // Discovery ranks metadata, not full document bodies. A reconciled local
117
+ // framework index avoids parsing the much larger fulltext export.
118
+ if (graph === 'framework' && localFramework) {
119
+ entries.push(...Object.values(localFramework.entries).map(entry => withIndexProvenance(entry, graph)));
120
+ continue;
121
+ }
122
+ if (resourceSource === 'local' && !params.graph && graph !== 'framework') {
123
+ const directory = getGraphIndexDir(cwd, graph);
124
+ if (!fs.existsSync(path.join(directory, 'metadata.json'))
125
+ && !fs.existsSync(path.join(path.dirname(directory), 'fortemi-core', graph, 'manifest.json'))) {
126
+ if (graph === 'project' && !indexWriteFailure)
127
+ entries.push(...(projectCapabilityFallback(cwd) ?? []));
96
128
  continue;
97
129
  }
98
130
  }
99
- if (loaded.sourceIndexNewer && resourceSource === 'local') {
131
+ const { loadFortemiCoreMetadataEntries, queryFortemiCoreAiwgDiscovery } = await import('./fortemi-core-query-adapter.js');
132
+ const loaded = loadFortemiCoreMetadataEntries(cwd, graph, verifiedSourcePaths);
133
+ if (loaded.reason && !indexWriteFailure && graph === 'project' && (!params.graph || projectBuildAttempted)) {
134
+ entries.push(...(projectCapabilityFallback(cwd) ?? []));
135
+ continue;
136
+ }
137
+ if (loaded.sourceIndexNewer && resourceSource === 'local' && !indexWriteFailure) {
100
138
  // Do not silently omit a graph whose derived cache is stale. Rank its
101
139
  // current source metadata, without consulting scores from the old cache.
102
140
  const index = loadGraphIndexFile(cwd, 'metadata.json', graph);
@@ -108,7 +146,7 @@ export async function discoverCapability(cwd, params) {
108
146
  }
109
147
  if (loaded.reason) {
110
148
  unavailableReason ??= loaded.reason;
111
- if (graph === 'framework' && !params.graph) {
149
+ if (graph === 'framework' && !params.graph && !indexWriteFailure) {
112
150
  console.error(`Warning: framework capabilities are unavailable: ${loaded.reason}`);
113
151
  }
114
152
  }
@@ -129,7 +167,7 @@ export async function discoverCapability(cwd, params) {
129
167
  }
130
168
  }
131
169
  }
132
- if (entries.length === 0 && unavailableReason) {
170
+ if (entries.length === 0 && unavailableReason && !projectBuildAttempted && !indexWriteFailure) {
133
171
  if (params.json) {
134
172
  console.log(JSON.stringify({
135
173
  query: {
@@ -164,6 +202,8 @@ export async function discoverCapability(cwd, params) {
164
202
  const idx = loadGraphIndexFile(cwd, 'metadata.json', params.graph);
165
203
  if (idx)
166
204
  entries = Object.values(idx.entries).map((entry) => withIndexProvenance(entry, params.graph));
205
+ if (!readOnly && !indexWriteFailure && params.graph === 'project' && !entries.length)
206
+ projectCapabilityFallback(cwd);
167
207
  }
168
208
  else {
169
209
  // discover is EXCLUSIVELY the agentic-capability surface (#1545): source
@@ -180,6 +220,8 @@ export async function discoverCapability(cwd, params) {
180
220
  const projIdx = loadGraphIndexFile(cwd, 'metadata.json', 'project');
181
221
  if (projIdx)
182
222
  entries.push(...Object.values(projIdx.entries).map((entry) => withIndexProvenance(entry, 'project')));
223
+ if (!readOnly && !indexWriteFailure && !Object.keys(projIdx?.entries ?? {}).length)
224
+ projectCapabilityFallback(cwd);
183
225
  if (includeUser) {
184
226
  const userIdx = loadGraphIndexFile(cwd, 'metadata.json', 'user');
185
227
  if (userIdx)
@@ -193,7 +235,28 @@ export async function discoverCapability(cwd, params) {
193
235
  entries.push(...Object.values(legacy.entries));
194
236
  }
195
237
  }
196
- if (entries.length === 0 && backend !== 'fortemi-core') {
238
+ if (readOnly && prebuiltRelations) {
239
+ // Reuse the validated shipped export without refreshing or persisting receipts.
240
+ const { loadFortemiCoreMetadataEntries } = await import('./fortemi-core-query-adapter.js');
241
+ const loaded = loadFortemiCoreMetadataEntries(cwd, 'framework', undefined, prebuiltSelection);
242
+ if (loaded.entries.length) {
243
+ entries = entries.filter(entry => !('indexGraph' in entry && entry.indexGraph === 'framework'));
244
+ entries.push(...loaded.entries.map(entry => withIndexProvenance(entry, 'framework')));
245
+ }
246
+ }
247
+ if (indexWriteFailure) {
248
+ if (!entries.length) {
249
+ const location = indexWriteFailure === 'framework' ? 'XDG_DATA_HOME' : 'AIWG_ARTIFACTS_PATH';
250
+ console.error(`Error: the capability index needs a writable location. Set ${location} to a writable directory and run \`aiwg index build --graph ${indexWriteFailure}\`.`);
251
+ process.exit(1);
252
+ }
253
+ console.error('Warning: capability index storage is not writable; using the existing index. Results may be stale.');
254
+ }
255
+ if (entries.length === 0 && params.promptContext) {
256
+ console.log(JSON.stringify({ results: [] }));
257
+ return;
258
+ }
259
+ if (entries.length === 0 && backend !== 'fortemi-core' && !params.noBuild && !projectBuildAttempted) {
197
260
  // Empty-index case (#1221). Surface a hint that explains the gap rather
198
261
  // than returning a bare zero-result envelope — the latter trains agents
199
262
  // to conclude "AIWG doesn't have a skill for that" when in fact the
@@ -221,10 +284,11 @@ export async function discoverCapability(cwd, params) {
221
284
  // fusion below can inject/lift curated capabilities into the top-K before
222
285
  // truncation — a capability that the lexical pass ranked outside `limit`
223
286
  // (or missed entirely) still surfaces when the query activates its facet.
287
+ const personaIdentitySuppressed = diagnoseFacetActivations(params.phrase).some(activation => activation.facet === 'persona-identity' && activation.status === 'suppressed');
224
288
  const lexicalDiagnostics = new Map();
225
289
  const legacyStrictScored = candidates
226
290
  .map(entry => {
227
- const detailed = scoreEntryDetailed(entry, params.phrase);
291
+ const detailed = scoreEntryDetailed(entry, params.phrase, { personaIdentitySuppressed });
228
292
  const legacyScore = detailed.score;
229
293
  const fortemiScore = fortemiCoreDiscoveryScores?.get(entry.path) ?? 0;
230
294
  lexicalDiagnostics.set(entry.path, detailed.diagnostic);
@@ -245,8 +309,8 @@ export async function discoverCapability(cwd, params) {
245
309
  // top-K instead of being out-scored by artifacts that merely mention the
246
310
  // word. Facet activation can also rescue an otherwise-empty strict pass.
247
311
  // #154 — a strict result anywhere in the corpus must not suppress relevant
248
- // partial matches for a natural-language query. Score the relaxed pass on
249
- // matched terms (unmatched terms do not divide the score), apply a noise
312
+ // partial matches for a natural-language query. Score the relaxed pass with
313
+ // query coverage (so weak hits cannot saturate), apply a noise
250
314
  // floor, and union it with strict matches before ranking. Word-boundary
251
315
  // token matching keeps this from resurrecting substring noise such as UX in
252
316
  // Linux.
@@ -254,7 +318,7 @@ export async function discoverCapability(cwd, params) {
254
318
  const strictPaths = new Set(strictScored.map(result => result.entry.path));
255
319
  const combinedByPath = new Map(strictScored.map(result => [result.entry.path, result]));
256
320
  for (const entry of candidates) {
257
- const detailed = scoreEntryDetailed(entry, params.phrase, { relaxOverlap: true });
321
+ const detailed = scoreEntryDetailed(entry, params.phrase, { relaxOverlap: true, personaIdentitySuppressed });
258
322
  if (detailed.score < RELAXED_MIN_SCORE)
259
323
  continue;
260
324
  const existing = combinedByPath.get(entry.path);
@@ -279,7 +343,18 @@ export async function discoverCapability(cwd, params) {
279
343
  }
280
344
  }
281
345
  const queryTimeMs = Date.now() - startTime;
282
- await emitDiscoverResults({ cwd, params, types, limit, aiwgRoot, entries, backend, resourceSource,
283
- resolvedWebRelease, prebuiltRelations, scored, relaxed, queryTimeMs, lexicalDiagnostics });
346
+ if (params.promptContext) {
347
+ const templateRelations = prebuiltRelations ?? loadBuiltRelations(cwd);
348
+ console.log(JSON.stringify({ results: scored.map(({ entry, score }) => ({
349
+ type: entry.type, name: entry.name ?? discoveryIdForEntry(entry),
350
+ ...templateRelationFields(entry, templateRelations, 3, false),
351
+ capability: entry.type === 'rule'
352
+ ? entry.ruleSummary || prebuiltRelations?.index.rules[discoveryIdForEntry(entry)]?.summary || entry.summary
353
+ : entry.capability ?? entry.summary, score,
354
+ })) }));
355
+ return;
356
+ }
357
+ await emitDiscoverResults({ cwd, params, indexStale: Boolean(indexWriteFailure), types, limit, aiwgRoot, entries, backend, resourceSource,
358
+ resolvedWebRelease, prebuiltRelations, prebuiltSelection, frameworkReconciled: Boolean(localFramework), scored, relaxed, queryTimeMs, lexicalDiagnostics });
284
359
  }
285
360
  //# sourceMappingURL=query-engine-discover.js.map
@@ -1,10 +1,11 @@
1
1
  // Share entry identity, provenance, graph selection, and discovery ordering helpers.
2
- import * as fs from 'node:fs';
2
+ import fs from 'node:fs';
3
3
  import * as path from 'node:path';
4
4
  import { projectAiwgPath, projectControlPath } from '../config/project-artifacts.js';
5
5
  import { recordTypeForEntry, stableRecordId } from './browser-export.js';
6
6
  import { loadGraphIndexFile } from './index-reader.js';
7
- import { isOperationalShowType, OPERATIONAL_DISCOVERY_TYPES } from './types.js';
7
+ import { isIndexWritePermissionError } from './framework-capabilities.js';
8
+ import { getGraphIndexDir, isOperationalShowType, OPERATIONAL_DISCOVERY_TYPES, loadUserGraphConfigs, GRAPH_CONFIGS, resolveGraphScanDir, } from './types.js';
8
9
  export function normalizeIndexedPath(entryPath) {
9
10
  return entryPath.replace(/\\/g, '/');
10
11
  }
@@ -54,19 +55,115 @@ export function graphScope(graph) {
54
55
  export function withIndexProvenance(entry, graph) {
55
56
  return { ...entry, indexGraph: graph, indexScope: graphScope(graph) };
56
57
  }
58
+ const projectBuilds = new Map();
59
+ /** Best-effort first-use preparation through the CLI's builder; return whether a build was attempted. */
60
+ export async function prepareProjectCapabilityIndex(cwd, onWriteFailure) {
61
+ const directory = getGraphIndexDir(cwd, 'project');
62
+ const pending = projectBuilds.get(directory);
63
+ const build = async () => {
64
+ let attempted = false;
65
+ let writeFailure;
66
+ try {
67
+ const index = loadGraphIndexFile(cwd, 'metadata.json', 'project');
68
+ if (Object.keys(index?.entries ?? {}).length)
69
+ return { attempted };
70
+ loadUserGraphConfigs(cwd);
71
+ // Avoid the explicit builder's missing-root exit and repeated empty builds.
72
+ if (!GRAPH_CONFIGS.project.scanDirs.some(dir => fs.existsSync(resolveGraphScanDir(cwd, dir))))
73
+ return { attempted };
74
+ const { collectGraphIndexFiles } = await import('./index-files.js');
75
+ if (!(await collectGraphIndexFiles(cwd, 'project')).length)
76
+ return { attempted };
77
+ fs.accessSync(cwd, fs.constants.W_OK);
78
+ let ancestor = directory;
79
+ while (!fs.existsSync(ancestor))
80
+ ancestor = path.dirname(ancestor);
81
+ fs.accessSync(ancestor, fs.constants.W_OK);
82
+ const { buildIndex } = await import('./index-builder.js');
83
+ attempted = true;
84
+ await buildIndex(cwd, { graph: 'project', quiet: true, explicit: false, lockWaitMs: 1000 });
85
+ // Match CLI build's derived-cache publication without its stdout progress.
86
+ const { syncFortemiCoreIndex } = await import('./fortemi-core-sync.js');
87
+ syncFortemiCoreIndex(cwd, { graph: 'project' });
88
+ }
89
+ catch (error) {
90
+ if (isIndexWritePermissionError(error))
91
+ writeFailure = error;
92
+ // The existing project fallback owns warnings and partial results.
93
+ }
94
+ // Permission failures get a single query-level diagnostic, including cold starts.
95
+ if (attempted && !writeFailure)
96
+ console.error('Building the project index for this workspace (first use)…');
97
+ return { attempted, writeFailure };
98
+ };
99
+ const promise = pending ?? build();
100
+ projectBuilds.set(directory, promise);
101
+ try {
102
+ const result = await promise;
103
+ if (result.writeFailure)
104
+ onWriteFailure?.(result.writeFailure);
105
+ return result.attempted;
106
+ }
107
+ finally {
108
+ projectBuilds.delete(directory);
109
+ }
110
+ }
57
111
  /** Keep existing project capabilities visible while their derived cache is unavailable. */
58
112
  export function projectCapabilityFallback(cwd) {
59
113
  const index = loadGraphIndexFile(cwd, 'metadata.json', 'project');
60
- if (index) {
61
- const entries = Object.values(index.entries).map((entry) => withIndexProvenance(entry, 'project'));
62
- if (entries.length > 0) {
63
- // One diagnostic per command, on stderr so JSON and skill bodies stay parseable.
64
- console.error('Warning: project capability cache is unavailable or stale; using the local project index. Run `aiwg index sync` to repair the cache.');
65
- return entries;
114
+ const receipt = path.join(getGraphIndexDir(cwd, 'project'), 'capability-warning.json');
115
+ if (index && Object.keys(index.entries).length) {
116
+ // Metadata fallback preserves every discovery candidate; results are intact.
117
+ try {
118
+ fs.rmSync(receipt, { force: true });
119
+ }
120
+ catch { /* read-only cache */ }
121
+ return Object.values(index.entries).map(entry => withIndexProvenance(entry, 'project'));
122
+ }
123
+ const sources = [];
124
+ const scan = (directory) => {
125
+ let children;
126
+ try {
127
+ children = fs.readdirSync(directory, { withFileTypes: true });
128
+ }
129
+ catch {
130
+ return;
131
+ }
132
+ for (const child of children) {
133
+ if (child.name.startsWith('.') || child.isSymbolicLink())
134
+ continue;
135
+ const file = path.join(directory, child.name);
136
+ if (child.isDirectory())
137
+ scan(file);
138
+ else if (/\.(?:md|ya?ml|json)$/.test(child.name) && !['registry.json', 'manifest.json'].includes(child.name)) {
139
+ const stat = fs.statSync(file);
140
+ sources.push(`${file}:${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}`);
141
+ }
142
+ }
143
+ };
144
+ for (const dir of ['extensions', 'addons', 'frameworks', 'plugins', 'skills'])
145
+ scan(projectAiwgPath(cwd, dir));
146
+ if (sources.length) {
147
+ const state = JSON.stringify(sources.sort());
148
+ let previous = '';
149
+ try {
150
+ previous = fs.readFileSync(receipt, 'utf8');
151
+ }
152
+ catch { /* first degraded lookup */ }
153
+ if (previous !== state) {
154
+ console.error('Warning: project capabilities could not be loaded: the cache is unavailable and the local project index is missing or empty. Run `aiwg index build --graph project` to repair discovery.');
155
+ try {
156
+ fs.mkdirSync(path.dirname(receipt), { recursive: true });
157
+ fs.writeFileSync(receipt, state);
158
+ }
159
+ catch { /* Diagnostics must also work with read-only caches. */ }
66
160
  }
67
161
  }
68
- if (['extensions', 'addons', 'frameworks', 'plugins', 'skills'].some((dir) => fs.existsSync(projectAiwgPath(cwd, dir)))) {
69
- console.error('Warning: project capabilities could not be loaded: the cache is unavailable and the local project index is missing or empty. Run `aiwg index build --graph project` to repair discovery.');
162
+ else {
163
+ try {
164
+ fs.rmSync(receipt, { force: true });
165
+ }
166
+ catch { /* read-only cache */ }
70
167
  }
71
168
  return index ? [] : null;
72
169
  }
@@ -0,0 +1,27 @@
1
+ // Resolve artifact availability from provider deployment paths and bundle records.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import os from 'node:os';
5
+ import { isCorpusBundleInstalled } from './framework-capabilities.js';
6
+ export async function isArtifactInstalled(cwd, root, entry, kind, bundle) {
7
+ if (entry.type === 'skill') {
8
+ const normalized = entry.path.replace(/\\/g, '/');
9
+ const slug = path.posix.basename(normalized) === 'SKILL.md'
10
+ ? path.posix.basename(path.posix.dirname(normalized)) : path.posix.basename(normalized, '.md');
11
+ const { listProviderDeploymentLayouts, resolveProviderPathValue } = await import('../providers/provider-definitions.js');
12
+ for (const provider of listProviderDeploymentLayouts()) {
13
+ const roots = [provider.paths.kernelSkills, provider.paths.artifacts.skills, provider.paths.contextDiscovery?.skills,
14
+ provider.smithPaths?.skills];
15
+ for (const base of [cwd, os.homedir()])
16
+ for (const relative of roots) {
17
+ if (!relative)
18
+ continue;
19
+ const directory = resolveProviderPathValue(relative, base);
20
+ if (fs.existsSync(path.join(directory, slug, 'SKILL.md')))
21
+ return true;
22
+ }
23
+ }
24
+ }
25
+ return isCorpusBundleInstalled(cwd, root, kind, bundle);
26
+ }
27
+ //# sourceMappingURL=query-engine-installation.js.map
@@ -1,2 +1,15 @@
1
- export {};
1
+ export async function readDiscoverPhrase(positional, flags, input = process.stdin) {
2
+ if (!flags.includes('--stdin'))
3
+ return positional.join(' ').trim();
4
+ if (positional.length > 0) {
5
+ throw new Error('--stdin cannot be combined with a positional search phrase');
6
+ }
7
+ const chunks = [];
8
+ for await (const chunk of input)
9
+ chunks.push(Buffer.from(chunk));
10
+ const phrase = Buffer.concat(chunks).toString('utf8').trim();
11
+ if (!phrase)
12
+ throw new Error('--stdin requires a non-empty search phrase');
13
+ return phrase;
14
+ }
2
15
  //# sourceMappingURL=query-engine-options.js.map