@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,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
@@ -0,0 +1,436 @@
1
+ // Tokenize discovery phrases and score metadata matches with lexical diagnostics.
2
+ import { diagnoseFacetActivations } from './discover-facets.js';
3
+ export function containsTokenSequence(haystack, needle) {
4
+ if (needle.length === 0 || haystack.length < needle.length)
5
+ return false;
6
+ for (let i = 0; i <= haystack.length - needle.length; i++) {
7
+ let matched = true;
8
+ for (let j = 0; j < needle.length; j++) {
9
+ if (haystack[i + j] !== needle[j]) {
10
+ matched = false;
11
+ break;
12
+ }
13
+ }
14
+ if (matched)
15
+ return true;
16
+ }
17
+ return false;
18
+ }
19
+ /**
20
+ * Stop-words to drop when tokenizing a discovery phrase. Keep short —
21
+ * we want the user's verbs and nouns to dominate scoring.
22
+ */
23
+ // Stopwords stripped from a discover QUERY before scoring (#1581). Two classes:
24
+ // 1. Grammatical filler (articles, prepositions, pronouns, question words,
25
+ // asking verbs) — a natural-language intent like "Find an AIWG skill that
26
+ // handles intake forms" carries the same meaning as "intake forms", but the
27
+ // filler tokens inflate the token count: the strict overlap gate is
28
+ // ceil(n/2), so a verbose query raises the bar above what the genuinely
29
+ // relevant short-match artifact can clear, and the (hits/n) term dilutes
30
+ // every score. Dropping filler collapses the query to its content tokens.
31
+ // 2. AIWG meta-type nouns ('aiwg', 'skill', 'agent', 'command', 'rule',
32
+ // 'flow', 'workflow') — in a discover query these carry zero discriminating
33
+ // signal (every result IS an aiwg skill/agent/…; the TYPE is filtered via
34
+ // --type). The content word after them is what matters
35
+ // ("…skill that handles >intake forms<"). Keeping them surfaces incidental
36
+ // junk matches (any artifact mentioning "skill"/"aiwg") above the real one.
37
+ // Only the query is tokenized here — entry fields are substring-matched — so this
38
+ // never changes what text an artifact exposes, only how the query is reduced.
39
+ export const SCORE_STOPWORDS = new Set([
40
+ // articles / conjunctions / prepositions / copula
41
+ 'the', 'a', 'an', 'and', 'or', 'of', 'for', 'to', 'in', 'on',
42
+ 'with', 'into', 'from', 'is', 'are', 'be', 'i', 'we', 'my',
43
+ // pronouns / determiners / fillers
44
+ 'it', 'you', 'me', 'us', 'your', 'our', 'this', 'that', 'these', 'those',
45
+ 'there', 'here', 'some', 'any', 'all', 'also', 'please', 'about', 'project',
46
+ // question words
47
+ 'how', 'what', 'which', 'where', 'when', 'who', 'why',
48
+ // asking / request verbs ("find a skill that handles …")
49
+ 'find', 'give', 'show', 'need', 'want', 'looking', 'look', 'help',
50
+ 'do', 'does', 'did', 'can', 'could', 'should', 'would', 'will',
51
+ 'handle', 'handles', 'handling',
52
+ // AIWG meta-type nouns — zero discriminating signal in a discover query
53
+ 'aiwg', 'skill', 'skills', 'agent', 'agents', 'command', 'commands',
54
+ 'rule', 'rules', 'schema', 'schemas', 'flow', 'flows', 'workflow', 'workflows',
55
+ 'template', 'templates',
56
+ ]);
57
+ /**
58
+ * Tokenize a query phrase into lowercased keywords for multi-word
59
+ * scoring. Splits on whitespace and punctuation; drops stopwords and
60
+ * single-character tokens.
61
+ */
62
+ export function tokenize(text) {
63
+ return text
64
+ .toLowerCase()
65
+ .split(/[^a-z0-9]+/)
66
+ .filter(t => t.length > 1 && !SCORE_STOPWORDS.has(t))
67
+ .map(token => token.length > 4 && token.endsWith('s') && !token.endsWith('ss')
68
+ ? token.slice(0, -1)
69
+ : token);
70
+ }
71
+ export function matchedFieldTokens(queryTokens, field) {
72
+ const fieldTokens = new Set(tokenize(field));
73
+ return queryTokens.filter(token => fieldTokens.has(token));
74
+ }
75
+ export function fieldContainsQuery(field, queryTokens) {
76
+ return containsTokenSequence(tokenize(field), queryTokens);
77
+ }
78
+ /**
79
+ * Score a metadata entry against a keyword query.
80
+ *
81
+ * Multi-word queries are tokenized; each token contributes its weighted
82
+ * match across the entry's searchable fields. The full phrase still
83
+ * earns bonus weight when it appears as a contiguous substring or as
84
+ * an exact trigger phrase (the most reliable signal).
85
+ *
86
+ * For AIWG artifact kinds (skills/agents/commands/rules) the entry
87
+ * carries `triggers` (declared activation phrases) and `capability`
88
+ * (one-line description). These get the highest weights so capability
89
+ * search via `aiwg index discover` ranks the right skill on top
90
+ * instead of bottoming out on a path-substring match (#1214).
91
+ */
92
+ /**
93
+ * Normalize a string for exact-name comparison (#1233) — lowercase and
94
+ * collapse `-` / `_` / whitespace runs so hyphenated kernel-skill names
95
+ * like `aiwg-doctor` match queries with spaces ("aiwg doctor") and the
96
+ * rendered title ("AIWG Doctor") matches the slug query.
97
+ */
98
+ export function normalizeName(s) {
99
+ return s.toLowerCase().replace(/[-_\s]+/g, ' ').trim();
100
+ }
101
+ export function damerauLevenshteinAtMostOne(a, b) {
102
+ if (a === b)
103
+ return true;
104
+ if (Math.abs(a.length - b.length) > 1)
105
+ return false;
106
+ if (a.length === b.length) {
107
+ let firstDiff = -1;
108
+ let diffCount = 0;
109
+ for (let i = 0; i < a.length; i++) {
110
+ if (a[i] !== b[i]) {
111
+ if (firstDiff < 0)
112
+ firstDiff = i;
113
+ diffCount++;
114
+ }
115
+ }
116
+ if (diffCount === 1)
117
+ return true;
118
+ return diffCount === 2
119
+ && firstDiff + 1 < a.length
120
+ && a[firstDiff] === b[firstDiff + 1]
121
+ && a[firstDiff + 1] === b[firstDiff];
122
+ }
123
+ const shorter = a.length < b.length ? a : b;
124
+ const longer = a.length < b.length ? b : a;
125
+ let i = 0;
126
+ let j = 0;
127
+ let edits = 0;
128
+ while (i < shorter.length && j < longer.length) {
129
+ if (shorter[i] === longer[j]) {
130
+ i++;
131
+ j++;
132
+ }
133
+ else {
134
+ edits++;
135
+ if (edits > 1)
136
+ return false;
137
+ j++;
138
+ }
139
+ }
140
+ return true;
141
+ }
142
+ export function nearNameMatch(query, name) {
143
+ const queryParts = normalizeName(query).split(/\s+/).filter(Boolean);
144
+ const nameParts = normalizeName(name).split(/\s+/).filter(Boolean);
145
+ if (queryParts.length !== nameParts.length)
146
+ return false;
147
+ return queryParts.every((part, i) => {
148
+ const target = nameParts[i];
149
+ if (part === target)
150
+ return true;
151
+ if (part.length < 5 || target.length < 5)
152
+ return false;
153
+ return damerauLevenshteinAtMostOne(part, target);
154
+ });
155
+ }
156
+ export function scoreEntryDetailed(entry, text, opts = {}) {
157
+ const tokens = tokenize(text);
158
+ // Field substring matching uses the stopword-stripped CONTENT phrase, not the
159
+ // raw query (#1581). Without this, a query that reduces to a single content
160
+ // token — e.g. "intake skill" or "find an intake skill" → ["intake"] — sets
161
+ // useMultiToken=false (1 token) and then fails the full-string `.includes()`
162
+ // checks because the raw phrase ("intake skill") isn't a substring of any
163
+ // field, while the one meaningful token is never matched. Joining the content
164
+ // tokens restores the invariant that a single content token IS the phrase, and
165
+ // for multi-token queries gives a tighter (content-only) phrase to match.
166
+ // Pure-stopword queries fall back to the raw text.
167
+ const lower = tokens.length > 0 ? tokens.join(' ') : text.toLowerCase().trim();
168
+ const rawLower = text.toLowerCase().trim();
169
+ const personaIdentitySuppressed = diagnoseFacetActivations(text).some((activation) => activation.facet === 'persona-identity' && activation.status === 'suppressed');
170
+ let score = 0;
171
+ const matches = [];
172
+ const creditedTokens = new Set();
173
+ const finish = (uncappedScore = score, cap = 1) => ({
174
+ score: Math.min(uncappedScore, cap),
175
+ diagnostic: {
176
+ content_tokens: tokens,
177
+ raw_score: uncappedScore,
178
+ score: Math.min(uncappedScore, cap),
179
+ score_cap_applied: uncappedScore > cap,
180
+ matches,
181
+ },
182
+ });
183
+ const addMatch = (contribution, match) => {
184
+ score += contribution;
185
+ matches.push({ ...match, contribution });
186
+ };
187
+ const addTokenMatch = (contributionPerToken, hits, match) => {
188
+ const newlyMatched = hits.filter(token => !creditedTokens.has(token));
189
+ if (newlyMatched.length === 0)
190
+ return;
191
+ newlyMatched.forEach(token => creditedTokens.add(token));
192
+ addMatch(contributionPerToken * newlyMatched.length, {
193
+ ...match,
194
+ matched_tokens: newlyMatched,
195
+ query_token_coverage: tokens.length > 0 ? newlyMatched.length / tokens.length : 0,
196
+ });
197
+ };
198
+ // Exact-name floor (#1233) — if the query (normalized) exactly matches
199
+ // the entry's canonical name, this is the artifact the user is asking
200
+ // for and it must surface at the top regardless of how cluttered the
201
+ // rest of the corpus scoring gets. Hyphens, underscores, and whitespace
202
+ // are interchangeable in the comparison so `aiwg-doctor`, `aiwg doctor`,
203
+ // and `aiwg_doctor` all match a kernel skill with `name: aiwg-doctor`.
204
+ //
205
+ // Returns 1.001 (not 1.0) so an exact-name hit sorts above the many
206
+ // capped-at-1.0 substring matches that share generic words like "use".
207
+ // Display rounding (Math.round(score * 100) / 100) hides the offset, so
208
+ // the user still sees `score: 1.0` while sort order is preserved.
209
+ if (entry.name) {
210
+ const queryNorm = normalizeName(text);
211
+ const nameNorm = normalizeName(entry.name);
212
+ if (queryNorm === nameNorm) {
213
+ matches.push({
214
+ field: 'name',
215
+ match: 'exact',
216
+ value: entry.name,
217
+ contribution: 1.001,
218
+ matched_tokens: tokens,
219
+ query_token_coverage: 1,
220
+ });
221
+ return finish(1.001, 1.001);
222
+ }
223
+ if (nearNameMatch(text, entry.name)) {
224
+ matches.push({
225
+ field: 'name',
226
+ match: 'near-name',
227
+ value: entry.name,
228
+ contribution: 0.951,
229
+ matched_tokens: tokens,
230
+ query_token_coverage: 1,
231
+ });
232
+ return finish(0.951);
233
+ }
234
+ }
235
+ // Searchable text — joined once so per-token includes() is cheap
236
+ const titleLower = entry.title.toLowerCase();
237
+ const summaryLower = entry.summary.toLowerCase();
238
+ const pathLower = entry.path.toLowerCase();
239
+ const typeLower = entry.type.toLowerCase();
240
+ const capabilityLower = entry.capability ? entry.capability.toLowerCase() : '';
241
+ const tagsLower = entry.tags.map(t => t.toLowerCase());
242
+ const triggersLower = (entry.triggers ?? []).map(trigger => trigger.toLowerCase());
243
+ const searchTermsLower = (entry.searchTerms ?? []).join(' ').toLowerCase();
244
+ const kindLower = entry.kind?.toLowerCase() ?? '';
245
+ const sourceTypeLower = entry.sourceType?.toLowerCase() ?? '';
246
+ // For multi-token queries, require ≥50% token overlap to count
247
+ // partial matches. This keeps gibberish queries (e.g.,
248
+ // `xyzzy_zzqwkjhg_42` after splitting on `_`) from surfacing
249
+ // incidental single-token hits.
250
+ const useMultiToken = tokens.length > 1;
251
+ // #1561 — verbose natural-language queries (e.g. "skill that handles intake
252
+ // forms") dilute the token hit ratio below the ceil(n/2) overlap gate and
253
+ // dead-end to zero results. When the strict pass finds nothing, callers
254
+ // re-score with `relaxOverlap` so a single meaningful token hit (intake /
255
+ // forms) still surfaces ranked candidates instead of an empty set.
256
+ const minHits = useMultiToken
257
+ ? (opts.relaxOverlap ? 1 : Math.ceil(tokens.length / 2))
258
+ : 1;
259
+ const overlapOK = (hits) => useMultiToken && hits >= minHits;
260
+ // Trigger phrase match — highest weight (4x). Exact match on the full
261
+ // phrase wins big; substring or token-overlap is still strong.
262
+ if (triggersLower.length > 0) {
263
+ for (const trigger of triggersLower) {
264
+ const triggerTokens = tokenize(trigger);
265
+ const matchedTokens = tokens.filter((token) => triggerTokens.includes(token));
266
+ const queryCoverage = tokens.length > 0 ? matchedTokens.length / tokens.length : 0;
267
+ if (trigger === lower || trigger === rawLower) {
268
+ matches.push({
269
+ field: 'trigger',
270
+ match: 'exact',
271
+ value: trigger,
272
+ contribution: 1.0008,
273
+ matched_tokens: matchedTokens,
274
+ query_token_coverage: 1,
275
+ });
276
+ return finish(1.0008, 1.0008);
277
+ }
278
+ else if (containsTokenSequence(triggerTokens, tokens) ||
279
+ containsTokenSequence(tokens, triggerTokens)) {
280
+ const triggerInsideQuery = containsTokenSequence(tokens, triggerTokens);
281
+ const containedCoverage = triggerInsideQuery
282
+ ? queryCoverage
283
+ : triggerTokens.length > 0
284
+ ? matchedTokens.length / triggerTokens.length
285
+ : 0;
286
+ // A complete multi-word trigger inside a noisier query is a strong
287
+ // metadata signal. The ambiguous one-word `persona` trigger is
288
+ // downweighted only when the facet classifier has identified buyer /
289
+ // audience marketing context; distinctive one-word triggers such as
290
+ // GRADE retain their established exact-trigger behavior (#1828).
291
+ const suppressedGenericPersona = personaIdentitySuppressed &&
292
+ triggerTokens.length === 1 &&
293
+ triggerTokens[0] === 'persona' &&
294
+ tokens.length > 1;
295
+ const contribution = suppressedGenericPersona
296
+ ? 0.24 * queryCoverage
297
+ : triggerTokens.length > 1
298
+ ? Math.min(1, 0.75 + 0.25 * containedCoverage)
299
+ : 1;
300
+ addMatch(contribution, {
301
+ field: 'trigger',
302
+ match: 'contained-phrase',
303
+ value: trigger,
304
+ matched_tokens: matchedTokens,
305
+ query_token_coverage: queryCoverage,
306
+ });
307
+ }
308
+ else if (useMultiToken) {
309
+ const hits = matchedFieldTokens(tokens, trigger);
310
+ if (overlapOK(hits.length)) {
311
+ addTokenMatch(0.1 * 4, hits, {
312
+ field: 'trigger',
313
+ match: 'token-overlap',
314
+ value: trigger,
315
+ });
316
+ }
317
+ }
318
+ }
319
+ }
320
+ // Capability description (2x weight) — full phrase first, then tokens
321
+ if (capabilityLower) {
322
+ if (fieldContainsQuery(capabilityLower, tokens)) {
323
+ addMatch(0.2 * 2, {
324
+ field: 'capability',
325
+ match: 'contained-phrase',
326
+ value: entry.capability,
327
+ });
328
+ }
329
+ else if (useMultiToken) {
330
+ const hits = matchedFieldTokens(tokens, capabilityLower);
331
+ if (overlapOK(hits.length)) {
332
+ addTokenMatch(0.1 * 2, hits, {
333
+ field: 'capability',
334
+ match: 'token-overlap',
335
+ value: entry.capability,
336
+ });
337
+ }
338
+ }
339
+ }
340
+ // Title (3x weight)
341
+ if (fieldContainsQuery(titleLower, tokens)) {
342
+ addMatch(0.3 * 3, {
343
+ field: 'title',
344
+ match: titleLower === lower ? 'exact' : 'contained-phrase',
345
+ value: entry.title,
346
+ });
347
+ if (titleLower === lower) {
348
+ addMatch(0.2, { field: 'title', match: 'exact', value: entry.title });
349
+ }
350
+ }
351
+ else if (useMultiToken) {
352
+ const hits = matchedFieldTokens(tokens, titleLower);
353
+ if (overlapOK(hits.length)) {
354
+ addTokenMatch(0.08 * 3, hits, {
355
+ field: 'title',
356
+ match: 'token-overlap',
357
+ value: entry.title,
358
+ });
359
+ }
360
+ }
361
+ // Tags (2x weight)
362
+ for (const tag of tagsLower) {
363
+ if (fieldContainsQuery(tag, tokens)) {
364
+ addMatch(0.2 * 2, { field: 'tag', match: 'contained-phrase', value: tag });
365
+ }
366
+ else if (useMultiToken) {
367
+ const hits = matchedFieldTokens(tokens, tag);
368
+ if (overlapOK(hits.length)) {
369
+ addTokenMatch(0.05 * 2, hits, {
370
+ field: 'tag',
371
+ match: 'token-overlap',
372
+ value: tag,
373
+ });
374
+ }
375
+ }
376
+ }
377
+ // Structure-aware language terms (1.5x weight). These are deliberately
378
+ // below declared triggers/capabilities but above generic body summaries.
379
+ if (fieldContainsQuery(searchTermsLower, tokens)) {
380
+ addMatch(0.18 * 1.5, { field: 'search_terms', match: 'contained-phrase' });
381
+ }
382
+ else if (useMultiToken) {
383
+ const hits = matchedFieldTokens(tokens, searchTermsLower);
384
+ if (overlapOK(hits.length)) {
385
+ addTokenMatch(0.06 * 1.5, hits, {
386
+ field: 'search_terms',
387
+ match: 'token-overlap',
388
+ });
389
+ }
390
+ }
391
+ // Exact declarative kind and physical source classification are compact,
392
+ // useful routing signals (e.g. FlowPlaybook vs OpsInventory; runbook that
393
+ // originated under templates/).
394
+ if (fieldContainsQuery(kindLower, tokens)) {
395
+ addMatch(0.15, { field: 'kind', match: 'contained-phrase', value: entry.kind });
396
+ }
397
+ if (fieldContainsQuery(sourceTypeLower, tokens)) {
398
+ addMatch(0.08, { field: 'source_type', match: 'contained-phrase', value: entry.sourceType });
399
+ }
400
+ // Summary (1x weight)
401
+ if (fieldContainsQuery(summaryLower, tokens)) {
402
+ addMatch(0.15, { field: 'summary', match: 'contained-phrase' });
403
+ }
404
+ else if (useMultiToken) {
405
+ const hits = matchedFieldTokens(tokens, summaryLower);
406
+ if (overlapOK(hits.length)) {
407
+ addTokenMatch(0.04, hits, {
408
+ field: 'summary',
409
+ match: 'token-overlap',
410
+ });
411
+ }
412
+ }
413
+ // Path (0.5x weight)
414
+ if (fieldContainsQuery(pathLower, tokens)) {
415
+ addMatch(0.1, { field: 'path', match: 'contained-phrase', value: entry.path });
416
+ }
417
+ else if (useMultiToken) {
418
+ const hits = matchedFieldTokens(tokens, pathLower);
419
+ if (overlapOK(hits.length)) {
420
+ addTokenMatch(0.03, hits, {
421
+ field: 'path',
422
+ match: 'token-overlap',
423
+ value: entry.path,
424
+ });
425
+ }
426
+ }
427
+ // Type (0.5x weight)
428
+ if (fieldContainsQuery(typeLower, tokens)) {
429
+ addMatch(0.1, { field: 'type', match: 'contained-phrase', value: entry.type });
430
+ }
431
+ return finish();
432
+ }
433
+ export function scoreEntry(entry, text, opts = {}) {
434
+ return scoreEntryDetailed(entry, text, opts).score;
435
+ }
436
+ //# sourceMappingURL=query-engine-scoring.js.map