@aiwg/cli 2026.10.16 → 2026.10.19

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 (155) hide show
  1. package/agentic/code/providers/capability-matrix.yaml +51 -0
  2. package/agentic/code/providers/flue/README.md +62 -0
  3. package/agentic/code/providers/flue/templates/aiwg/tools.ts +120 -0
  4. package/agentic/code/providers/model-capabilities.v1.json +23 -0
  5. package/agentic/code/providers/model-catalog.v1.json +9 -0
  6. package/dist/src/artifacts/corpus-tools/resolve.js +28 -6
  7. package/dist/src/artifacts/query-engine-corpus.js +217 -0
  8. package/dist/src/artifacts/query-engine-discover-output.js +229 -0
  9. package/dist/src/artifacts/query-engine-discover.js +285 -0
  10. package/dist/src/artifacts/query-engine-entries.js +188 -0
  11. package/dist/src/artifacts/query-engine-index.js +249 -0
  12. package/dist/src/artifacts/query-engine-matching.js +143 -0
  13. package/dist/src/artifacts/query-engine-options.js +2 -0
  14. package/dist/src/artifacts/query-engine-rules.js +202 -0
  15. package/dist/src/artifacts/query-engine-scoring.js +436 -0
  16. package/dist/src/artifacts/query-engine-show-card.js +194 -0
  17. package/dist/src/artifacts/query-engine-show-load.js +211 -0
  18. package/dist/src/artifacts/query-engine-show.js +300 -0
  19. package/dist/src/artifacts/query-engine.js +7 -2576
  20. package/dist/src/cli/handlers/help.js +1 -1
  21. package/dist/src/cli/handlers/init.js +1 -0
  22. package/dist/src/cli/handlers/mc-agents.js +111 -0
  23. package/dist/src/cli/handlers/mc-args.js +54 -0
  24. package/dist/src/cli/handlers/mc-control.js +227 -0
  25. package/dist/src/cli/handlers/mc-dispatch.js +203 -0
  26. package/dist/src/cli/handlers/mc-help.js +171 -0
  27. package/dist/src/cli/handlers/mc-run.js +343 -0
  28. package/dist/src/cli/handlers/mc-session.js +138 -0
  29. package/dist/src/cli/handlers/mc-status.js +258 -0
  30. package/dist/src/cli/handlers/mc-summary.js +43 -0
  31. package/dist/src/cli/handlers/mc-types.js +3 -0
  32. package/dist/src/cli/handlers/mc-worker.js +205 -0
  33. package/dist/src/cli/handlers/mc.js +12 -1665
  34. package/dist/src/cli/handlers/models-refusal.js +13 -0
  35. package/dist/src/cli/handlers/models.js +2 -1
  36. package/dist/src/cli/handlers/remove-bundled.js +133 -0
  37. package/dist/src/cli/handlers/remove-options.js +31 -0
  38. package/dist/src/cli/handlers/remove-user.js +174 -0
  39. package/dist/src/cli/handlers/remove.js +201 -0
  40. package/dist/src/cli/handlers/subcommands-bundles.js +257 -0
  41. package/dist/src/cli/handlers/subcommands-discovery.js +165 -0
  42. package/dist/src/cli/handlers/subcommands-list-format.js +129 -0
  43. package/dist/src/cli/handlers/subcommands-list.js +250 -0
  44. package/dist/src/cli/handlers/subcommands-plugins.js +213 -0
  45. package/dist/src/cli/handlers/subcommands-quickref.js +58 -0
  46. package/dist/src/cli/handlers/subcommands-rlm.js +113 -0
  47. package/dist/src/cli/handlers/subcommands-services.js +66 -0
  48. package/dist/src/cli/handlers/subcommands-storage.js +259 -0
  49. package/dist/src/cli/handlers/subcommands.js +18 -1984
  50. package/dist/src/cli/handlers/use.js +11 -5
  51. package/dist/src/cli/scope-resolver.js +1 -142
  52. package/dist/src/cli/services/deployment-verification.js +3 -0
  53. package/dist/src/cli/user-scope-mirror.js +173 -0
  54. package/dist/src/config/dispatch-host-thresholds.js +2 -0
  55. package/dist/src/config/dispatch-thresholds-runtime.mjs +4 -0
  56. package/dist/src/config/host-resource-report.d.mts +5 -0
  57. package/dist/src/config/host-resource-report.mjs +36 -6
  58. package/dist/src/config/host-resource-runtime.d.mts +3 -0
  59. package/dist/src/config/host-resource-runtime.mjs +9 -6
  60. package/dist/src/decision/ensemble-study/artifacts.js +7 -0
  61. package/dist/src/decision/ensemble-study/gate-policy.js +58 -0
  62. package/dist/src/decision/ensemble-study/gates.js +78 -0
  63. package/dist/src/decision/ensemble-study/protocol.js +18 -21
  64. package/dist/src/decision/ensemble-study/score.js +3 -2
  65. package/dist/src/decision/ensemble-study/statistics.js +7 -26
  66. package/dist/src/decision/sensitivity/comparative-gates.js +135 -0
  67. package/dist/src/decision/sensitivity/comparative.js +18 -41
  68. package/dist/src/extensions/claude-hooks-installer.js +18 -0
  69. package/dist/src/gates/evaluate.js +2 -358
  70. package/dist/src/gates/observations.js +363 -0
  71. package/dist/src/gates/pack-composition.js +270 -0
  72. package/dist/src/gates/pack-tightening.js +197 -0
  73. package/dist/src/gates/pack-validation.js +262 -0
  74. package/dist/src/gates/registry-error.js +5 -0
  75. package/dist/src/gates/registry.js +13 -685
  76. package/dist/src/mcp/json-document.mjs +29 -0
  77. package/dist/src/mcp/muse-native-config.mjs +1 -28
  78. package/dist/src/memory/provider-memory-adapter.js +1 -0
  79. package/dist/src/mission-protocol/worker-review-gate.js +7 -0
  80. package/dist/src/models/model-capabilities.v1.json +23 -0
  81. package/dist/src/models/model-catalog.v1.json +9 -0
  82. package/dist/src/models/policy-resources.js +1 -1
  83. package/dist/src/models/worker-plan.js +5 -5
  84. package/dist/src/plugin/command-ownership.js +34 -0
  85. package/dist/src/plugin/skill-command-frontmatter.js +197 -0
  86. package/dist/src/plugin/skill-command-translator.js +6 -232
  87. package/dist/src/providers/capability-matrix.yaml +51 -0
  88. package/dist/src/providers/context-output-ownership.js +26 -0
  89. package/dist/src/providers/deployment-ownership.d.mts +20 -0
  90. package/dist/src/providers/deployment-ownership.mjs +236 -0
  91. package/dist/src/providers/deployment-removal.js +222 -0
  92. package/dist/src/providers/provider-context-contracts.js +8 -0
  93. package/dist/src/providers/provider-definition-schema.js +1 -0
  94. package/dist/src/providers/provider-definitions.js +1 -0
  95. package/dist/src/providers/provider-seeds-3.js +18 -0
  96. package/dist/src/providers/removal-transaction.js +86 -0
  97. package/dist/src/providers/settings-document.d.mts +3 -0
  98. package/dist/src/providers/settings-document.mjs +47 -0
  99. package/dist/src/providers/settings-removal.js +190 -0
  100. package/dist/src/providers/skill-ownership.d.mts +20 -2
  101. package/dist/src/providers/skill-ownership.mjs +12 -4
  102. package/dist/src/providers/transformation-receipt-integration.js +15 -271
  103. package/dist/src/providers/transformation-receipt-outputs.js +99 -0
  104. package/dist/src/providers/transformation-receipt-source.js +194 -0
  105. package/dist/src/research/identity.js +8 -2
  106. package/dist/src/research/reference-match.js +66 -8
  107. package/dist/src/rules/activation.mjs +15 -6
  108. package/dist/src/rules/core-startup.mjs +2 -2
  109. package/dist/src/serve/mission-conductor.js +4 -0
  110. package/dist/src/serve/mission-summary.js +56 -0
  111. package/dist/src/skills/deployment-ownership.js +2 -2
  112. package/dist/src/skills/deployment-policy.js +9 -0
  113. package/dist/src/smiths/context-pipeline/aiwg-md.js +23 -0
  114. package/dist/src/smiths/context-pipeline/context-file-safety.js +3 -0
  115. package/dist/src/smiths/context-pipeline/flue-context.js +25 -0
  116. package/dist/src/smiths/context-pipeline/generator.js +7 -2
  117. package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +9 -7
  118. package/dist/src/smiths/hook-bridge/index.js +9 -0
  119. package/package.json +5 -1
  120. package/schemas/decision/D17StudyProtocol.v1.schema.json +39 -67
  121. package/tools/agents/deploy-agents.mjs +21 -680
  122. package/tools/agents/deploy-command-mirrors.mjs +229 -0
  123. package/tools/agents/deploy-options.mjs +267 -0
  124. package/tools/agents/deploy-support.mjs +165 -0
  125. package/tools/agents/providers/base-addon-discovery.mjs +139 -0
  126. package/tools/agents/providers/base-behaviors.mjs +168 -0
  127. package/tools/agents/providers/base-context.mjs +205 -0
  128. package/tools/agents/providers/base-contract.mjs +116 -0
  129. package/tools/agents/providers/base-files.mjs +252 -0
  130. package/tools/agents/providers/base-flat-artifacts.mjs +233 -0
  131. package/tools/agents/providers/base-framework-discovery.mjs +309 -0
  132. package/tools/agents/providers/base-frontmatter.mjs +196 -0
  133. package/tools/agents/providers/base-inventory.mjs +269 -0
  134. package/tools/agents/providers/base-kernel-skills.mjs +354 -0
  135. package/tools/agents/providers/base-migrations.mjs +258 -0
  136. package/tools/agents/providers/base-models-platforms.mjs +273 -0
  137. package/tools/agents/providers/base-rule-index.mjs +450 -0
  138. package/tools/agents/providers/base-runtime.mjs +60 -0
  139. package/tools/agents/providers/base-skill-copy.mjs +273 -0
  140. package/tools/agents/providers/base.mjs +16 -3364
  141. package/tools/agents/providers/claude-post-deploy.mjs +10 -2
  142. package/tools/agents/providers/flue-project.mjs +79 -0
  143. package/tools/agents/providers/flue-specialists.mjs +64 -0
  144. package/tools/agents/providers/flue.mjs +50 -0
  145. package/tools/agents/providers/hermes-startup.mjs +0 -5
  146. package/tools/agents/providers/muse.mjs +7 -2
  147. package/tools/agents/providers/rule-delivery-surface.mjs +33 -5
  148. package/tools/agents/providers/rule-deployment-commit.mjs +19 -15
  149. package/tools/agents/providers/rule-deployment-prepare.mjs +13 -3
  150. package/tools/agents/providers/rule-projection.mjs +3 -0
  151. package/tools/agents/providers/rule-startup.mjs +3 -3
  152. package/tools/agents/use-rule-selection.mjs +17 -0
  153. package/tools/ralph-external/lib/worker-invocation-processes.mjs +4 -2
  154. package/tools/ralph-external/lib/worker-termination.mjs +15 -8
  155. package/vscode-extension/schemas/aiwg.config.v1.json +2 -4
@@ -0,0 +1,229 @@
1
+ // Shape capability discovery diagnostics, rule checks, and CLI output.
2
+ import * as path from 'node:path';
3
+ import { diagnoseFacetActivations } from './discover-facets.js';
4
+ import { buildRunHint, DISCOVER_TYPE_ORDER, discoveryIdForEntry, normalizeIndexedPath, scopeRank, showHintForDiscoverResult, } from './query-engine-entries.js';
5
+ import { boundRuleDescriptor, compoundGoverningRules, governingRuleFields, governingRuleStats, RULE_CHECK_OBLIGATION, statsText, } from './query-engine-rules.js';
6
+ import { tokenize } from './query-engine-scoring.js';
7
+ import { ensureRelations } from './relations.js';
8
+ export async function emitDiscoverResults(context) {
9
+ const { cwd, params, types, limit, aiwgRoot, entries, backend, resourceSource, resolvedWebRelease, prebuiltRelations, scored, relaxed, queryTimeMs, lexicalDiagnostics } = context;
10
+ /**
11
+ * Resolve a stored framework-graph path to an absolute AIWG_ROOT
12
+ * path (#1217). Framework-graph entries are stored as paths relative
13
+ * to the AIWG repo root (e.g. `agentic/code/frameworks/.../SKILL.md`);
14
+ * anchoring them to `AIWG_ROOT` makes them readable from any project
15
+ * working directory.
16
+ *
17
+ * Kernel skills are anchored the same way (#1230) — `aiwg show` reads
18
+ * the source corpus, not platform deploy mirrors, so kernel entries
19
+ * need the same `AIWG_ROOT` anchoring as non-kernel framework entries.
20
+ * Non-framework entries (project / codebase graphs) keep their stored
21
+ * paths unchanged.
22
+ */
23
+ function resolvePath(entry) {
24
+ const normalizedPath = normalizeIndexedPath(entry.path);
25
+ if (!aiwgRoot)
26
+ return normalizedPath;
27
+ if (path.isAbsolute(entry.path))
28
+ return entry.path;
29
+ if (normalizedPath.startsWith('agentic/code/'))
30
+ return path.join(aiwgRoot, normalizedPath);
31
+ return normalizedPath;
32
+ }
33
+ // Build a hint string when the index has entries but no scored matches —
34
+ // this is the second silent-failure mode #1221 calls out. When the workspace
35
+ // has project-local content (.aiwg/{extensions,addons,frameworks,plugins,providers}/)
36
+ // surface a project-graph rebuild hint (#1235).
37
+ // discover-appropriate hint (#1545): never push index/graph mechanics. If
38
+ // nothing scored, the phrase didn't match an indexed capability — suggest a
39
+ // broader phrase / type filter, and a capability refresh via `aiwg use`.
40
+ const emptyResultHint = scored.length === 0
41
+ ? backend === 'fortemi-core'
42
+ ? `No capability matched "${params.phrase}" among ${entries.length} Fortemi Core static-cache capabilities. Try a broader phrase or a \`--type\` filter. If the local index changed, refresh the cache with \`aiwg index sync ${params.graph ? `--graph ${params.graph}` : '--all'}\`, or pass \`--backend local\` to use the legacy local index.`
43
+ : `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
+ : null;
45
+ const relations = resourceSource === 'local' && (!params.graph || params.graph === 'framework')
46
+ ? prebuiltRelations ?? await ensureRelations(cwd) : undefined;
47
+ const governing = scored.map(result => compoundGoverningRules(entries, result.entry, relations ?? undefined, params.phrase));
48
+ const responseRules = new Map();
49
+ for (const item of governing.flat()) {
50
+ const key = `${item.rule.type}:${item.rule.path}`, prior = responseRules.get(key);
51
+ responseRules.set(key, { rule: item.rule, applicability: [...new Set([...(prior?.applicability ?? []), ...item.applicability])] });
52
+ }
53
+ const responseFields = governingRuleFields([...responseRules.values()]);
54
+ const responseRuleStats = governingRuleStats([...responseRules.values()]);
55
+ const includePaths = params.includePaths ?? true;
56
+ const facetActivations = diagnoseFacetActivations(params.phrase);
57
+ const roundDiagnostic = (value) => Math.round(value * 1_000_000) / 1_000_000;
58
+ const rankingDiagnostic = (entry, finalScore, facetDiagnostics) => {
59
+ const lexical = lexicalDiagnostics.get(entry.path) ?? {
60
+ content_tokens: tokenize(params.phrase),
61
+ raw_score: 0,
62
+ score: 0,
63
+ score_cap_applied: false,
64
+ matches: [],
65
+ };
66
+ const scope = entry.indexScope ?? 'unknown';
67
+ return {
68
+ lexical_score: roundDiagnostic(lexical.score),
69
+ lexical_raw_score: roundDiagnostic(lexical.raw_score),
70
+ final_score: roundDiagnostic(finalScore),
71
+ score_cap_applied: lexical.score_cap_applied,
72
+ matches: lexical.matches.map((match) => ({
73
+ ...match,
74
+ contribution: roundDiagnostic(match.contribution),
75
+ ...(match.query_token_coverage === undefined
76
+ ? {}
77
+ : { query_token_coverage: roundDiagnostic(match.query_token_coverage) }),
78
+ })),
79
+ facets: (facetDiagnostics ?? []).map((facet) => ({
80
+ ...facet,
81
+ activation_floor: roundDiagnostic(facet.activation_floor),
82
+ base_score: roundDiagnostic(facet.base_score),
83
+ rrf_tiebreak: roundDiagnostic(facet.rrf_tiebreak),
84
+ })),
85
+ tie_breakers: {
86
+ scope,
87
+ scope_rank: scopeRank(entry),
88
+ type_rank: DISCOVER_TYPE_ORDER.get(entry.type) ?? 99,
89
+ },
90
+ };
91
+ };
92
+ const { loadRelations } = await import('./relations.js');
93
+ const ruleRelations = resourceSource === 'local' ? loadRelations(cwd) ?? (aiwgRoot ? loadRelations(aiwgRoot, cwd) : null) : null;
94
+ if (params.json) {
95
+ const jsonIndent = params.jsonPretty === false ? undefined : 2;
96
+ console.log(JSON.stringify({
97
+ query: {
98
+ phrase: params.phrase,
99
+ types,
100
+ limit,
101
+ aiwg_root: aiwgRoot ?? null,
102
+ backend,
103
+ graph: backend === 'fortemi-core'
104
+ ? resourceSource === 'web' ? 'framework' : params.graph ?? 'capability-default'
105
+ : params.graph,
106
+ ...(resourceSource === 'web'
107
+ ? {
108
+ resource_source: 'web',
109
+ aiwg_selector: resolvedWebRelease?.selector,
110
+ aiwg_version: resolvedWebRelease?.version,
111
+ manifest_sha256: resolvedWebRelease?.manifestDigest,
112
+ manifest_url: resolvedWebRelease?.manifestUrl,
113
+ }
114
+ : {}),
115
+ },
116
+ results: scored.map((r, resultIndex) => ({
117
+ id: discoveryIdForEntry(r.entry),
118
+ ...(includePaths ? { path: resolvePath(r.entry) } : {}),
119
+ type: r.entry.type,
120
+ name: r.entry.name,
121
+ title: r.entry.title,
122
+ score: Math.round(r.score * 100) / 100,
123
+ ranking: rankingDiagnostic(r.entry, r.score, r.facetDiagnostics),
124
+ ...governingRuleFields(governing[resultIndex]),
125
+ triggers: r.entry.triggers ?? [],
126
+ capability: r.entry.capability ?? r.entry.summary,
127
+ kernel: r.entry.kernel ?? false,
128
+ ...(['skill', 'agent', 'flow', 'command'].includes(r.entry.type) && ruleRelations
129
+ && ruleRelations.rulesForTarget(r.entry.type, discoveryIdForEntry(r.entry)).length ? {
130
+ startup_rule_stats: ruleRelations.ruleStats(r.entry.type, discoveryIdForEntry(r.entry)),
131
+ } : {}),
132
+ provenance: {
133
+ graph: r.entry.indexGraph ?? null,
134
+ scope: r.entry.indexScope ?? null,
135
+ },
136
+ // #1227 — surface script-bearing skills so agents know to use
137
+ // `aiwg run skill <name>` instead of executing instructions
138
+ // themselves.
139
+ ...(r.entry.script
140
+ ? {
141
+ executable: true,
142
+ run_hint: buildRunHint(r.entry),
143
+ }
144
+ : {}),
145
+ })),
146
+ rule_stats: responseRuleStats,
147
+ ...(responseFields.required_rule_checks ? { required_rule_checks: responseFields.required_rule_checks, rule_check_obligation: RULE_CHECK_OBLIGATION } : {}),
148
+ total: scored.length,
149
+ query_time_ms: queryTimeMs,
150
+ diagnostics: {
151
+ content_tokens: tokenize(params.phrase),
152
+ facet_activations: facetActivations,
153
+ score_tie_break_order: ['score', 'scope', 'type', 'name', 'path'],
154
+ },
155
+ ...(relaxed ? { relaxed_overlap: true } : {}),
156
+ ...(emptyResultHint ? { hint: emptyResultHint } : {}),
157
+ }, null, jsonIndent));
158
+ return;
159
+ }
160
+ if (scored.length === 0) {
161
+ console.log(`No discovery matches for "${params.phrase}" in types: ${types.join(',')}.`);
162
+ console.log(backend === 'fortemi-core'
163
+ ? emptyResultHint
164
+ : 'Try a broader phrase or a `--type` filter. If capabilities were just added, refresh with `aiwg use <framework>` (or `aiwg index build`).');
165
+ return;
166
+ }
167
+ const relaxedNote = relaxed ? ' — relaxed match (verbose query)' : '';
168
+ console.log(`Discovery results for "${params.phrase}" (${scored.length} matches, ${queryTimeMs}ms)${relaxedNote}:`);
169
+ console.log(statsText(responseRuleStats));
170
+ console.log('');
171
+ for (const diagnostic of facetActivations) {
172
+ if (diagnostic.status === 'suppressed' && diagnostic.reason) {
173
+ console.log(`Routing diagnostic: ${diagnostic.reason}.`);
174
+ console.log('');
175
+ }
176
+ }
177
+ for (let i = 0; i < scored.length; i++) {
178
+ const r = scored[i];
179
+ const ranking = rankingDiagnostic(r.entry, r.score, r.facetDiagnostics);
180
+ const id = discoveryIdForEntry(r.entry);
181
+ const score = r.score.toFixed(2);
182
+ const flags = [
183
+ r.entry.kernel ? 'kernel' : null,
184
+ r.entry.script ? 'exec' : null,
185
+ ].filter(Boolean).join(', ');
186
+ const locator = includePaths ? resolvePath(r.entry) : id;
187
+ const topTriggerMatch = ranking.matches
188
+ .filter((match) => match.field === 'trigger')
189
+ .reduce((best, match) => !best || match.contribution > best.contribution ? match : best, undefined);
190
+ const topTrigger = topTriggerMatch?.value ??
191
+ (r.entry.triggers && r.entry.triggers.length > 0 ? r.entry.triggers[0] : '');
192
+ console.log(`${i + 1}. ${r.entry.title}`);
193
+ console.log(` type: ${r.entry.type} score: ${score}${flags ? ` flags: ${flags}` : ''}`);
194
+ console.log(` ${includePaths ? 'path' : 'id'}: ${locator}`);
195
+ if (r.entry.name) {
196
+ console.log(` name: ${r.entry.name}`);
197
+ }
198
+ if (r.entry.capability) {
199
+ console.log(` capability: ${r.entry.capability}`);
200
+ }
201
+ if (topTrigger) {
202
+ console.log(` trigger: "${topTrigger}"`);
203
+ }
204
+ const triggerCoverage = topTriggerMatch?.query_token_coverage;
205
+ const rankingParts = [
206
+ `lexical ${ranking.lexical_score.toFixed(4)} -> final ${ranking.final_score.toFixed(4)}`,
207
+ triggerCoverage === undefined
208
+ ? null
209
+ : `trigger covers ${Math.round(triggerCoverage * 100)}% of query tokens`,
210
+ `scope ${ranking.tie_breakers.scope}`,
211
+ ].filter((part) => Boolean(part));
212
+ console.log(` ranking: ${rankingParts.join('; ')}`);
213
+ if (governing[i].length) {
214
+ console.log(` ${statsText(governingRuleStats(governing[i]))}`);
215
+ console.log(` ${RULE_CHECK_OBLIGATION}`);
216
+ for (const { rule, applicability } of governing[i])
217
+ console.log(` - ${rule.name ?? rule.path}: ${rule.ruleSummary ?? ''} (${applicability.join('; ')}) — \`${boundRuleDescriptor(rule).show_command}\``);
218
+ }
219
+ if (r.entry.script) {
220
+ console.log(` run: ${buildRunHint(r.entry)}`);
221
+ }
222
+ else if (!includePaths) {
223
+ console.log(` show: ${showHintForDiscoverResult(r.entry, id)}`);
224
+ }
225
+ console.log('');
226
+ }
227
+ console.log('Use `--format json` for machine-readable output. Use `aiwg show metadata <id>` for paths and full metadata.');
228
+ }
229
+ //# sourceMappingURL=query-engine-discover-output.js.map
@@ -0,0 +1,285 @@
1
+ import { applyFacetFusion } from './discover-facets.js';
2
+ import { refreshFrameworkCapabilities, resolveFrameworkCorpusRoot } from './framework-capabilities.js';
3
+ import { resolveFrameworkIndexRoot } from './framework-index-paths.js';
4
+ import { loadGraphIndexFile, loadMetadataIndex } from './index-reader.js';
5
+ 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';
7
+ import { scoreEntryDetailed } from './query-engine-scoring.js';
8
+ import { emptyRuleStats, selectPrebuiltRelations } from './relations.js';
9
+ import { loadGlobalGraphConfigs } from './types.js';
10
+ export async function discoverCapability(cwd, params) {
11
+ loadGlobalGraphConfigs();
12
+ const startTime = Date.now();
13
+ const types = params.typeFilter && params.typeFilter.length > 0
14
+ ? params.typeFilter
15
+ : DEFAULT_DISCOVER_TYPES;
16
+ // Default top-K = 5 (Wave A from #1218): peer-reviewed work on tool
17
+ // retrieval (Semantic Tool Discovery for MCP, arXiv:2603.20313) reports
18
+ // 97.1% hit@K=3 at scale; K=5 keeps a buffer above K=3 while halving
19
+ // the prior K=10 default. Operators wanting more breadth can pass
20
+ // `--limit N` explicitly.
21
+ const limit = params.limit ?? 5;
22
+ // For framework-graph entries, anchor returned paths to AIWG_ROOT so
23
+ // they resolve from any project working directory (#1217).
24
+ const aiwgRoot = resolveFrameworkIndexRoot(cwd);
25
+ // Source: prefer `framework` graph (built post-deploy), fall back to
26
+ // project / codebase / legacy depending on what's available.
27
+ let entries = [];
28
+ const backend = params.backend ?? DEFAULT_ARTIFACT_SEARCH_BACKEND;
29
+ let fortemiCoreDiscoveryScores = null;
30
+ let resourceSource = params.resourceSource ?? 'local';
31
+ let resolvedWebRelease;
32
+ 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')) {
36
+ const root = resolveFrameworkCorpusRoot(cwd) ?? aiwgRoot;
37
+ if (root) {
38
+ try {
39
+ await refreshFrameworkCapabilities(root, backend === 'fortemi-core');
40
+ }
41
+ catch (error) {
42
+ console.error(`Warning: capability index refresh failed: ${error instanceof Error ? error.message : String(error)}`);
43
+ }
44
+ }
45
+ }
46
+ if (resourceSource === 'auto') {
47
+ const { loadFortemiCoreMetadataEntries } = await import('./fortemi-core-query-adapter.js');
48
+ const localGraphs = params.graph ? [params.graph] : defaultCapabilityGraphs(cwd);
49
+ const localAvailable = localGraphs.some((graph) => loadFortemiCoreMetadataEntries(cwd, graph).entries.length > 0
50
+ || Object.keys(loadGraphIndexFile(cwd, 'metadata.json', graph)?.entries ?? {}).length > 0);
51
+ resourceSource = localAvailable ? 'local' : 'web';
52
+ }
53
+ if (resourceSource === 'web') {
54
+ if (backend !== 'fortemi-core') {
55
+ console.error('Error: --resource-source web requires the Fortemi Core query backend; --backend local remains available with local resources.');
56
+ process.exit(1);
57
+ }
58
+ if (params.graph && params.graph !== 'framework') {
59
+ console.error("Error: web-backed capability discovery currently supports only the 'framework' graph.");
60
+ process.exit(1);
61
+ }
62
+ try {
63
+ const { resolveWebRelease } = await import('../resources/web-release.js');
64
+ const release = await resolveWebRelease({
65
+ ...params.webReleaseOptions,
66
+ selector: params.aiwgVersion ?? 'stable',
67
+ offline: params.offline,
68
+ });
69
+ resolvedWebRelease = release;
70
+ verifiedSourcePaths = {
71
+ manifestPath: release.fortemiManifestPath,
72
+ exportPath: release.fortemiExportPath,
73
+ manifestSha256: release.fortemiManifestSha256,
74
+ manifestSize: release.fortemiManifestSize,
75
+ exportSha256: release.fortemiExportSha256,
76
+ exportSize: release.fortemiExportSize,
77
+ };
78
+ }
79
+ catch (error) {
80
+ console.error(`Error: AIWG web resource resolution failed: ${error instanceof Error ? error.message : String(error)}`);
81
+ process.exit(1);
82
+ }
83
+ }
84
+ if (backend === 'fortemi-core') {
85
+ const graphs = resourceSource === 'web'
86
+ ? ['framework']
87
+ : params.graph ? [params.graph] : defaultCapabilityGraphs(cwd);
88
+ const { loadFortemiCoreMetadataEntries, queryFortemiCoreAiwgDiscovery, } = await import('./fortemi-core-query-adapter.js');
89
+ let unavailableReason;
90
+ 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);
96
+ continue;
97
+ }
98
+ }
99
+ if (loaded.sourceIndexNewer && resourceSource === 'local') {
100
+ // Do not silently omit a graph whose derived cache is stale. Rank its
101
+ // current source metadata, without consulting scores from the old cache.
102
+ const index = loadGraphIndexFile(cwd, 'metadata.json', graph);
103
+ if (index) {
104
+ console.error(`Warning: ${graph} capability cache is unavailable or stale; using the local ${graph} index. ${loaded.reason}`);
105
+ entries.push(...Object.values(index.entries).map((entry) => withIndexProvenance(entry, graph)));
106
+ continue;
107
+ }
108
+ }
109
+ if (loaded.reason) {
110
+ unavailableReason ??= loaded.reason;
111
+ if (graph === 'framework' && !params.graph) {
112
+ console.error(`Warning: framework capabilities are unavailable: ${loaded.reason}`);
113
+ }
114
+ }
115
+ entries.push(...loaded.entries.map((entry) => withIndexProvenance(entry, graph)));
116
+ const discovered = await queryFortemiCoreAiwgDiscovery(cwd, {
117
+ graph,
118
+ text: params.phrase,
119
+ limit: Math.max(limit * 10, 50),
120
+ types,
121
+ sourcePaths: verifiedSourcePaths,
122
+ });
123
+ if (!discovered.reason) {
124
+ fortemiCoreDiscoveryScores ??= new Map();
125
+ for (const result of discovered.results) {
126
+ if (result.score <= 0)
127
+ continue;
128
+ fortemiCoreDiscoveryScores.set(result.entry.path, Math.max(fortemiCoreDiscoveryScores.get(result.entry.path) ?? 0, result.score));
129
+ }
130
+ }
131
+ }
132
+ if (entries.length === 0 && unavailableReason) {
133
+ if (params.json) {
134
+ console.log(JSON.stringify({
135
+ query: {
136
+ phrase: params.phrase,
137
+ types,
138
+ limit,
139
+ backend: 'fortemi-core',
140
+ graph: resourceSource === 'web' ? 'framework' : params.graph ?? 'capability-default',
141
+ ...(resourceSource === 'web'
142
+ ? {
143
+ resource_source: 'web',
144
+ aiwg_selector: resolvedWebRelease?.selector,
145
+ aiwg_version: resolvedWebRelease?.version,
146
+ manifest_sha256: resolvedWebRelease?.manifestDigest,
147
+ manifest_url: resolvedWebRelease?.manifestUrl,
148
+ }
149
+ : {}),
150
+ },
151
+ results: [],
152
+ rule_stats: emptyRuleStats(),
153
+ total: 0,
154
+ hint: unavailableReason,
155
+ }, null, 2));
156
+ }
157
+ else {
158
+ console.error('Error: ' + unavailableReason);
159
+ }
160
+ process.exit(1);
161
+ }
162
+ }
163
+ else if (params.graph) {
164
+ const idx = loadGraphIndexFile(cwd, 'metadata.json', params.graph);
165
+ if (idx)
166
+ entries = Object.values(idx.entries).map((entry) => withIndexProvenance(entry, params.graph));
167
+ }
168
+ else {
169
+ // discover is EXCLUSIVELY the agentic-capability surface (#1545): source
170
+ // the `framework` graph (deployed AIWG capabilities) + project-local
171
+ // capability artifacts. NEVER `codebase` — source code is not a capability
172
+ // surface. The framework
173
+ // index is reconciled with its source above, including existing indexes
174
+ // left behind by an older runtime or a different checkout.
175
+ const fwIdx = loadGraphIndexFile(cwd, 'metadata.json', 'framework');
176
+ const includeUser = projectAllowsUserIndices(cwd);
177
+ // Project-local operational artifacts authored in this project. The
178
+ // DEFAULT_DISCOVER_TYPES filter keeps non-capability project artifacts
179
+ // (requirements, ADRs, …) out of results.
180
+ const projIdx = loadGraphIndexFile(cwd, 'metadata.json', 'project');
181
+ if (projIdx)
182
+ entries.push(...Object.values(projIdx.entries).map((entry) => withIndexProvenance(entry, 'project')));
183
+ if (includeUser) {
184
+ const userIdx = loadGraphIndexFile(cwd, 'metadata.json', 'user');
185
+ if (userIdx)
186
+ entries.push(...Object.values(userIdx.entries).map((entry) => withIndexProvenance(entry, 'user')));
187
+ }
188
+ if (fwIdx)
189
+ entries.push(...Object.values(fwIdx.entries).map((entry) => withIndexProvenance(entry, 'framework')));
190
+ if (entries.length === 0) {
191
+ const legacy = loadMetadataIndex(cwd);
192
+ if (legacy)
193
+ entries.push(...Object.values(legacy.entries));
194
+ }
195
+ }
196
+ if (entries.length === 0 && backend !== 'fortemi-core') {
197
+ // Empty-index case (#1221). Surface a hint that explains the gap rather
198
+ // than returning a bare zero-result envelope — the latter trains agents
199
+ // to conclude "AIWG doesn't have a skill for that" when in fact the
200
+ // index simply hasn't been built in this workspace yet.
201
+ const hint = 'No artifact index found. Run `aiwg index build --graph framework` (or `aiwg use <framework>`) first.';
202
+ if (params.json) {
203
+ console.log(JSON.stringify({
204
+ query: { phrase: params.phrase, types },
205
+ results: [],
206
+ rule_stats: emptyRuleStats(),
207
+ total: 0,
208
+ hint,
209
+ }, null, 2));
210
+ }
211
+ else {
212
+ console.error('Error: No artifact index found.');
213
+ console.log('Run `aiwg index build --graph framework` (or `aiwg use <framework>`) first.');
214
+ }
215
+ process.exit(1);
216
+ }
217
+ // Filter by type
218
+ entries = entries.filter(entry => isOrdinaryMemoryEntry(entry, cwd));
219
+ const candidates = entries.filter(e => types.includes(e.type));
220
+ // Score (strict overlap gate). Keep the full sorted list so the facet
221
+ // fusion below can inject/lift curated capabilities into the top-K before
222
+ // truncation — a capability that the lexical pass ranked outside `limit`
223
+ // (or missed entirely) still surfaces when the query activates its facet.
224
+ const lexicalDiagnostics = new Map();
225
+ const legacyStrictScored = candidates
226
+ .map(entry => {
227
+ const detailed = scoreEntryDetailed(entry, params.phrase);
228
+ const legacyScore = detailed.score;
229
+ const fortemiScore = fortemiCoreDiscoveryScores?.get(entry.path) ?? 0;
230
+ lexicalDiagnostics.set(entry.path, detailed.diagnostic);
231
+ return {
232
+ entry,
233
+ score: legacyScore > 0 ? legacyScore : fortemiScore * 0.2,
234
+ legacyScore,
235
+ };
236
+ })
237
+ .filter(r => r.score > 0)
238
+ .sort(compareDiscoverResults);
239
+ const strictScored = (legacyStrictScored.some(result => result.legacyScore > 0)
240
+ ? legacyStrictScored.filter(result => result.legacyScore > 0)
241
+ : legacyStrictScored).map(({ entry, score }) => ({ entry, score }));
242
+ // Single-pass facet fusion (#1623 U3): fuse the curated feature→capability
243
+ // facets (expansion / persona / project / provider-capability) into the
244
+ // lexical ranking so canonical domain phrases rank their owning capability
245
+ // top-K instead of being out-scored by artifacts that merely mention the
246
+ // word. Facet activation can also rescue an otherwise-empty strict pass.
247
+ // #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
250
+ // floor, and union it with strict matches before ranking. Word-boundary
251
+ // token matching keeps this from resurrecting substring noise such as UX in
252
+ // Linux.
253
+ const RELAXED_MIN_SCORE = 0.02;
254
+ const strictPaths = new Set(strictScored.map(result => result.entry.path));
255
+ const combinedByPath = new Map(strictScored.map(result => [result.entry.path, result]));
256
+ for (const entry of candidates) {
257
+ const detailed = scoreEntryDetailed(entry, params.phrase, { relaxOverlap: true });
258
+ if (detailed.score < RELAXED_MIN_SCORE)
259
+ continue;
260
+ const existing = combinedByPath.get(entry.path);
261
+ if (!existing || detailed.score > existing.score) {
262
+ combinedByPath.set(entry.path, { entry, score: detailed.score });
263
+ lexicalDiagnostics.set(entry.path, detailed.diagnostic);
264
+ }
265
+ }
266
+ const scored = dedupeDiscoverResults(await applyFacetFusion(Array.from(combinedByPath.values()).sort(compareDiscoverResults), candidates, params.phrase)).slice(0, limit);
267
+ const relaxed = scored.some(result => !strictPaths.has(result.entry.path));
268
+ if (params.shadowRoute) {
269
+ try {
270
+ await params.shadowRoute.observe(params.phrase, scored.map(result => ({
271
+ id: discoveryIdForEntry(result.entry), name: result.entry.name ?? result.entry.title,
272
+ type: result.entry.type, capability: result.entry.capability ?? result.entry.summary,
273
+ score: result.score,
274
+ })));
275
+ }
276
+ catch {
277
+ // An optional observation failure must never replace deterministic discovery.
278
+ params.shadowRoute.disable();
279
+ }
280
+ }
281
+ const queryTimeMs = Date.now() - startTime;
282
+ await emitDiscoverResults({ cwd, params, types, limit, aiwgRoot, entries, backend, resourceSource,
283
+ resolvedWebRelease, prebuiltRelations, scored, relaxed, queryTimeMs, lexicalDiagnostics });
284
+ }
285
+ //# sourceMappingURL=query-engine-discover.js.map