@aiwg/cli 2026.10.16 → 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 (128) hide show
  1. package/dist/src/artifacts/corpus-tools/resolve.js +21 -4
  2. package/dist/src/artifacts/query-engine-corpus.js +217 -0
  3. package/dist/src/artifacts/query-engine-discover-output.js +229 -0
  4. package/dist/src/artifacts/query-engine-discover.js +285 -0
  5. package/dist/src/artifacts/query-engine-entries.js +188 -0
  6. package/dist/src/artifacts/query-engine-index.js +249 -0
  7. package/dist/src/artifacts/query-engine-matching.js +143 -0
  8. package/dist/src/artifacts/query-engine-options.js +2 -0
  9. package/dist/src/artifacts/query-engine-rules.js +202 -0
  10. package/dist/src/artifacts/query-engine-scoring.js +436 -0
  11. package/dist/src/artifacts/query-engine-show-card.js +194 -0
  12. package/dist/src/artifacts/query-engine-show-load.js +211 -0
  13. package/dist/src/artifacts/query-engine-show.js +300 -0
  14. package/dist/src/artifacts/query-engine.js +7 -2576
  15. package/dist/src/cli/handlers/mc-agents.js +111 -0
  16. package/dist/src/cli/handlers/mc-args.js +54 -0
  17. package/dist/src/cli/handlers/mc-control.js +227 -0
  18. package/dist/src/cli/handlers/mc-dispatch.js +203 -0
  19. package/dist/src/cli/handlers/mc-help.js +171 -0
  20. package/dist/src/cli/handlers/mc-run.js +343 -0
  21. package/dist/src/cli/handlers/mc-session.js +138 -0
  22. package/dist/src/cli/handlers/mc-status.js +258 -0
  23. package/dist/src/cli/handlers/mc-summary.js +43 -0
  24. package/dist/src/cli/handlers/mc-types.js +3 -0
  25. package/dist/src/cli/handlers/mc-worker.js +205 -0
  26. package/dist/src/cli/handlers/mc.js +12 -1665
  27. package/dist/src/cli/handlers/models-refusal.js +13 -0
  28. package/dist/src/cli/handlers/models.js +2 -1
  29. package/dist/src/cli/handlers/remove-bundled.js +133 -0
  30. package/dist/src/cli/handlers/remove-options.js +31 -0
  31. package/dist/src/cli/handlers/remove-user.js +174 -0
  32. package/dist/src/cli/handlers/remove.js +201 -0
  33. package/dist/src/cli/handlers/subcommands-bundles.js +257 -0
  34. package/dist/src/cli/handlers/subcommands-discovery.js +165 -0
  35. package/dist/src/cli/handlers/subcommands-list-format.js +129 -0
  36. package/dist/src/cli/handlers/subcommands-list.js +250 -0
  37. package/dist/src/cli/handlers/subcommands-plugins.js +213 -0
  38. package/dist/src/cli/handlers/subcommands-quickref.js +58 -0
  39. package/dist/src/cli/handlers/subcommands-rlm.js +113 -0
  40. package/dist/src/cli/handlers/subcommands-services.js +66 -0
  41. package/dist/src/cli/handlers/subcommands-storage.js +259 -0
  42. package/dist/src/cli/handlers/subcommands.js +18 -1984
  43. package/dist/src/cli/scope-resolver.js +1 -142
  44. package/dist/src/cli/user-scope-mirror.js +173 -0
  45. package/dist/src/config/dispatch-host-thresholds.js +2 -0
  46. package/dist/src/config/dispatch-thresholds-runtime.mjs +4 -0
  47. package/dist/src/config/host-resource-report.d.mts +5 -0
  48. package/dist/src/config/host-resource-report.mjs +36 -6
  49. package/dist/src/config/host-resource-runtime.d.mts +3 -0
  50. package/dist/src/config/host-resource-runtime.mjs +9 -6
  51. package/dist/src/decision/ensemble-study/artifacts.js +7 -0
  52. package/dist/src/decision/ensemble-study/gate-policy.js +58 -0
  53. package/dist/src/decision/ensemble-study/gates.js +78 -0
  54. package/dist/src/decision/ensemble-study/protocol.js +18 -21
  55. package/dist/src/decision/ensemble-study/score.js +3 -2
  56. package/dist/src/decision/ensemble-study/statistics.js +7 -26
  57. package/dist/src/decision/sensitivity/comparative-gates.js +135 -0
  58. package/dist/src/decision/sensitivity/comparative.js +18 -41
  59. package/dist/src/extensions/claude-hooks-installer.js +18 -0
  60. package/dist/src/gates/evaluate.js +2 -358
  61. package/dist/src/gates/observations.js +363 -0
  62. package/dist/src/gates/pack-composition.js +270 -0
  63. package/dist/src/gates/pack-tightening.js +197 -0
  64. package/dist/src/gates/pack-validation.js +262 -0
  65. package/dist/src/gates/registry-error.js +5 -0
  66. package/dist/src/gates/registry.js +13 -685
  67. package/dist/src/mcp/json-document.mjs +29 -0
  68. package/dist/src/mcp/muse-native-config.mjs +1 -28
  69. package/dist/src/mission-protocol/worker-review-gate.js +7 -0
  70. package/dist/src/models/worker-plan.js +5 -5
  71. package/dist/src/plugin/command-ownership.js +34 -0
  72. package/dist/src/plugin/skill-command-frontmatter.js +197 -0
  73. package/dist/src/plugin/skill-command-translator.js +6 -232
  74. package/dist/src/providers/context-output-ownership.js +26 -0
  75. package/dist/src/providers/deployment-ownership.d.mts +19 -0
  76. package/dist/src/providers/deployment-ownership.mjs +226 -0
  77. package/dist/src/providers/deployment-removal.js +200 -0
  78. package/dist/src/providers/removal-transaction.js +86 -0
  79. package/dist/src/providers/settings-document.d.mts +3 -0
  80. package/dist/src/providers/settings-document.mjs +47 -0
  81. package/dist/src/providers/settings-removal.js +190 -0
  82. package/dist/src/providers/skill-ownership.d.mts +19 -2
  83. package/dist/src/providers/skill-ownership.mjs +12 -4
  84. package/dist/src/providers/transformation-receipt-integration.js +15 -271
  85. package/dist/src/providers/transformation-receipt-outputs.js +99 -0
  86. package/dist/src/providers/transformation-receipt-source.js +194 -0
  87. package/dist/src/research/identity.js +8 -2
  88. package/dist/src/research/reference-match.js +42 -7
  89. package/dist/src/rules/activation.mjs +15 -6
  90. package/dist/src/rules/core-startup.mjs +2 -2
  91. package/dist/src/serve/mission-conductor.js +4 -0
  92. package/dist/src/serve/mission-summary.js +56 -0
  93. package/dist/src/smiths/context-pipeline/aiwg-md.js +23 -0
  94. package/dist/src/smiths/context-pipeline/context-file-safety.js +3 -0
  95. package/dist/src/smiths/context-pipeline/generator.js +1 -1
  96. package/dist/src/smiths/hook-bridge/index.js +9 -0
  97. package/package.json +4 -1
  98. package/schemas/decision/D17StudyProtocol.v1.schema.json +39 -67
  99. package/tools/agents/deploy-agents.mjs +16 -677
  100. package/tools/agents/deploy-command-mirrors.mjs +229 -0
  101. package/tools/agents/deploy-options.mjs +258 -0
  102. package/tools/agents/deploy-support.mjs +165 -0
  103. package/tools/agents/providers/base-addon-discovery.mjs +139 -0
  104. package/tools/agents/providers/base-behaviors.mjs +168 -0
  105. package/tools/agents/providers/base-context.mjs +205 -0
  106. package/tools/agents/providers/base-contract.mjs +116 -0
  107. package/tools/agents/providers/base-files.mjs +252 -0
  108. package/tools/agents/providers/base-flat-artifacts.mjs +233 -0
  109. package/tools/agents/providers/base-framework-discovery.mjs +309 -0
  110. package/tools/agents/providers/base-frontmatter.mjs +196 -0
  111. package/tools/agents/providers/base-inventory.mjs +269 -0
  112. package/tools/agents/providers/base-kernel-skills.mjs +354 -0
  113. package/tools/agents/providers/base-migrations.mjs +258 -0
  114. package/tools/agents/providers/base-models-platforms.mjs +273 -0
  115. package/tools/agents/providers/base-rule-index.mjs +450 -0
  116. package/tools/agents/providers/base-runtime.mjs +60 -0
  117. package/tools/agents/providers/base-skill-copy.mjs +273 -0
  118. package/tools/agents/providers/base.mjs +16 -3364
  119. package/tools/agents/providers/claude-post-deploy.mjs +10 -2
  120. package/tools/agents/providers/hermes-startup.mjs +0 -5
  121. package/tools/agents/providers/muse.mjs +7 -2
  122. package/tools/agents/providers/rule-delivery-surface.mjs +31 -4
  123. package/tools/agents/providers/rule-deployment-commit.mjs +19 -15
  124. package/tools/agents/providers/rule-deployment-prepare.mjs +11 -2
  125. package/tools/agents/providers/rule-projection.mjs +3 -0
  126. package/tools/ralph-external/lib/worker-invocation-processes.mjs +4 -2
  127. package/tools/ralph-external/lib/worker-termination.mjs +15 -8
  128. package/vscode-extension/schemas/aiwg.config.v1.json +2 -4
@@ -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
@@ -0,0 +1,194 @@
1
+ // Render show metadata cards, sections, and companion resources.
2
+ import * as fs from 'node:fs';
3
+ import * as path from 'node:path';
4
+ import { isCorpusBundleInstalled } from './framework-capabilities.js';
5
+ import { extractMarkdownLinks, parseFlowDoc, parseFrontmatter } from './index-builder.js';
6
+ import { buildRunHint, discoveryIdForEntry, normalizeIndexedPath } from './query-engine-entries.js';
7
+ import { RULE_CHECK_OBLIGATION, statsText } from './query-engine-rules.js';
8
+ import { emptyRuleStats } from './relations.js';
9
+ /** Sections include their nested headings, stopping at the next peer/ancestor. */
10
+ export function showSections(content) {
11
+ const body = parseFrontmatter(content).body;
12
+ const headings = [];
13
+ let offset = 0;
14
+ let fence = '';
15
+ const lines = body.match(/[^\n]*\n|[^\n]+$/g) ?? [];
16
+ for (let i = 0; i < lines.length; i++) {
17
+ const line = lines[i];
18
+ const marker = line.match(/^ {0,3}(`{3,}|~{3,})/);
19
+ if (marker) {
20
+ if (!fence)
21
+ fence = marker[1];
22
+ else if (marker[1][0] === fence[0] && marker[1].length >= fence.length)
23
+ fence = '';
24
+ }
25
+ else if (!fence) {
26
+ const atx = line.match(/^ {0,3}(#{1,6})\s+(.+?)(?:\s+#+)?\s*$/);
27
+ const setext = i + 1 < lines.length && lines[i + 1].match(/^ {0,3}(=+|-+)\s*$/);
28
+ if (atx)
29
+ headings.push({ heading: atx[2], level: atx[1].length, start: offset });
30
+ else if (line.trim() && setext)
31
+ headings.push({ heading: line.trim(), level: setext[1][0] === '=' ? 1 : 2, start: offset });
32
+ }
33
+ offset += line.length;
34
+ }
35
+ return headings.map((heading, i) => {
36
+ const end = headings.slice(i + 1).find(next => next.level <= heading.level)?.start ?? body.length;
37
+ const text = body.slice(heading.start, end);
38
+ return { heading: heading.heading, level: heading.level, bytes: Buffer.byteLength(text),
39
+ lines: text.split('\n').length - (text.endsWith('\n') ? 1 : 0), text };
40
+ });
41
+ }
42
+ /** List companion directories and explicitly linked resources within the owning bundle.
43
+ * Resolve paths against that boundary and exclude symlink components. */
44
+ export function showResources(filePath, source, release) {
45
+ if (release) {
46
+ const base = path.posix.dirname(filePath);
47
+ const linked = new Set(extractMarkdownLinks(source).map(link => path.posix.normalize(path.posix.join(base, link))));
48
+ const boundary = filePath.match(/^(raw\/agentic\/code\/(?:frameworks|addons|extensions)\/[^/]+)\//)?.[1];
49
+ return [...release.descriptors.values()].filter(descriptor => {
50
+ const relative = path.posix.relative(base, descriptor.path);
51
+ const category = /(?:^|\/)(?:templates|scripts|references|resources|assets)\//.test(relative);
52
+ const inside = relative !== '..' && !relative.startsWith('../');
53
+ return (inside && category || linked.has(descriptor.path) && (inside || category))
54
+ && (!boundary || descriptor.path.startsWith(`${boundary}/`));
55
+ }).map(descriptor => ({ path: path.posix.relative(base, descriptor.path), bytes: descriptor.size }))
56
+ .sort((a, b) => a.path.localeCompare(b.path));
57
+ }
58
+ const base = path.dirname(filePath);
59
+ const normalizedBase = normalizeIndexedPath(base);
60
+ const boundary = normalizedBase.match(/^(.*\/(?:frameworks|addons|extensions)\/[^/]+)(?:\/|$)/)?.[1]
61
+ ?? normalizedBase.match(/^(.*\/\.aiwg)(?:\/|$)/)?.[1] ?? base;
62
+ const resources = new Map();
63
+ const walk = (relative) => {
64
+ const absolute = path.resolve(base, relative);
65
+ const contained = path.relative(boundary, absolute);
66
+ if (contained === '..' || contained.startsWith(`..${path.sep}`) || path.isAbsolute(contained))
67
+ return;
68
+ let cursor = boundary;
69
+ let stat;
70
+ try {
71
+ for (const component of contained.split(path.sep)) {
72
+ cursor = path.join(cursor, component);
73
+ stat = fs.lstatSync(cursor);
74
+ if (stat.isSymbolicLink())
75
+ return;
76
+ }
77
+ }
78
+ catch {
79
+ return;
80
+ }
81
+ if (stat?.isDirectory()) {
82
+ for (const name of fs.readdirSync(absolute).sort())
83
+ walk(path.join(relative, name));
84
+ }
85
+ else if (stat?.isFile() && absolute !== filePath) {
86
+ const key = normalizeIndexedPath(path.relative(base, absolute));
87
+ resources.set(key, { path: key, bytes: stat.size });
88
+ }
89
+ };
90
+ for (const directory of ['templates', 'scripts', 'references', 'resources', 'assets'])
91
+ walk(directory);
92
+ const { data } = parseFrontmatter(source);
93
+ const declared = Array.isArray(data.resources) ? data.resources.filter((value) => typeof value === 'string') : [];
94
+ for (const link of [...extractMarkdownLinks(source), ...declared]) {
95
+ if (path.isAbsolute(link) || /^[a-z]+:/i.test(link))
96
+ continue;
97
+ const relative = path.relative(base, path.resolve(base, link));
98
+ // Outside the artifact directory, only declared companion categories qualify.
99
+ if ((relative === '..' || relative.startsWith(`..${path.sep}`)) && !/(?:^|\/)(?:templates|scripts|references|resources|assets)\//.test(normalizeIndexedPath(relative)))
100
+ continue;
101
+ walk(relative);
102
+ }
103
+ return [...resources.values()].sort((a, b) => a.path.localeCompare(b.path));
104
+ }
105
+ export async function emitShowCard(cwd, aiwgRoot, entry, filePath, source, params, bindings, extra, local, release) {
106
+ const { data } = parseFrontmatter(source);
107
+ const flow = entry.type === 'flow' || entry.type === 'runbook' ? parseFlowDoc(source, entry.path) : null;
108
+ const sections = showSections(source);
109
+ const selected = (params.sections ?? []).map(heading => {
110
+ const exact = sections.filter(section => section.heading === heading);
111
+ const matches = exact.length ? exact : sections.filter(section => section.heading.toLowerCase() === heading.toLowerCase());
112
+ if (matches.length !== 1)
113
+ throw new Error(`${matches.length ? 'Ambiguous' : 'Unknown'} heading "${heading}". Headings: ${sections.map(section => section.heading).join(', ') || '(none)'}`);
114
+ return matches[0].text;
115
+ });
116
+ const owner = normalizeIndexedPath(entry.path).match(/(?:^|\/)(?:agentic\/code|\.aiwg)\/(frameworks|addons|extensions)\/([^/]+)\//);
117
+ const kind = owner ? { frameworks: 'framework', addons: 'addon', extensions: 'extension' }[owner[1]] : null;
118
+ const installed = local && (owner && aiwgRoot
119
+ ? await isCorpusBundleInstalled(cwd, aiwgRoot, kind, owner[2]) : true);
120
+ const resources = local || release ? showResources(filePath, source, release) : [];
121
+ const resource = params.resource ? resources.find(resource => resource.path === params.resource) : undefined;
122
+ if (params.resource && !resource)
123
+ throw new Error(`Unknown resource "${params.resource}". Resources: ${resources.map(resource => resource.path).join(', ') || '(none)'}`);
124
+ const quote = (value) => '"' + value.replace(/["\\$`]/g, '\\$&') + '"';
125
+ const command = `aiwg show ${entry.type} ${extra.hint ? params.name : discoveryIdForEntry(entry)}`
126
+ + (params.graph ? ` --graph ${quote(params.graph)}` : '')
127
+ + (params.backend ? ` --backend ${params.backend}` : '')
128
+ + (params.resourceSource ? ` --resource-source ${params.resourceSource}` : '')
129
+ + (params.aiwgVersion ? ` --aiwg-version ${quote(params.aiwgVersion)}` : '')
130
+ + (params.offline ? ' --offline' : '');
131
+ let resourceBody;
132
+ if (resource) {
133
+ if (local)
134
+ resourceBody = fs.readFileSync(path.join(path.dirname(filePath), resource.path), 'utf8');
135
+ else if (release) {
136
+ const { fetchVerifiedRawResource } = await import('../resources/web-release.js');
137
+ resourceBody = (await fetchVerifiedRawResource(release, path.posix.normalize(path.posix.join(path.posix.dirname(filePath), resource.path)), { ...params.webReleaseOptions, offline: params.offline })).toString('utf8');
138
+ }
139
+ }
140
+ const localPin = extra.local_pin;
141
+ const pinNote = localPin ? `Pinned locally: kernel (canonical ${localPin.canonical_activation}; ${localPin.matches.map(match => match.source).join(', ')}).` : '';
142
+ const contentNotice = 'This is a metadata card. The component body has not been fetched. Before deciding or applying its workflow, read the needed sections or --body using the drill-in commands below. Read full governing rules before governed work; --rules alone lists checks.';
143
+ const card = {
144
+ id: discoveryIdForEntry(entry), type: entry.type, name: entry.name ?? String(data.name ?? entry.title),
145
+ title: entry.title, path: filePath, description: String(data.description ?? data.summary ?? flow?.description ?? entry.capability ?? entry.ruleSummary ?? entry.summary ?? ''),
146
+ capability: owner ? { kind, name: owner[2] } : null, installed, kernel: entry.kernel ?? false,
147
+ ...(['rule', 'behavior'].includes(entry.type) ? {
148
+ activation: localPin ? 'kernel' : entry.activation ?? data.activation ?? null, enforcement: data.enforcement ?? entry.ruleEnforcement ?? null,
149
+ bound_to: data.bound_to ?? entry.bound_to ?? {},
150
+ } : {}),
151
+ bound_rules: [], rule_stats: emptyRuleStats(), required_rule_checks: [], rule_check_obligation: RULE_CHECK_OBLIGATION,
152
+ ...bindings.fields,
153
+ outline: sections.map(({ text: _text, ...metadata }) => metadata), resources,
154
+ ...(!params.body && !selected.length ? { content_notice: contentNotice } : {}),
155
+ drill_in: {
156
+ sections: sections.map(section => `${command} --section ${quote(section.heading)}`),
157
+ rules: `${command} --rules`, rule_bodies: `${command} --rules --with-rule-bodies`,
158
+ resources: `${command} --resources`, resource: resources.map(resource => `${command} --resource ${quote(resource.path)}`),
159
+ body: `${command} --body`,
160
+ },
161
+ ...extra,
162
+ ...(params.body || selected.length ? { content: params.body ? source : selected.join('\n') } : {}),
163
+ ...(resource ? { resource: { ...resource, body: resourceBody } } : {}),
164
+ };
165
+ if (params.json) {
166
+ console.log(JSON.stringify(card, null, 2));
167
+ return;
168
+ }
169
+ if ('content' in card) {
170
+ if (extra.hint)
171
+ process.stdout.write(`<!-- AIWG: ${card.installed ? 'installed bundle artifact — not in the selected index.' : 'corpus-only artifact — not in the indexed workspace.'}\n ${extra.hint}\n Origin: ${filePath}\n-->\n\n`);
172
+ if (entry.script)
173
+ process.stdout.write(`<!-- AIWG: executable skill — run via: ${buildRunHint(entry)} -->\n`);
174
+ if (pinNote)
175
+ process.stdout.write(`${pinNote}\n`);
176
+ process.stdout.write(card.content);
177
+ if (!card.content.endsWith('\n'))
178
+ process.stdout.write('\n');
179
+ if (bindings.text)
180
+ process.stdout.write(bindings.text);
181
+ return;
182
+ }
183
+ const lines = [`# ${card.type}: ${card.name}`, `ID: ${card.id}`, card.description,
184
+ `Owner: ${card.capability ? `${card.capability.kind}:${card.capability.name}` : 'project/unowned'} | installed: ${card.installed}`, statsText(card.rule_stats)];
185
+ if (pinNote)
186
+ lines.push(pinNote);
187
+ if ('activation' in card)
188
+ lines.push(`Activation: ${card.activation} | enforcement: ${card.enforcement}`, `Bound targets: ${JSON.stringify(card.bound_to)}`);
189
+ lines.push(contentNotice, bindings.text || RULE_CHECK_OBLIGATION, '\n## Outline', ...card.outline.map(section => `- ${section.heading} (${section.bytes} bytes, ${section.lines} lines)`), '\n## Resources', ...resources.map(resource => `- ${resource.path} (${resource.bytes} bytes)`), '\n## Drill in', ...Object.values(card.drill_in).flat().map(command => `- ${command}`));
190
+ if (card.resource)
191
+ lines.push(`\n## Resource: ${card.resource.path}`, card.resource.body);
192
+ console.log(lines.join('\n'));
193
+ }
194
+ //# sourceMappingURL=query-engine-show-card.js.map