@aiwg/cli 2026.10.15 → 2026.10.18

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 (286) hide show
  1. package/agentic/code/providers/pi/aiwg-bridge.ts +45 -7
  2. package/dist/src/artifacts/citation-parser.js +7 -6
  3. package/dist/src/artifacts/corpus-tools/citation-densify.js +4 -2
  4. package/dist/src/artifacts/corpus-tools/cli.js +8 -3
  5. package/dist/src/artifacts/corpus-tools/discovery-log.js +26 -24
  6. package/dist/src/artifacts/corpus-tools/expand-cli.js +3 -2
  7. package/dist/src/artifacts/corpus-tools/expand-dates.js +107 -0
  8. package/dist/src/artifacts/corpus-tools/expand-queue.js +4 -1
  9. package/dist/src/artifacts/corpus-tools/expand-review.js +104 -0
  10. package/dist/src/artifacts/corpus-tools/expand-state.js +17 -1
  11. package/dist/src/artifacts/corpus-tools/expand.js +16 -17
  12. package/dist/src/artifacts/corpus-tools/induction-audit.js +7 -6
  13. package/dist/src/artifacts/corpus-tools/integrity-scan.js +3 -3
  14. package/dist/src/artifacts/corpus-tools/radar-shared.js +7 -9
  15. package/dist/src/artifacts/corpus-tools/ref-files.js +11 -0
  16. package/dist/src/artifacts/corpus-tools/resolve-cli.js +11 -3
  17. package/dist/src/artifacts/corpus-tools/resolve.js +42 -11
  18. package/dist/src/artifacts/corpus-tools/retrieval-lab.js +2 -1
  19. package/dist/src/artifacts/corpus-tools/sidecar-lint.js +4 -4
  20. package/dist/src/artifacts/corpus-tools/sidecar-repair.js +2 -1
  21. package/dist/src/artifacts/corpus-views/ref-parser.js +3 -17
  22. package/dist/src/artifacts/graph-query.js +5 -3
  23. package/dist/src/artifacts/hybrid-query.js +11 -2
  24. package/dist/src/artifacts/index-refresh.js +2 -0
  25. package/dist/src/artifacts/query-engine-corpus.js +217 -0
  26. package/dist/src/artifacts/query-engine-discover-output.js +229 -0
  27. package/dist/src/artifacts/query-engine-discover.js +285 -0
  28. package/dist/src/artifacts/query-engine-entries.js +188 -0
  29. package/dist/src/artifacts/query-engine-index.js +249 -0
  30. package/dist/src/artifacts/query-engine-matching.js +143 -0
  31. package/dist/src/artifacts/query-engine-options.js +2 -0
  32. package/dist/src/artifacts/query-engine-rules.js +202 -0
  33. package/dist/src/artifacts/query-engine-scoring.js +436 -0
  34. package/dist/src/artifacts/query-engine-show-card.js +194 -0
  35. package/dist/src/artifacts/query-engine-show-load.js +211 -0
  36. package/dist/src/artifacts/query-engine-show.js +300 -0
  37. package/dist/src/artifacts/query-engine.js +7 -2576
  38. package/dist/src/cli/handlers/daemon.js +17 -1
  39. package/dist/src/cli/handlers/doctor-args.js +10 -5
  40. package/dist/src/cli/handlers/doctor-help.js +4 -1
  41. package/dist/src/cli/handlers/index.js +2 -2
  42. package/dist/src/cli/handlers/mc-agents.js +111 -0
  43. package/dist/src/cli/handlers/mc-args.js +54 -0
  44. package/dist/src/cli/handlers/mc-control.js +227 -0
  45. package/dist/src/cli/handlers/mc-dispatch.js +203 -0
  46. package/dist/src/cli/handlers/mc-help.js +171 -0
  47. package/dist/src/cli/handlers/mc-run.js +343 -0
  48. package/dist/src/cli/handlers/mc-session.js +138 -0
  49. package/dist/src/cli/handlers/mc-status.js +258 -0
  50. package/dist/src/cli/handlers/mc-summary.js +43 -0
  51. package/dist/src/cli/handlers/mc-types.js +3 -0
  52. package/dist/src/cli/handlers/mc-worker.js +205 -0
  53. package/dist/src/cli/handlers/mc.js +12 -1665
  54. package/dist/src/cli/handlers/models-refusal.js +13 -0
  55. package/dist/src/cli/handlers/models-resource-sample.js +10 -0
  56. package/dist/src/cli/handlers/models.js +5 -3
  57. package/dist/src/cli/handlers/regenerate.js +8 -16
  58. package/dist/src/cli/handlers/remove-bundled.js +133 -0
  59. package/dist/src/cli/handlers/remove-options.js +31 -0
  60. package/dist/src/cli/handlers/remove-user.js +174 -0
  61. package/dist/src/cli/handlers/remove.js +201 -0
  62. package/dist/src/cli/handlers/sessions.js +7 -7
  63. package/dist/src/cli/handlers/subcommands-bundles.js +257 -0
  64. package/dist/src/cli/handlers/subcommands-discovery.js +165 -0
  65. package/dist/src/cli/handlers/subcommands-list-format.js +129 -0
  66. package/dist/src/cli/handlers/subcommands-list.js +250 -0
  67. package/dist/src/cli/handlers/subcommands-plugins.js +213 -0
  68. package/dist/src/cli/handlers/subcommands-quickref.js +58 -0
  69. package/dist/src/cli/handlers/subcommands-rlm.js +113 -0
  70. package/dist/src/cli/handlers/subcommands-services.js +66 -0
  71. package/dist/src/cli/handlers/subcommands-storage.js +259 -0
  72. package/dist/src/cli/handlers/subcommands.js +18 -1976
  73. package/dist/src/cli/handlers/update.js +157 -0
  74. package/dist/src/cli/handlers/use.js +14 -4
  75. package/dist/src/cli/handlers/utilities.js +3 -560
  76. package/dist/src/cli/handlers/utility-doctor.js +412 -0
  77. package/dist/src/cli/scope-resolver.js +1 -142
  78. package/dist/src/cli/services/deployment-verification.js +0 -1
  79. package/dist/src/cli/user-scope-mirror.js +173 -0
  80. package/dist/src/config/aiwg-config.js +2 -1
  81. package/dist/src/config/authorization-cli.js +7 -3
  82. package/dist/src/config/dispatch-host-thresholds.js +2 -0
  83. package/dist/src/config/dispatch-thresholds-runtime.d.mts +3 -2
  84. package/dist/src/config/dispatch-thresholds-runtime.mjs +21 -7
  85. package/dist/src/config/framework-aliases.js +12 -0
  86. package/dist/src/config/host-resource-report.d.mts +24 -0
  87. package/dist/src/config/host-resource-report.mjs +110 -0
  88. package/dist/src/config/host-resource-runtime.d.mts +37 -0
  89. package/dist/src/config/host-resource-runtime.mjs +296 -0
  90. package/dist/src/config/installed-selection.js +22 -0
  91. package/dist/src/config/worker-invocation-marker.d.mts +1 -0
  92. package/dist/src/config/worker-invocation-marker.mjs +2 -0
  93. package/dist/src/decision/ensemble-study/artifacts.js +7 -0
  94. package/dist/src/decision/ensemble-study/gate-policy.js +58 -0
  95. package/dist/src/decision/ensemble-study/gates.js +78 -0
  96. package/dist/src/decision/ensemble-study/protocol.js +18 -21
  97. package/dist/src/decision/ensemble-study/score.js +3 -2
  98. package/dist/src/decision/ensemble-study/statistics.js +7 -26
  99. package/dist/src/decision/heldout/access.js +74 -0
  100. package/dist/src/decision/heldout/calibration.js +1 -0
  101. package/dist/src/decision/heldout/collector.js +8 -1
  102. package/dist/src/decision/sensitivity/comparative-gates.js +135 -0
  103. package/dist/src/decision/sensitivity/comparative.js +18 -41
  104. package/dist/src/effects/verifiers/file.js +22 -5
  105. package/dist/src/extensions/claude-attribution.js +82 -0
  106. package/dist/src/extensions/claude-hooks-installer.js +133 -69
  107. package/dist/src/extensions/commands/daemon.js +109 -0
  108. package/dist/src/extensions/commands/definitions.js +5 -89
  109. package/dist/src/gates/evaluate.js +2 -358
  110. package/dist/src/gates/heldout.js +17 -7
  111. package/dist/src/gates/observations.js +363 -0
  112. package/dist/src/gates/pack-composition.js +270 -0
  113. package/dist/src/gates/pack-tightening.js +197 -0
  114. package/dist/src/gates/pack-validation.js +262 -0
  115. package/dist/src/gates/registry-error.js +5 -0
  116. package/dist/src/gates/registry.js +13 -685
  117. package/dist/src/lint/check-patterns.js +163 -0
  118. package/dist/src/lint/checks.js +268 -0
  119. package/dist/src/lint/reference-resolution.js +54 -0
  120. package/dist/src/lint/runner.js +3 -465
  121. package/dist/src/mcp/helpers.mjs +11 -1
  122. package/dist/src/mcp/json-document.mjs +29 -0
  123. package/dist/src/mcp/muse-native-config.mjs +1 -28
  124. package/dist/src/memory/project-registry.js +44 -4
  125. package/dist/src/mission-protocol/worker-review-gate.js +7 -0
  126. package/dist/src/models/worker-plan.js +36 -5
  127. package/dist/src/models/wrapper-deployment.js +25 -12
  128. package/dist/src/models/wrapper-enforcement.js +47 -7
  129. package/dist/src/network-analysis/research.js +2 -1
  130. package/dist/src/plugin/command-ownership.js +34 -0
  131. package/dist/src/plugin/skill-command-frontmatter.js +197 -0
  132. package/dist/src/plugin/skill-command-translator.js +6 -232
  133. package/dist/src/policy/hitl-check.js +14 -4
  134. package/dist/src/policy/hitl-consume.js +54 -0
  135. package/dist/src/policy/hitl-receipt.js +2 -0
  136. package/dist/src/policy/hitl.js +11 -3
  137. package/dist/src/providers/context-output-ownership.js +26 -0
  138. package/dist/src/providers/deployment-ownership.d.mts +19 -0
  139. package/dist/src/providers/deployment-ownership.mjs +226 -0
  140. package/dist/src/providers/deployment-removal.js +200 -0
  141. package/dist/src/providers/provider-context-contracts.js +162 -0
  142. package/dist/src/providers/provider-definition-schema.js +136 -0
  143. package/dist/src/providers/provider-definitions.js +8 -1298
  144. package/dist/src/providers/provider-seeds-1.js +360 -0
  145. package/dist/src/providers/provider-seeds-2.js +387 -0
  146. package/dist/src/providers/provider-seeds-3.js +262 -0
  147. package/dist/src/providers/removal-transaction.js +86 -0
  148. package/dist/src/providers/settings-document.d.mts +3 -0
  149. package/dist/src/providers/settings-document.mjs +47 -0
  150. package/dist/src/providers/settings-removal.js +190 -0
  151. package/dist/src/providers/skill-ownership.d.mts +19 -2
  152. package/dist/src/providers/skill-ownership.mjs +12 -4
  153. package/dist/src/providers/transformation-receipt-integration.js +15 -271
  154. package/dist/src/providers/transformation-receipt-outputs.js +99 -0
  155. package/dist/src/providers/transformation-receipt-source.js +194 -0
  156. package/dist/src/research/clients/arxiv.js +4 -30
  157. package/dist/src/research/clients/base.js +48 -22
  158. package/dist/src/research/identity.js +42 -4
  159. package/dist/src/research/query-cli.js +3 -87
  160. package/dist/src/research/query-options.js +87 -0
  161. package/dist/src/research/reference-match.js +105 -24
  162. package/dist/src/research/services/acquisition.js +9 -7
  163. package/dist/src/research/services/citation.js +5 -2
  164. package/dist/src/research/types.js +2 -0
  165. package/dist/src/rules/activation.mjs +15 -6
  166. package/dist/src/rules/core-startup.mjs +2 -2
  167. package/dist/src/serve/mission-conductor.js +52 -4
  168. package/dist/src/serve/mission-summary.js +56 -0
  169. package/dist/src/sessions/adapters/grok-build-native.js +23 -0
  170. package/dist/src/sessions/adapters/grok-build.js +14 -7
  171. package/dist/src/sessions/workspace-discovery.js +5 -5
  172. package/dist/src/smiths/context-pipeline/aiwg-md.js +39 -46
  173. package/dist/src/smiths/context-pipeline/claude-hook.js +1 -1
  174. package/dist/src/smiths/context-pipeline/code-regions.js +28 -0
  175. package/dist/src/smiths/context-pipeline/context-file-safety.js +3 -0
  176. package/dist/src/smiths/context-pipeline/finalization.js +81 -51
  177. package/dist/src/smiths/context-pipeline/generator.js +10 -11
  178. package/dist/src/smiths/context-pipeline/managed-hook.js +1 -1
  179. package/dist/src/smiths/context-pipeline/muse-bridge.js +2 -2
  180. package/dist/src/smiths/context-pipeline/provider-policy.js +6 -12
  181. package/dist/src/smiths/context-pipeline/workspace-audit.js +299 -0
  182. package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +148 -0
  183. package/dist/src/smiths/context-pipeline/workspace-context-shared.js +111 -0
  184. package/dist/src/smiths/context-pipeline/workspace-context.js +8 -1373
  185. package/dist/src/smiths/context-pipeline/workspace-doctor.js +192 -0
  186. package/dist/src/smiths/context-pipeline/workspace-document.js +201 -0
  187. package/dist/src/smiths/context-pipeline/workspace-extraction.js +205 -0
  188. package/dist/src/smiths/context-pipeline/workspace-migration.js +250 -0
  189. package/dist/src/smiths/hook-bridge/index.js +9 -0
  190. package/package.json +13 -1
  191. package/schemas/decision/D17StudyProtocol.v1.schema.json +39 -67
  192. package/schemas/decision/D29Study.v10.schema.json +65 -0
  193. package/tools/agents/deploy-agents.mjs +24 -675
  194. package/tools/agents/deploy-command-mirrors.mjs +229 -0
  195. package/tools/agents/deploy-options.mjs +258 -0
  196. package/tools/agents/deploy-support.mjs +165 -0
  197. package/tools/agents/providers/base-addon-discovery.mjs +139 -0
  198. package/tools/agents/providers/base-behaviors.mjs +168 -0
  199. package/tools/agents/providers/base-context.mjs +205 -0
  200. package/tools/agents/providers/base-contract.mjs +116 -0
  201. package/tools/agents/providers/base-files.mjs +252 -0
  202. package/tools/agents/providers/base-flat-artifacts.mjs +233 -0
  203. package/tools/agents/providers/base-framework-discovery.mjs +309 -0
  204. package/tools/agents/providers/base-frontmatter.mjs +196 -0
  205. package/tools/agents/providers/base-inventory.mjs +269 -0
  206. package/tools/agents/providers/base-kernel-skills.mjs +354 -0
  207. package/tools/agents/providers/base-migrations.mjs +258 -0
  208. package/tools/agents/providers/base-models-platforms.mjs +273 -0
  209. package/tools/agents/providers/base-rule-index.mjs +450 -0
  210. package/tools/agents/providers/base-runtime.mjs +60 -0
  211. package/tools/agents/providers/base-skill-copy.mjs +273 -0
  212. package/tools/agents/providers/base.mjs +16 -3364
  213. package/tools/agents/providers/claude-post-deploy.mjs +20 -1
  214. package/tools/agents/providers/context-write.mjs +4 -0
  215. package/tools/agents/providers/hermes-startup.mjs +0 -5
  216. package/tools/agents/providers/muse.mjs +7 -2
  217. package/tools/agents/providers/pi.mjs +3 -1
  218. package/tools/agents/providers/rule-delivery-surface.mjs +359 -0
  219. package/tools/agents/providers/rule-delivery.mjs +20 -1144
  220. package/tools/agents/providers/rule-deployment-commit.mjs +148 -0
  221. package/tools/agents/providers/rule-deployment-prepare.mjs +461 -0
  222. package/tools/agents/providers/rule-deployment-state.mjs +300 -0
  223. package/tools/agents/providers/rule-projection.mjs +3 -0
  224. package/tools/daemon/README.md +511 -0
  225. package/tools/daemon/adapters/base-adapter.mjs +84 -0
  226. package/tools/daemon/adapters/webhook-adapter.mjs +107 -0
  227. package/tools/daemon/agent-supervisor.mjs +299 -0
  228. package/tools/daemon/automation-engine.mjs +310 -0
  229. package/tools/daemon/autonomous-engine.mjs +346 -0
  230. package/tools/daemon/behavior-loader.mjs +316 -0
  231. package/tools/daemon/behavior.mjs +174 -0
  232. package/tools/daemon/concierge/intent-router.mjs +401 -0
  233. package/tools/daemon/concierge/orchestrator.mjs +272 -0
  234. package/tools/daemon/concierge/response-translator.mjs +462 -0
  235. package/tools/daemon/config.mjs +377 -0
  236. package/tools/daemon/cron-scheduler.mjs +178 -0
  237. package/tools/daemon/daemon-main.mjs +1169 -0
  238. package/tools/daemon/event-router.mjs +84 -0
  239. package/tools/daemon/file-watcher.mjs +383 -0
  240. package/tools/daemon/index.mjs +1181 -0
  241. package/tools/daemon/init-profile.mjs +124 -0
  242. package/tools/daemon/ipc-client.mjs +197 -0
  243. package/tools/daemon/ipc-ops-handlers.mjs +236 -0
  244. package/tools/daemon/ipc-server.mjs +275 -0
  245. package/tools/daemon/maintenance-owner.mjs +79 -0
  246. package/tools/daemon/memory-manager.mjs +386 -0
  247. package/tools/daemon/message-router.mjs +194 -0
  248. package/tools/daemon/provider-watcher.mjs +585 -0
  249. package/tools/daemon/pty-adapter.mjs +420 -0
  250. package/tools/daemon/repl-chat.mjs +359 -0
  251. package/tools/daemon/resource-bounds.mjs +88 -0
  252. package/tools/daemon/sandbox-transport.mjs +295 -0
  253. package/tools/daemon/scheduled-task-runner.mjs +535 -0
  254. package/tools/daemon/task-store.mjs +450 -0
  255. package/tools/daemon/tmux-manager.mjs +324 -0
  256. package/tools/daemon/update-policy.mjs +517 -0
  257. package/tools/daemon/web-server.mjs +399 -0
  258. package/tools/daemon/web-ui/index.html +585 -0
  259. package/tools/daemon/web-ui/styles.css +156 -0
  260. package/tools/docker/Dockerfile.daemon +35 -0
  261. package/tools/docker/container-manager.mjs +291 -0
  262. package/tools/messaging/adapter-registry.mjs +230 -0
  263. package/tools/messaging/adapters/base.mjs +326 -0
  264. package/tools/messaging/adapters/discord.mjs +462 -0
  265. package/tools/messaging/adapters/slack.mjs +402 -0
  266. package/tools/messaging/adapters/telegram.mjs +552 -0
  267. package/tools/messaging/chat-handler.mjs +297 -0
  268. package/tools/messaging/command-router.mjs +269 -0
  269. package/tools/messaging/event-bus.mjs +199 -0
  270. package/tools/messaging/index.mjs +456 -0
  271. package/tools/messaging/message-formatter.mjs +320 -0
  272. package/tools/messaging/room-manager.mjs +277 -0
  273. package/tools/messaging/types.mjs +94 -0
  274. package/tools/providers/pi-bridge-policy.mjs +4 -0
  275. package/tools/ralph-external/daemon-supervisor.mjs +394 -0
  276. package/tools/ralph-external/lib/behavior-registry.mjs +270 -0
  277. package/tools/ralph-external/lib/worker-invocation-processes.mjs +7 -4
  278. package/tools/ralph-external/lib/worker-isolation-args.mjs +217 -0
  279. package/tools/ralph-external/lib/worker-isolation-status.mjs +19 -0
  280. package/tools/ralph-external/lib/worker-isolation.mjs +11 -237
  281. package/tools/ralph-external/lib/worker-overflow.mjs +10 -2
  282. package/tools/ralph-external/lib/worker-termination.mjs +15 -8
  283. package/tools/ralph-external/lib/worker-unit-cleanup.mjs +72 -0
  284. package/tools/ralph-external/session-launcher.mjs +7 -7
  285. package/tools/scripts/resource-preflight.mjs +3 -242
  286. package/vscode-extension/schemas/aiwg.config.v1.json +2 -4
@@ -8,2580 +8,11 @@
8
8
  * @source @src/artifacts/types.ts
9
9
  * @tests @test/unit/artifacts/query-engine.test.ts
10
10
  */
11
- import { refreshFrameworkCapabilities, resolveFrameworkCorpusRoot, isCorpusBundleInstalled } from './framework-capabilities.js';
12
- import { resolveFrameworkIndexRoot } from './framework-index-paths.js';
13
- import { ensureRelations, selectPrebuiltRelations, emptyRuleStats } from './relations.js';
14
- import { minimatch } from 'minimatch';
15
- import { selectBindingTargetIdentities, preferCanonicalBindingTargets } from './binding-target-identity.js';
16
- import { inferRuleActivation } from '../rules/activation.mjs';
17
- import * as fs from 'node:fs';
18
- import * as path from 'node:path';
19
- import { OPERATIONAL_DISCOVERY_TYPES, OPERATIONAL_SHOW_TYPES, isOperationalShowType, loadGlobalGraphConfigs, getGraphIndexDir, } from './types.js';
20
- import { loadMetadataIndex, loadGraphIndexFile } from './index-reader.js';
21
- import { bm25Rank } from './fulltext.js';
22
- import { parseFrontmatter, parseFlowDoc, extractMarkdownLinks } from './index-builder.js';
23
- import { applyFacetFusion, diagnoseFacetActivations, } from './discover-facets.js';
24
- import { recordTypeForEntry, stableRecordId, } from './browser-export.js';
25
- import { loadProviderModelMetadata } from '../models/provider-models.js';
26
- import { projectAiwgPath, projectControlPath } from '../config/project-artifacts.js';
27
- import { operationalStateQueryProjection, } from './operational-state.js';
28
- function normalizeIndexedPath(entryPath) {
29
- return entryPath.replace(/\\/g, '/');
30
- }
31
- /** Historical records stay in the index for explicit show/history lookup. */
32
- export function isOrdinaryMemoryEntry(entry, _cwd) {
33
- // Maintenance owners publish dispositions into the index before returning.
34
- // Retrieval must not read sources: ordinary legacy entries need no memory
35
- // stamp, and temporary source I/O failures cannot hide active metadata.
36
- return !entry.memoryRecord || (entry.memoryRecord.lifecycle === 'active' && entry.memoryRecord.placement !== 'archived');
37
- }
38
- /**
39
- * Resolve an index entry's source file path and read its body (frontmatter
40
- * stripped). Entry paths are normally relative to the project; framework-graph
41
- * entries may be absolute or anchored to $AIWG_ROOT. Returns null when the
42
- * file can't be read (stale index entry) so full-text ranking skips it.
43
- */
44
- function readEntryBody(cwd, entryPath) {
45
- const candidates = [];
46
- if (path.isAbsolute(entryPath))
47
- candidates.push(entryPath);
48
- else {
49
- const normalizedPath = normalizeIndexedPath(entryPath);
50
- if (normalizedPath.startsWith('.aiwg/')) {
51
- candidates.push(projectAiwgPath(cwd, normalizedPath.slice('.aiwg/'.length)));
52
- }
53
- candidates.push(path.resolve(cwd, normalizedPath));
54
- if (process.env.AIWG_ROOT)
55
- candidates.push(path.resolve(process.env.AIWG_ROOT, normalizedPath));
56
- }
57
- for (const p of candidates) {
58
- try {
59
- const raw = fs.readFileSync(p, 'utf8');
60
- return parseFrontmatter(raw).body;
61
- }
62
- catch {
63
- /* try next candidate */
64
- }
65
- }
66
- return null;
67
- }
68
- const DEFAULT_ARTIFACT_SEARCH_BACKEND = 'fortemi-core';
69
- const DISCOVER_TYPE_ORDER = new Map([...OPERATIONAL_DISCOVERY_TYPES, 'hook', 'doc'].map((type, index) => [type, index]));
70
- function canonicalLocalityRank(entryPath) {
71
- const normalized = entryPath.replace(/\\/g, '/');
72
- if (normalized.startsWith('.aiwg/') || normalized.includes('/.aiwg/'))
73
- return 0;
74
- // Top-level persona mirrors are the least canonical source for a name a bundle
75
- // also owns. Without this they fell into the catch-all below and scored 1,
76
- // beating the bundle copy at 2 — the opposite of #1643. It only ever looked
77
- // correct because a populated user index supplied provenance and `scopeRank`
78
- // never reached this fallback (#2544).
79
- if (normalized.startsWith('agentic/code/agents/') || normalized.includes('/agentic/code/agents/'))
80
- return 4;
81
- if (normalized.includes('/plugins/') || normalized.startsWith('agentic/code/plugins/'))
82
- return 3;
83
- if (normalized.includes('/frameworks/') ||
84
- normalized.includes('/addons/') ||
85
- normalized.includes('/extensions/') ||
86
- normalized.startsWith('agentic/code/frameworks/') ||
87
- normalized.startsWith('agentic/code/addons/') ||
88
- normalized.startsWith('agentic/code/extensions/')) {
89
- return 2;
90
- }
91
- return 1;
92
- }
93
- function graphScope(graph) {
94
- if (graph === 'project')
95
- return 'project';
96
- if (graph === 'user' || graph.startsWith('user-'))
97
- return 'user';
98
- if (graph === 'framework')
99
- return 'packaged';
100
- if (graph === 'codebase' || graph === 'source')
101
- return 'codebase';
102
- return 'custom';
103
- }
104
- function containsTokenSequence(haystack, needle) {
105
- if (needle.length === 0 || haystack.length < needle.length)
106
- return false;
107
- for (let i = 0; i <= haystack.length - needle.length; i++) {
108
- let matched = true;
109
- for (let j = 0; j < needle.length; j++) {
110
- if (haystack[i + j] !== needle[j]) {
111
- matched = false;
112
- break;
113
- }
114
- }
115
- if (matched)
116
- return true;
117
- }
118
- return false;
119
- }
120
- function withIndexProvenance(entry, graph) {
121
- return { ...entry, indexGraph: graph, indexScope: graphScope(graph) };
122
- }
123
- /** Keep existing project capabilities visible while their derived cache is unavailable. */
124
- function projectCapabilityFallback(cwd) {
125
- const index = loadGraphIndexFile(cwd, 'metadata.json', 'project');
126
- if (index) {
127
- const entries = Object.values(index.entries).map((entry) => withIndexProvenance(entry, 'project'));
128
- if (entries.length > 0) {
129
- // One diagnostic per command, on stderr so JSON and skill bodies stay parseable.
130
- console.error('Warning: project capability cache is unavailable or stale; using the local project index. Run `aiwg index sync` to repair the cache.');
131
- return entries;
132
- }
133
- }
134
- if (['extensions', 'addons', 'frameworks', 'plugins', 'skills'].some((dir) => fs.existsSync(projectAiwgPath(cwd, dir)))) {
135
- 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.');
136
- }
137
- return index ? [] : null;
138
- }
139
- function discoveryIdForEntry(entry) {
140
- return stableRecordId(recordTypeForEntry(entry, 'v2'), entry.path);
141
- }
142
- function logicalDiscoverKey(entry) {
143
- const identity = (entry.name ?? entry.title ?? path.basename(entry.path))
144
- .toLowerCase()
145
- .replace(/[-_\s]+/g, ' ')
146
- .trim();
147
- return `${entry.type}:${identity}`;
148
- }
149
- function dedupeDiscoverResults(results) {
150
- const bestByIdentity = new Map();
151
- for (const result of results) {
152
- const key = logicalDiscoverKey(result.entry);
153
- const existing = bestByIdentity.get(key);
154
- if (!existing || compareDiscoverResults(result, existing) < 0) {
155
- bestByIdentity.set(key, result);
156
- }
157
- }
158
- return Array.from(bestByIdentity.values()).sort(compareDiscoverResults);
159
- }
160
- function scopeRank(entry) {
161
- const scope = entry.indexScope;
162
- if (scope === 'project')
163
- return 0;
164
- if (scope === 'user')
165
- return 1;
166
- if (scope === 'custom')
167
- return 2;
168
- if (scope === 'packaged')
169
- return 3;
170
- if (scope === 'codebase')
171
- return 4;
172
- return canonicalLocalityRank(entry.path);
173
- }
174
- function compareText(left, right) {
175
- return (left ?? '').localeCompare(right ?? '');
176
- }
177
- export function compareDiscoverResults(left, right) {
178
- const scoreCmp = right.score - left.score;
179
- if (scoreCmp !== 0)
180
- return scoreCmp;
181
- const localityCmp = scopeRank(left.entry) - scopeRank(right.entry);
182
- if (localityCmp !== 0)
183
- return localityCmp;
184
- const typeCmp = (DISCOVER_TYPE_ORDER.get(left.entry.type) ?? 99) -
185
- (DISCOVER_TYPE_ORDER.get(right.entry.type) ?? 99);
186
- if (typeCmp !== 0)
187
- return typeCmp;
188
- const nameCmp = compareText(left.entry.name ?? left.entry.title, right.entry.name ?? right.entry.title);
189
- if (nameCmp !== 0)
190
- return nameCmp;
191
- return left.entry.path.localeCompare(right.entry.path);
192
- }
193
- /**
194
- * Stop-words to drop when tokenizing a discovery phrase. Keep short —
195
- * we want the user's verbs and nouns to dominate scoring.
196
- */
197
- // Stopwords stripped from a discover QUERY before scoring (#1581). Two classes:
198
- // 1. Grammatical filler (articles, prepositions, pronouns, question words,
199
- // asking verbs) — a natural-language intent like "Find an AIWG skill that
200
- // handles intake forms" carries the same meaning as "intake forms", but the
201
- // filler tokens inflate the token count: the strict overlap gate is
202
- // ceil(n/2), so a verbose query raises the bar above what the genuinely
203
- // relevant short-match artifact can clear, and the (hits/n) term dilutes
204
- // every score. Dropping filler collapses the query to its content tokens.
205
- // 2. AIWG meta-type nouns ('aiwg', 'skill', 'agent', 'command', 'rule',
206
- // 'flow', 'workflow') — in a discover query these carry zero discriminating
207
- // signal (every result IS an aiwg skill/agent/…; the TYPE is filtered via
208
- // --type). The content word after them is what matters
209
- // ("…skill that handles >intake forms<"). Keeping them surfaces incidental
210
- // junk matches (any artifact mentioning "skill"/"aiwg") above the real one.
211
- // Only the query is tokenized here — entry fields are substring-matched — so this
212
- // never changes what text an artifact exposes, only how the query is reduced.
213
- const SCORE_STOPWORDS = new Set([
214
- // articles / conjunctions / prepositions / copula
215
- 'the', 'a', 'an', 'and', 'or', 'of', 'for', 'to', 'in', 'on',
216
- 'with', 'into', 'from', 'is', 'are', 'be', 'i', 'we', 'my',
217
- // pronouns / determiners / fillers
218
- 'it', 'you', 'me', 'us', 'your', 'our', 'this', 'that', 'these', 'those',
219
- 'there', 'here', 'some', 'any', 'all', 'also', 'please', 'about', 'project',
220
- // question words
221
- 'how', 'what', 'which', 'where', 'when', 'who', 'why',
222
- // asking / request verbs ("find a skill that handles …")
223
- 'find', 'give', 'show', 'need', 'want', 'looking', 'look', 'help',
224
- 'do', 'does', 'did', 'can', 'could', 'should', 'would', 'will',
225
- 'handle', 'handles', 'handling',
226
- // AIWG meta-type nouns — zero discriminating signal in a discover query
227
- 'aiwg', 'skill', 'skills', 'agent', 'agents', 'command', 'commands',
228
- 'rule', 'rules', 'schema', 'schemas', 'flow', 'flows', 'workflow', 'workflows',
229
- 'template', 'templates',
230
- ]);
231
- /**
232
- * Tokenize a query phrase into lowercased keywords for multi-word
233
- * scoring. Splits on whitespace and punctuation; drops stopwords and
234
- * single-character tokens.
235
- */
236
- function tokenize(text) {
237
- return text
238
- .toLowerCase()
239
- .split(/[^a-z0-9]+/)
240
- .filter(t => t.length > 1 && !SCORE_STOPWORDS.has(t))
241
- .map(token => token.length > 4 && token.endsWith('s') && !token.endsWith('ss')
242
- ? token.slice(0, -1)
243
- : token);
244
- }
245
- function matchedFieldTokens(queryTokens, field) {
246
- const fieldTokens = new Set(tokenize(field));
247
- return queryTokens.filter(token => fieldTokens.has(token));
248
- }
249
- function fieldContainsQuery(field, queryTokens) {
250
- return containsTokenSequence(tokenize(field), queryTokens);
251
- }
252
- /**
253
- * Score a metadata entry against a keyword query.
254
- *
255
- * Multi-word queries are tokenized; each token contributes its weighted
256
- * match across the entry's searchable fields. The full phrase still
257
- * earns bonus weight when it appears as a contiguous substring or as
258
- * an exact trigger phrase (the most reliable signal).
259
- *
260
- * For AIWG artifact kinds (skills/agents/commands/rules) the entry
261
- * carries `triggers` (declared activation phrases) and `capability`
262
- * (one-line description). These get the highest weights so capability
263
- * search via `aiwg index discover` ranks the right skill on top
264
- * instead of bottoming out on a path-substring match (#1214).
265
- */
266
- /**
267
- * Normalize a string for exact-name comparison (#1233) — lowercase and
268
- * collapse `-` / `_` / whitespace runs so hyphenated kernel-skill names
269
- * like `aiwg-doctor` match queries with spaces ("aiwg doctor") and the
270
- * rendered title ("AIWG Doctor") matches the slug query.
271
- */
272
- function normalizeName(s) {
273
- return s.toLowerCase().replace(/[-_\s]+/g, ' ').trim();
274
- }
275
- function damerauLevenshteinAtMostOne(a, b) {
276
- if (a === b)
277
- return true;
278
- if (Math.abs(a.length - b.length) > 1)
279
- return false;
280
- if (a.length === b.length) {
281
- let firstDiff = -1;
282
- let diffCount = 0;
283
- for (let i = 0; i < a.length; i++) {
284
- if (a[i] !== b[i]) {
285
- if (firstDiff < 0)
286
- firstDiff = i;
287
- diffCount++;
288
- }
289
- }
290
- if (diffCount === 1)
291
- return true;
292
- return diffCount === 2
293
- && firstDiff + 1 < a.length
294
- && a[firstDiff] === b[firstDiff + 1]
295
- && a[firstDiff + 1] === b[firstDiff];
296
- }
297
- const shorter = a.length < b.length ? a : b;
298
- const longer = a.length < b.length ? b : a;
299
- let i = 0;
300
- let j = 0;
301
- let edits = 0;
302
- while (i < shorter.length && j < longer.length) {
303
- if (shorter[i] === longer[j]) {
304
- i++;
305
- j++;
306
- }
307
- else {
308
- edits++;
309
- if (edits > 1)
310
- return false;
311
- j++;
312
- }
313
- }
314
- return true;
315
- }
316
- function nearNameMatch(query, name) {
317
- const queryParts = normalizeName(query).split(/\s+/).filter(Boolean);
318
- const nameParts = normalizeName(name).split(/\s+/).filter(Boolean);
319
- if (queryParts.length !== nameParts.length)
320
- return false;
321
- return queryParts.every((part, i) => {
322
- const target = nameParts[i];
323
- if (part === target)
324
- return true;
325
- if (part.length < 5 || target.length < 5)
326
- return false;
327
- return damerauLevenshteinAtMostOne(part, target);
328
- });
329
- }
330
- function scoreEntryDetailed(entry, text, opts = {}) {
331
- const tokens = tokenize(text);
332
- // Field substring matching uses the stopword-stripped CONTENT phrase, not the
333
- // raw query (#1581). Without this, a query that reduces to a single content
334
- // token — e.g. "intake skill" or "find an intake skill" → ["intake"] — sets
335
- // useMultiToken=false (1 token) and then fails the full-string `.includes()`
336
- // checks because the raw phrase ("intake skill") isn't a substring of any
337
- // field, while the one meaningful token is never matched. Joining the content
338
- // tokens restores the invariant that a single content token IS the phrase, and
339
- // for multi-token queries gives a tighter (content-only) phrase to match.
340
- // Pure-stopword queries fall back to the raw text.
341
- const lower = tokens.length > 0 ? tokens.join(' ') : text.toLowerCase().trim();
342
- const rawLower = text.toLowerCase().trim();
343
- const personaIdentitySuppressed = diagnoseFacetActivations(text).some((activation) => activation.facet === 'persona-identity' && activation.status === 'suppressed');
344
- let score = 0;
345
- const matches = [];
346
- const creditedTokens = new Set();
347
- const finish = (uncappedScore = score, cap = 1) => ({
348
- score: Math.min(uncappedScore, cap),
349
- diagnostic: {
350
- content_tokens: tokens,
351
- raw_score: uncappedScore,
352
- score: Math.min(uncappedScore, cap),
353
- score_cap_applied: uncappedScore > cap,
354
- matches,
355
- },
356
- });
357
- const addMatch = (contribution, match) => {
358
- score += contribution;
359
- matches.push({ ...match, contribution });
360
- };
361
- const addTokenMatch = (contributionPerToken, hits, match) => {
362
- const newlyMatched = hits.filter(token => !creditedTokens.has(token));
363
- if (newlyMatched.length === 0)
364
- return;
365
- newlyMatched.forEach(token => creditedTokens.add(token));
366
- addMatch(contributionPerToken * newlyMatched.length, {
367
- ...match,
368
- matched_tokens: newlyMatched,
369
- query_token_coverage: tokens.length > 0 ? newlyMatched.length / tokens.length : 0,
370
- });
371
- };
372
- // Exact-name floor (#1233) — if the query (normalized) exactly matches
373
- // the entry's canonical name, this is the artifact the user is asking
374
- // for and it must surface at the top regardless of how cluttered the
375
- // rest of the corpus scoring gets. Hyphens, underscores, and whitespace
376
- // are interchangeable in the comparison so `aiwg-doctor`, `aiwg doctor`,
377
- // and `aiwg_doctor` all match a kernel skill with `name: aiwg-doctor`.
378
- //
379
- // Returns 1.001 (not 1.0) so an exact-name hit sorts above the many
380
- // capped-at-1.0 substring matches that share generic words like "use".
381
- // Display rounding (Math.round(score * 100) / 100) hides the offset, so
382
- // the user still sees `score: 1.0` while sort order is preserved.
383
- if (entry.name) {
384
- const queryNorm = normalizeName(text);
385
- const nameNorm = normalizeName(entry.name);
386
- if (queryNorm === nameNorm) {
387
- matches.push({
388
- field: 'name',
389
- match: 'exact',
390
- value: entry.name,
391
- contribution: 1.001,
392
- matched_tokens: tokens,
393
- query_token_coverage: 1,
394
- });
395
- return finish(1.001, 1.001);
396
- }
397
- if (nearNameMatch(text, entry.name)) {
398
- matches.push({
399
- field: 'name',
400
- match: 'near-name',
401
- value: entry.name,
402
- contribution: 0.951,
403
- matched_tokens: tokens,
404
- query_token_coverage: 1,
405
- });
406
- return finish(0.951);
407
- }
408
- }
409
- // Searchable text — joined once so per-token includes() is cheap
410
- const titleLower = entry.title.toLowerCase();
411
- const summaryLower = entry.summary.toLowerCase();
412
- const pathLower = entry.path.toLowerCase();
413
- const typeLower = entry.type.toLowerCase();
414
- const capabilityLower = entry.capability ? entry.capability.toLowerCase() : '';
415
- const tagsLower = entry.tags.map(t => t.toLowerCase());
416
- const triggersLower = (entry.triggers ?? []).map(trigger => trigger.toLowerCase());
417
- const searchTermsLower = (entry.searchTerms ?? []).join(' ').toLowerCase();
418
- const kindLower = entry.kind?.toLowerCase() ?? '';
419
- const sourceTypeLower = entry.sourceType?.toLowerCase() ?? '';
420
- // For multi-token queries, require ≥50% token overlap to count
421
- // partial matches. This keeps gibberish queries (e.g.,
422
- // `xyzzy_zzqwkjhg_42` after splitting on `_`) from surfacing
423
- // incidental single-token hits.
424
- const useMultiToken = tokens.length > 1;
425
- // #1561 — verbose natural-language queries (e.g. "skill that handles intake
426
- // forms") dilute the token hit ratio below the ceil(n/2) overlap gate and
427
- // dead-end to zero results. When the strict pass finds nothing, callers
428
- // re-score with `relaxOverlap` so a single meaningful token hit (intake /
429
- // forms) still surfaces ranked candidates instead of an empty set.
430
- const minHits = useMultiToken
431
- ? (opts.relaxOverlap ? 1 : Math.ceil(tokens.length / 2))
432
- : 1;
433
- const overlapOK = (hits) => useMultiToken && hits >= minHits;
434
- // Trigger phrase match — highest weight (4x). Exact match on the full
435
- // phrase wins big; substring or token-overlap is still strong.
436
- if (triggersLower.length > 0) {
437
- for (const trigger of triggersLower) {
438
- const triggerTokens = tokenize(trigger);
439
- const matchedTokens = tokens.filter((token) => triggerTokens.includes(token));
440
- const queryCoverage = tokens.length > 0 ? matchedTokens.length / tokens.length : 0;
441
- if (trigger === lower || trigger === rawLower) {
442
- matches.push({
443
- field: 'trigger',
444
- match: 'exact',
445
- value: trigger,
446
- contribution: 1.0008,
447
- matched_tokens: matchedTokens,
448
- query_token_coverage: 1,
449
- });
450
- return finish(1.0008, 1.0008);
451
- }
452
- else if (containsTokenSequence(triggerTokens, tokens) ||
453
- containsTokenSequence(tokens, triggerTokens)) {
454
- const triggerInsideQuery = containsTokenSequence(tokens, triggerTokens);
455
- const containedCoverage = triggerInsideQuery
456
- ? queryCoverage
457
- : triggerTokens.length > 0
458
- ? matchedTokens.length / triggerTokens.length
459
- : 0;
460
- // A complete multi-word trigger inside a noisier query is a strong
461
- // metadata signal. The ambiguous one-word `persona` trigger is
462
- // downweighted only when the facet classifier has identified buyer /
463
- // audience marketing context; distinctive one-word triggers such as
464
- // GRADE retain their established exact-trigger behavior (#1828).
465
- const suppressedGenericPersona = personaIdentitySuppressed &&
466
- triggerTokens.length === 1 &&
467
- triggerTokens[0] === 'persona' &&
468
- tokens.length > 1;
469
- const contribution = suppressedGenericPersona
470
- ? 0.24 * queryCoverage
471
- : triggerTokens.length > 1
472
- ? Math.min(1, 0.75 + 0.25 * containedCoverage)
473
- : 1;
474
- addMatch(contribution, {
475
- field: 'trigger',
476
- match: 'contained-phrase',
477
- value: trigger,
478
- matched_tokens: matchedTokens,
479
- query_token_coverage: queryCoverage,
480
- });
481
- }
482
- else if (useMultiToken) {
483
- const hits = matchedFieldTokens(tokens, trigger);
484
- if (overlapOK(hits.length)) {
485
- addTokenMatch(0.1 * 4, hits, {
486
- field: 'trigger',
487
- match: 'token-overlap',
488
- value: trigger,
489
- });
490
- }
491
- }
492
- }
493
- }
494
- // Capability description (2x weight) — full phrase first, then tokens
495
- if (capabilityLower) {
496
- if (fieldContainsQuery(capabilityLower, tokens)) {
497
- addMatch(0.2 * 2, {
498
- field: 'capability',
499
- match: 'contained-phrase',
500
- value: entry.capability,
501
- });
502
- }
503
- else if (useMultiToken) {
504
- const hits = matchedFieldTokens(tokens, capabilityLower);
505
- if (overlapOK(hits.length)) {
506
- addTokenMatch(0.1 * 2, hits, {
507
- field: 'capability',
508
- match: 'token-overlap',
509
- value: entry.capability,
510
- });
511
- }
512
- }
513
- }
514
- // Title (3x weight)
515
- if (fieldContainsQuery(titleLower, tokens)) {
516
- addMatch(0.3 * 3, {
517
- field: 'title',
518
- match: titleLower === lower ? 'exact' : 'contained-phrase',
519
- value: entry.title,
520
- });
521
- if (titleLower === lower) {
522
- addMatch(0.2, { field: 'title', match: 'exact', value: entry.title });
523
- }
524
- }
525
- else if (useMultiToken) {
526
- const hits = matchedFieldTokens(tokens, titleLower);
527
- if (overlapOK(hits.length)) {
528
- addTokenMatch(0.08 * 3, hits, {
529
- field: 'title',
530
- match: 'token-overlap',
531
- value: entry.title,
532
- });
533
- }
534
- }
535
- // Tags (2x weight)
536
- for (const tag of tagsLower) {
537
- if (fieldContainsQuery(tag, tokens)) {
538
- addMatch(0.2 * 2, { field: 'tag', match: 'contained-phrase', value: tag });
539
- }
540
- else if (useMultiToken) {
541
- const hits = matchedFieldTokens(tokens, tag);
542
- if (overlapOK(hits.length)) {
543
- addTokenMatch(0.05 * 2, hits, {
544
- field: 'tag',
545
- match: 'token-overlap',
546
- value: tag,
547
- });
548
- }
549
- }
550
- }
551
- // Structure-aware language terms (1.5x weight). These are deliberately
552
- // below declared triggers/capabilities but above generic body summaries.
553
- if (fieldContainsQuery(searchTermsLower, tokens)) {
554
- addMatch(0.18 * 1.5, { field: 'search_terms', match: 'contained-phrase' });
555
- }
556
- else if (useMultiToken) {
557
- const hits = matchedFieldTokens(tokens, searchTermsLower);
558
- if (overlapOK(hits.length)) {
559
- addTokenMatch(0.06 * 1.5, hits, {
560
- field: 'search_terms',
561
- match: 'token-overlap',
562
- });
563
- }
564
- }
565
- // Exact declarative kind and physical source classification are compact,
566
- // useful routing signals (e.g. FlowPlaybook vs OpsInventory; runbook that
567
- // originated under templates/).
568
- if (fieldContainsQuery(kindLower, tokens)) {
569
- addMatch(0.15, { field: 'kind', match: 'contained-phrase', value: entry.kind });
570
- }
571
- if (fieldContainsQuery(sourceTypeLower, tokens)) {
572
- addMatch(0.08, { field: 'source_type', match: 'contained-phrase', value: entry.sourceType });
573
- }
574
- // Summary (1x weight)
575
- if (fieldContainsQuery(summaryLower, tokens)) {
576
- addMatch(0.15, { field: 'summary', match: 'contained-phrase' });
577
- }
578
- else if (useMultiToken) {
579
- const hits = matchedFieldTokens(tokens, summaryLower);
580
- if (overlapOK(hits.length)) {
581
- addTokenMatch(0.04, hits, {
582
- field: 'summary',
583
- match: 'token-overlap',
584
- });
585
- }
586
- }
587
- // Path (0.5x weight)
588
- if (fieldContainsQuery(pathLower, tokens)) {
589
- addMatch(0.1, { field: 'path', match: 'contained-phrase', value: entry.path });
590
- }
591
- else if (useMultiToken) {
592
- const hits = matchedFieldTokens(tokens, pathLower);
593
- if (overlapOK(hits.length)) {
594
- addTokenMatch(0.03, hits, {
595
- field: 'path',
596
- match: 'token-overlap',
597
- value: entry.path,
598
- });
599
- }
600
- }
601
- // Type (0.5x weight)
602
- if (fieldContainsQuery(typeLower, tokens)) {
603
- addMatch(0.1, { field: 'type', match: 'contained-phrase', value: entry.type });
604
- }
605
- return finish();
606
- }
607
- function scoreEntry(entry, text, opts = {}) {
608
- return scoreEntryDetailed(entry, text, opts).score;
609
- }
610
- /**
611
- * Query the artifact index
612
- */
613
- export async function queryIndex(cwd, params, options = {}) {
614
- const { graph } = options;
615
- const backend = options.backend ?? DEFAULT_ARTIFACT_SEARCH_BACKEND;
616
- const startTime = Date.now();
617
- let candidates;
618
- if (backend === 'fortemi-core') {
619
- const { loadFortemiCoreMetadataEntries } = await import('./fortemi-core-query-adapter.js');
620
- const loaded = loadFortemiCoreMetadataEntries(cwd, graph ?? 'project');
621
- if (loaded.reason) {
622
- if (options.json) {
623
- console.log(JSON.stringify({
624
- query: { text: params.text, backend: 'fortemi-core', graph: graph ?? 'project' },
625
- results: [],
626
- total: 0,
627
- hint: loaded.reason ?? 'Fortemi Core static index is unavailable.',
628
- }, null, 2));
629
- }
630
- else {
631
- console.error('Error: ' + (loaded.reason ?? 'Fortemi Core static index is unavailable.'));
632
- }
633
- process.exit(1);
634
- }
635
- candidates = loaded.entries;
636
- }
637
- else if (graph) {
638
- // Single graph mode
639
- const index = loadGraphIndexFile(cwd, 'metadata.json', graph);
640
- if (!index) {
641
- console.error(`Error: No artifact index found for graph '${graph}'.`);
642
- console.log("Run 'aiwg index build' first to create the index.");
643
- process.exit(1);
644
- }
645
- candidates = Object.values(index.entries);
646
- }
647
- else {
648
- // No graph specified: search across all project-local graphs
649
- const graphTypes = ['project', 'codebase'];
650
- const allEntries = [];
651
- for (const g of graphTypes) {
652
- const idx = loadGraphIndexFile(cwd, 'metadata.json', g);
653
- if (idx)
654
- allEntries.push(...Object.values(idx.entries));
655
- }
656
- // Fall back to legacy root index
657
- if (allEntries.length === 0) {
658
- const legacy = loadMetadataIndex(cwd);
659
- if (!legacy) {
660
- console.error('Error: No artifact index found.');
661
- console.log("Run 'aiwg index build' first to create the index.");
662
- process.exit(1);
663
- }
664
- allEntries.push(...Object.values(legacy.entries));
665
- }
666
- candidates = allEntries;
667
- }
668
- // Retained tombstones are history, never ordinary retrieval results.
669
- candidates = candidates.filter(entry => isOrdinaryMemoryEntry(entry, cwd));
670
- // Apply filters
671
- if (params.type) {
672
- candidates = candidates.filter(e => e.type === params.type);
673
- }
674
- if (params.phase) {
675
- candidates = candidates.filter(e => e.phase === params.phase);
676
- }
677
- if (params.tags && params.tags.length > 0) {
678
- candidates = candidates.filter(e => params.tags.every(tag => e.tags.includes(tag)));
679
- }
680
- if (params.path) {
681
- candidates = candidates.filter(e => minimatch(e.path, params.path));
682
- }
683
- if (params.updatedAfter) {
684
- const cutoff = new Date(params.updatedAfter).getTime();
685
- candidates = candidates.filter(e => new Date(e.updated).getTime() >= cutoff);
686
- }
687
- // Score and rank
688
- let results;
689
- const matchedById = new Map();
690
- const operationalStateById = new Map();
691
- if (params.text && params.fulltext && backend === 'fortemi-core') {
692
- const { queryFortemiCoreStaticFulltextIndex } = await import('./fortemi-core-query-adapter.js');
693
- const queried = queryFortemiCoreStaticFulltextIndex(cwd, {
694
- graph: graph ?? 'project',
695
- text: params.text,
696
- limit: params.limit ?? 20,
697
- path: params.path,
698
- type: params.type,
699
- phase: params.phase,
700
- tags: params.tags,
701
- });
702
- if (queried.reason) {
703
- if (options.json) {
704
- console.log(JSON.stringify({
705
- query: { text: params.text, backend: 'fortemi-core', graph: graph ?? 'project' },
706
- mode: 'fulltext',
707
- results: [],
708
- total: 0,
709
- hint: queried.reason,
710
- }, null, 2));
711
- }
712
- else {
713
- console.error('Error: ' + queried.reason);
714
- }
715
- process.exit(1);
716
- }
717
- const candidateByPath = new Map(candidates.map(entry => [entry.path, entry]));
718
- results = queried.results.filter(result => candidateByPath.has(result.path)).map(result => {
719
- const entry = {
720
- ...(candidateByPath.get(result.path)?.memoryRecord ? { memoryRecord: candidateByPath.get(result.path).memoryRecord } : {}),
721
- path: result.path,
722
- type: result.type,
723
- phase: result.phase,
724
- title: result.title,
725
- tags: result.tags,
726
- created: '',
727
- updated: '',
728
- checksum: '',
729
- summary: result.summary,
730
- dependencies: [],
731
- dependents: [],
732
- };
733
- matchedById.set(result.path, result.matched);
734
- if (result.operational_state) {
735
- operationalStateById.set(result.path, result.operational_state);
736
- }
737
- return { entry, score: result.score };
738
- });
739
- }
740
- else if (params.text && params.fulltext) {
741
- // Lexical full-text (#1494): read candidate bodies and BM25-rank. The
742
- // index is the candidate set; ranking is over actual body content, not
743
- // the metadata/summary the default path scores.
744
- const byPath = new Map();
745
- const docs = [];
746
- for (const entry of candidates) {
747
- const body = readEntryBody(cwd, entry.path);
748
- if (body === null)
749
- continue;
750
- byPath.set(entry.path, entry);
751
- docs.push({ id: entry.path, text: body });
752
- }
753
- const hits = bm25Rank(docs, params.text);
754
- results = hits
755
- .map(h => {
756
- matchedById.set(h.id, h.matchedTerms);
757
- return { entry: byPath.get(h.id), score: h.score };
758
- })
759
- .filter(r => r.entry);
760
- }
761
- else if (params.text) {
762
- results = candidates
763
- .map(entry => ({ entry, score: scoreEntry(entry, params.text) }))
764
- .filter(r => r.score > 0)
765
- .sort(compareDiscoverResults);
766
- }
767
- else {
768
- // No keyword — return all filtered results with score 1.0
769
- results = candidates.map(entry => ({ entry, score: 1.0 }));
770
- }
771
- // Apply limit
772
- const limit = params.limit ?? 20;
773
- results = results.filter(result => isOrdinaryMemoryEntry(result.entry, cwd)).slice(0, limit);
774
- const queryTimeMs = Date.now() - startTime;
775
- // Output
776
- if (options.json) {
777
- console.log(JSON.stringify({
778
- query: { text: params.text, filters: { type: params.type, phase: params.phase, tags: params.tags, path: params.path }, backend },
779
- mode: params.fulltext ? 'fulltext' : 'metadata',
780
- results: results.map(r => ({
781
- path: r.entry.path,
782
- type: r.entry.type,
783
- phase: r.entry.phase,
784
- title: r.entry.title,
785
- score: Math.round(r.score * 100) / 100,
786
- summary: r.entry.summary,
787
- ...(operationalStateById.has(r.entry.path)
788
- ? { operational_state: operationalStateById.get(r.entry.path) }
789
- : r.entry.operationalState
790
- ? { operational_state: operationalStateQueryProjection(r.entry.operationalState) }
791
- : {}),
792
- ...(params.fulltext ? { matched: matchedById.get(r.entry.path) ?? [] } : {}),
793
- })),
794
- total: results.length,
795
- query_time_ms: queryTimeMs,
796
- }, null, 2));
797
- }
798
- else {
799
- const queryDesc = params.text ? `"${params.text}"` : 'all';
800
- console.log(`Results for ${queryDesc} (${results.length} matches, ${queryTimeMs}ms):`);
801
- console.log('');
802
- console.log(' # Score Type Phase Path');
803
- for (let i = 0; i < results.length; i++) {
804
- const r = results[i];
805
- const num = String(i + 1).padStart(3);
806
- const score = r.score.toFixed(2).padStart(4);
807
- const type = r.entry.type.padEnd(12).slice(0, 12);
808
- const phase = r.entry.phase.padEnd(14).slice(0, 14);
809
- console.log(` ${num} ${score} ${type} ${phase} ${r.entry.path}`);
810
- }
811
- if (results.length === 0) {
812
- console.log(' No results found.');
813
- }
814
- console.log('');
815
- }
816
- }
817
- const DEFAULT_DISCOVER_TYPES = [...OPERATIONAL_DISCOVERY_TYPES];
818
- const DEFAULT_CAPABILITY_GRAPHS = ['project', 'user', 'framework'];
819
- function projectAllowsUserIndices(cwd) {
820
- try {
821
- const configPath = projectControlPath(cwd, 'aiwg.config');
822
- if (!fs.existsSync(configPath))
823
- return true;
824
- const parsed = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
825
- const index = parsed.index;
826
- const userIndices = index?.userIndices;
827
- if (userIndices?.enabled === false)
828
- return false;
829
- const indices = parsed.indices;
830
- const user = indices?.user;
831
- if (user?.enabled === false)
832
- return false;
833
- }
834
- catch {
835
- return true;
836
- }
837
- return true;
838
- }
839
- function defaultCapabilityGraphs(cwd) {
840
- if (projectAllowsUserIndices(cwd))
841
- return DEFAULT_CAPABILITY_GRAPHS;
842
- return DEFAULT_CAPABILITY_GRAPHS.filter((graph) => graph !== 'user' && !graph.startsWith('user-'));
843
- }
844
- /**
845
- * Resolve the AIWG installation root for path-anchoring discover output.
846
- * Discover returns paths anchored to AIWG_ROOT so the agent's `Read`
847
- * tool can resolve them from any project working directory (#1217).
848
- */
849
- /**
850
- * Build the `run_hint` string for a script-bearing skill entry (#1227).
851
- *
852
- * Format: `aiwg run skill <name> [-- <argsHint>]`. The skill name is the
853
- * basename of its source directory (skills/<name>/SKILL.md), which is
854
- * what `aiwg run skill` accepts.
855
- */
856
- function buildRunHint(entry) {
857
- // Use the directory basename for slug-layout skills, filename stem otherwise.
858
- const lastSlash = entry.path.lastIndexOf('/');
859
- const tail = lastSlash >= 0 ? entry.path.slice(lastSlash + 1) : entry.path;
860
- let name;
861
- if (tail === 'SKILL.md' && lastSlash >= 0) {
862
- const dir = entry.path.slice(0, lastSlash);
863
- const dirSlash = dir.lastIndexOf('/');
864
- name = dirSlash >= 0 ? dir.slice(dirSlash + 1) : dir;
865
- }
866
- else {
867
- name = tail.replace(/\.[^.]+$/, '');
868
- }
869
- const argsHint = entry.script?.argsHint ? ` -- ${entry.script.argsHint}` : '';
870
- return `aiwg run skill ${name}${argsHint}`;
871
- }
872
- function showHintForDiscoverResult(entry, id) {
873
- if (isOperationalShowType(entry.type)) {
874
- return `aiwg show ${entry.type} ${id}`;
875
- }
876
- return `aiwg show ${id}`;
877
- }
878
- export async function discoverCapability(cwd, params) {
879
- loadGlobalGraphConfigs();
880
- const startTime = Date.now();
881
- const types = params.typeFilter && params.typeFilter.length > 0
882
- ? params.typeFilter
883
- : DEFAULT_DISCOVER_TYPES;
884
- // Default top-K = 5 (Wave A from #1218): peer-reviewed work on tool
885
- // retrieval (Semantic Tool Discovery for MCP, arXiv:2603.20313) reports
886
- // 97.1% hit@K=3 at scale; K=5 keeps a buffer above K=3 while halving
887
- // the prior K=10 default. Operators wanting more breadth can pass
888
- // `--limit N` explicitly.
889
- const limit = params.limit ?? 5;
890
- // For framework-graph entries, anchor returned paths to AIWG_ROOT so
891
- // they resolve from any project working directory (#1217).
892
- const aiwgRoot = resolveFrameworkIndexRoot(cwd);
893
- // Source: prefer `framework` graph (built post-deploy), fall back to
894
- // project / codebase / legacy depending on what's available.
895
- let entries = [];
896
- const backend = params.backend ?? DEFAULT_ARTIFACT_SEARCH_BACKEND;
897
- let fortemiCoreDiscoveryScores = null;
898
- let resourceSource = params.resourceSource ?? 'local';
899
- let resolvedWebRelease;
900
- let verifiedSourcePaths;
901
- const prebuiltRelations = resourceSource !== 'web' && (!params.graph || params.graph === 'framework')
902
- ? selectPrebuiltRelations(cwd).reader : null;
903
- if ((!prebuiltRelations || backend === 'local') && resourceSource !== 'web' && (!params.graph || params.graph === 'framework')) {
904
- const root = resolveFrameworkCorpusRoot(cwd) ?? aiwgRoot;
905
- if (root) {
906
- try {
907
- await refreshFrameworkCapabilities(root, backend === 'fortemi-core');
908
- }
909
- catch (error) {
910
- console.error(`Warning: capability index refresh failed: ${error instanceof Error ? error.message : String(error)}`);
911
- }
912
- }
913
- }
914
- if (resourceSource === 'auto') {
915
- const { loadFortemiCoreMetadataEntries } = await import('./fortemi-core-query-adapter.js');
916
- const localGraphs = params.graph ? [params.graph] : defaultCapabilityGraphs(cwd);
917
- const localAvailable = localGraphs.some((graph) => loadFortemiCoreMetadataEntries(cwd, graph).entries.length > 0
918
- || Object.keys(loadGraphIndexFile(cwd, 'metadata.json', graph)?.entries ?? {}).length > 0);
919
- resourceSource = localAvailable ? 'local' : 'web';
920
- }
921
- if (resourceSource === 'web') {
922
- if (backend !== 'fortemi-core') {
923
- console.error('Error: --resource-source web requires the Fortemi Core query backend; --backend local remains available with local resources.');
924
- process.exit(1);
925
- }
926
- if (params.graph && params.graph !== 'framework') {
927
- console.error("Error: web-backed capability discovery currently supports only the 'framework' graph.");
928
- process.exit(1);
929
- }
930
- try {
931
- const { resolveWebRelease } = await import('../resources/web-release.js');
932
- const release = await resolveWebRelease({
933
- ...params.webReleaseOptions,
934
- selector: params.aiwgVersion ?? 'stable',
935
- offline: params.offline,
936
- });
937
- resolvedWebRelease = release;
938
- verifiedSourcePaths = {
939
- manifestPath: release.fortemiManifestPath,
940
- exportPath: release.fortemiExportPath,
941
- manifestSha256: release.fortemiManifestSha256,
942
- manifestSize: release.fortemiManifestSize,
943
- exportSha256: release.fortemiExportSha256,
944
- exportSize: release.fortemiExportSize,
945
- };
946
- }
947
- catch (error) {
948
- console.error(`Error: AIWG web resource resolution failed: ${error instanceof Error ? error.message : String(error)}`);
949
- process.exit(1);
950
- }
951
- }
952
- if (backend === 'fortemi-core') {
953
- const graphs = resourceSource === 'web'
954
- ? ['framework']
955
- : params.graph ? [params.graph] : defaultCapabilityGraphs(cwd);
956
- const { loadFortemiCoreMetadataEntries, queryFortemiCoreAiwgDiscovery, } = await import('./fortemi-core-query-adapter.js');
957
- let unavailableReason;
958
- for (const graph of graphs) {
959
- const loaded = loadFortemiCoreMetadataEntries(cwd, graph, verifiedSourcePaths);
960
- if (loaded.reason && graph === 'project' && !params.graph) {
961
- const fallback = projectCapabilityFallback(cwd);
962
- if (fallback) {
963
- entries.push(...fallback);
964
- continue;
965
- }
966
- }
967
- if (loaded.sourceIndexNewer && resourceSource === 'local') {
968
- // Do not silently omit a graph whose derived cache is stale. Rank its
969
- // current source metadata, without consulting scores from the old cache.
970
- const index = loadGraphIndexFile(cwd, 'metadata.json', graph);
971
- if (index) {
972
- console.error(`Warning: ${graph} capability cache is unavailable or stale; using the local ${graph} index. ${loaded.reason}`);
973
- entries.push(...Object.values(index.entries).map((entry) => withIndexProvenance(entry, graph)));
974
- continue;
975
- }
976
- }
977
- if (loaded.reason) {
978
- unavailableReason ??= loaded.reason;
979
- if (graph === 'framework' && !params.graph) {
980
- console.error(`Warning: framework capabilities are unavailable: ${loaded.reason}`);
981
- }
982
- }
983
- entries.push(...loaded.entries.map((entry) => withIndexProvenance(entry, graph)));
984
- const discovered = await queryFortemiCoreAiwgDiscovery(cwd, {
985
- graph,
986
- text: params.phrase,
987
- limit: Math.max(limit * 10, 50),
988
- types,
989
- sourcePaths: verifiedSourcePaths,
990
- });
991
- if (!discovered.reason) {
992
- fortemiCoreDiscoveryScores ??= new Map();
993
- for (const result of discovered.results) {
994
- if (result.score <= 0)
995
- continue;
996
- fortemiCoreDiscoveryScores.set(result.entry.path, Math.max(fortemiCoreDiscoveryScores.get(result.entry.path) ?? 0, result.score));
997
- }
998
- }
999
- }
1000
- if (entries.length === 0 && unavailableReason) {
1001
- if (params.json) {
1002
- console.log(JSON.stringify({
1003
- query: {
1004
- phrase: params.phrase,
1005
- types,
1006
- limit,
1007
- backend: 'fortemi-core',
1008
- graph: resourceSource === 'web' ? 'framework' : params.graph ?? 'capability-default',
1009
- ...(resourceSource === 'web'
1010
- ? {
1011
- resource_source: 'web',
1012
- aiwg_selector: resolvedWebRelease?.selector,
1013
- aiwg_version: resolvedWebRelease?.version,
1014
- manifest_sha256: resolvedWebRelease?.manifestDigest,
1015
- manifest_url: resolvedWebRelease?.manifestUrl,
1016
- }
1017
- : {}),
1018
- },
1019
- results: [],
1020
- rule_stats: emptyRuleStats(),
1021
- total: 0,
1022
- hint: unavailableReason,
1023
- }, null, 2));
1024
- }
1025
- else {
1026
- console.error('Error: ' + unavailableReason);
1027
- }
1028
- process.exit(1);
1029
- }
1030
- }
1031
- else if (params.graph) {
1032
- const idx = loadGraphIndexFile(cwd, 'metadata.json', params.graph);
1033
- if (idx)
1034
- entries = Object.values(idx.entries).map((entry) => withIndexProvenance(entry, params.graph));
1035
- }
1036
- else {
1037
- // discover is EXCLUSIVELY the agentic-capability surface (#1545): source
1038
- // the `framework` graph (deployed AIWG capabilities) + project-local
1039
- // capability artifacts. NEVER `codebase` — source code is not a capability
1040
- // surface. The framework
1041
- // index is reconciled with its source above, including existing indexes
1042
- // left behind by an older runtime or a different checkout.
1043
- const fwIdx = loadGraphIndexFile(cwd, 'metadata.json', 'framework');
1044
- const includeUser = projectAllowsUserIndices(cwd);
1045
- // Project-local operational artifacts authored in this project. The
1046
- // DEFAULT_DISCOVER_TYPES filter keeps non-capability project artifacts
1047
- // (requirements, ADRs, …) out of results.
1048
- const projIdx = loadGraphIndexFile(cwd, 'metadata.json', 'project');
1049
- if (projIdx)
1050
- entries.push(...Object.values(projIdx.entries).map((entry) => withIndexProvenance(entry, 'project')));
1051
- if (includeUser) {
1052
- const userIdx = loadGraphIndexFile(cwd, 'metadata.json', 'user');
1053
- if (userIdx)
1054
- entries.push(...Object.values(userIdx.entries).map((entry) => withIndexProvenance(entry, 'user')));
1055
- }
1056
- if (fwIdx)
1057
- entries.push(...Object.values(fwIdx.entries).map((entry) => withIndexProvenance(entry, 'framework')));
1058
- if (entries.length === 0) {
1059
- const legacy = loadMetadataIndex(cwd);
1060
- if (legacy)
1061
- entries.push(...Object.values(legacy.entries));
1062
- }
1063
- }
1064
- if (entries.length === 0 && backend !== 'fortemi-core') {
1065
- // Empty-index case (#1221). Surface a hint that explains the gap rather
1066
- // than returning a bare zero-result envelope — the latter trains agents
1067
- // to conclude "AIWG doesn't have a skill for that" when in fact the
1068
- // index simply hasn't been built in this workspace yet.
1069
- const hint = 'No artifact index found. Run `aiwg index build --graph framework` (or `aiwg use <framework>`) first.';
1070
- if (params.json) {
1071
- console.log(JSON.stringify({
1072
- query: { phrase: params.phrase, types },
1073
- results: [],
1074
- rule_stats: emptyRuleStats(),
1075
- total: 0,
1076
- hint,
1077
- }, null, 2));
1078
- }
1079
- else {
1080
- console.error('Error: No artifact index found.');
1081
- console.log('Run `aiwg index build --graph framework` (or `aiwg use <framework>`) first.');
1082
- }
1083
- process.exit(1);
1084
- }
1085
- // Filter by type
1086
- entries = entries.filter(entry => isOrdinaryMemoryEntry(entry, cwd));
1087
- const candidates = entries.filter(e => types.includes(e.type));
1088
- // Score (strict overlap gate). Keep the full sorted list so the facet
1089
- // fusion below can inject/lift curated capabilities into the top-K before
1090
- // truncation — a capability that the lexical pass ranked outside `limit`
1091
- // (or missed entirely) still surfaces when the query activates its facet.
1092
- const lexicalDiagnostics = new Map();
1093
- const legacyStrictScored = candidates
1094
- .map(entry => {
1095
- const detailed = scoreEntryDetailed(entry, params.phrase);
1096
- const legacyScore = detailed.score;
1097
- const fortemiScore = fortemiCoreDiscoveryScores?.get(entry.path) ?? 0;
1098
- lexicalDiagnostics.set(entry.path, detailed.diagnostic);
1099
- return {
1100
- entry,
1101
- score: legacyScore > 0 ? legacyScore : fortemiScore * 0.2,
1102
- legacyScore,
1103
- };
1104
- })
1105
- .filter(r => r.score > 0)
1106
- .sort(compareDiscoverResults);
1107
- const strictScored = (legacyStrictScored.some(result => result.legacyScore > 0)
1108
- ? legacyStrictScored.filter(result => result.legacyScore > 0)
1109
- : legacyStrictScored).map(({ entry, score }) => ({ entry, score }));
1110
- // Single-pass facet fusion (#1623 U3): fuse the curated feature→capability
1111
- // facets (expansion / persona / project / provider-capability) into the
1112
- // lexical ranking so canonical domain phrases rank their owning capability
1113
- // top-K instead of being out-scored by artifacts that merely mention the
1114
- // word. Facet activation can also rescue an otherwise-empty strict pass.
1115
- // #154 — a strict result anywhere in the corpus must not suppress relevant
1116
- // partial matches for a natural-language query. Score the relaxed pass on
1117
- // matched terms (unmatched terms do not divide the score), apply a noise
1118
- // floor, and union it with strict matches before ranking. Word-boundary
1119
- // token matching keeps this from resurrecting substring noise such as UX in
1120
- // Linux.
1121
- const RELAXED_MIN_SCORE = 0.02;
1122
- const strictPaths = new Set(strictScored.map(result => result.entry.path));
1123
- const combinedByPath = new Map(strictScored.map(result => [result.entry.path, result]));
1124
- for (const entry of candidates) {
1125
- const detailed = scoreEntryDetailed(entry, params.phrase, { relaxOverlap: true });
1126
- if (detailed.score < RELAXED_MIN_SCORE)
1127
- continue;
1128
- const existing = combinedByPath.get(entry.path);
1129
- if (!existing || detailed.score > existing.score) {
1130
- combinedByPath.set(entry.path, { entry, score: detailed.score });
1131
- lexicalDiagnostics.set(entry.path, detailed.diagnostic);
1132
- }
1133
- }
1134
- const scored = dedupeDiscoverResults(await applyFacetFusion(Array.from(combinedByPath.values()).sort(compareDiscoverResults), candidates, params.phrase)).slice(0, limit);
1135
- const relaxed = scored.some(result => !strictPaths.has(result.entry.path));
1136
- if (params.shadowRoute) {
1137
- try {
1138
- await params.shadowRoute.observe(params.phrase, scored.map(result => ({
1139
- id: discoveryIdForEntry(result.entry), name: result.entry.name ?? result.entry.title,
1140
- type: result.entry.type, capability: result.entry.capability ?? result.entry.summary,
1141
- score: result.score,
1142
- })));
1143
- }
1144
- catch {
1145
- // An optional observation failure must never replace deterministic discovery.
1146
- params.shadowRoute.disable();
1147
- }
1148
- }
1149
- const queryTimeMs = Date.now() - startTime;
1150
- /**
1151
- * Resolve a stored framework-graph path to an absolute AIWG_ROOT
1152
- * path (#1217). Framework-graph entries are stored as paths relative
1153
- * to the AIWG repo root (e.g. `agentic/code/frameworks/.../SKILL.md`);
1154
- * anchoring them to `AIWG_ROOT` makes them readable from any project
1155
- * working directory.
1156
- *
1157
- * Kernel skills are anchored the same way (#1230) — `aiwg show` reads
1158
- * the source corpus, not platform deploy mirrors, so kernel entries
1159
- * need the same `AIWG_ROOT` anchoring as non-kernel framework entries.
1160
- * Non-framework entries (project / codebase graphs) keep their stored
1161
- * paths unchanged.
1162
- */
1163
- function resolvePath(entry) {
1164
- const normalizedPath = normalizeIndexedPath(entry.path);
1165
- if (!aiwgRoot)
1166
- return normalizedPath;
1167
- if (path.isAbsolute(entry.path))
1168
- return entry.path;
1169
- if (normalizedPath.startsWith('agentic/code/'))
1170
- return path.join(aiwgRoot, normalizedPath);
1171
- return normalizedPath;
1172
- }
1173
- // Build a hint string when the index has entries but no scored matches —
1174
- // this is the second silent-failure mode #1221 calls out. When the workspace
1175
- // has project-local content (.aiwg/{extensions,addons,frameworks,plugins,providers}/)
1176
- // surface a project-graph rebuild hint (#1235).
1177
- // discover-appropriate hint (#1545): never push index/graph mechanics. If
1178
- // nothing scored, the phrase didn't match an indexed capability — suggest a
1179
- // broader phrase / type filter, and a capability refresh via `aiwg use`.
1180
- const emptyResultHint = scored.length === 0
1181
- ? backend === 'fortemi-core'
1182
- ? `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.`
1183
- : `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\`).`
1184
- : null;
1185
- const relations = resourceSource === 'local' && (!params.graph || params.graph === 'framework')
1186
- ? prebuiltRelations ?? await ensureRelations(cwd) : undefined;
1187
- const governing = scored.map(result => compoundGoverningRules(entries, result.entry, relations ?? undefined, params.phrase));
1188
- const responseRules = new Map();
1189
- for (const item of governing.flat()) {
1190
- const key = `${item.rule.type}:${item.rule.path}`, prior = responseRules.get(key);
1191
- responseRules.set(key, { rule: item.rule, applicability: [...new Set([...(prior?.applicability ?? []), ...item.applicability])] });
1192
- }
1193
- const responseFields = governingRuleFields([...responseRules.values()]);
1194
- const responseRuleStats = governingRuleStats([...responseRules.values()]);
1195
- const includePaths = params.includePaths ?? true;
1196
- const facetActivations = diagnoseFacetActivations(params.phrase);
1197
- const roundDiagnostic = (value) => Math.round(value * 1_000_000) / 1_000_000;
1198
- const rankingDiagnostic = (entry, finalScore, facetDiagnostics) => {
1199
- const lexical = lexicalDiagnostics.get(entry.path) ?? {
1200
- content_tokens: tokenize(params.phrase),
1201
- raw_score: 0,
1202
- score: 0,
1203
- score_cap_applied: false,
1204
- matches: [],
1205
- };
1206
- const scope = entry.indexScope ?? 'unknown';
1207
- return {
1208
- lexical_score: roundDiagnostic(lexical.score),
1209
- lexical_raw_score: roundDiagnostic(lexical.raw_score),
1210
- final_score: roundDiagnostic(finalScore),
1211
- score_cap_applied: lexical.score_cap_applied,
1212
- matches: lexical.matches.map((match) => ({
1213
- ...match,
1214
- contribution: roundDiagnostic(match.contribution),
1215
- ...(match.query_token_coverage === undefined
1216
- ? {}
1217
- : { query_token_coverage: roundDiagnostic(match.query_token_coverage) }),
1218
- })),
1219
- facets: (facetDiagnostics ?? []).map((facet) => ({
1220
- ...facet,
1221
- activation_floor: roundDiagnostic(facet.activation_floor),
1222
- base_score: roundDiagnostic(facet.base_score),
1223
- rrf_tiebreak: roundDiagnostic(facet.rrf_tiebreak),
1224
- })),
1225
- tie_breakers: {
1226
- scope,
1227
- scope_rank: scopeRank(entry),
1228
- type_rank: DISCOVER_TYPE_ORDER.get(entry.type) ?? 99,
1229
- },
1230
- };
1231
- };
1232
- const { loadRelations } = await import('./relations.js');
1233
- const ruleRelations = resourceSource === 'local' ? loadRelations(cwd) ?? (aiwgRoot ? loadRelations(aiwgRoot, cwd) : null) : null;
1234
- if (params.json) {
1235
- const jsonIndent = params.jsonPretty === false ? undefined : 2;
1236
- console.log(JSON.stringify({
1237
- query: {
1238
- phrase: params.phrase,
1239
- types,
1240
- limit,
1241
- aiwg_root: aiwgRoot ?? null,
1242
- backend,
1243
- graph: backend === 'fortemi-core'
1244
- ? resourceSource === 'web' ? 'framework' : params.graph ?? 'capability-default'
1245
- : params.graph,
1246
- ...(resourceSource === 'web'
1247
- ? {
1248
- resource_source: 'web',
1249
- aiwg_selector: resolvedWebRelease?.selector,
1250
- aiwg_version: resolvedWebRelease?.version,
1251
- manifest_sha256: resolvedWebRelease?.manifestDigest,
1252
- manifest_url: resolvedWebRelease?.manifestUrl,
1253
- }
1254
- : {}),
1255
- },
1256
- results: scored.map((r, resultIndex) => ({
1257
- id: discoveryIdForEntry(r.entry),
1258
- ...(includePaths ? { path: resolvePath(r.entry) } : {}),
1259
- type: r.entry.type,
1260
- name: r.entry.name,
1261
- title: r.entry.title,
1262
- score: Math.round(r.score * 100) / 100,
1263
- ranking: rankingDiagnostic(r.entry, r.score, r.facetDiagnostics),
1264
- ...governingRuleFields(governing[resultIndex]),
1265
- triggers: r.entry.triggers ?? [],
1266
- capability: r.entry.capability ?? r.entry.summary,
1267
- kernel: r.entry.kernel ?? false,
1268
- ...(['skill', 'agent', 'flow', 'command'].includes(r.entry.type) && ruleRelations
1269
- && ruleRelations.rulesForTarget(r.entry.type, discoveryIdForEntry(r.entry)).length ? {
1270
- startup_rule_stats: ruleRelations.ruleStats(r.entry.type, discoveryIdForEntry(r.entry)),
1271
- } : {}),
1272
- provenance: {
1273
- graph: r.entry.indexGraph ?? null,
1274
- scope: r.entry.indexScope ?? null,
1275
- },
1276
- // #1227 — surface script-bearing skills so agents know to use
1277
- // `aiwg run skill <name>` instead of executing instructions
1278
- // themselves.
1279
- ...(r.entry.script
1280
- ? {
1281
- executable: true,
1282
- run_hint: buildRunHint(r.entry),
1283
- }
1284
- : {}),
1285
- })),
1286
- rule_stats: responseRuleStats,
1287
- ...(responseFields.required_rule_checks ? { required_rule_checks: responseFields.required_rule_checks, rule_check_obligation: RULE_CHECK_OBLIGATION } : {}),
1288
- total: scored.length,
1289
- query_time_ms: queryTimeMs,
1290
- diagnostics: {
1291
- content_tokens: tokenize(params.phrase),
1292
- facet_activations: facetActivations,
1293
- score_tie_break_order: ['score', 'scope', 'type', 'name', 'path'],
1294
- },
1295
- ...(relaxed ? { relaxed_overlap: true } : {}),
1296
- ...(emptyResultHint ? { hint: emptyResultHint } : {}),
1297
- }, null, jsonIndent));
1298
- return;
1299
- }
1300
- if (scored.length === 0) {
1301
- console.log(`No discovery matches for "${params.phrase}" in types: ${types.join(',')}.`);
1302
- console.log(backend === 'fortemi-core'
1303
- ? emptyResultHint
1304
- : 'Try a broader phrase or a `--type` filter. If capabilities were just added, refresh with `aiwg use <framework>` (or `aiwg index build`).');
1305
- return;
1306
- }
1307
- const relaxedNote = relaxed ? ' — relaxed match (verbose query)' : '';
1308
- console.log(`Discovery results for "${params.phrase}" (${scored.length} matches, ${queryTimeMs}ms)${relaxedNote}:`);
1309
- console.log(statsText(responseRuleStats));
1310
- console.log('');
1311
- for (const diagnostic of facetActivations) {
1312
- if (diagnostic.status === 'suppressed' && diagnostic.reason) {
1313
- console.log(`Routing diagnostic: ${diagnostic.reason}.`);
1314
- console.log('');
1315
- }
1316
- }
1317
- for (let i = 0; i < scored.length; i++) {
1318
- const r = scored[i];
1319
- const ranking = rankingDiagnostic(r.entry, r.score, r.facetDiagnostics);
1320
- const id = discoveryIdForEntry(r.entry);
1321
- const score = r.score.toFixed(2);
1322
- const flags = [
1323
- r.entry.kernel ? 'kernel' : null,
1324
- r.entry.script ? 'exec' : null,
1325
- ].filter(Boolean).join(', ');
1326
- const locator = includePaths ? resolvePath(r.entry) : id;
1327
- const topTriggerMatch = ranking.matches
1328
- .filter((match) => match.field === 'trigger')
1329
- .reduce((best, match) => !best || match.contribution > best.contribution ? match : best, undefined);
1330
- const topTrigger = topTriggerMatch?.value ??
1331
- (r.entry.triggers && r.entry.triggers.length > 0 ? r.entry.triggers[0] : '');
1332
- console.log(`${i + 1}. ${r.entry.title}`);
1333
- console.log(` type: ${r.entry.type} score: ${score}${flags ? ` flags: ${flags}` : ''}`);
1334
- console.log(` ${includePaths ? 'path' : 'id'}: ${locator}`);
1335
- if (r.entry.name) {
1336
- console.log(` name: ${r.entry.name}`);
1337
- }
1338
- if (r.entry.capability) {
1339
- console.log(` capability: ${r.entry.capability}`);
1340
- }
1341
- if (topTrigger) {
1342
- console.log(` trigger: "${topTrigger}"`);
1343
- }
1344
- const triggerCoverage = topTriggerMatch?.query_token_coverage;
1345
- const rankingParts = [
1346
- `lexical ${ranking.lexical_score.toFixed(4)} -> final ${ranking.final_score.toFixed(4)}`,
1347
- triggerCoverage === undefined
1348
- ? null
1349
- : `trigger covers ${Math.round(triggerCoverage * 100)}% of query tokens`,
1350
- `scope ${ranking.tie_breakers.scope}`,
1351
- ].filter((part) => Boolean(part));
1352
- console.log(` ranking: ${rankingParts.join('; ')}`);
1353
- if (governing[i].length) {
1354
- console.log(` ${statsText(governingRuleStats(governing[i]))}`);
1355
- console.log(` ${RULE_CHECK_OBLIGATION}`);
1356
- for (const { rule, applicability } of governing[i])
1357
- console.log(` - ${rule.name ?? rule.path}: ${rule.ruleSummary ?? ''} (${applicability.join('; ')}) — \`${boundRuleDescriptor(rule).show_command}\``);
1358
- }
1359
- if (r.entry.script) {
1360
- console.log(` run: ${buildRunHint(r.entry)}`);
1361
- }
1362
- else if (!includePaths) {
1363
- console.log(` show: ${showHintForDiscoverResult(r.entry, id)}`);
1364
- }
1365
- console.log('');
1366
- }
1367
- console.log('Use `--format json` for machine-readable output. Use `aiwg show metadata <id>` for paths and full metadata.');
1368
- }
1369
- function resolveMetadataPath(cwd, aiwgRoot, entry) {
1370
- if (path.isAbsolute(entry.path))
1371
- return entry.path;
1372
- const normalizedPath = normalizeIndexedPath(entry.path);
1373
- if (aiwgRoot && normalizedPath.startsWith('agentic/code/')) {
1374
- return path.join(aiwgRoot, normalizedPath);
1375
- }
1376
- if (entry.indexScope === 'user' && normalizedPath.startsWith('~/.aiwg/')) {
1377
- return path.join(process.env.HOME ?? '', normalizedPath.slice(2));
1378
- }
1379
- if (normalizedPath.startsWith('.aiwg/')) {
1380
- return projectAiwgPath(cwd, normalizedPath.slice('.aiwg/'.length));
1381
- }
1382
- return path.join(cwd, normalizedPath);
1383
- }
1384
- async function loadShowEntries(cwd, params, compact = false) {
1385
- const aiwgRoot = resolveFrameworkIndexRoot(cwd);
1386
- const backend = params.backend ?? DEFAULT_ARTIFACT_SEARCH_BACKEND;
1387
- let resourceSource = params.resourceSource ?? 'local';
1388
- let entries = [];
1389
- let relations;
1390
- if (compact && resourceSource !== 'web' && (!params.graph || params.graph === 'framework')) {
1391
- relations = await ensureRelations(cwd) ?? undefined;
1392
- if (relations?.index.artifacts) {
1393
- const reader = relations;
1394
- const matched = findShowMatches(Object.values(reader.index.artifacts), params.typeFilter ?? [...OPERATIONAL_SHOW_TYPES], params.name.trim());
1395
- const frameworkEntries = matched.map(entry => {
1396
- const id = discoveryIdForEntry(entry);
1397
- const rule = reader.index.rules[id];
1398
- return withIndexProvenance({ ...entry, phase: '', tags: [], created: '', updated: '', checksum: '', summary: '', dependencies: [], dependents: [],
1399
- ...(rule ? { activation: reader.pinnedRuleIds.has(id) ? 'kernel' : rule.activation ?? undefined,
1400
- ruleSummary: rule.summary, ruleEnforcement: rule.enforcement ?? undefined, bound_to: rule.bound_to } : {}),
1401
- }, 'framework');
1402
- });
1403
- const localEntries = params.graph ? [] : defaultCapabilityGraphs(cwd).filter(graph => graph !== 'framework')
1404
- .flatMap(graph => loadLocalCapabilityEntries(cwd, graph, undefined, true));
1405
- const compactEntries = [...localEntries, ...frameworkEntries];
1406
- if ((params.typeFilter?.every(type => ['skill', 'agent', 'flow', 'command', 'rule', 'behavior'].includes(type)))
1407
- || findShowMatches(compactEntries, params.typeFilter ?? [...OPERATIONAL_SHOW_TYPES], params.name.trim()).length) {
1408
- return { entries: compactEntries, aiwgRoot, resourceSource: 'local', relations };
1409
- }
1410
- }
1411
- }
1412
- if (resourceSource !== 'web' && (!params.graph || params.graph === 'framework')) {
1413
- const root = resolveFrameworkCorpusRoot(cwd) ?? aiwgRoot;
1414
- if (root) {
1415
- try {
1416
- await refreshFrameworkCapabilities(root, backend === 'fortemi-core' && params.backend !== undefined);
1417
- }
1418
- catch (error) {
1419
- console.error(`Warning: capability index refresh failed: ${error instanceof Error ? error.message : String(error)}`);
1420
- }
1421
- }
1422
- }
1423
- if (resourceSource === 'auto' && backend === 'fortemi-core') {
1424
- const { loadFortemiCoreMetadataEntries } = await import('./fortemi-core-query-adapter.js');
1425
- const localGraphs = params.graph ? [params.graph] : defaultCapabilityGraphs(cwd);
1426
- resourceSource = localGraphs.some((graph) => loadFortemiCoreMetadataEntries(cwd, graph).entries.length > 0) ? 'local' : 'web';
1427
- }
1428
- else if (resourceSource === 'auto') {
1429
- resourceSource = 'local';
1430
- }
1431
- if (resourceSource === 'web') {
1432
- if (backend !== 'fortemi-core') {
1433
- console.error('Error: --resource-source web requires the Fortemi Core query backend; --backend local remains available with local resources.');
1434
- process.exit(1);
1435
- }
1436
- if (params.graph && params.graph !== 'framework') {
1437
- console.error("Error: web-backed show currently supports only the 'framework' graph.");
1438
- process.exit(1);
1439
- }
1440
- try {
1441
- const { resolveWebRelease } = await import('../resources/web-release.js');
1442
- const webRelease = await resolveWebRelease({
1443
- ...params.webReleaseOptions,
1444
- selector: params.aiwgVersion ?? 'stable',
1445
- offline: params.offline,
1446
- });
1447
- const sourcePaths = {
1448
- manifestPath: webRelease.fortemiManifestPath,
1449
- exportPath: webRelease.fortemiExportPath,
1450
- manifestSha256: webRelease.fortemiManifestSha256,
1451
- manifestSize: webRelease.fortemiManifestSize,
1452
- exportSha256: webRelease.fortemiExportSha256,
1453
- exportSize: webRelease.fortemiExportSize,
1454
- };
1455
- const { loadFortemiCoreMetadataEntries } = await import('./fortemi-core-query-adapter.js');
1456
- const loaded = loadFortemiCoreMetadataEntries(cwd, 'framework', sourcePaths);
1457
- if (loaded.reason)
1458
- throw new Error(loaded.reason);
1459
- entries = loaded.entries.map((entry) => withIndexProvenance(entry, 'framework'));
1460
- return { entries, aiwgRoot, resourceSource: 'web', webRelease, sourcePaths };
1461
- }
1462
- catch (error) {
1463
- console.error(`Error: AIWG web resource resolution failed: ${error instanceof Error ? error.message : String(error)}`);
1464
- process.exit(1);
1465
- }
1466
- }
1467
- // Preserve the direct API's historical local-index behavior when callers
1468
- // omit `backend`. The CLI always passes its explicit Fortemi default, while
1469
- // an explicit `auto` source also opts into Fortemi-backed availability.
1470
- if (params.backend === 'fortemi-core' || params.resourceSource === 'auto') {
1471
- const { loadFortemiCoreMetadataEntries } = await import('./fortemi-core-query-adapter.js');
1472
- const graphs = params.graph ? [params.graph] : defaultCapabilityGraphs(cwd);
1473
- let unavailableReason;
1474
- for (const graph of graphs) {
1475
- const loaded = loadFortemiCoreMetadataEntries(cwd, graph);
1476
- if (loaded.reason && graph === 'project' && !params.graph) {
1477
- const fallback = projectCapabilityFallback(cwd);
1478
- if (fallback) {
1479
- entries.push(...fallback);
1480
- continue;
1481
- }
1482
- }
1483
- if (loaded.reason) {
1484
- unavailableReason ??= loaded.reason;
1485
- if (graph === 'framework' && !params.graph) {
1486
- console.error(`Warning: framework capabilities are unavailable: ${loaded.reason}`);
1487
- }
1488
- }
1489
- entries.push(...loaded.entries.map((entry) => withIndexProvenance(entry, graph)));
1490
- }
1491
- if (entries.length === 0 && unavailableReason) {
1492
- if (params.json) {
1493
- console.log(JSON.stringify({
1494
- backend: 'fortemi-core',
1495
- name: params.name,
1496
- error: unavailableReason,
1497
- }, null, 2));
1498
- }
1499
- else {
1500
- console.error('Error: ' + unavailableReason);
1501
- }
1502
- process.exit(1);
1503
- }
1504
- }
1505
- else {
1506
- entries = loadLocalCapabilityEntries(cwd, params.graph, undefined, true);
1507
- }
1508
- return { entries, aiwgRoot, resourceSource: 'local', relations };
1509
- }
1510
- /** Local index inputs shared by show and exact rule-binding validation (#2938). */
1511
- export function loadLocalCapabilityEntries(cwd, graph, snapshot, includeHistory = false) {
1512
- const entries = [];
1513
- for (const selectedGraph of graph ? [graph] : defaultCapabilityGraphs(cwd)) {
1514
- const key = snapshot && `${selectedGraph}:${getGraphIndexDir(cwd, selectedGraph)}`;
1515
- let selected = key ? snapshot.get(key) : undefined;
1516
- if (!selected) {
1517
- const index = loadGraphIndexFile(cwd, 'metadata.json', selectedGraph);
1518
- selected = index ? Object.values(index.entries).map(entry => withIndexProvenance(entry, selectedGraph)) : [];
1519
- if (key)
1520
- snapshot.set(key, selected);
1521
- }
1522
- entries.push(...selected);
1523
- }
1524
- if (!graph && entries.length === 0) {
1525
- const legacy = loadMetadataIndex(cwd);
1526
- if (legacy)
1527
- entries.push(...Object.values(legacy.entries));
1528
- }
1529
- return includeHistory ? entries : entries.filter(entry => isOrdinaryMemoryEntry(entry, cwd));
1530
- }
1531
- /** Project/user inputs only; package artifacts come from a validated compact table. */
1532
- export function loadLocalOverrideCapabilityEntries(cwd) {
1533
- const local = defaultCapabilityGraphs(cwd).filter(graph => graph !== 'framework')
1534
- .flatMap(graph => loadLocalCapabilityEntries(cwd, graph));
1535
- if (local.length)
1536
- return local;
1537
- const canonical = (directory) => {
1538
- try {
1539
- return fs.realpathSync(directory);
1540
- }
1541
- catch {
1542
- return path.resolve(directory);
1543
- }
1544
- };
1545
- const packageRoot = canonical(resolveFrameworkIndexRoot(cwd));
1546
- // Retain the legacy PROJECT index, never use the package's full index as a fallback.
1547
- if (canonical(cwd) === packageRoot)
1548
- return [];
1549
- const legacy = loadMetadataIndex(cwd);
1550
- return Object.values(legacy?.entries ?? {}).filter(entry => {
1551
- const provenance = entry;
1552
- if (provenance.indexGraph === 'framework' || provenance.indexScope === 'packaged'
1553
- || normalizeIndexedPath(entry.path).startsWith('agentic/code/'))
1554
- return false;
1555
- const relative = path.relative(packageRoot, path.resolve(cwd, entry.path));
1556
- return relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative);
1557
- }).map(entry => withIndexProvenance(entry, 'project'));
1558
- }
1559
- function findShowMatches(entries, types, needle) {
1560
- const needleLower = needle.toLowerCase();
1561
- const normalizedNeedle = normalizeIndexedPath(needle);
1562
- const candidates = entries.filter(e => types.includes(e.type));
1563
- let matches = needle.startsWith('aiwg:') ? candidates.filter(e => discoveryIdForEntry(e) === needle) : [];
1564
- if (matches.length === 0) {
1565
- matches = candidates.filter(e => e.path === needle || normalizeIndexedPath(e.path) === normalizedNeedle);
1566
- }
1567
- if (matches.length === 0) {
1568
- matches = candidates.filter(e => {
1569
- const normalizedPath = normalizeIndexedPath(e.path);
1570
- const dirStem = path.basename(path.dirname(normalizedPath));
1571
- const basename = path.basename(normalizedPath);
1572
- const fileStem = basename.replace(/\.[^.]+$/, '');
1573
- const slugLayoutMatch = ((basename === 'SKILL.md' && e.type === 'skill') ||
1574
- (basename === 'BEHAVIOR.md' && e.type === 'behavior')) &&
1575
- dirStem === needle;
1576
- if (slugLayoutMatch || fileStem === needle || e.name === needle)
1577
- return true;
1578
- if (e.type === 'gate-pack' && typeof e.name === 'string') {
1579
- const gateStem = fileStem.replace(/\.gatepack$/i, '');
1580
- const rest = e.name.includes(':') ? e.name.slice(e.name.indexOf(':') + 1) : e.name;
1581
- const short = rest.includes('/') ? rest.slice(rest.indexOf('/') + 1) : rest;
1582
- return gateStem === needle || rest === needle || short === needle;
1583
- }
1584
- return false;
1585
- });
1586
- }
1587
- if (matches.length === 0) {
1588
- matches = candidates.filter(e => typeof e.title === 'string' && e.title.toLowerCase() === needleLower);
1589
- }
1590
- matches = uniqueEntriesByPath(matches);
1591
- matches = matches.sort((a, b) => scopeRank(a) - scopeRank(b) || a.path.localeCompare(b.path));
1592
- if (matches.length > 1) {
1593
- const sameIdentity = matches.every((entry) => entry.type === matches[0].type &&
1594
- (entry.name ?? '').toLowerCase() === (matches[0].name ?? '').toLowerCase());
1595
- if (sameIdentity && scopeRank(matches[0]) < scopeRank(matches[1])) {
1596
- matches = [matches[0]];
1597
- }
1598
- }
1599
- if (matches.length > 1 && types.includes('skill')) {
1600
- const frameworkSkillMatches = matches.filter(e => isFrameworkSourceSkillPath(e.path));
1601
- if (frameworkSkillMatches.length === 1)
1602
- matches = frameworkSkillMatches;
1603
- }
1604
- if (matches.length > 1 && types.includes('skill')) {
1605
- const sourceSkillMatches = matches.filter(e => isCanonicalSourceSkillPath(e.path));
1606
- if (sourceSkillMatches.length === 1)
1607
- matches = sourceSkillMatches;
1608
- }
1609
- if (matches.length > 1 && types.includes('agent')) {
1610
- const canonicalSourceMatches = matches.filter(e => isCanonicalSourceAgentPath(e.path));
1611
- if (canonicalSourceMatches.length === 1)
1612
- matches = canonicalSourceMatches;
1613
- }
1614
- if (matches.length > 1 && types.includes('agent')) {
1615
- const canonicalBundleMatches = matches.filter(e => isCanonicalBundleAgentPath(e.path));
1616
- const canonicalBundlePaths = uniqueEntriesByPath(canonicalBundleMatches);
1617
- if (canonicalBundlePaths.length === 1)
1618
- matches = canonicalBundlePaths;
1619
- }
1620
- if (matches.length > 1 && types.includes('agent')) {
1621
- const nonPersonaMatches = matches.filter(e => !isTopLevelPersonaAgentPath(e.path));
1622
- if (nonPersonaMatches.length === 1)
1623
- matches = nonPersonaMatches;
1624
- }
1625
- return matches;
1626
- }
1627
- /** Preselect exact candidates once; the canonical resolver still owns precedence and ambiguity. */
1628
- export function createRuleBindingTargetResolver(entries, options = {}) {
1629
- const candidates = new Map();
1630
- for (const entry of entries) {
1631
- if (!['skill', 'agent', 'flow'].includes(entry.type))
1632
- continue;
1633
- const normalized = normalizeIndexedPath(entry.path);
1634
- const basename = path.posix.basename(normalized);
1635
- const slug = /^(?:SKILL|AGENT|FLOW)\.md$/i.test(basename)
1636
- ? path.posix.basename(path.posix.dirname(normalized))
1637
- : basename.replace(/\.[^.]+$/, '');
1638
- for (const id of new Set([entry.name, discoveryIdForEntry(entry), slug])) {
1639
- if (typeof id !== 'string')
1640
- continue;
1641
- const key = `${entry.type}\0${id}`;
1642
- const selected = candidates.get(key) ?? [];
1643
- selected.push(entry);
1644
- candidates.set(key, selected);
1645
- }
1646
- }
1647
- return (type, id, bundleRoot = options.bundleRoot) => resolveRuleBindingTarget(candidates.get(`${type}\0${id}`) ?? [], type, id, { ...options, bundleRoot });
1648
- }
1649
- /** Resolve exact rule binding IDs using the same precedence and ambiguity as show.
1650
- * Canonical layout slugs remain valid when frontmatter names are display names.
1651
- * Titles and filesystem paths are deliberately excluded (#2938).
1652
- */
1653
- export function resolveRuleBindingTarget(entries, type, id, options = {}) {
1654
- const exact = entries.filter(entry => {
1655
- if (entry.type !== type)
1656
- return false;
1657
- const normalized = normalizeIndexedPath(entry.path);
1658
- const basename = path.posix.basename(normalized);
1659
- const slug = /^(?:SKILL|AGENT|FLOW)\.md$/i.test(basename)
1660
- ? path.posix.basename(path.posix.dirname(normalized))
1661
- : basename.replace(/\.[^.]+$/, '');
1662
- return entry.name === id || discoveryIdForEntry(entry) === id || slug === id;
1663
- });
1664
- const matches = preferCanonicalBindingTargets(findShowMatches(selectBindingTargetIdentities(exact, options), [type], id));
1665
- if (matches.length === 0)
1666
- throw new Error(`Missing ${type} binding target: ${id}`);
1667
- if (matches.length > 1)
1668
- throw new Error(`Ambiguous ${type} binding target: ${id}: ${matches.map(entry => entry.path).join(', ')}`);
1669
- return matches[0];
1670
- }
1671
- async function fortemiRecordForEntry(cwd, entry, sourcePaths) {
1672
- const graph = (entry.indexGraph ?? 'project');
1673
- const { loadFortemiCoreExport } = await import('./fortemi-core-query-adapter.js');
1674
- const loaded = loadFortemiCoreExport(cwd, graph, sourcePaths);
1675
- if (!loaded.exported)
1676
- return null;
1677
- const id = discoveryIdForEntry(entry);
1678
- return loaded.exported.items.find((record) => record.id === id || record.source.path === entry.path) ?? null;
1679
- }
1680
- /**
1681
- * Scan bundle `gate-packs/` directories for a pack matching `needle` (#2830).
1682
- *
1683
- * Accepts the full namespaced id, the rest-path or the short pack name and
1684
- * probes `<bundle>/gate-packs/<pack>.gatepack.{yaml,yml,json}`. Never looks
1685
- * under `gates/`, which agent-persistence HITL owns.
1686
- */
1687
- async function findGatePackInCorpus(groups, needle) {
1688
- const path = await import('node:path');
1689
- const fsp = (await import('node:fs')).promises;
1690
- const trimmed = needle.trim();
1691
- const rest = trimmed.includes(':') ? trimmed.slice(trimmed.indexOf(':') + 1) : trimmed;
1692
- const slash = rest.indexOf('/');
1693
- const wantedBundle = slash >= 0 ? rest.slice(0, slash) : null;
1694
- const wantedPack = slash >= 0 ? rest.slice(slash + 1) : rest;
1695
- if (!wantedPack || /\s/.test(wantedPack) || wantedPack.includes(':') || wantedPack.includes('/'))
1696
- return null;
1697
- const extensions = ['.gatepack.yaml', '.gatepack.yml', '.gatepack.json'];
1698
- const ordered = wantedBundle
1699
- ? groups.flatMap(group => [{ group, bundle: wantedBundle }])
1700
- : null;
1701
- const probe = async (group, bundle) => {
1702
- for (const extension of extensions) {
1703
- const candidate = path.join(group.dir, bundle, 'gate-packs', `${wantedPack}${extension}`);
1704
- try {
1705
- const stat = await fsp.stat(candidate);
1706
- if (stat.isFile())
1707
- return { path: candidate, bundleKind: group.kind, bundleId: bundle };
1708
- }
1709
- catch {
1710
- // not present — continue
1711
- }
1712
- }
1713
- return null;
1714
- };
1715
- if (ordered) {
1716
- for (const { group, bundle } of ordered) {
1717
- const found = await probe(group, bundle);
1718
- if (found)
1719
- return found;
1720
- }
1721
- return null;
1722
- }
1723
- for (const group of groups) {
1724
- let bundles;
1725
- try {
1726
- bundles = (await fsp.readdir(group.dir, { withFileTypes: true }))
1727
- .filter(d => d.isDirectory())
1728
- .map(d => d.name)
1729
- .sort();
1730
- }
1731
- catch {
1732
- continue;
1733
- }
1734
- for (const bundle of bundles) {
1735
- const found = await probe(group, bundle);
1736
- if (found)
1737
- return found;
1738
- }
1739
- }
1740
- return null;
1741
- }
1742
- /**
1743
- * Scan the AIWG_ROOT corpus for an artifact matching `name` (#1221).
1744
- *
1745
- * Walks the well-known artifact layouts under
1746
- * `agentic/code/{frameworks,addons,extensions,plugins}/<bundle>/{skills,agents,commands,rules,templates,behaviors,flows}/`
1747
- * and returns the first match. Used as a fallback in `aiwg show` when an
1748
- * artifact isn't in any built index — either because the workspace hasn't
1749
- * been deployed to yet, or because the bundle hasn't been installed.
1750
- *
1751
- * Returns the resolved absolute path plus enough metadata for the caller
1752
- * to surface a useful install hint. Returns null if nothing matches.
1753
- */
1754
- async function findCorpusArtifact(aiwgRoot, name, typeFilter) {
1755
- const fs = await import('node:fs');
1756
- const path = await import('node:path');
1757
- const fsp = fs.promises;
1758
- const groups = [
1759
- { kind: 'framework', dir: path.join(aiwgRoot, 'agentic/code/frameworks') },
1760
- { kind: 'addon', dir: path.join(aiwgRoot, 'agentic/code/addons') },
1761
- { kind: 'extension', dir: path.join(aiwgRoot, 'agentic/code/extensions') },
1762
- { kind: 'plugin', dir: path.join(aiwgRoot, 'agentic/code/plugins') },
1763
- ];
1764
- // (subdir, type, layout) — 'flat' = `<name>.md`, 'slug' = `<name>/SKILL.md`
1765
- const tries = [
1766
- { sub: 'skills', type: 'skill', layout: 'slug' },
1767
- { sub: 'skills', type: 'skill', layout: 'flat' },
1768
- { sub: 'agents', type: 'agent', layout: 'flat' },
1769
- { sub: 'commands', type: 'command', layout: 'flat' },
1770
- { sub: 'rules', type: 'rule', layout: 'flat' },
1771
- { sub: 'templates', type: 'template', layout: 'flat' },
1772
- { sub: 'behaviors', type: 'behavior', layout: 'flat' },
1773
- { sub: 'flows', type: 'flow', layout: 'flat' },
1774
- { sub: 'runbooks', type: 'runbook', layout: 'flat' },
1775
- { sub: 'decisions', type: 'decision-definition', layout: 'flat', extension: '.json' },
1776
- { sub: 'rulesets', type: 'decision-ruleset', layout: 'flat', extension: '.json' },
1777
- { sub: 'bindings', type: 'decision-binding', layout: 'flat', extension: '.json' },
1778
- ];
1779
- for (const group of groups) {
1780
- let bundles;
1781
- try {
1782
- bundles = (await fsp.readdir(group.dir, { withFileTypes: true }))
1783
- .filter(d => d.isDirectory())
1784
- .map(d => d.name);
1785
- }
1786
- catch {
1787
- continue;
1788
- }
1789
- for (const bundle of bundles) {
1790
- for (const t of tries) {
1791
- if (typeFilter.length > 0 && !typeFilter.includes(t.type))
1792
- continue;
1793
- const candidate = t.layout === 'slug'
1794
- ? path.join(group.dir, bundle, t.sub, name, 'SKILL.md')
1795
- : path.join(group.dir, bundle, t.sub, `${name}${t.extension ?? '.md'}`);
1796
- try {
1797
- const stat = await fsp.stat(candidate);
1798
- if (stat.isFile()) {
1799
- return { path: candidate, type: t.type, bundleKind: group.kind, bundleId: bundle };
1800
- }
1801
- }
1802
- catch {
1803
- // not present — continue
1804
- }
1805
- }
1806
- }
1807
- }
1808
- // Gate packs live in `<bundle>/gate-packs/*.gatepack.yaml|json` (never
1809
- // `gates/`, which agent-persistence HITL uses). The needle may be the full
1810
- // namespaced id (`aiwg:decision-engine/integrity-ceiling`), the rest-path
1811
- // (`decision-engine/integrity-ceiling`) or the short pack name
1812
- // (`integrity-ceiling`). (#2830)
1813
- if (typeFilter.length === 0 || typeFilter.includes('gate-pack')) {
1814
- const gateMatch = await findGatePackInCorpus(groups, name);
1815
- if (gateMatch)
1816
- return { ...gateMatch, type: 'gate-pack' };
1817
- }
1818
- // Top-level agents live at `agentic/code/agents/<category>/<name>.md`
1819
- // (e.g. `personas/aiwg-writer.md`) — a flat-under-category layout the
1820
- // bundle groups above do not cover. Scan it directly so persona/agent
1821
- // `show` survives un-indexed (or stale-framework-index) workspaces, where
1822
- // the corpus fallback is the only resolution path. (#1623 U5)
1823
- if (typeFilter.length === 0 || typeFilter.includes('agent')) {
1824
- const agentMatch = await findAgentInCorpus(path.join(aiwgRoot, 'agentic/code/agents'), name);
1825
- if (agentMatch) {
1826
- return { path: agentMatch, type: 'agent', bundleKind: null, bundleId: null };
1827
- }
1828
- }
1829
- // Behaviors commonly use a slug layout: `behaviors/<name>/BEHAVIOR.md`.
1830
- if (typeFilter.length === 0 || typeFilter.includes('behavior')) {
1831
- for (const group of groups) {
1832
- let bundles;
1833
- try {
1834
- bundles = (await fsp.readdir(group.dir, { withFileTypes: true }))
1835
- .filter(d => d.isDirectory())
1836
- .map(d => d.name);
1837
- }
1838
- catch {
1839
- continue;
1840
- }
1841
- for (const bundle of bundles) {
1842
- const candidate = path.join(group.dir, bundle, 'behaviors', name, 'BEHAVIOR.md');
1843
- try {
1844
- const stat = await fsp.stat(candidate);
1845
- if (stat.isFile()) {
1846
- return { path: candidate, type: 'behavior', bundleKind: group.kind, bundleId: bundle };
1847
- }
1848
- }
1849
- catch {
1850
- // not present — continue
1851
- }
1852
- }
1853
- }
1854
- }
1855
- return null;
1856
- }
1857
- /**
1858
- * Recursively scan `agentic/code/agents` for a flat `<name>.md` agent file.
1859
- *
1860
- * Agents use an `agents/<category>/<name>.md` layout (e.g. `personas/`) that
1861
- * differs from the bundle `<dir>/<bundle>/<sub>/<name>.md` layout the generic
1862
- * corpus scan walks, so persona agents are otherwise missed. Bounded depth —
1863
- * the agents tree is shallow. Returns the first matching absolute path, or
1864
- * null. Direct files at each level take priority over subdirectories. (#1623)
1865
- */
1866
- async function findAgentInCorpus(agentsRoot, name, depth = 0) {
1867
- if (depth > 3)
1868
- return null;
1869
- const fs = await import('node:fs');
1870
- const path = await import('node:path');
1871
- const fsp = fs.promises;
1872
- let entries;
1873
- try {
1874
- entries = await fsp.readdir(agentsRoot, { withFileTypes: true });
1875
- }
1876
- catch {
1877
- return null;
1878
- }
1879
- // Prefer a direct `<name>.md` at this level before descending.
1880
- for (const entry of entries) {
1881
- if (entry.isFile() && entry.name === `${name}.md`) {
1882
- return path.join(agentsRoot, entry.name);
1883
- }
1884
- }
1885
- // Descend into category subdirectories (e.g. personas/).
1886
- for (const entry of entries) {
1887
- if (entry.isDirectory()) {
1888
- const found = await findAgentInCorpus(path.join(agentsRoot, entry.name), name, depth + 1);
1889
- if (found)
1890
- return found;
1891
- }
1892
- }
1893
- return null;
1894
- }
1895
- /** Build an ephemeral reverse lookup from the already-loaded rule metadata. */
1896
- export function rulesBoundTo(entries, target) {
1897
- const key = { skill: 'skills', agent: 'agents', flow: 'flows' }[target.type];
1898
- if (!key)
1899
- return [];
1900
- const file = path.basename(normalizeIndexedPath(target.path));
1901
- const aliases = [target.name, target.title, target.path, discoveryIdForEntry(target),
1902
- file === 'SKILL.md' ? path.basename(path.dirname(normalizeIndexedPath(target.path))) : file.replace(/\.[^.]+$/, '')]
1903
- .filter((alias) => !!alias);
1904
- const seen = new Set();
1905
- return entries.filter(rule => {
1906
- if (rule.type !== 'rule' && rule.type !== 'behavior')
1907
- return false;
1908
- const patterns = rule.bound_to?.[key];
1909
- if (!Array.isArray(patterns) || !patterns.some(pattern => typeof pattern === 'string'
1910
- && aliases.some(alias => alias === pattern || minimatch(alias, pattern, { nonegate: true, nocomment: true }))))
1911
- return false;
1912
- const identity = `${rule.type}:${rule.path}`;
1913
- if (seen.has(identity))
1914
- return false;
1915
- seen.add(identity);
1916
- return true;
1917
- }).sort((a, b) => (a.name ?? a.path).localeCompare(b.name ?? b.path) || a.path.localeCompare(b.path));
1918
- }
1919
- /** Relationship metadata for shipped targets, merged with project/user contracts. */
1920
- export function relationshipRules(entries, target, relations) {
1921
- const local = rulesBoundTo(relations ? entries.filter(entry => !normalizeIndexedPath(entry.path).startsWith('agentic/code/')) : entries, target);
1922
- if (!relations || !['skill', 'agent', 'flow', 'command'].includes(target.type))
1923
- return local;
1924
- const asMetadata = (id) => {
1925
- const rule = relations.index.rules[id];
1926
- return { path: rule.path, type: rule.type, name: rule.name, activation: rule.activation ?? undefined,
1927
- bound_to: rule.bound_to, ruleSummary: rule.summary, ruleEnforcement: rule.enforcement ?? undefined, rulePaths: rule.paths, triggers: rule.triggers };
1928
- };
1929
- const key = `${target.type}:${discoveryIdForEntry(target)}`;
1930
- const shipped = Object.hasOwn(relations.index.targets, key)
1931
- ? relations.rulesForTarget(target.type, discoveryIdForEntry(target)).map(asMetadata)
1932
- // Project/user overrides keep the old alias/glob behavior using only small records.
1933
- : rulesBoundTo(Object.keys(relations.index.rules).map(asMetadata), target);
1934
- const merged = new Map([...local, ...shipped].map(rule => [`${rule.type}:${rule.path}`, rule]));
1935
- return [...merged.values()].sort((a, b) => (a.name ?? a.path).localeCompare(b.name ?? b.path) || a.path.localeCompare(b.path));
1936
- }
1937
- export const RULE_CHECK_OBLIGATION = 'Before governed work, fetch and follow every required rule below; a discovery summary is not the full rule.';
1938
- function relationMetadata(relations) {
1939
- return Object.values(relations.index.rules).map(rule => ({ path: rule.path, type: rule.type, name: rule.name,
1940
- activation: rule.activation ?? undefined, ruleSummary: rule.summary, ruleEnforcement: rule.enforcement ?? undefined,
1941
- bound_to: rule.bound_to, rulePaths: rule.paths, triggers: rule.triggers }));
1942
- }
1943
- /** Post-ranking enrichment: relationship lookup never loads the full metadata index. */
1944
- export function compoundGoverningRules(entries, target, relations, phrase = '', includeMatches = true, excludeKernel = true) {
1945
- if (!['skill', 'agent', 'flow', 'command'].includes(target.type))
1946
- return [];
1947
- const found = new Map();
1948
- const add = (rule, why) => {
1949
- const activation = rule.activation ?? (rule.type === 'behavior' ? 'kernel' : inferRuleActivation(rule.ruleEnforcement));
1950
- if (excludeKernel && (activation === 'kernel' || activation === 'core' || rule.kernel || relations?.pinnedRuleIds.has(discoveryIdForEntry(rule))))
1951
- return;
1952
- const key = `${rule.type}:${rule.path}`, item = found.get(key) ?? { rule, applicability: [] };
1953
- if (!item.applicability.includes(why))
1954
- item.applicability.push(why);
1955
- found.set(key, item);
1956
- };
1957
- for (const rule of relationshipRules(entries, target, relations))
1958
- add(rule, `bound:${target.type}:${discoveryIdForEntry(target)}`);
1959
- if (relations && target.type === 'skill' && target.name?.startsWith('projected:')) {
1960
- for (const id of relations.rulesForTarget('skill', target.name)) {
1961
- const rule = relationMetadata(relations).find(rule => discoveryIdForEntry(rule) === id);
1962
- if (rule)
1963
- add(rule, `projected-flow:${target.name.slice('projected:'.length)}`);
1964
- }
1965
- }
1966
- if (includeMatches) {
1967
- const query = phrase.toLowerCase();
1968
- const queryPaths = (phrase.replace(/\\/g, '/').match(/[\w@./*?-]+/g) ?? []).map(value => value.replace(/[.,;:!?]+$/, ''));
1969
- const corpus = relations ? relationMetadata(relations) : [];
1970
- const rules = new Map([...corpus, ...entries.filter(entry => ['rule', 'behavior'].includes(entry.type))]
1971
- .map(rule => [`${rule.type}:${rule.path}`, rule]));
1972
- for (const rule of rules.values()) {
1973
- for (const glob of rule.rulePaths ?? [])
1974
- for (const candidate of [...queryPaths.filter(value => /[./*?]/.test(value) || value === glob), ...(target.governedPaths ?? [])]) {
1975
- if (minimatch(candidate, glob, { dot: true, nonegate: true, nocomment: true })
1976
- || ((target.governedPaths ?? []).includes(candidate) && minimatch(glob, candidate, { dot: true, nonegate: true, nocomment: true })))
1977
- add(rule, `path:${candidate}`);
1978
- }
1979
- for (const trigger of rule.triggers ?? []) {
1980
- const normalized = trigger.trim().toLowerCase();
1981
- let offset = normalized ? query.indexOf(normalized) : -1;
1982
- while (offset >= 0) {
1983
- if ((offset === 0 || !/\w/.test(query[offset - 1]))
1984
- && (offset + normalized.length === query.length || !/\w/.test(query[offset + normalized.length]))) {
1985
- add(rule, `trigger:${trigger}`);
1986
- break;
1987
- }
1988
- offset = query.indexOf(normalized, offset + 1);
1989
- }
1990
- }
1991
- }
1992
- }
1993
- return [...found.values()].sort((a, b) => (a.rule.name ?? a.rule.path).localeCompare(b.rule.name ?? b.rule.path) || a.rule.path.localeCompare(b.rule.path));
1994
- }
1995
- function boundRuleDescriptor(rule) {
1996
- return { name: rule.name ?? path.basename(rule.path, '.md'), activation: rule.activation ?? null, enforcement: rule.ruleEnforcement ?? null,
1997
- summary: (rule.ruleSummary ?? '').replace(/\s+/g, ' ').trim(), show_command: `aiwg show ${rule.type} ${rule.name ?? path.basename(rule.path, '.md')} --body` };
1998
- }
1999
- /** Counts unique attached contracts; every emitted check is required irrespective of severity. */
2000
- export function governingRuleStats(governing) {
2001
- const stats = emptyRuleStats();
2002
- for (const { rule } of new Map(governing.map(item => [`${item.rule.type}:${item.rule.path}`, item])).values()) {
2003
- const enforcement = rule.ruleEnforcement?.toLowerCase() ?? 'unknown', activation = rule.activation ?? 'unknown';
2004
- stats.by_enforcement[enforcement] = (stats.by_enforcement[enforcement] ?? 0) + 1;
2005
- stats.by_activation[activation] = (stats.by_activation[activation] ?? 0) + 1;
2006
- stats.required_checks++;
2007
- }
2008
- return stats;
2009
- }
2010
- export function governingRuleFields(governing) {
2011
- if (!governing.length)
2012
- return {};
2013
- return { bound_rules: governing.map(({ rule }) => boundRuleDescriptor(rule)), rule_stats: governingRuleStats(governing),
2014
- required_rule_checks: governing.map(({ rule, applicability }) => ({ rule_id: discoveryIdForEntry(rule),
2015
- applicability, fetch_command: `aiwg show ${rule.type} ${discoveryIdForEntry(rule)} --body` })), rule_check_obligation: RULE_CHECK_OBLIGATION };
2016
- }
2017
- function statsText(stats) {
2018
- return `rules: ${Object.entries(stats.by_enforcement).map(([level, count]) => `${count} ${level}`).join(', ') || '0'} · activation: ${Object.entries(stats.by_activation).map(([mode, count]) => `${count} ${mode}`).join(', ') || 'none'} · ${stats.required_checks} required checks`;
2019
- }
2020
- export function relationshipRuleStats(entries, target, relations) {
2021
- const shipped = Object.hasOwn(relations.index.targets, `${target.type}:${discoveryIdForEntry(target)}`);
2022
- const stats = shipped ? relations.ruleStats(target.type, discoveryIdForEntry(target)) : emptyRuleStats();
2023
- // Shipped counts are precomputed; project/user contracts and overrides are overlays.
2024
- const overlay = shipped ? rulesBoundTo(entries.filter(entry => !normalizeIndexedPath(entry.path).startsWith('agentic/code/')), target)
2025
- : relationshipRules(entries, target, relations);
2026
- for (const rule of overlay) {
2027
- const enforcement = rule.ruleEnforcement ?? 'unknown';
2028
- const activation = rule.activation ?? 'unknown';
2029
- stats.by_enforcement[enforcement] = (stats.by_enforcement[enforcement] ?? 0) + 1;
2030
- stats.by_activation[activation] = (stats.by_activation[activation] ?? 0) + 1;
2031
- if (enforcement === 'critical' || enforcement === 'high')
2032
- stats.required_checks++;
2033
- }
2034
- return stats;
2035
- }
2036
- async function showBindings(entries, target, content, params, read, relations) {
2037
- const governing = compoundGoverningRules(entries, target, relations, '', false, false);
2038
- for (const { rule } of governing)
2039
- if (relations?.pinnedRuleIds.has(discoveryIdForEntry(rule)))
2040
- rule.activation = 'kernel';
2041
- const rules = governing.map(item => item.rule);
2042
- const boundRules = await Promise.all(rules.map(async (rule) => ({
2043
- ...boundRuleDescriptor(rule),
2044
- ...((params.boundRuleBodies || params.withRuleBodies) ? { content: await read(rule) } : {}),
2045
- })));
2046
- // Parse the selected rule for reverse lookup, including corpus-only rules.
2047
- const targets = target.type === 'rule' || target.type === 'behavior'
2048
- ? parseFrontmatter(content).data.bound_to : undefined;
2049
- const boundTo = targets && typeof targets === 'object' && !Array.isArray(targets)
2050
- ? Object.fromEntries(['skills', 'agents', 'flows'].flatMap(key => {
2051
- const values = targets[key];
2052
- const names = Array.isArray(values) ? [...new Set(values.filter((value) => typeof value === 'string' && !!value.trim()))] : [];
2053
- return names.length ? [[key, names]] : [];
2054
- })) : {};
2055
- const boundTargets = new Map();
2056
- if (target.type === 'rule' || target.type === 'behavior') {
2057
- for (const edge of relations?.targetsForRule(discoveryIdForEntry(target)) ?? []) {
2058
- boundTargets.set(`${edge.type}:${edge.id}`, { ...edge, name: relations?.index.artifacts?.[edge.id]?.name
2059
- ?? relations?.index.targets[`${edge.type}:${edge.id}`]?.name });
2060
- }
2061
- const selectedRule = { ...target, bound_to: boundTo };
2062
- for (const candidate of entries)
2063
- if (rulesBoundTo([selectedRule], candidate).length) {
2064
- const id = discoveryIdForEntry(candidate);
2065
- boundTargets.set(`${candidate.type}:${id}`, { type: candidate.type, id, name: candidate.name });
2066
- }
2067
- }
2068
- let text = '';
2069
- if (boundRules.length) {
2070
- // Cards already print these stats in the header; body/section output has no header.
2071
- const stats = params.body || params.sections?.length ? `${statsText(governingRuleStats(governing))}\n\n` : '';
2072
- text += `\n## Bound rules\n\n${RULE_CHECK_OBLIGATION}\n\n${stats}` + boundRules.map(rule => `- **${rule.name}** [${rule.activation ?? 'unknown'} / ${rule.enforcement ?? 'unknown'}]: ${rule.summary} (\`${rule.show_command}\`)`
2073
- + ('content' in rule ? `\n\n${rule.content}` : '')).join('\n') + '\n';
2074
- }
2075
- if (Object.keys(boundTo).length) {
2076
- text += '\n## Bound targets\n\n' + Object.entries(boundTo)
2077
- .map(([key, names]) => `- ${key}: ${names.map(name => `\`${name}\``).join(', ')}`).join('\n') + '\n';
2078
- }
2079
- if (boundTargets.size)
2080
- text += '\nResolved targets: ' + [...boundTargets.values()].map(target => `${target.type} ${target.name ?? target.id}`).join(', ') + '\n';
2081
- return { fields: {
2082
- ...governingRuleFields(governing),
2083
- ...(['rule', 'behavior'].includes(target.type) ? { bound_to: boundTo, bound_targets: [...boundTargets.values()] } : {}),
2084
- ...(boundRules.length ? { bound_rules: boundRules } : {}),
2085
- ...(Object.keys(boundTo).length ? { bound_to: boundTo } : {}),
2086
- }, text };
2087
- }
2088
- /** Sections include their nested headings, stopping at the next peer/ancestor. */
2089
- function showSections(content) {
2090
- const body = parseFrontmatter(content).body;
2091
- const headings = [];
2092
- let offset = 0;
2093
- let fence = '';
2094
- const lines = body.match(/[^\n]*\n|[^\n]+$/g) ?? [];
2095
- for (let i = 0; i < lines.length; i++) {
2096
- const line = lines[i];
2097
- const marker = line.match(/^ {0,3}(`{3,}|~{3,})/);
2098
- if (marker) {
2099
- if (!fence)
2100
- fence = marker[1];
2101
- else if (marker[1][0] === fence[0] && marker[1].length >= fence.length)
2102
- fence = '';
2103
- }
2104
- else if (!fence) {
2105
- const atx = line.match(/^ {0,3}(#{1,6})\s+(.+?)(?:\s+#+)?\s*$/);
2106
- const setext = i + 1 < lines.length && lines[i + 1].match(/^ {0,3}(=+|-+)\s*$/);
2107
- if (atx)
2108
- headings.push({ heading: atx[2], level: atx[1].length, start: offset });
2109
- else if (line.trim() && setext)
2110
- headings.push({ heading: line.trim(), level: setext[1][0] === '=' ? 1 : 2, start: offset });
2111
- }
2112
- offset += line.length;
2113
- }
2114
- return headings.map((heading, i) => {
2115
- const end = headings.slice(i + 1).find(next => next.level <= heading.level)?.start ?? body.length;
2116
- const text = body.slice(heading.start, end);
2117
- return { heading: heading.heading, level: heading.level, bytes: Buffer.byteLength(text),
2118
- lines: text.split('\n').length - (text.endsWith('\n') ? 1 : 0), text };
2119
- });
2120
- }
2121
- /** List companion directories and explicitly linked resources within the owning bundle.
2122
- * Resolve paths against that boundary and exclude symlink components. */
2123
- function showResources(filePath, source, release) {
2124
- if (release) {
2125
- const base = path.posix.dirname(filePath);
2126
- const linked = new Set(extractMarkdownLinks(source).map(link => path.posix.normalize(path.posix.join(base, link))));
2127
- const boundary = filePath.match(/^(raw\/agentic\/code\/(?:frameworks|addons|extensions)\/[^/]+)\//)?.[1];
2128
- return [...release.descriptors.values()].filter(descriptor => {
2129
- const relative = path.posix.relative(base, descriptor.path);
2130
- const category = /(?:^|\/)(?:templates|scripts|references|resources|assets)\//.test(relative);
2131
- const inside = relative !== '..' && !relative.startsWith('../');
2132
- return (inside && category || linked.has(descriptor.path) && (inside || category))
2133
- && (!boundary || descriptor.path.startsWith(`${boundary}/`));
2134
- }).map(descriptor => ({ path: path.posix.relative(base, descriptor.path), bytes: descriptor.size }))
2135
- .sort((a, b) => a.path.localeCompare(b.path));
2136
- }
2137
- const base = path.dirname(filePath);
2138
- const normalizedBase = normalizeIndexedPath(base);
2139
- const boundary = normalizedBase.match(/^(.*\/(?:frameworks|addons|extensions)\/[^/]+)(?:\/|$)/)?.[1]
2140
- ?? normalizedBase.match(/^(.*\/\.aiwg)(?:\/|$)/)?.[1] ?? base;
2141
- const resources = new Map();
2142
- const walk = (relative) => {
2143
- const absolute = path.resolve(base, relative);
2144
- const contained = path.relative(boundary, absolute);
2145
- if (contained === '..' || contained.startsWith(`..${path.sep}`) || path.isAbsolute(contained))
2146
- return;
2147
- let cursor = boundary;
2148
- let stat;
2149
- try {
2150
- for (const component of contained.split(path.sep)) {
2151
- cursor = path.join(cursor, component);
2152
- stat = fs.lstatSync(cursor);
2153
- if (stat.isSymbolicLink())
2154
- return;
2155
- }
2156
- }
2157
- catch {
2158
- return;
2159
- }
2160
- if (stat?.isDirectory()) {
2161
- for (const name of fs.readdirSync(absolute).sort())
2162
- walk(path.join(relative, name));
2163
- }
2164
- else if (stat?.isFile() && absolute !== filePath) {
2165
- const key = normalizeIndexedPath(path.relative(base, absolute));
2166
- resources.set(key, { path: key, bytes: stat.size });
2167
- }
2168
- };
2169
- for (const directory of ['templates', 'scripts', 'references', 'resources', 'assets'])
2170
- walk(directory);
2171
- const { data } = parseFrontmatter(source);
2172
- const declared = Array.isArray(data.resources) ? data.resources.filter((value) => typeof value === 'string') : [];
2173
- for (const link of [...extractMarkdownLinks(source), ...declared]) {
2174
- if (path.isAbsolute(link) || /^[a-z]+:/i.test(link))
2175
- continue;
2176
- const relative = path.relative(base, path.resolve(base, link));
2177
- // Outside the artifact directory, only declared companion categories qualify.
2178
- if ((relative === '..' || relative.startsWith(`..${path.sep}`)) && !/(?:^|\/)(?:templates|scripts|references|resources|assets)\//.test(normalizeIndexedPath(relative)))
2179
- continue;
2180
- walk(relative);
2181
- }
2182
- return [...resources.values()].sort((a, b) => a.path.localeCompare(b.path));
2183
- }
2184
- async function emitShowCard(cwd, aiwgRoot, entry, filePath, source, params, bindings, extra, local, release) {
2185
- const { data } = parseFrontmatter(source);
2186
- const flow = entry.type === 'flow' || entry.type === 'runbook' ? parseFlowDoc(source, entry.path) : null;
2187
- const sections = showSections(source);
2188
- const selected = (params.sections ?? []).map(heading => {
2189
- const exact = sections.filter(section => section.heading === heading);
2190
- const matches = exact.length ? exact : sections.filter(section => section.heading.toLowerCase() === heading.toLowerCase());
2191
- if (matches.length !== 1)
2192
- throw new Error(`${matches.length ? 'Ambiguous' : 'Unknown'} heading "${heading}". Headings: ${sections.map(section => section.heading).join(', ') || '(none)'}`);
2193
- return matches[0].text;
2194
- });
2195
- const owner = normalizeIndexedPath(entry.path).match(/(?:^|\/)(?:agentic\/code|\.aiwg)\/(frameworks|addons|extensions)\/([^/]+)\//);
2196
- const kind = owner ? { frameworks: 'framework', addons: 'addon', extensions: 'extension' }[owner[1]] : null;
2197
- const installed = local && (owner && aiwgRoot
2198
- ? await isCorpusBundleInstalled(cwd, aiwgRoot, kind, owner[2]) : true);
2199
- const resources = local || release ? showResources(filePath, source, release) : [];
2200
- const resource = params.resource ? resources.find(resource => resource.path === params.resource) : undefined;
2201
- if (params.resource && !resource)
2202
- throw new Error(`Unknown resource "${params.resource}". Resources: ${resources.map(resource => resource.path).join(', ') || '(none)'}`);
2203
- const quote = (value) => '"' + value.replace(/["\\$`]/g, '\\$&') + '"';
2204
- const command = `aiwg show ${entry.type} ${extra.hint ? params.name : discoveryIdForEntry(entry)}`
2205
- + (params.graph ? ` --graph ${quote(params.graph)}` : '')
2206
- + (params.backend ? ` --backend ${params.backend}` : '')
2207
- + (params.resourceSource ? ` --resource-source ${params.resourceSource}` : '')
2208
- + (params.aiwgVersion ? ` --aiwg-version ${quote(params.aiwgVersion)}` : '')
2209
- + (params.offline ? ' --offline' : '');
2210
- let resourceBody;
2211
- if (resource) {
2212
- if (local)
2213
- resourceBody = fs.readFileSync(path.join(path.dirname(filePath), resource.path), 'utf8');
2214
- else if (release) {
2215
- const { fetchVerifiedRawResource } = await import('../resources/web-release.js');
2216
- resourceBody = (await fetchVerifiedRawResource(release, path.posix.normalize(path.posix.join(path.posix.dirname(filePath), resource.path)), { ...params.webReleaseOptions, offline: params.offline })).toString('utf8');
2217
- }
2218
- }
2219
- const localPin = extra.local_pin;
2220
- const pinNote = localPin ? `Pinned locally: kernel (canonical ${localPin.canonical_activation}; ${localPin.matches.map(match => match.source).join(', ')}).` : '';
2221
- const contentNotice = 'This is a metadata card. The component body has not been fetched. Before deciding or applying its workflow, read the needed sections or --body using the drill-in commands below. Read full governing rules before governed work; --rules alone lists checks.';
2222
- const card = {
2223
- id: discoveryIdForEntry(entry), type: entry.type, name: entry.name ?? String(data.name ?? entry.title),
2224
- title: entry.title, path: filePath, description: String(data.description ?? data.summary ?? flow?.description ?? entry.capability ?? entry.ruleSummary ?? entry.summary ?? ''),
2225
- capability: owner ? { kind, name: owner[2] } : null, installed, kernel: entry.kernel ?? false,
2226
- ...(['rule', 'behavior'].includes(entry.type) ? {
2227
- activation: localPin ? 'kernel' : entry.activation ?? data.activation ?? null, enforcement: data.enforcement ?? entry.ruleEnforcement ?? null,
2228
- bound_to: data.bound_to ?? entry.bound_to ?? {},
2229
- } : {}),
2230
- bound_rules: [], rule_stats: emptyRuleStats(), required_rule_checks: [], rule_check_obligation: RULE_CHECK_OBLIGATION,
2231
- ...bindings.fields,
2232
- outline: sections.map(({ text: _text, ...metadata }) => metadata), resources,
2233
- ...(!params.body && !selected.length ? { content_notice: contentNotice } : {}),
2234
- drill_in: {
2235
- sections: sections.map(section => `${command} --section ${quote(section.heading)}`),
2236
- rules: `${command} --rules`, rule_bodies: `${command} --rules --with-rule-bodies`,
2237
- resources: `${command} --resources`, resource: resources.map(resource => `${command} --resource ${quote(resource.path)}`),
2238
- body: `${command} --body`,
2239
- },
2240
- ...extra,
2241
- ...(params.body || selected.length ? { content: params.body ? source : selected.join('\n') } : {}),
2242
- ...(resource ? { resource: { ...resource, body: resourceBody } } : {}),
2243
- };
2244
- if (params.json) {
2245
- console.log(JSON.stringify(card, null, 2));
2246
- return;
2247
- }
2248
- if ('content' in card) {
2249
- if (extra.hint)
2250
- process.stdout.write(`<!-- AIWG: ${card.installed ? 'installed bundle artifact — not in the selected index.' : 'corpus-only artifact — not in the indexed workspace.'}\n ${extra.hint}\n Origin: ${filePath}\n-->\n\n`);
2251
- if (entry.script)
2252
- process.stdout.write(`<!-- AIWG: executable skill — run via: ${buildRunHint(entry)} -->\n`);
2253
- if (pinNote)
2254
- process.stdout.write(`${pinNote}\n`);
2255
- process.stdout.write(card.content);
2256
- if (!card.content.endsWith('\n'))
2257
- process.stdout.write('\n');
2258
- if (bindings.text)
2259
- process.stdout.write(bindings.text);
2260
- return;
2261
- }
2262
- const lines = [`# ${card.type}: ${card.name}`, `ID: ${card.id}`, card.description,
2263
- `Owner: ${card.capability ? `${card.capability.kind}:${card.capability.name}` : 'project/unowned'} | installed: ${card.installed}`, statsText(card.rule_stats)];
2264
- if (pinNote)
2265
- lines.push(pinNote);
2266
- if ('activation' in card)
2267
- lines.push(`Activation: ${card.activation} | enforcement: ${card.enforcement}`, `Bound targets: ${JSON.stringify(card.bound_to)}`);
2268
- lines.push(contentNotice, bindings.text || RULE_CHECK_OBLIGATION, '\n## Outline', ...card.outline.map(section => `- ${section.heading} (${section.bytes} bytes, ${section.lines} lines)`), '\n## Resources', ...resources.map(resource => `- ${resource.path} (${resource.bytes} bytes)`), '\n## Drill in', ...Object.values(card.drill_in).flat().map(command => `- ${command}`));
2269
- if (card.resource)
2270
- lines.push(`\n## Resource: ${card.resource.path}`, card.resource.body);
2271
- console.log(lines.join('\n'));
2272
- }
2273
- /**
2274
- * Emit a metadata card, with opt-in body/section drill-ins for a
2275
- * SKILL.md. Consumers don't need to know where AIWG stores skills —
2276
- * they pass the skill name and the CLI reads the file from the indexed
2277
- * location.
2278
- *
2279
- * Lookup order:
2280
- * 1. Stable discover/Fortemi id
2281
- * 2. Exact path match against any indexed entry's stored path
2282
- * 3. Basename match (e.g. `intake-wizard` matches an entry whose
2283
- * directory basename is `intake-wizard`)
2284
- * 4. Title match (case-insensitive)
2285
- * 5. Corpus fallback under AIWG_ROOT (#1221)
2286
- *
2287
- * On ambiguity, lists all matches and exits with code 2 unless
2288
- * `--first` is supplied.
2289
- */
2290
- export async function showArtifact(cwd, params) {
2291
- loadGlobalGraphConfigs();
2292
- const { promises: fs } = await import('node:fs');
2293
- const types = params.typeFilter && params.typeFilter.length > 0
2294
- ? params.typeFilter
2295
- : [...OPERATIONAL_SHOW_TYPES];
2296
- const { entries, aiwgRoot, resourceSource, webRelease, relations, } = await loadShowEntries(cwd, params, true);
2297
- if (entries.length === 0 && !relations && params.backend !== 'fortemi-core') {
2298
- console.error('Error: No artifact index found.');
2299
- console.error('Run `aiwg index build --graph framework` (or `aiwg use <framework>`) first.');
2300
- process.exit(1);
2301
- }
2302
- const needle = params.name.trim();
2303
- let matches = findShowMatches(entries, types, needle);
2304
- if (matches.length === 0) {
2305
- // Corpus fallback (#1221): when the artifact isn't in any indexed graph,
2306
- // scan the AIWG_ROOT corpus for a likely match and render it with an
2307
- // installation-aware banner. This keeps `aiwg show` useful in workspaces
2308
- // where the operator hasn't run `aiwg use` yet, or where the framework
2309
- // index is stale, rather than exiting with a misleading "not found".
2310
- if (resourceSource === 'local' && aiwgRoot && params.backend !== 'fortemi-core') {
2311
- const corpusMatch = await findCorpusArtifact(aiwgRoot, needle, types);
2312
- if (corpusMatch) {
2313
- let content;
2314
- try {
2315
- content = await fs.readFile(corpusMatch.path, 'utf8');
2316
- }
2317
- catch (err) {
2318
- const e = err;
2319
- console.error(`Error reading ${corpusMatch.path}: ${e.message ?? String(err)}`);
2320
- process.exit(1);
2321
- }
2322
- const localPin = corpusMatch.type === 'rule' ? (await import('../rules/pin-state.js')).rulePinState(cwd, aiwgRoot).rules.find(rule => rule.path === corpusMatch.path) : undefined;
2323
- const installed = await isCorpusBundleInstalled(cwd, aiwgRoot, corpusMatch.bundleKind, corpusMatch.bundleId);
2324
- const installHint = installed
2325
- ? 'The installed bundle is missing from this index. Run `aiwg index build --graph framework` to refresh it.'
2326
- : corpusMatch.bundleKind && corpusMatch.bundleId
2327
- ? `Run \`aiwg use ${corpusMatch.bundleId}\` to install this ${corpusMatch.bundleKind} into the workspace.`
2328
- : 'Run `aiwg index build --graph framework` to refresh the artifact index.';
2329
- const fallbackEntry = { path: path.relative(aiwgRoot, corpusMatch.path), type: corpusMatch.type, name: needle, title: needle };
2330
- const bindings = await showBindings(entries, fallbackEntry, content, params, rule => fs.readFile(resolveMetadataPath(cwd, aiwgRoot, rule), 'utf8'), relations);
2331
- await emitShowCard(cwd, aiwgRoot, fallbackEntry, corpusMatch.path, content, params, bindings, { uninstalled: !installed, installed, hint: installHint,
2332
- ...(localPin ? { local_pin: localPin } : {}) }, true);
2333
- return;
2334
- }
2335
- }
2336
- console.error(`Error: no artifact found matching "${needle}".`);
2337
- console.error('Try `aiwg discover "<phrase>"` to find the right name.');
2338
- process.exit(1);
2339
- }
2340
- // Resolve relative framework-graph paths to absolute paths.
2341
- // Kernel entries are anchored the same way as non-kernel framework entries
2342
- // (#1230) — show reads the source corpus, not platform deploy mirrors.
2343
- const resolvePath = (entry) => resourceSource === 'web'
2344
- ? `raw/${normalizeIndexedPath(entry.path)}`
2345
- : resolveMetadataPath(cwd, aiwgRoot, entry);
2346
- if (matches.length > 1 && !params.first) {
2347
- if (params.json) {
2348
- console.log(JSON.stringify({
2349
- ambiguous: true,
2350
- name: needle,
2351
- matches: matches.map(e => ({
2352
- id: discoveryIdForEntry(e),
2353
- path: resolvePath(e),
2354
- type: e.type,
2355
- name: e.name,
2356
- title: e.title,
2357
- kernel: e.kernel ?? false,
2358
- provenance: {
2359
- graph: e.indexGraph ?? null,
2360
- scope: e.indexScope ?? null,
2361
- ...(webRelease
2362
- ? {
2363
- resource_source: 'web',
2364
- aiwg_selector: webRelease.selector,
2365
- aiwg_version: webRelease.version,
2366
- manifest_sha256: webRelease.manifestDigest,
2367
- manifest_url: webRelease.manifestUrl,
2368
- }
2369
- : {}),
2370
- },
2371
- })),
2372
- }, null, 2));
2373
- }
2374
- else {
2375
- console.error(`Ambiguous: "${needle}" matches ${matches.length} artifacts. Disambiguate with --type or pass the stable id:`);
2376
- for (const e of matches) {
2377
- console.error(` ${e.type.padEnd(7)} ${discoveryIdForEntry(e)} ${e.title}`);
2378
- }
2379
- console.error('');
2380
- console.error('Re-run with `--first` to pick the top match, `--type skill` to filter, or `aiwg show metadata <id>` for paths.');
2381
- }
2382
- process.exit(2);
2383
- }
2384
- const entry = matches[0];
2385
- const filePath = resolvePath(entry);
2386
- let content;
2387
- if (resourceSource === 'web') {
2388
- try {
2389
- if (!webRelease)
2390
- throw new Error('verified web release context is unavailable');
2391
- const { logicalIdFromFirstPartyPath, resolveAiwgResourceBytes } = await import('../resources/resolver.js');
2392
- const logicalId = logicalIdFromFirstPartyPath(entry.path);
2393
- if (!logicalId)
2394
- throw new Error(`indexed path is not a first-party AIWG resource: ${entry.path}`);
2395
- const resolved = await resolveAiwgResourceBytes(logicalId, {
2396
- source: 'web',
2397
- frameworkRoot: aiwgRoot ?? cwd,
2398
- webRelease,
2399
- webReleaseOptions: params.webReleaseOptions,
2400
- offline: params.offline,
2401
- });
2402
- content = resolved.bytes.toString('utf8');
2403
- }
2404
- catch (error) {
2405
- console.error(`Error: AIWG web resource show failed: ${error instanceof Error ? error.message : String(error)}`);
2406
- process.exit(1);
2407
- }
2408
- }
2409
- else {
2410
- try {
2411
- content = await fs.readFile(filePath, 'utf8');
2412
- }
2413
- catch (err) {
2414
- const e = err;
2415
- console.error(`Error reading ${filePath}: ${e.message ?? String(err)}`);
2416
- process.exit(1);
2417
- }
2418
- }
2419
- const localPin = entry.type === 'rule' ? (await import('../rules/pin-state.js')).rulePinState(cwd, aiwgRoot ?? cwd).rules.find(rule => rule.path === filePath) : undefined;
2420
- const bindings = await showBindings(entries, entry, content, params, async (rule) => {
2421
- if (resourceSource === 'local')
2422
- return fs.readFile(resolvePath(rule), 'utf8');
2423
- const { logicalIdFromFirstPartyPath, resolveAiwgResourceBytes } = await import('../resources/resolver.js');
2424
- const logicalId = logicalIdFromFirstPartyPath(rule.path);
2425
- if (!logicalId || !webRelease)
2426
- throw new Error(`Cannot resolve bound rule: ${rule.path}`);
2427
- const resolved = await resolveAiwgResourceBytes(logicalId, {
2428
- source: 'web', frameworkRoot: aiwgRoot ?? cwd, webRelease,
2429
- webReleaseOptions: params.webReleaseOptions, offline: params.offline,
2430
- });
2431
- return resolved.bytes.toString('utf8');
2432
- }, relations);
2433
- const providerModels = resourceSource === 'local' ? await loadProviderModelMetadata(cwd, aiwgRoot) : null;
2434
- await emitShowCard(cwd, aiwgRoot, entry, filePath, content, params, bindings, {
2435
- provenance: {
2436
- graph: entry.indexGraph ?? null,
2437
- scope: entry.indexScope ?? null,
2438
- ...(webRelease ? { resource_source: 'web', aiwg_selector: webRelease.selector, aiwg_version: webRelease.version,
2439
- manifest_sha256: webRelease.manifestDigest, manifest_url: webRelease.manifestUrl } : {}),
2440
- },
2441
- ...(entry.script ? { executable: true, run_hint: buildRunHint(entry) } : {}),
2442
- ...(providerModels ? { providerModels } : {}),
2443
- ...(localPin ? { local_pin: localPin } : {}),
2444
- }, resourceSource === 'local', webRelease);
2445
- }
2446
- export async function showMetadata(cwd, params) {
2447
- loadGlobalGraphConfigs();
2448
- const types = params.typeFilter && params.typeFilter.length > 0
2449
- ? params.typeFilter
2450
- : [...OPERATIONAL_SHOW_TYPES];
2451
- const { entries, aiwgRoot, resourceSource, webRelease, sourcePaths, } = await loadShowEntries(cwd, params);
2452
- if (entries.length === 0 && params.backend !== 'fortemi-core') {
2453
- console.error('Error: No artifact index found.');
2454
- console.error('Run `aiwg index build --graph framework` (or `aiwg use <framework>`) first.');
2455
- process.exit(1);
2456
- }
2457
- const needle = params.name.trim();
2458
- const matches = findShowMatches(entries, types, needle);
2459
- if (matches.length === 0) {
2460
- console.error(`Error: no artifact metadata found matching "${needle}".`);
2461
- console.error('Try `aiwg discover "<phrase>" --json` to find the stable id.');
2462
- process.exit(1);
2463
- }
2464
- const resolvePath = (entry) => resourceSource === 'web'
2465
- ? `raw/${normalizeIndexedPath(entry.path)}`
2466
- : resolveMetadataPath(cwd, aiwgRoot, entry);
2467
- if (matches.length > 1 && !params.first) {
2468
- if (params.json) {
2469
- console.log(JSON.stringify({
2470
- ambiguous: true,
2471
- name: needle,
2472
- matches: matches.map((entry) => ({
2473
- id: discoveryIdForEntry(entry),
2474
- type: entry.type,
2475
- name: entry.name,
2476
- title: entry.title,
2477
- provenance: {
2478
- graph: entry.indexGraph ?? null,
2479
- scope: entry.indexScope ?? null,
2480
- ...(webRelease
2481
- ? {
2482
- resource_source: 'web',
2483
- aiwg_selector: webRelease.selector,
2484
- aiwg_version: webRelease.version,
2485
- manifest_sha256: webRelease.manifestDigest,
2486
- manifest_url: webRelease.manifestUrl,
2487
- }
2488
- : {}),
2489
- },
2490
- })),
2491
- }, null, 2));
2492
- }
2493
- else {
2494
- console.error(`Ambiguous: "${needle}" matches ${matches.length} artifacts. Disambiguate with the stable id:`);
2495
- for (const entry of matches) {
2496
- console.error(` ${entry.type.padEnd(7)} ${discoveryIdForEntry(entry)} ${entry.title}`);
2497
- }
2498
- }
2499
- process.exit(2);
2500
- }
2501
- const entry = matches[0];
2502
- const absolutePath = resolvePath(entry);
2503
- const backend = params.backend ?? DEFAULT_ARTIFACT_SEARCH_BACKEND;
2504
- const record = backend === 'fortemi-core'
2505
- ? await fortemiRecordForEntry(cwd, entry, sourcePaths)
2506
- : null;
2507
- const payload = {
2508
- id: discoveryIdForEntry(entry),
2509
- backend,
2510
- type: entry.type,
2511
- name: entry.name,
2512
- title: entry.title,
2513
- paths: {
2514
- absolute: absolutePath,
2515
- indexed: entry.path,
2516
- repo_relative: record?.source.repo_relative_path ?? entry.path,
2517
- locator: record?.source.locator ?? entry.name ?? entry.title,
2518
- },
2519
- provenance: {
2520
- graph: entry.indexGraph ?? null,
2521
- scope: entry.indexScope ?? null,
2522
- ...(webRelease
2523
- ? {
2524
- resource_source: 'web',
2525
- aiwg_selector: webRelease.selector,
2526
- aiwg_version: webRelease.version,
2527
- manifest_sha256: webRelease.manifestDigest,
2528
- manifest_url: webRelease.manifestUrl,
2529
- }
2530
- : {}),
2531
- },
2532
- metadata: record ?? entry,
2533
- providerModels: resourceSource === 'local'
2534
- ? await loadProviderModelMetadata(cwd, aiwgRoot)
2535
- : null,
2536
- };
2537
- if (params.json) {
2538
- console.log(JSON.stringify(payload, null, 2));
2539
- return;
2540
- }
2541
- console.log(`${payload.type} ${payload.title}`);
2542
- console.log(` id: ${payload.id}`);
2543
- if (payload.name)
2544
- console.log(` name: ${payload.name}`);
2545
- console.log(` graph: ${payload.provenance.graph ?? 'unknown'}`);
2546
- console.log(` scope: ${payload.provenance.scope ?? 'unknown'}`);
2547
- console.log(` path: ${payload.paths.absolute}`);
2548
- console.log(` indexed_path: ${payload.paths.indexed}`);
2549
- if (payload.providerModels) {
2550
- console.log(' provider_models:');
2551
- for (const [provider, hints] of Object.entries(payload.providerModels.providers)) {
2552
- console.log(` ${provider}:`);
2553
- for (const hint of hints) {
2554
- console.log(` ${hint.role}: ${hint.model} (wrapper: ${hint.wrapper}, status: ${hint.status})`);
2555
- }
2556
- }
2557
- }
2558
- console.log('');
2559
- console.log(JSON.stringify(payload.metadata, null, 2));
2560
- }
2561
- function isTopLevelPersonaAgentPath(entryPath) {
2562
- return /(^|[/\\])agentic[/\\]code[/\\]agents[/\\]personas[/\\][^/\\]+\.md$/.test(entryPath);
2563
- }
2564
- function isCanonicalBundleAgentPath(entryPath) {
2565
- return /(^|[/\\])agentic[/\\]code[/\\](?:frameworks|addons|extensions|plugins)[/\\][^/\\]+[/\\]agents[/\\][^/\\]+\.md$/.test(entryPath);
2566
- }
2567
- function isCanonicalSourceAgentPath(entryPath) {
2568
- return /(^|[/\\])agentic[/\\]code[/\\](?:frameworks|addons|extensions)[/\\][^/\\]+[/\\]agents[/\\][^/\\]+\.md$/.test(entryPath);
2569
- }
2570
- function isFrameworkSourceSkillPath(entryPath) {
2571
- return /(^|[/\\])agentic[/\\]code[/\\]frameworks[/\\][^/\\]+[/\\]skills[/\\][^/\\]+[/\\]SKILL\.md$/.test(entryPath);
2572
- }
2573
- function isCanonicalSourceSkillPath(entryPath) {
2574
- return /(^|[/\\])agentic[/\\]code[/\\](?:frameworks|addons|extensions)[/\\][^/\\]+[/\\]skills[/\\][^/\\]+[/\\]SKILL\.md$/.test(entryPath);
2575
- }
2576
- function uniqueEntriesByPath(entries) {
2577
- const seen = new Set();
2578
- const unique = [];
2579
- for (const entry of entries) {
2580
- if (seen.has(entry.path))
2581
- continue;
2582
- seen.add(entry.path);
2583
- unique.push(entry);
2584
- }
2585
- return unique;
2586
- }
11
+ export { isOrdinaryMemoryEntry, compareDiscoverResults } from './query-engine-entries.js';
12
+ export { queryIndex } from './query-engine-index.js';
13
+ export { discoverCapability } from './query-engine-discover.js';
14
+ export { loadLocalCapabilityEntries, loadLocalOverrideCapabilityEntries } from './query-engine-show-load.js';
15
+ export { createRuleBindingTargetResolver, resolveRuleBindingTarget } from './query-engine-matching.js';
16
+ export { rulesBoundTo, relationshipRules, RULE_CHECK_OBLIGATION, compoundGoverningRules, governingRuleStats, governingRuleFields, relationshipRuleStats, } from './query-engine-rules.js';
17
+ export { showArtifact, showMetadata } from './query-engine-show.js';
2587
18
  //# sourceMappingURL=query-engine.js.map