@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
@@ -0,0 +1,249 @@
1
+ // Search artifact indexes and emit ranked query results.
2
+ import { minimatch } from 'minimatch';
3
+ import * as fs from 'node:fs';
4
+ import * as path from 'node:path';
5
+ import { projectAiwgPath } from '../config/project-artifacts.js';
6
+ import { bm25Rank } from './fulltext.js';
7
+ import { parseFrontmatter } from './index-builder.js';
8
+ import { loadGraphIndexFile, loadMetadataIndex } from './index-reader.js';
9
+ import { operationalStateQueryProjection } from './operational-state.js';
10
+ import { compareDiscoverResults, DEFAULT_ARTIFACT_SEARCH_BACKEND, isOrdinaryMemoryEntry, normalizeIndexedPath, } from './query-engine-entries.js';
11
+ import { scoreEntry } from './query-engine-scoring.js';
12
+ /**
13
+ * Resolve an index entry's source file path and read its body (frontmatter
14
+ * stripped). Entry paths are normally relative to the project; framework-graph
15
+ * entries may be absolute or anchored to $AIWG_ROOT. Returns null when the
16
+ * file can't be read (stale index entry) so full-text ranking skips it.
17
+ */
18
+ export function readEntryBody(cwd, entryPath) {
19
+ const candidates = [];
20
+ if (path.isAbsolute(entryPath))
21
+ candidates.push(entryPath);
22
+ else {
23
+ const normalizedPath = normalizeIndexedPath(entryPath);
24
+ if (normalizedPath.startsWith('.aiwg/')) {
25
+ candidates.push(projectAiwgPath(cwd, normalizedPath.slice('.aiwg/'.length)));
26
+ }
27
+ candidates.push(path.resolve(cwd, normalizedPath));
28
+ if (process.env.AIWG_ROOT)
29
+ candidates.push(path.resolve(process.env.AIWG_ROOT, normalizedPath));
30
+ }
31
+ for (const p of candidates) {
32
+ try {
33
+ const raw = fs.readFileSync(p, 'utf8');
34
+ return parseFrontmatter(raw).body;
35
+ }
36
+ catch {
37
+ /* try next candidate */
38
+ }
39
+ }
40
+ return null;
41
+ }
42
+ /**
43
+ * Query the artifact index
44
+ */
45
+ export async function queryIndex(cwd, params, options = {}) {
46
+ const { graph } = options;
47
+ const backend = options.backend ?? DEFAULT_ARTIFACT_SEARCH_BACKEND;
48
+ const startTime = Date.now();
49
+ let candidates;
50
+ if (backend === 'fortemi-core') {
51
+ const { loadFortemiCoreMetadataEntries } = await import('./fortemi-core-query-adapter.js');
52
+ const loaded = loadFortemiCoreMetadataEntries(cwd, graph ?? 'project');
53
+ if (loaded.reason) {
54
+ if (options.json) {
55
+ console.log(JSON.stringify({
56
+ query: { text: params.text, backend: 'fortemi-core', graph: graph ?? 'project' },
57
+ results: [],
58
+ total: 0,
59
+ hint: loaded.reason ?? 'Fortemi Core static index is unavailable.',
60
+ }, null, 2));
61
+ }
62
+ else {
63
+ console.error('Error: ' + (loaded.reason ?? 'Fortemi Core static index is unavailable.'));
64
+ }
65
+ process.exit(1);
66
+ }
67
+ candidates = loaded.entries;
68
+ }
69
+ else if (graph) {
70
+ // Single graph mode
71
+ const index = loadGraphIndexFile(cwd, 'metadata.json', graph);
72
+ if (!index) {
73
+ console.error(`Error: No artifact index found for graph '${graph}'.`);
74
+ console.log("Run 'aiwg index build' first to create the index.");
75
+ process.exit(1);
76
+ }
77
+ candidates = Object.values(index.entries);
78
+ }
79
+ else {
80
+ // No graph specified: search across all project-local graphs
81
+ const graphTypes = ['project', 'codebase'];
82
+ const allEntries = [];
83
+ for (const g of graphTypes) {
84
+ const idx = loadGraphIndexFile(cwd, 'metadata.json', g);
85
+ if (idx)
86
+ allEntries.push(...Object.values(idx.entries));
87
+ }
88
+ // Fall back to legacy root index
89
+ if (allEntries.length === 0) {
90
+ const legacy = loadMetadataIndex(cwd);
91
+ if (!legacy) {
92
+ console.error('Error: No artifact index found.');
93
+ console.log("Run 'aiwg index build' first to create the index.");
94
+ process.exit(1);
95
+ }
96
+ allEntries.push(...Object.values(legacy.entries));
97
+ }
98
+ candidates = allEntries;
99
+ }
100
+ // Retained tombstones are history, never ordinary retrieval results.
101
+ candidates = candidates.filter(entry => isOrdinaryMemoryEntry(entry, cwd));
102
+ // Apply filters
103
+ if (params.type) {
104
+ candidates = candidates.filter(e => e.type === params.type);
105
+ }
106
+ if (params.phase) {
107
+ candidates = candidates.filter(e => e.phase === params.phase);
108
+ }
109
+ if (params.tags && params.tags.length > 0) {
110
+ candidates = candidates.filter(e => params.tags.every(tag => e.tags.includes(tag)));
111
+ }
112
+ if (params.path) {
113
+ candidates = candidates.filter(e => minimatch(e.path, params.path));
114
+ }
115
+ if (params.updatedAfter) {
116
+ const cutoff = new Date(params.updatedAfter).getTime();
117
+ candidates = candidates.filter(e => new Date(e.updated).getTime() >= cutoff);
118
+ }
119
+ // Score and rank
120
+ let results;
121
+ const matchedById = new Map();
122
+ const operationalStateById = new Map();
123
+ if (params.text && params.fulltext && backend === 'fortemi-core') {
124
+ const { queryFortemiCoreStaticFulltextIndex } = await import('./fortemi-core-query-adapter.js');
125
+ const queried = queryFortemiCoreStaticFulltextIndex(cwd, {
126
+ graph: graph ?? 'project',
127
+ text: params.text,
128
+ limit: params.limit ?? 20,
129
+ path: params.path,
130
+ type: params.type,
131
+ phase: params.phase,
132
+ tags: params.tags,
133
+ });
134
+ if (queried.reason) {
135
+ if (options.json) {
136
+ console.log(JSON.stringify({
137
+ query: { text: params.text, backend: 'fortemi-core', graph: graph ?? 'project' },
138
+ mode: 'fulltext',
139
+ results: [],
140
+ total: 0,
141
+ hint: queried.reason,
142
+ }, null, 2));
143
+ }
144
+ else {
145
+ console.error('Error: ' + queried.reason);
146
+ }
147
+ process.exit(1);
148
+ }
149
+ const candidateByPath = new Map(candidates.map(entry => [entry.path, entry]));
150
+ results = queried.results.filter(result => candidateByPath.has(result.path)).map(result => {
151
+ const entry = {
152
+ ...(candidateByPath.get(result.path)?.memoryRecord ? { memoryRecord: candidateByPath.get(result.path).memoryRecord } : {}),
153
+ path: result.path,
154
+ type: result.type,
155
+ phase: result.phase,
156
+ title: result.title,
157
+ tags: result.tags,
158
+ created: '',
159
+ updated: '',
160
+ checksum: '',
161
+ summary: result.summary,
162
+ dependencies: [],
163
+ dependents: [],
164
+ };
165
+ matchedById.set(result.path, result.matched);
166
+ if (result.operational_state) {
167
+ operationalStateById.set(result.path, result.operational_state);
168
+ }
169
+ return { entry, score: result.score };
170
+ });
171
+ }
172
+ else if (params.text && params.fulltext) {
173
+ // Lexical full-text (#1494): read candidate bodies and BM25-rank. The
174
+ // index is the candidate set; ranking is over actual body content, not
175
+ // the metadata/summary the default path scores.
176
+ const byPath = new Map();
177
+ const docs = [];
178
+ for (const entry of candidates) {
179
+ const body = readEntryBody(cwd, entry.path);
180
+ if (body === null)
181
+ continue;
182
+ byPath.set(entry.path, entry);
183
+ docs.push({ id: entry.path, text: body });
184
+ }
185
+ const hits = bm25Rank(docs, params.text);
186
+ results = hits
187
+ .map(h => {
188
+ matchedById.set(h.id, h.matchedTerms);
189
+ return { entry: byPath.get(h.id), score: h.score };
190
+ })
191
+ .filter(r => r.entry);
192
+ }
193
+ else if (params.text) {
194
+ results = candidates
195
+ .map(entry => ({ entry, score: scoreEntry(entry, params.text) }))
196
+ .filter(r => r.score > 0)
197
+ .sort(compareDiscoverResults);
198
+ }
199
+ else {
200
+ // No keyword — return all filtered results with score 1.0
201
+ results = candidates.map(entry => ({ entry, score: 1.0 }));
202
+ }
203
+ // Apply limit
204
+ const limit = params.limit ?? 20;
205
+ results = results.filter(result => isOrdinaryMemoryEntry(result.entry, cwd)).slice(0, limit);
206
+ const queryTimeMs = Date.now() - startTime;
207
+ // Output
208
+ if (options.json) {
209
+ console.log(JSON.stringify({
210
+ query: { text: params.text, filters: { type: params.type, phase: params.phase, tags: params.tags, path: params.path }, backend },
211
+ mode: params.fulltext ? 'fulltext' : 'metadata',
212
+ results: results.map(r => ({
213
+ path: r.entry.path,
214
+ type: r.entry.type,
215
+ phase: r.entry.phase,
216
+ title: r.entry.title,
217
+ score: Math.round(r.score * 100) / 100,
218
+ summary: r.entry.summary,
219
+ ...(operationalStateById.has(r.entry.path)
220
+ ? { operational_state: operationalStateById.get(r.entry.path) }
221
+ : r.entry.operationalState
222
+ ? { operational_state: operationalStateQueryProjection(r.entry.operationalState) }
223
+ : {}),
224
+ ...(params.fulltext ? { matched: matchedById.get(r.entry.path) ?? [] } : {}),
225
+ })),
226
+ total: results.length,
227
+ query_time_ms: queryTimeMs,
228
+ }, null, 2));
229
+ }
230
+ else {
231
+ const queryDesc = params.text ? `"${params.text}"` : 'all';
232
+ console.log(`Results for ${queryDesc} (${results.length} matches, ${queryTimeMs}ms):`);
233
+ console.log('');
234
+ console.log(' # Score Type Phase Path');
235
+ for (let i = 0; i < results.length; i++) {
236
+ const r = results[i];
237
+ const num = String(i + 1).padStart(3);
238
+ const score = r.score.toFixed(2).padStart(4);
239
+ const type = r.entry.type.padEnd(12).slice(0, 12);
240
+ const phase = r.entry.phase.padEnd(14).slice(0, 14);
241
+ console.log(` ${num} ${score} ${type} ${phase} ${r.entry.path}`);
242
+ }
243
+ if (results.length === 0) {
244
+ console.log(' No results found.');
245
+ }
246
+ console.log('');
247
+ }
248
+ }
249
+ //# sourceMappingURL=query-engine-index.js.map
@@ -0,0 +1,143 @@
1
+ // Resolve show matches and exact rule-binding target identities.
2
+ import * as path from 'node:path';
3
+ import { preferCanonicalBindingTargets, selectBindingTargetIdentities, } from './binding-target-identity.js';
4
+ import { discoveryIdForEntry, normalizeIndexedPath, scopeRank } from './query-engine-entries.js';
5
+ export function findShowMatches(entries, types, needle) {
6
+ const needleLower = needle.toLowerCase();
7
+ const normalizedNeedle = normalizeIndexedPath(needle);
8
+ const candidates = entries.filter(e => types.includes(e.type));
9
+ let matches = needle.startsWith('aiwg:') ? candidates.filter(e => discoveryIdForEntry(e) === needle) : [];
10
+ if (matches.length === 0) {
11
+ matches = candidates.filter(e => e.path === needle || normalizeIndexedPath(e.path) === normalizedNeedle);
12
+ }
13
+ if (matches.length === 0) {
14
+ matches = candidates.filter(e => {
15
+ const normalizedPath = normalizeIndexedPath(e.path);
16
+ const dirStem = path.basename(path.dirname(normalizedPath));
17
+ const basename = path.basename(normalizedPath);
18
+ const fileStem = basename.replace(/\.[^.]+$/, '');
19
+ const slugLayoutMatch = ((basename === 'SKILL.md' && e.type === 'skill') ||
20
+ (basename === 'BEHAVIOR.md' && e.type === 'behavior')) &&
21
+ dirStem === needle;
22
+ if (slugLayoutMatch || fileStem === needle || e.name === needle)
23
+ return true;
24
+ if (e.type === 'gate-pack' && typeof e.name === 'string') {
25
+ const gateStem = fileStem.replace(/\.gatepack$/i, '');
26
+ const rest = e.name.includes(':') ? e.name.slice(e.name.indexOf(':') + 1) : e.name;
27
+ const short = rest.includes('/') ? rest.slice(rest.indexOf('/') + 1) : rest;
28
+ return gateStem === needle || rest === needle || short === needle;
29
+ }
30
+ return false;
31
+ });
32
+ }
33
+ if (matches.length === 0) {
34
+ matches = candidates.filter(e => typeof e.title === 'string' && e.title.toLowerCase() === needleLower);
35
+ }
36
+ matches = uniqueEntriesByPath(matches);
37
+ matches = matches.sort((a, b) => scopeRank(a) - scopeRank(b) || a.path.localeCompare(b.path));
38
+ if (matches.length > 1) {
39
+ const sameIdentity = matches.every((entry) => entry.type === matches[0].type &&
40
+ (entry.name ?? '').toLowerCase() === (matches[0].name ?? '').toLowerCase());
41
+ if (sameIdentity && scopeRank(matches[0]) < scopeRank(matches[1])) {
42
+ matches = [matches[0]];
43
+ }
44
+ }
45
+ if (matches.length > 1 && types.includes('skill')) {
46
+ const frameworkSkillMatches = matches.filter(e => isFrameworkSourceSkillPath(e.path));
47
+ if (frameworkSkillMatches.length === 1)
48
+ matches = frameworkSkillMatches;
49
+ }
50
+ if (matches.length > 1 && types.includes('skill')) {
51
+ const sourceSkillMatches = matches.filter(e => isCanonicalSourceSkillPath(e.path));
52
+ if (sourceSkillMatches.length === 1)
53
+ matches = sourceSkillMatches;
54
+ }
55
+ if (matches.length > 1 && types.includes('agent')) {
56
+ const canonicalSourceMatches = matches.filter(e => isCanonicalSourceAgentPath(e.path));
57
+ if (canonicalSourceMatches.length === 1)
58
+ matches = canonicalSourceMatches;
59
+ }
60
+ if (matches.length > 1 && types.includes('agent')) {
61
+ const canonicalBundleMatches = matches.filter(e => isCanonicalBundleAgentPath(e.path));
62
+ const canonicalBundlePaths = uniqueEntriesByPath(canonicalBundleMatches);
63
+ if (canonicalBundlePaths.length === 1)
64
+ matches = canonicalBundlePaths;
65
+ }
66
+ if (matches.length > 1 && types.includes('agent')) {
67
+ const nonPersonaMatches = matches.filter(e => !isTopLevelPersonaAgentPath(e.path));
68
+ if (nonPersonaMatches.length === 1)
69
+ matches = nonPersonaMatches;
70
+ }
71
+ return matches;
72
+ }
73
+ /** Preselect exact candidates once; the canonical resolver still owns precedence and ambiguity. */
74
+ export function createRuleBindingTargetResolver(entries, options = {}) {
75
+ const candidates = new Map();
76
+ for (const entry of entries) {
77
+ if (!['skill', 'agent', 'flow'].includes(entry.type))
78
+ continue;
79
+ const normalized = normalizeIndexedPath(entry.path);
80
+ const basename = path.posix.basename(normalized);
81
+ const slug = /^(?:SKILL|AGENT|FLOW)\.md$/i.test(basename)
82
+ ? path.posix.basename(path.posix.dirname(normalized))
83
+ : basename.replace(/\.[^.]+$/, '');
84
+ for (const id of new Set([entry.name, discoveryIdForEntry(entry), slug])) {
85
+ if (typeof id !== 'string')
86
+ continue;
87
+ const key = `${entry.type}\0${id}`;
88
+ const selected = candidates.get(key) ?? [];
89
+ selected.push(entry);
90
+ candidates.set(key, selected);
91
+ }
92
+ }
93
+ return (type, id, bundleRoot = options.bundleRoot) => resolveRuleBindingTarget(candidates.get(`${type}\0${id}`) ?? [], type, id, { ...options, bundleRoot });
94
+ }
95
+ /** Resolve exact rule binding IDs using the same precedence and ambiguity as show.
96
+ * Canonical layout slugs remain valid when frontmatter names are display names.
97
+ * Titles and filesystem paths are deliberately excluded (#2938).
98
+ */
99
+ export function resolveRuleBindingTarget(entries, type, id, options = {}) {
100
+ const exact = entries.filter(entry => {
101
+ if (entry.type !== type)
102
+ return false;
103
+ const normalized = normalizeIndexedPath(entry.path);
104
+ const basename = path.posix.basename(normalized);
105
+ const slug = /^(?:SKILL|AGENT|FLOW)\.md$/i.test(basename)
106
+ ? path.posix.basename(path.posix.dirname(normalized))
107
+ : basename.replace(/\.[^.]+$/, '');
108
+ return entry.name === id || discoveryIdForEntry(entry) === id || slug === id;
109
+ });
110
+ const matches = preferCanonicalBindingTargets(findShowMatches(selectBindingTargetIdentities(exact, options), [type], id));
111
+ if (matches.length === 0)
112
+ throw new Error(`Missing ${type} binding target: ${id}`);
113
+ if (matches.length > 1)
114
+ throw new Error(`Ambiguous ${type} binding target: ${id}: ${matches.map(entry => entry.path).join(', ')}`);
115
+ return matches[0];
116
+ }
117
+ export function isTopLevelPersonaAgentPath(entryPath) {
118
+ return /(^|[/\\])agentic[/\\]code[/\\]agents[/\\]personas[/\\][^/\\]+\.md$/.test(entryPath);
119
+ }
120
+ export function isCanonicalBundleAgentPath(entryPath) {
121
+ return /(^|[/\\])agentic[/\\]code[/\\](?:frameworks|addons|extensions|plugins)[/\\][^/\\]+[/\\]agents[/\\][^/\\]+\.md$/.test(entryPath);
122
+ }
123
+ export function isCanonicalSourceAgentPath(entryPath) {
124
+ return /(^|[/\\])agentic[/\\]code[/\\](?:frameworks|addons|extensions)[/\\][^/\\]+[/\\]agents[/\\][^/\\]+\.md$/.test(entryPath);
125
+ }
126
+ export function isFrameworkSourceSkillPath(entryPath) {
127
+ return /(^|[/\\])agentic[/\\]code[/\\]frameworks[/\\][^/\\]+[/\\]skills[/\\][^/\\]+[/\\]SKILL\.md$/.test(entryPath);
128
+ }
129
+ export function isCanonicalSourceSkillPath(entryPath) {
130
+ return /(^|[/\\])agentic[/\\]code[/\\](?:frameworks|addons|extensions)[/\\][^/\\]+[/\\]skills[/\\][^/\\]+[/\\]SKILL\.md$/.test(entryPath);
131
+ }
132
+ export function uniqueEntriesByPath(entries) {
133
+ const seen = new Set();
134
+ const unique = [];
135
+ for (const entry of entries) {
136
+ if (seen.has(entry.path))
137
+ continue;
138
+ seen.add(entry.path);
139
+ unique.push(entry);
140
+ }
141
+ return unique;
142
+ }
143
+ //# sourceMappingURL=query-engine-matching.js.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=query-engine-options.js.map
@@ -0,0 +1,202 @@
1
+ // Resolve governing rules and shape bound-rule checks and summaries.
2
+ import { minimatch } from 'minimatch';
3
+ import * as path from 'node:path';
4
+ import { inferRuleActivation } from '../rules/activation.mjs';
5
+ import { parseFrontmatter } from './index-builder.js';
6
+ import { discoveryIdForEntry, normalizeIndexedPath } from './query-engine-entries.js';
7
+ import { emptyRuleStats } from './relations.js';
8
+ /** Build an ephemeral reverse lookup from the already-loaded rule metadata. */
9
+ export function rulesBoundTo(entries, target) {
10
+ const key = { skill: 'skills', agent: 'agents', flow: 'flows' }[target.type];
11
+ if (!key)
12
+ return [];
13
+ const file = path.basename(normalizeIndexedPath(target.path));
14
+ const aliases = [target.name, target.title, target.path, discoveryIdForEntry(target),
15
+ file === 'SKILL.md' ? path.basename(path.dirname(normalizeIndexedPath(target.path))) : file.replace(/\.[^.]+$/, '')]
16
+ .filter((alias) => !!alias);
17
+ const seen = new Set();
18
+ return entries.filter(rule => {
19
+ if (rule.type !== 'rule' && rule.type !== 'behavior')
20
+ return false;
21
+ const patterns = rule.bound_to?.[key];
22
+ if (!Array.isArray(patterns) || !patterns.some(pattern => typeof pattern === 'string'
23
+ && aliases.some(alias => alias === pattern || minimatch(alias, pattern, { nonegate: true, nocomment: true }))))
24
+ return false;
25
+ const identity = `${rule.type}:${rule.path}`;
26
+ if (seen.has(identity))
27
+ return false;
28
+ seen.add(identity);
29
+ return true;
30
+ }).sort((a, b) => (a.name ?? a.path).localeCompare(b.name ?? b.path) || a.path.localeCompare(b.path));
31
+ }
32
+ /** Relationship metadata for shipped targets, merged with project/user contracts. */
33
+ export function relationshipRules(entries, target, relations) {
34
+ const local = rulesBoundTo(relations ? entries.filter(entry => !normalizeIndexedPath(entry.path).startsWith('agentic/code/')) : entries, target);
35
+ if (!relations || !['skill', 'agent', 'flow', 'command'].includes(target.type))
36
+ return local;
37
+ const asMetadata = (id) => {
38
+ const rule = relations.index.rules[id];
39
+ return { path: rule.path, type: rule.type, name: rule.name, activation: rule.activation ?? undefined,
40
+ bound_to: rule.bound_to, ruleSummary: rule.summary, ruleEnforcement: rule.enforcement ?? undefined, rulePaths: rule.paths, triggers: rule.triggers };
41
+ };
42
+ const key = `${target.type}:${discoveryIdForEntry(target)}`;
43
+ const shipped = Object.hasOwn(relations.index.targets, key)
44
+ ? relations.rulesForTarget(target.type, discoveryIdForEntry(target)).map(asMetadata)
45
+ // Project/user overrides keep the old alias/glob behavior using only small records.
46
+ : rulesBoundTo(Object.keys(relations.index.rules).map(asMetadata), target);
47
+ const merged = new Map([...local, ...shipped].map(rule => [`${rule.type}:${rule.path}`, rule]));
48
+ return [...merged.values()].sort((a, b) => (a.name ?? a.path).localeCompare(b.name ?? b.path) || a.path.localeCompare(b.path));
49
+ }
50
+ export const RULE_CHECK_OBLIGATION = 'Before governed work, fetch and follow every required rule below; a discovery summary is not the full rule.';
51
+ export function relationMetadata(relations) {
52
+ return Object.values(relations.index.rules).map(rule => ({ path: rule.path, type: rule.type, name: rule.name,
53
+ activation: rule.activation ?? undefined, ruleSummary: rule.summary, ruleEnforcement: rule.enforcement ?? undefined,
54
+ bound_to: rule.bound_to, rulePaths: rule.paths, triggers: rule.triggers }));
55
+ }
56
+ /** Post-ranking enrichment: relationship lookup never loads the full metadata index. */
57
+ export function compoundGoverningRules(entries, target, relations, phrase = '', includeMatches = true, excludeKernel = true) {
58
+ if (!['skill', 'agent', 'flow', 'command'].includes(target.type))
59
+ return [];
60
+ const found = new Map();
61
+ const add = (rule, why, binding = false) => {
62
+ const pinned = relations?.pinnedRuleIds.has(discoveryIdForEntry(rule));
63
+ const activation = rule.activation ?? (rule.type === 'behavior' ? 'kernel' : inferRuleActivation(rule.ruleEnforcement));
64
+ // Delivery mode never removes an explicit contract; only ambient matches are filtered.
65
+ if (!binding && excludeKernel && (activation === 'kernel' || activation === 'core' || rule.kernel || pinned))
66
+ return;
67
+ const key = `${rule.type}:${rule.path}`, item = found.get(key) ?? {
68
+ rule: pinned ? { ...rule, activation: 'kernel' } : rule, applicability: [],
69
+ };
70
+ if (!item.applicability.includes(why))
71
+ item.applicability.push(why);
72
+ found.set(key, item);
73
+ };
74
+ for (const rule of relationshipRules(entries, target, relations))
75
+ add(rule, `bound:${target.type}:${discoveryIdForEntry(target)}`, true);
76
+ if (relations && target.type === 'skill' && target.name?.startsWith('projected:')) {
77
+ for (const id of relations.rulesForTarget('skill', target.name)) {
78
+ const rule = relationMetadata(relations).find(rule => discoveryIdForEntry(rule) === id);
79
+ if (rule)
80
+ add(rule, `projected-flow:${target.name.slice('projected:'.length)}`, true);
81
+ }
82
+ }
83
+ if (includeMatches) {
84
+ const query = phrase.toLowerCase();
85
+ const queryPaths = (phrase.replace(/\\/g, '/').match(/[\w@./*?-]+/g) ?? []).map(value => value.replace(/[.,;:!?]+$/, ''));
86
+ const corpus = relations ? relationMetadata(relations) : [];
87
+ const rules = new Map([...corpus, ...entries.filter(entry => ['rule', 'behavior'].includes(entry.type))]
88
+ .map(rule => [`${rule.type}:${rule.path}`, rule]));
89
+ for (const rule of rules.values()) {
90
+ for (const glob of rule.rulePaths ?? [])
91
+ for (const candidate of [...queryPaths.filter(value => /[./*?]/.test(value) || value === glob), ...(target.governedPaths ?? [])]) {
92
+ if (minimatch(candidate, glob, { dot: true, nonegate: true, nocomment: true })
93
+ || ((target.governedPaths ?? []).includes(candidate) && minimatch(glob, candidate, { dot: true, nonegate: true, nocomment: true })))
94
+ add(rule, `path:${candidate}`);
95
+ }
96
+ for (const trigger of rule.triggers ?? []) {
97
+ const normalized = trigger.trim().toLowerCase();
98
+ let offset = normalized ? query.indexOf(normalized) : -1;
99
+ while (offset >= 0) {
100
+ if ((offset === 0 || !/\w/.test(query[offset - 1]))
101
+ && (offset + normalized.length === query.length || !/\w/.test(query[offset + normalized.length]))) {
102
+ add(rule, `trigger:${trigger}`);
103
+ break;
104
+ }
105
+ offset = query.indexOf(normalized, offset + 1);
106
+ }
107
+ }
108
+ }
109
+ }
110
+ 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));
111
+ }
112
+ export function boundRuleDescriptor(rule) {
113
+ return { name: rule.name ?? path.basename(rule.path, '.md'), activation: rule.activation ?? null, enforcement: rule.ruleEnforcement ?? null,
114
+ summary: (rule.ruleSummary ?? '').replace(/\s+/g, ' ').trim(), show_command: `aiwg show ${rule.type} ${rule.name ?? path.basename(rule.path, '.md')} --body` };
115
+ }
116
+ /** Counts unique attached contracts; every emitted check is required irrespective of severity. */
117
+ export function governingRuleStats(governing) {
118
+ const stats = emptyRuleStats();
119
+ for (const { rule } of new Map(governing.map(item => [`${item.rule.type}:${item.rule.path}`, item])).values()) {
120
+ const enforcement = rule.ruleEnforcement?.toLowerCase() ?? 'unknown', activation = rule.activation ?? 'unknown';
121
+ stats.by_enforcement[enforcement] = (stats.by_enforcement[enforcement] ?? 0) + 1;
122
+ stats.by_activation[activation] = (stats.by_activation[activation] ?? 0) + 1;
123
+ stats.required_checks++;
124
+ }
125
+ return stats;
126
+ }
127
+ export function governingRuleFields(governing) {
128
+ if (!governing.length)
129
+ return {};
130
+ return { bound_rules: governing.map(({ rule }) => boundRuleDescriptor(rule)), rule_stats: governingRuleStats(governing),
131
+ required_rule_checks: governing.map(({ rule, applicability }) => ({ rule_id: discoveryIdForEntry(rule),
132
+ applicability, fetch_command: `aiwg show ${rule.type} ${discoveryIdForEntry(rule)} --body` })), rule_check_obligation: RULE_CHECK_OBLIGATION };
133
+ }
134
+ export function statsText(stats) {
135
+ 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`;
136
+ }
137
+ export function relationshipRuleStats(entries, target, relations) {
138
+ const shipped = Object.hasOwn(relations.index.targets, `${target.type}:${discoveryIdForEntry(target)}`);
139
+ const stats = shipped ? relations.ruleStats(target.type, discoveryIdForEntry(target)) : emptyRuleStats();
140
+ // Shipped counts are precomputed; project/user contracts and overrides are overlays.
141
+ const overlay = shipped ? rulesBoundTo(entries.filter(entry => !normalizeIndexedPath(entry.path).startsWith('agentic/code/')), target)
142
+ : relationshipRules(entries, target, relations);
143
+ for (const rule of overlay) {
144
+ const enforcement = rule.ruleEnforcement ?? 'unknown';
145
+ const activation = rule.activation ?? 'unknown';
146
+ stats.by_enforcement[enforcement] = (stats.by_enforcement[enforcement] ?? 0) + 1;
147
+ stats.by_activation[activation] = (stats.by_activation[activation] ?? 0) + 1;
148
+ if (enforcement === 'critical' || enforcement === 'high')
149
+ stats.required_checks++;
150
+ }
151
+ return stats;
152
+ }
153
+ export async function showBindings(entries, target, content, params, read, relations) {
154
+ const governing = compoundGoverningRules(entries, target, relations, '', false, false);
155
+ const rules = governing.map(item => item.rule);
156
+ const boundRules = await Promise.all(rules.map(async (rule) => ({
157
+ ...boundRuleDescriptor(rule),
158
+ ...((params.boundRuleBodies || params.withRuleBodies) ? { content: await read(rule) } : {}),
159
+ })));
160
+ // Parse the selected rule for reverse lookup, including corpus-only rules.
161
+ const targets = target.type === 'rule' || target.type === 'behavior'
162
+ ? parseFrontmatter(content).data.bound_to : undefined;
163
+ const boundTo = targets && typeof targets === 'object' && !Array.isArray(targets)
164
+ ? Object.fromEntries(['skills', 'agents', 'flows'].flatMap(key => {
165
+ const values = targets[key];
166
+ const names = Array.isArray(values) ? [...new Set(values.filter((value) => typeof value === 'string' && !!value.trim()))] : [];
167
+ return names.length ? [[key, names]] : [];
168
+ })) : {};
169
+ const boundTargets = new Map();
170
+ if (target.type === 'rule' || target.type === 'behavior') {
171
+ for (const edge of relations?.targetsForRule(discoveryIdForEntry(target)) ?? []) {
172
+ boundTargets.set(`${edge.type}:${edge.id}`, { ...edge, name: relations?.index.artifacts?.[edge.id]?.name
173
+ ?? relations?.index.targets[`${edge.type}:${edge.id}`]?.name });
174
+ }
175
+ const selectedRule = { ...target, bound_to: boundTo };
176
+ for (const candidate of entries)
177
+ if (rulesBoundTo([selectedRule], candidate).length) {
178
+ const id = discoveryIdForEntry(candidate);
179
+ boundTargets.set(`${candidate.type}:${id}`, { type: candidate.type, id, name: candidate.name });
180
+ }
181
+ }
182
+ let text = '';
183
+ if (boundRules.length) {
184
+ // Cards already print these stats in the header; body/section output has no header.
185
+ const stats = params.body || params.sections?.length ? `${statsText(governingRuleStats(governing))}\n\n` : '';
186
+ 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}\`)`
187
+ + ('content' in rule ? `\n\n${rule.content}` : '')).join('\n') + '\n';
188
+ }
189
+ if (Object.keys(boundTo).length) {
190
+ text += '\n## Bound targets\n\n' + Object.entries(boundTo)
191
+ .map(([key, names]) => `- ${key}: ${names.map(name => `\`${name}\``).join(', ')}`).join('\n') + '\n';
192
+ }
193
+ if (boundTargets.size)
194
+ text += '\nResolved targets: ' + [...boundTargets.values()].map(target => `${target.type} ${target.name ?? target.id}`).join(', ') + '\n';
195
+ return { fields: {
196
+ ...governingRuleFields(governing),
197
+ ...(['rule', 'behavior'].includes(target.type) ? { bound_to: boundTo, bound_targets: [...boundTargets.values()] } : {}),
198
+ ...(boundRules.length ? { bound_rules: boundRules } : {}),
199
+ ...(Object.keys(boundTo).length ? { bound_to: boundTo } : {}),
200
+ }, text };
201
+ }
202
+ //# sourceMappingURL=query-engine-rules.js.map