@aiwg/cli 2026.10.16 → 2026.10.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. package/agentic/code/providers/capability-matrix.yaml +51 -0
  2. package/agentic/code/providers/flue/README.md +62 -0
  3. package/agentic/code/providers/flue/templates/aiwg/tools.ts +120 -0
  4. package/agentic/code/providers/model-capabilities.v1.json +23 -0
  5. package/agentic/code/providers/model-catalog.v1.json +9 -0
  6. package/dist/src/artifacts/corpus-tools/resolve.js +28 -6
  7. package/dist/src/artifacts/query-engine-corpus.js +217 -0
  8. package/dist/src/artifacts/query-engine-discover-output.js +229 -0
  9. package/dist/src/artifacts/query-engine-discover.js +285 -0
  10. package/dist/src/artifacts/query-engine-entries.js +188 -0
  11. package/dist/src/artifacts/query-engine-index.js +249 -0
  12. package/dist/src/artifacts/query-engine-matching.js +143 -0
  13. package/dist/src/artifacts/query-engine-options.js +2 -0
  14. package/dist/src/artifacts/query-engine-rules.js +202 -0
  15. package/dist/src/artifacts/query-engine-scoring.js +436 -0
  16. package/dist/src/artifacts/query-engine-show-card.js +194 -0
  17. package/dist/src/artifacts/query-engine-show-load.js +211 -0
  18. package/dist/src/artifacts/query-engine-show.js +300 -0
  19. package/dist/src/artifacts/query-engine.js +7 -2576
  20. package/dist/src/cli/handlers/help.js +1 -1
  21. package/dist/src/cli/handlers/init.js +1 -0
  22. package/dist/src/cli/handlers/mc-agents.js +111 -0
  23. package/dist/src/cli/handlers/mc-args.js +54 -0
  24. package/dist/src/cli/handlers/mc-control.js +227 -0
  25. package/dist/src/cli/handlers/mc-dispatch.js +203 -0
  26. package/dist/src/cli/handlers/mc-help.js +171 -0
  27. package/dist/src/cli/handlers/mc-run.js +343 -0
  28. package/dist/src/cli/handlers/mc-session.js +138 -0
  29. package/dist/src/cli/handlers/mc-status.js +258 -0
  30. package/dist/src/cli/handlers/mc-summary.js +43 -0
  31. package/dist/src/cli/handlers/mc-types.js +3 -0
  32. package/dist/src/cli/handlers/mc-worker.js +205 -0
  33. package/dist/src/cli/handlers/mc.js +12 -1665
  34. package/dist/src/cli/handlers/models-refusal.js +13 -0
  35. package/dist/src/cli/handlers/models.js +2 -1
  36. package/dist/src/cli/handlers/remove-bundled.js +133 -0
  37. package/dist/src/cli/handlers/remove-options.js +31 -0
  38. package/dist/src/cli/handlers/remove-user.js +174 -0
  39. package/dist/src/cli/handlers/remove.js +201 -0
  40. package/dist/src/cli/handlers/subcommands-bundles.js +257 -0
  41. package/dist/src/cli/handlers/subcommands-discovery.js +165 -0
  42. package/dist/src/cli/handlers/subcommands-list-format.js +129 -0
  43. package/dist/src/cli/handlers/subcommands-list.js +250 -0
  44. package/dist/src/cli/handlers/subcommands-plugins.js +213 -0
  45. package/dist/src/cli/handlers/subcommands-quickref.js +58 -0
  46. package/dist/src/cli/handlers/subcommands-rlm.js +113 -0
  47. package/dist/src/cli/handlers/subcommands-services.js +66 -0
  48. package/dist/src/cli/handlers/subcommands-storage.js +259 -0
  49. package/dist/src/cli/handlers/subcommands.js +18 -1984
  50. package/dist/src/cli/handlers/use.js +11 -5
  51. package/dist/src/cli/scope-resolver.js +1 -142
  52. package/dist/src/cli/services/deployment-verification.js +3 -0
  53. package/dist/src/cli/user-scope-mirror.js +173 -0
  54. package/dist/src/config/dispatch-host-thresholds.js +2 -0
  55. package/dist/src/config/dispatch-thresholds-runtime.mjs +4 -0
  56. package/dist/src/config/host-resource-report.d.mts +5 -0
  57. package/dist/src/config/host-resource-report.mjs +36 -6
  58. package/dist/src/config/host-resource-runtime.d.mts +3 -0
  59. package/dist/src/config/host-resource-runtime.mjs +9 -6
  60. package/dist/src/decision/ensemble-study/artifacts.js +7 -0
  61. package/dist/src/decision/ensemble-study/gate-policy.js +58 -0
  62. package/dist/src/decision/ensemble-study/gates.js +78 -0
  63. package/dist/src/decision/ensemble-study/protocol.js +18 -21
  64. package/dist/src/decision/ensemble-study/score.js +3 -2
  65. package/dist/src/decision/ensemble-study/statistics.js +7 -26
  66. package/dist/src/decision/sensitivity/comparative-gates.js +135 -0
  67. package/dist/src/decision/sensitivity/comparative.js +18 -41
  68. package/dist/src/extensions/claude-hooks-installer.js +18 -0
  69. package/dist/src/gates/evaluate.js +2 -358
  70. package/dist/src/gates/observations.js +363 -0
  71. package/dist/src/gates/pack-composition.js +270 -0
  72. package/dist/src/gates/pack-tightening.js +197 -0
  73. package/dist/src/gates/pack-validation.js +262 -0
  74. package/dist/src/gates/registry-error.js +5 -0
  75. package/dist/src/gates/registry.js +13 -685
  76. package/dist/src/mcp/json-document.mjs +29 -0
  77. package/dist/src/mcp/muse-native-config.mjs +1 -28
  78. package/dist/src/memory/provider-memory-adapter.js +1 -0
  79. package/dist/src/mission-protocol/worker-review-gate.js +7 -0
  80. package/dist/src/models/model-capabilities.v1.json +23 -0
  81. package/dist/src/models/model-catalog.v1.json +9 -0
  82. package/dist/src/models/policy-resources.js +1 -1
  83. package/dist/src/models/worker-plan.js +5 -5
  84. package/dist/src/plugin/command-ownership.js +34 -0
  85. package/dist/src/plugin/skill-command-frontmatter.js +197 -0
  86. package/dist/src/plugin/skill-command-translator.js +6 -232
  87. package/dist/src/providers/capability-matrix.yaml +51 -0
  88. package/dist/src/providers/context-output-ownership.js +26 -0
  89. package/dist/src/providers/deployment-ownership.d.mts +20 -0
  90. package/dist/src/providers/deployment-ownership.mjs +236 -0
  91. package/dist/src/providers/deployment-removal.js +222 -0
  92. package/dist/src/providers/provider-context-contracts.js +8 -0
  93. package/dist/src/providers/provider-definition-schema.js +1 -0
  94. package/dist/src/providers/provider-definitions.js +1 -0
  95. package/dist/src/providers/provider-seeds-3.js +18 -0
  96. package/dist/src/providers/removal-transaction.js +86 -0
  97. package/dist/src/providers/settings-document.d.mts +3 -0
  98. package/dist/src/providers/settings-document.mjs +47 -0
  99. package/dist/src/providers/settings-removal.js +190 -0
  100. package/dist/src/providers/skill-ownership.d.mts +20 -2
  101. package/dist/src/providers/skill-ownership.mjs +12 -4
  102. package/dist/src/providers/transformation-receipt-integration.js +15 -271
  103. package/dist/src/providers/transformation-receipt-outputs.js +99 -0
  104. package/dist/src/providers/transformation-receipt-source.js +194 -0
  105. package/dist/src/research/identity.js +8 -2
  106. package/dist/src/research/reference-match.js +66 -8
  107. package/dist/src/rules/activation.mjs +15 -6
  108. package/dist/src/rules/core-startup.mjs +2 -2
  109. package/dist/src/serve/mission-conductor.js +4 -0
  110. package/dist/src/serve/mission-summary.js +56 -0
  111. package/dist/src/skills/deployment-ownership.js +2 -2
  112. package/dist/src/skills/deployment-policy.js +9 -0
  113. package/dist/src/smiths/context-pipeline/aiwg-md.js +23 -0
  114. package/dist/src/smiths/context-pipeline/context-file-safety.js +3 -0
  115. package/dist/src/smiths/context-pipeline/flue-context.js +25 -0
  116. package/dist/src/smiths/context-pipeline/generator.js +7 -2
  117. package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +9 -7
  118. package/dist/src/smiths/hook-bridge/index.js +9 -0
  119. package/package.json +5 -1
  120. package/schemas/decision/D17StudyProtocol.v1.schema.json +39 -67
  121. package/tools/agents/deploy-agents.mjs +21 -680
  122. package/tools/agents/deploy-command-mirrors.mjs +229 -0
  123. package/tools/agents/deploy-options.mjs +267 -0
  124. package/tools/agents/deploy-support.mjs +165 -0
  125. package/tools/agents/providers/base-addon-discovery.mjs +139 -0
  126. package/tools/agents/providers/base-behaviors.mjs +168 -0
  127. package/tools/agents/providers/base-context.mjs +205 -0
  128. package/tools/agents/providers/base-contract.mjs +116 -0
  129. package/tools/agents/providers/base-files.mjs +252 -0
  130. package/tools/agents/providers/base-flat-artifacts.mjs +233 -0
  131. package/tools/agents/providers/base-framework-discovery.mjs +309 -0
  132. package/tools/agents/providers/base-frontmatter.mjs +196 -0
  133. package/tools/agents/providers/base-inventory.mjs +269 -0
  134. package/tools/agents/providers/base-kernel-skills.mjs +354 -0
  135. package/tools/agents/providers/base-migrations.mjs +258 -0
  136. package/tools/agents/providers/base-models-platforms.mjs +273 -0
  137. package/tools/agents/providers/base-rule-index.mjs +450 -0
  138. package/tools/agents/providers/base-runtime.mjs +60 -0
  139. package/tools/agents/providers/base-skill-copy.mjs +273 -0
  140. package/tools/agents/providers/base.mjs +16 -3364
  141. package/tools/agents/providers/claude-post-deploy.mjs +10 -2
  142. package/tools/agents/providers/flue-project.mjs +79 -0
  143. package/tools/agents/providers/flue-specialists.mjs +64 -0
  144. package/tools/agents/providers/flue.mjs +50 -0
  145. package/tools/agents/providers/hermes-startup.mjs +0 -5
  146. package/tools/agents/providers/muse.mjs +7 -2
  147. package/tools/agents/providers/rule-delivery-surface.mjs +33 -5
  148. package/tools/agents/providers/rule-deployment-commit.mjs +19 -15
  149. package/tools/agents/providers/rule-deployment-prepare.mjs +13 -3
  150. package/tools/agents/providers/rule-projection.mjs +3 -0
  151. package/tools/agents/providers/rule-startup.mjs +3 -3
  152. package/tools/agents/use-rule-selection.mjs +17 -0
  153. package/tools/ralph-external/lib/worker-invocation-processes.mjs +4 -2
  154. package/tools/ralph-external/lib/worker-termination.mjs +15 -8
  155. package/vscode-extension/schemas/aiwg.config.v1.json +2 -4
@@ -0,0 +1,188 @@
1
+ // Share entry identity, provenance, graph selection, and discovery ordering helpers.
2
+ import * as fs from 'node:fs';
3
+ import * as path from 'node:path';
4
+ import { projectAiwgPath, projectControlPath } from '../config/project-artifacts.js';
5
+ import { recordTypeForEntry, stableRecordId } from './browser-export.js';
6
+ import { loadGraphIndexFile } from './index-reader.js';
7
+ import { isOperationalShowType, OPERATIONAL_DISCOVERY_TYPES } from './types.js';
8
+ export function normalizeIndexedPath(entryPath) {
9
+ return entryPath.replace(/\\/g, '/');
10
+ }
11
+ /** Historical records stay in the index for explicit show/history lookup. */
12
+ export function isOrdinaryMemoryEntry(entry, _cwd) {
13
+ // Maintenance owners publish dispositions into the index before returning.
14
+ // Retrieval must not read sources: ordinary legacy entries need no memory
15
+ // stamp, and temporary source I/O failures cannot hide active metadata.
16
+ return !entry.memoryRecord || (entry.memoryRecord.lifecycle === 'active' && entry.memoryRecord.placement !== 'archived');
17
+ }
18
+ export const DEFAULT_ARTIFACT_SEARCH_BACKEND = 'fortemi-core';
19
+ export const DISCOVER_TYPE_ORDER = new Map([...OPERATIONAL_DISCOVERY_TYPES, 'hook', 'doc'].map((type, index) => [type, index]));
20
+ export function canonicalLocalityRank(entryPath) {
21
+ const normalized = entryPath.replace(/\\/g, '/');
22
+ if (normalized.startsWith('.aiwg/') || normalized.includes('/.aiwg/'))
23
+ return 0;
24
+ // Top-level persona mirrors are the least canonical source for a name a bundle
25
+ // also owns. Without this they fell into the catch-all below and scored 1,
26
+ // beating the bundle copy at 2 — the opposite of #1643. It only ever looked
27
+ // correct because a populated user index supplied provenance and `scopeRank`
28
+ // never reached this fallback (#2544).
29
+ if (normalized.startsWith('agentic/code/agents/') || normalized.includes('/agentic/code/agents/'))
30
+ return 4;
31
+ if (normalized.includes('/plugins/') || normalized.startsWith('agentic/code/plugins/'))
32
+ return 3;
33
+ if (normalized.includes('/frameworks/') ||
34
+ normalized.includes('/addons/') ||
35
+ normalized.includes('/extensions/') ||
36
+ normalized.startsWith('agentic/code/frameworks/') ||
37
+ normalized.startsWith('agentic/code/addons/') ||
38
+ normalized.startsWith('agentic/code/extensions/')) {
39
+ return 2;
40
+ }
41
+ return 1;
42
+ }
43
+ export function graphScope(graph) {
44
+ if (graph === 'project')
45
+ return 'project';
46
+ if (graph === 'user' || graph.startsWith('user-'))
47
+ return 'user';
48
+ if (graph === 'framework')
49
+ return 'packaged';
50
+ if (graph === 'codebase' || graph === 'source')
51
+ return 'codebase';
52
+ return 'custom';
53
+ }
54
+ export function withIndexProvenance(entry, graph) {
55
+ return { ...entry, indexGraph: graph, indexScope: graphScope(graph) };
56
+ }
57
+ /** Keep existing project capabilities visible while their derived cache is unavailable. */
58
+ export function projectCapabilityFallback(cwd) {
59
+ const index = loadGraphIndexFile(cwd, 'metadata.json', 'project');
60
+ if (index) {
61
+ const entries = Object.values(index.entries).map((entry) => withIndexProvenance(entry, 'project'));
62
+ if (entries.length > 0) {
63
+ // One diagnostic per command, on stderr so JSON and skill bodies stay parseable.
64
+ console.error('Warning: project capability cache is unavailable or stale; using the local project index. Run `aiwg index sync` to repair the cache.');
65
+ return entries;
66
+ }
67
+ }
68
+ if (['extensions', 'addons', 'frameworks', 'plugins', 'skills'].some((dir) => fs.existsSync(projectAiwgPath(cwd, dir)))) {
69
+ console.error('Warning: project capabilities could not be loaded: the cache is unavailable and the local project index is missing or empty. Run `aiwg index build --graph project` to repair discovery.');
70
+ }
71
+ return index ? [] : null;
72
+ }
73
+ export function discoveryIdForEntry(entry) {
74
+ return stableRecordId(recordTypeForEntry(entry, 'v2'), entry.path);
75
+ }
76
+ export function logicalDiscoverKey(entry) {
77
+ const identity = (entry.name ?? entry.title ?? path.basename(entry.path))
78
+ .toLowerCase()
79
+ .replace(/[-_\s]+/g, ' ')
80
+ .trim();
81
+ return `${entry.type}:${identity}`;
82
+ }
83
+ export function dedupeDiscoverResults(results) {
84
+ const bestByIdentity = new Map();
85
+ for (const result of results) {
86
+ const key = logicalDiscoverKey(result.entry);
87
+ const existing = bestByIdentity.get(key);
88
+ if (!existing || compareDiscoverResults(result, existing) < 0) {
89
+ bestByIdentity.set(key, result);
90
+ }
91
+ }
92
+ return Array.from(bestByIdentity.values()).sort(compareDiscoverResults);
93
+ }
94
+ export function scopeRank(entry) {
95
+ const scope = entry.indexScope;
96
+ if (scope === 'project')
97
+ return 0;
98
+ if (scope === 'user')
99
+ return 1;
100
+ if (scope === 'custom')
101
+ return 2;
102
+ if (scope === 'packaged')
103
+ return 3;
104
+ if (scope === 'codebase')
105
+ return 4;
106
+ return canonicalLocalityRank(entry.path);
107
+ }
108
+ export function compareText(left, right) {
109
+ return (left ?? '').localeCompare(right ?? '');
110
+ }
111
+ export function compareDiscoverResults(left, right) {
112
+ const scoreCmp = right.score - left.score;
113
+ if (scoreCmp !== 0)
114
+ return scoreCmp;
115
+ const localityCmp = scopeRank(left.entry) - scopeRank(right.entry);
116
+ if (localityCmp !== 0)
117
+ return localityCmp;
118
+ const typeCmp = (DISCOVER_TYPE_ORDER.get(left.entry.type) ?? 99) -
119
+ (DISCOVER_TYPE_ORDER.get(right.entry.type) ?? 99);
120
+ if (typeCmp !== 0)
121
+ return typeCmp;
122
+ const nameCmp = compareText(left.entry.name ?? left.entry.title, right.entry.name ?? right.entry.title);
123
+ if (nameCmp !== 0)
124
+ return nameCmp;
125
+ return left.entry.path.localeCompare(right.entry.path);
126
+ }
127
+ export const DEFAULT_DISCOVER_TYPES = [...OPERATIONAL_DISCOVERY_TYPES];
128
+ export const DEFAULT_CAPABILITY_GRAPHS = ['project', 'user', 'framework'];
129
+ export function projectAllowsUserIndices(cwd) {
130
+ try {
131
+ const configPath = projectControlPath(cwd, 'aiwg.config');
132
+ if (!fs.existsSync(configPath))
133
+ return true;
134
+ const parsed = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
135
+ const index = parsed.index;
136
+ const userIndices = index?.userIndices;
137
+ if (userIndices?.enabled === false)
138
+ return false;
139
+ const indices = parsed.indices;
140
+ const user = indices?.user;
141
+ if (user?.enabled === false)
142
+ return false;
143
+ }
144
+ catch {
145
+ return true;
146
+ }
147
+ return true;
148
+ }
149
+ export function defaultCapabilityGraphs(cwd) {
150
+ if (projectAllowsUserIndices(cwd))
151
+ return DEFAULT_CAPABILITY_GRAPHS;
152
+ return DEFAULT_CAPABILITY_GRAPHS.filter((graph) => graph !== 'user' && !graph.startsWith('user-'));
153
+ }
154
+ /**
155
+ * Resolve the AIWG installation root for path-anchoring discover output.
156
+ * Discover returns paths anchored to AIWG_ROOT so the agent's `Read`
157
+ * tool can resolve them from any project working directory (#1217).
158
+ */
159
+ /**
160
+ * Build the `run_hint` string for a script-bearing skill entry (#1227).
161
+ *
162
+ * Format: `aiwg run skill <name> [-- <argsHint>]`. The skill name is the
163
+ * basename of its source directory (skills/<name>/SKILL.md), which is
164
+ * what `aiwg run skill` accepts.
165
+ */
166
+ export function buildRunHint(entry) {
167
+ // Use the directory basename for slug-layout skills, filename stem otherwise.
168
+ const lastSlash = entry.path.lastIndexOf('/');
169
+ const tail = lastSlash >= 0 ? entry.path.slice(lastSlash + 1) : entry.path;
170
+ let name;
171
+ if (tail === 'SKILL.md' && lastSlash >= 0) {
172
+ const dir = entry.path.slice(0, lastSlash);
173
+ const dirSlash = dir.lastIndexOf('/');
174
+ name = dirSlash >= 0 ? dir.slice(dirSlash + 1) : dir;
175
+ }
176
+ else {
177
+ name = tail.replace(/\.[^.]+$/, '');
178
+ }
179
+ const argsHint = entry.script?.argsHint ? ` -- ${entry.script.argsHint}` : '';
180
+ return `aiwg run skill ${name}${argsHint}`;
181
+ }
182
+ export function showHintForDiscoverResult(entry, id) {
183
+ if (isOperationalShowType(entry.type)) {
184
+ return `aiwg show ${entry.type} ${id}`;
185
+ }
186
+ return `aiwg show ${id}`;
187
+ }
188
+ //# sourceMappingURL=query-engine-entries.js.map
@@ -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