@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,269 @@
1
+ // Shared provider inventory utilities.
2
+ import { fs, path } from './base-runtime.mjs';
3
+ import { collectFrameworkArtifacts } from './base-framework-discovery.mjs';
4
+ import { getAddonAgentFiles, getAddonCommandFiles } from './base-addon-discovery.mjs';
5
+ import { getAddonRuleFiles } from './base-rule-index.mjs';
6
+ import { MANAGED_MARKER_RE, MANIFEST_FILENAME, readSidecarManifest, writeSidecarManifest } from './base-files.mjs';
7
+
8
+
9
+ // ============================================================================
10
+ // Flat-File Stale-Artifact Prune (agents / commands / rules) — #1627
11
+ // ============================================================================
12
+
13
+ /**
14
+ * Reduce a deployed artifact filename to a provider-extension-agnostic stem.
15
+ *
16
+ * Different providers emit the same source rule/agent/command under different
17
+ * extensions (`.md`, `.mdc`, `.agent.md`, `.prompt.md`, `.instructions.md`).
18
+ * Matching by stem lets the stale-prune compare a source basename
19
+ * (`foo.md` → `foo`) against any provider's on-disk form (`foo.agent.md` →
20
+ * `foo`) without hard-coding the per-provider extension map.
21
+ *
22
+ * Strips a trailing `.md`/`.mdc`, then a secondary copilot-style
23
+ * `.agent`/`.prompt`/`.instructions` qualifier.
24
+ *
25
+ * @param {string} name basename
26
+ * @returns {string} extension-agnostic stem
27
+ */
28
+ export function artifactStem(name) {
29
+ return String(name)
30
+ .replace(/\.(md|mdc)$/i, '')
31
+ .replace(/\.(agent|prompt|instructions)$/i, '');
32
+ }
33
+
34
+
35
+ /**
36
+ * Compute the global set of source-basename stems AIWG ships for a flat
37
+ * artifact type, across ALL frameworks and addons (mode-independent).
38
+ *
39
+ * Used as the "desired" set by `pruneStaleAiwgFiles`. Mode independence is
40
+ * deliberate and mirrors `computeAllKernelNames` for skills: `aiwg use sdlc`
41
+ * must not prune a marketing agent that a prior `aiwg use all` deployed and
42
+ * that is still a valid AIWG artifact. Only artifacts whose source no longer
43
+ * exists ANYWHERE in the tree (renamed/removed) fall out of this set and
44
+ * become prune-eligible.
45
+ *
46
+ * Anchors to the AIWG root (resolved by walking up from `srcRoot` for the
47
+ * `agentic/code/frameworks` + `agentic/code/addons` pair, or `AIWG_ROOT`),
48
+ * NOT the raw `srcRoot`. This matters because `deploy-agents.mjs` can be
49
+ * invoked with `--source <project-local-bundle>`; computing the desired set
50
+ * against a bundle dir would be empty and make every AIWG artifact look stale.
51
+ * Returns `null` when no AIWG framework/addon tree is found — the caller MUST
52
+ * then skip pruning (a bundle-only deploy has no global desired set).
53
+ *
54
+ * @param {string} srcRoot AIWG repo / install root (or a subdir of it)
55
+ * @param {'agents'|'commands'|'rules'} type artifact type
56
+ * @returns {Set<string>|null} stems of every source file of that type, or null
57
+ * if the AIWG framework/addon tree can't be located
58
+ */
59
+ export function computeAllArtifactBasenames(srcRoot, type) {
60
+ const aiwgRoot = resolveAiwgRoot(srcRoot);
61
+ if (!aiwgRoot) return null;
62
+
63
+ const stems = new Set();
64
+ const add = (files) => {
65
+ for (const f of files) stems.add(artifactStem(path.basename(f)));
66
+ };
67
+
68
+ const frameworkArtifacts = collectFrameworkArtifacts(aiwgRoot, 'all', {
69
+ includeAgents: type === 'agents',
70
+ includeCommands: type === 'commands',
71
+ includeRules: type === 'rules',
72
+ includeSkills: false,
73
+ recursiveCommands: true,
74
+ });
75
+
76
+ if (type === 'agents') {
77
+ add(frameworkArtifacts.agents);
78
+ // Soul companions live alongside agents and are deployed with them —
79
+ // keep their stems in the desired set so the prune never removes them.
80
+ add(frameworkArtifacts.souls || []);
81
+ add(getAddonAgentFiles(aiwgRoot, [], { includeExplicit: true }));
82
+ } else if (type === 'commands') {
83
+ add(frameworkArtifacts.commands);
84
+ add(getAddonCommandFiles(aiwgRoot, [], { includeExplicit: true }));
85
+ } else if (type === 'rules') {
86
+ add(frameworkArtifacts.rules);
87
+ add(getAddonRuleFiles(aiwgRoot, [], { includeExplicit: true }));
88
+ }
89
+
90
+ return stems;
91
+ }
92
+
93
+
94
+ /**
95
+ * Resolve the AIWG install/repo root from a possibly-nested srcRoot.
96
+ *
97
+ * Mirrors the walk-up logic in `computeAllKernelNames`: honor `AIWG_ROOT`,
98
+ * else climb up to 8 levels looking for the directory that holds BOTH
99
+ * `agentic/code/frameworks` and `agentic/code/addons`. Returns `null` when
100
+ * no such root is found (e.g. a standalone project-local bundle).
101
+ *
102
+ * @param {string} srcRoot
103
+ * @returns {string|null}
104
+ */
105
+ export function resolveAiwgRoot(srcRoot) {
106
+ const hasTree = (dir) =>
107
+ fs.existsSync(path.join(dir, 'agentic', 'code', 'frameworks')) &&
108
+ fs.existsSync(path.join(dir, 'agentic', 'code', 'addons'));
109
+ const isRootOrSourceDescendant = (candidate, original) => {
110
+ const root = path.resolve(candidate);
111
+ const source = path.resolve(original);
112
+ const agenticCode = path.join(root, 'agentic', 'code');
113
+ return source === root || source === agenticCode || source.startsWith(`${agenticCode}${path.sep}`);
114
+ };
115
+
116
+ if (process.env.AIWG_ROOT && hasTree(process.env.AIWG_ROOT)) {
117
+ return process.env.AIWG_ROOT;
118
+ }
119
+ let cur = path.resolve(srcRoot);
120
+ for (let i = 0; i < 8; i++) {
121
+ if (hasTree(cur) && isRootOrSourceDescendant(cur, srcRoot)) return cur;
122
+ const parent = path.dirname(cur);
123
+ if (parent === cur) break;
124
+ cur = parent;
125
+ }
126
+ return null;
127
+ }
128
+
129
+
130
+ /**
131
+ * Names of every skill AIWG ships, kernel and standard alike (#2511).
132
+ *
133
+ * `computeAllKernelNames` filters to kernel skills, but skill-command wrappers
134
+ * are generated from both tiers, so retiring an orphaned wrapper needs the full
135
+ * set. Anchored to the AIWG root rather than `srcRoot` for the same reason
136
+ * `computeAllArtifactBasenames` is: a bundle-scoped deploy must not produce an
137
+ * empty desired set and retire everything.
138
+ *
139
+ * @param {string} srcRoot AIWG repo / install root (or a subdir of it)
140
+ * @returns {Set<string>|null} skill directory names, or null when no AIWG tree
141
+ * is found — callers MUST then skip pruning.
142
+ */
143
+ export function computeAllSkillNames(srcRoot) {
144
+ const aiwgRoot = resolveAiwgRoot(srcRoot);
145
+ if (!aiwgRoot) return null;
146
+
147
+ const names = new Set();
148
+ for (const group of ['frameworks', 'addons']) {
149
+ const root = path.join(aiwgRoot, 'agentic', 'code', group);
150
+ if (!fs.existsSync(root)) continue;
151
+ for (const component of fs.readdirSync(root, { withFileTypes: true })) {
152
+ if (!component.isDirectory()) continue;
153
+ const skillsDir = path.join(root, component.name, 'skills');
154
+ if (!fs.existsSync(skillsDir)) continue;
155
+ for (const skill of fs.readdirSync(skillsDir, { withFileTypes: true })) {
156
+ if (skill.isDirectory()) names.add(skill.name);
157
+ }
158
+ }
159
+ }
160
+ return names;
161
+ }
162
+
163
+
164
+ /**
165
+ * Holistic post-deploy prune of stale AIWG-managed flat artifacts
166
+ * (agents / commands / rules). The flat-file analogue of
167
+ * `pruneStaleAiwgSkills`.
168
+ *
169
+ * Removes a file from `destDir` only when ALL hold:
170
+ * 1. It has an allowed deployed-artifact extension (`.md` / `.mdc` by
171
+ * default; callers may include `.toml`), is not `RULES-INDEX.md`,
172
+ * and not the sidecar manifest.
173
+ * 2. Its stem is NOT in `desiredStems` (the source no longer ships it).
174
+ * 3. It carries an AIWG ownership signal — either a `.aiwg-manifest.json`
175
+ * sidecar entry, or an in-file `aiwg:managed` marker.
176
+ *
177
+ * User-authored files (no ownership signal) and current AIWG artifacts (stem
178
+ * in the desired set) are never touched. Pruned files also have their sidecar
179
+ * entry dropped so the manifest stays accurate.
180
+ *
181
+ * Safe to call on every deploy invocation: `desiredStems` is the global
182
+ * (mode-independent) source set, so sibling-framework files are never
183
+ * collateral.
184
+ *
185
+ * @param {string} destDir absolute path to the provider artifact dir
186
+ * @param {Set<string>|string[]} desiredStems stems that should remain
187
+ * @param {object} opts `{ dryRun, verbose }`
188
+ * @returns {string[]} removed (or would-be-removed) file paths
189
+ */
190
+ export function pruneStaleAiwgFiles(destDir, desiredStems, opts = {}) {
191
+ const { dryRun = false, verbose = false } = opts;
192
+ const artifactExtensions = opts.artifactExtensions || ['.md', '.mdc'];
193
+ // When supplied, skill-command wrappers are retired against the set of skills
194
+ // that still exist rather than exempted outright (#2511). `null`/absent keeps
195
+ // the blanket exemption, so callers without a skill inventory cannot retire a
196
+ // wrapper by accident.
197
+ const skillCommandStems = opts.skillCommandStems instanceof Set
198
+ ? opts.skillCommandStems
199
+ : Array.isArray(opts.skillCommandStems)
200
+ ? new Set(opts.skillCommandStems)
201
+ : null;
202
+ const removed = [];
203
+ if (!destDir || !fs.existsSync(destDir)) return removed;
204
+
205
+ const desired = desiredStems instanceof Set ? desiredStems : new Set(desiredStems);
206
+ const sidecar = readSidecarManifest(destDir) || { managed: {} };
207
+ const managed = sidecar.managed || {};
208
+ let sidecarDirty = false;
209
+
210
+ let entries;
211
+ try {
212
+ entries = fs.readdirSync(destDir, { withFileTypes: true });
213
+ } catch {
214
+ return removed;
215
+ }
216
+
217
+ for (const entry of entries) {
218
+ if (!entry.isFile()) continue;
219
+ const name = entry.name;
220
+ if (name === MANIFEST_FILENAME) continue;
221
+ if (name === 'RULES-INDEX.md') continue;
222
+ if (name === 'RULES-ONDEMAND.md') continue; // generated on-demand index (#1673)
223
+ const lower = name.toLowerCase();
224
+ if (!artifactExtensions.some(extension => lower.endsWith(extension))) continue;
225
+
226
+ if (desired.has(artifactStem(name))) continue;
227
+
228
+ // Skill-command wrappers are named after skills, not command sources, so
229
+ // they are absent from the command desired set by construction — pruning
230
+ // them against it would delete wrappers the same deploy just wrote (#2507).
231
+ // They are retired against the skill inventory instead, when one is given
232
+ // (#2511); without one they stay exempt.
233
+ if (managed[name]?.kind === 'skill-command') {
234
+ if (!skillCommandStems || skillCommandStems.has(artifactStem(name))) continue;
235
+ }
236
+
237
+ // Ownership gate — never delete a file AIWG didn't deploy.
238
+ let owned = Object.prototype.hasOwnProperty.call(managed, name);
239
+ if (!owned) {
240
+ try {
241
+ owned = MANAGED_MARKER_RE.test(fs.readFileSync(path.join(destDir, name), 'utf8'));
242
+ } catch {
243
+ owned = false; // unreadable → leave it alone
244
+ }
245
+ }
246
+ if (!owned) continue;
247
+
248
+ const target = path.join(destDir, name);
249
+ removed.push(target);
250
+ if (dryRun) {
251
+ if (verbose) console.log(`[dry-run] would prune stale AIWG artifact: ${path.relative(process.cwd(), target)}`);
252
+ continue;
253
+ }
254
+ try {
255
+ fs.unlinkSync(target);
256
+ if (Object.prototype.hasOwnProperty.call(managed, name)) {
257
+ delete managed[name];
258
+ sidecarDirty = true;
259
+ }
260
+ if (verbose) console.log(`pruned stale AIWG artifact: ${path.relative(process.cwd(), target)}`);
261
+ } catch (err) {
262
+ removed.pop();
263
+ if (verbose) console.warn(`Warning: could not prune ${target}: ${err.message}`);
264
+ }
265
+ }
266
+
267
+ if (sidecarDirty) writeSidecarManifest(destDir, sidecar, dryRun);
268
+ return removed;
269
+ }
@@ -0,0 +1,354 @@
1
+ // Shared provider kernel skills utilities.
2
+ import { fs, path } from './base-runtime.mjs';
3
+ import { parseFrontmatter } from './base-frontmatter.mjs';
4
+ import { ensureDir } from './base-files.mjs';
5
+ import { deploySkillDir, pruneMissingStandardSkills } from './base-skill-copy.mjs';
6
+
7
+
8
+ /**
9
+ * Read a skill's SKILL.md frontmatter and return whether it is a
10
+ * "kernel" skill — always-loaded, deploys to the platform's native
11
+ * skills directory rather than the AIWG-namespaced one. Per epic
12
+ * #1212. A skill opts in by setting `kernel: true` in its frontmatter.
13
+ *
14
+ * Note: `parseFrontmatter` keeps values as strings (no YAML coercion).
15
+ * Accept both the string `"true"` and the boolean `true` so callers
16
+ * are not surprised if a future parser upgrade returns booleans.
17
+ */
18
+ export function isKernelSkill(skillDir) {
19
+ const skillMdPath = path.join(skillDir, 'SKILL.md');
20
+ if (!fs.existsSync(skillMdPath)) return false;
21
+ const content = fs.readFileSync(skillMdPath, 'utf8');
22
+ const { metadata } = parseFrontmatter(content);
23
+ const v = metadata?.kernel;
24
+ return v === true || v === 'true';
25
+ }
26
+
27
+
28
+ /**
29
+ * Deploy skills with kernel-vs-standard routing (#1212/#1216/#1217).
30
+ *
31
+ * Partitions `skillDirs` into kernel skills (frontmatter `kernel: true`)
32
+ * and standard skills.
33
+ *
34
+ * **Kernel skills** copy to `kernelDestDir` (platform-native dir,
35
+ * always-loaded by the platform). Small set: currently 24 skills spanning
36
+ * framework quickrefs, routing maps, and self-maintenance operations.
37
+ *
38
+ * **Standard skills** are NOT copied per-project (#1217). They live at
39
+ * `$AIWG_ROOT/agentic/code/.../skills/<name>/` and `aiwg discover`
40
+ * returns absolute paths anchored there. The agent reads them directly
41
+ * via the `Read` tool — no per-project mirror, no stale-copy risk.
42
+ * `standardDestDir` is retained as a fallback when `$AIWG_ROOT` is not
43
+ * readable, and as the cleanup target for legacy `.aiwg/skills/`
44
+ * directories from rc.13 and earlier deploys.
45
+ *
46
+ * @param skillDirs absolute paths to source skill directories
47
+ * @param standardDestDir absolute path for standard skills (legacy
48
+ * per-project mirror — used only as cleanup
49
+ * target by default; populated if
50
+ * `opts.copyStandardSkills` is true)
51
+ * @param kernelDestDir absolute path for kernel skills
52
+ * (e.g., `.cursor/skills`); pass null/undefined
53
+ * to disable kernel routing
54
+ * @param opts standard deploy opts forwarded to
55
+ * `deploySkillDir`. New optional flags:
56
+ * - `copyStandardSkills` (default: false) —
57
+ * force per-project copy of standard skills
58
+ * (used when $AIWG_ROOT is not readable from
59
+ * the agent's working directory)
60
+ *
61
+ * @returns `{ kernel, standardCopied, prunedFromKernelDir,
62
+ * prunedFromStandardDir, prunedKernelFromStandardDir }`
63
+ * deployed/pruned counts
64
+ *
65
+ * Cleanup behavior:
66
+ * - Kernel dir: prune any AIWG-shaped skill whose name now belongs
67
+ * to the standard tier (rc.13 behavior, preserved).
68
+ * - Standard dir: when standard copies are NOT being deployed this
69
+ * run, prune any AIWG-shaped skill that exists under
70
+ * `standardDestDir`. These are legacy per-project mirrors from
71
+ * rc.13 deploys; the canonical source is now `$AIWG_ROOT`.
72
+ * - User-authored skills (no SKILL.md, or names not in our deploy
73
+ * manifest) survive untouched in both directories.
74
+ */
75
+ export function deploySkillsWithKernelRouting(
76
+ skillDirs,
77
+ standardDestDir,
78
+ kernelDestDir,
79
+ opts,
80
+ ) {
81
+ // Caller opts in via `opts.copyStandardSkills` (set by `--copy-all`
82
+ // CLI flag, #1219). Default (#1217) is no-copy: standard skills stay
83
+ // at their source path under $AIWG_ROOT and are reached via the
84
+ // artifact index.
85
+ const copyStandardSkills = opts?.copyStandardSkills === true;
86
+
87
+ const kernel = [];
88
+ const standard = [];
89
+ for (const dir of skillDirs) {
90
+ if (kernelDestDir && isKernelSkill(dir)) kernel.push(dir);
91
+ else standard.push(dir);
92
+ }
93
+
94
+ // Names of skills in the deploy manifest — bound the cleanup to
95
+ // names AIWG manages so user-authored content survives.
96
+ const standardNames = new Set(standard.map(p => path.basename(p)));
97
+ const allSkillNames = new Set([...standardNames, ...kernel.map(p => path.basename(p))]);
98
+
99
+ if (kernel.length > 0 && kernelDestDir) {
100
+ ensureDir(kernelDestDir, opts?.dryRun);
101
+ for (const dir of kernel) deploySkillDir(dir, kernelDestDir, opts);
102
+ }
103
+
104
+ // Standard tier copy is OFF by default (#1217). Only fires when the
105
+ // operator explicitly opts in via `copyStandardSkills` — typically
106
+ // because $AIWG_ROOT isn't readable from the agent's working dir.
107
+ let standardCopied = 0;
108
+ if (copyStandardSkills && standard.length > 0) {
109
+ ensureDir(standardDestDir, opts?.dryRun);
110
+ for (const dir of standard) {
111
+ deploySkillDir(dir, standardDestDir, opts);
112
+ standardCopied++;
113
+ }
114
+ }
115
+
116
+ // A skill promoted from standard → kernel may still have an older managed
117
+ // copy in the opt-in standard mirror. Remove that duplicate even when
118
+ // --copy-all remains enabled; otherwise providers that recursively scan
119
+ // both tiers can surface the same skill twice after a tier transition.
120
+ let prunedKernelFromStandardDir = 0;
121
+ if (
122
+ standardDestDir &&
123
+ fs.existsSync(standardDestDir) &&
124
+ !opts?.dryRun &&
125
+ kernel.length > 0
126
+ ) {
127
+ const kernelNames = new Set(kernel.map(p => path.basename(p)));
128
+ for (const entry of fs.readdirSync(standardDestDir, { withFileTypes: true })) {
129
+ if (!entry.isDirectory() || !kernelNames.has(entry.name)) continue;
130
+ const target = path.join(standardDestDir, entry.name);
131
+ const skillMd = path.join(target, 'SKILL.md');
132
+ if (!fs.existsSync(skillMd)) continue;
133
+ const marker = path.join(target, '.aiwg-managed');
134
+ let managed = fs.existsSync(marker);
135
+ if (!managed) {
136
+ try {
137
+ managed = /^\s*namespace:\s*["']?aiwg["']?\s*$/m.test(
138
+ parseFrontmatter(fs.readFileSync(skillMd, 'utf8')).frontmatter ?? '',
139
+ );
140
+ } catch { /* preserve unreadable/operator-owned content */ }
141
+ }
142
+ if (!managed) continue;
143
+ fs.rmSync(target, { recursive: true, force: true });
144
+ prunedKernelFromStandardDir++;
145
+ if (opts?.verbose) console.log(`pruned promoted kernel from standard dir: ${entry.name}`);
146
+ }
147
+ }
148
+
149
+ // Kernel-dir cleanup: prune skills whose name moved to the standard
150
+ // tier (rc.13 logic). Holistic cleanup of orphaned skills (renamed or
151
+ // removed sources) happens in a separate post-all-deploys step
152
+ // (`pruneStaleAiwgSkills`) — running per-call here would race because
153
+ // `deploySkills` may be invoked multiple times in one orchestration.
154
+ let prunedFromKernelDir = 0;
155
+ if (kernelDestDir && fs.existsSync(kernelDestDir) && !opts?.dryRun) {
156
+ for (const entry of fs.readdirSync(kernelDestDir, { withFileTypes: true })) {
157
+ if (!entry.isDirectory()) continue;
158
+ const skillMd = path.join(kernelDestDir, entry.name, 'SKILL.md');
159
+ if (!fs.existsSync(skillMd)) continue;
160
+ if (!standardNames.has(entry.name)) continue;
161
+ const target = path.join(kernelDestDir, entry.name);
162
+ try {
163
+ fs.rmSync(target, { recursive: true, force: true });
164
+ prunedFromKernelDir++;
165
+ if (opts?.verbose) console.log(`pruned legacy from kernel dir: ${entry.name}`);
166
+ } catch (err) {
167
+ if (opts?.verbose) console.warn(`Warning: could not prune ${target}: ${err.message}`);
168
+ }
169
+ }
170
+ }
171
+
172
+ // Standard-dir cleanup (#1217): when we're NOT copying standard
173
+ // skills, anything AIWG-named under standardDestDir is a legacy
174
+ // mirror from a rc.13-or-earlier deploy. Prune to clean up.
175
+ let prunedFromStandardDir = pruneMissingStandardSkills(standardDestDir, opts);
176
+ if (
177
+ !copyStandardSkills &&
178
+ standardDestDir &&
179
+ fs.existsSync(standardDestDir) &&
180
+ !opts?.dryRun
181
+ ) {
182
+ for (const entry of fs.readdirSync(standardDestDir, { withFileTypes: true })) {
183
+ if (!entry.isDirectory()) continue;
184
+ const skillMd = path.join(standardDestDir, entry.name, 'SKILL.md');
185
+ if (!fs.existsSync(skillMd)) continue;
186
+ // Only prune skills AIWG manages — bound by the deploy manifest.
187
+ if (!allSkillNames.has(entry.name)) continue;
188
+ const target = path.join(standardDestDir, entry.name);
189
+ try {
190
+ fs.rmSync(target, { recursive: true, force: true });
191
+ prunedFromStandardDir++;
192
+ if (opts?.verbose) console.log(`pruned legacy from standard dir: ${entry.name}`);
193
+ } catch (err) {
194
+ if (opts?.verbose) console.warn(`Warning: could not prune ${target}: ${err.message}`);
195
+ }
196
+ }
197
+ // Try to remove the now-empty standard dir + its parent .aiwg/
198
+ // wrapper if both end up empty. Best-effort.
199
+ try {
200
+ const remaining = fs.readdirSync(standardDestDir);
201
+ if (remaining.length === 0) {
202
+ fs.rmdirSync(standardDestDir);
203
+ const aiwgWrapper = path.dirname(standardDestDir);
204
+ if (path.basename(aiwgWrapper) === '.aiwg') {
205
+ const wrapperRemaining = fs.readdirSync(aiwgWrapper);
206
+ if (wrapperRemaining.length === 0) fs.rmdirSync(aiwgWrapper);
207
+ }
208
+ }
209
+ } catch { /* non-fatal */ }
210
+ }
211
+
212
+ return {
213
+ kernel: kernel.length,
214
+ standardCopied,
215
+ prunedFromKernelDir,
216
+ prunedFromStandardDir,
217
+ prunedKernelFromStandardDir,
218
+ };
219
+ }
220
+
221
+
222
+ /**
223
+ * Compute the global desired-kernel set by walking the entire AIWG
224
+ * source tree (frameworks + addons), regardless of which deploy mode
225
+ * is in flight. Used by `pruneStaleAiwgSkills` so cleanup never races
226
+ * with sibling deploy invocations (`aiwg use` runs `deploy-agents.mjs`
227
+ * multiple times — once per framework, once per addon batch).
228
+ *
229
+ * @param {string} srcRoot AIWG repo / install root
230
+ * @returns {string[]|null} basenames of every source skill dir whose
231
+ * SKILL.md frontmatter has `kernel: true`, or `null` when no AIWG
232
+ * framework/addon tree can be located. A `null` return signals the
233
+ * caller (`pruneStaleAiwgSkills`) to SKIP pruning rather than treat an
234
+ * empty set as "delete every AIWG skill" (#123). Mirrors the contract of
235
+ * `computeAllArtifactBasenames` (#1627).
236
+ */
237
+ export function computeAllKernelNames(srcRoot) {
238
+ const hasAiwgTree = (dir) =>
239
+ fs.existsSync(path.join(dir, 'agentic', 'code', 'frameworks')) &&
240
+ fs.existsSync(path.join(dir, 'agentic', 'code', 'addons'));
241
+ const isRootOrSourceDescendant = (candidate, original) => {
242
+ const root = path.resolve(candidate);
243
+ const source = path.resolve(original);
244
+ const agenticCode = path.join(root, 'agentic', 'code');
245
+ return source === root || source === agenticCode || source.startsWith(`${agenticCode}${path.sep}`);
246
+ };
247
+
248
+ // Prefer an explicit AIWG_ROOT, but only when it actually points at a real
249
+ // AIWG tree — a stale/bogus env value must not silently yield an empty
250
+ // desired set. Otherwise walk up from srcRoot (the caller may pass an
251
+ // addon/framework/project-local-bundle path, not the install root).
252
+ let aiwgRoot = null;
253
+ if (process.env.AIWG_ROOT && hasAiwgTree(process.env.AIWG_ROOT)) {
254
+ aiwgRoot = process.env.AIWG_ROOT;
255
+ } else {
256
+ let cur = path.resolve(srcRoot);
257
+ for (let i = 0; i < 8; i++) {
258
+ if (hasAiwgTree(cur) && isRootOrSourceDescendant(cur, srcRoot)) { aiwgRoot = cur; break; }
259
+ const parent = path.dirname(cur);
260
+ if (parent === cur) break;
261
+ cur = parent;
262
+ }
263
+ }
264
+
265
+ // No AIWG framework/addon tree found — e.g. deploying a project-local
266
+ // bundle with AIWG_ROOT unset. Return null so the prune is skipped.
267
+ if (!aiwgRoot) return null;
268
+
269
+ const names = new Set();
270
+ const roots = [
271
+ path.join(aiwgRoot, 'agentic', 'code', 'frameworks'),
272
+ path.join(aiwgRoot, 'agentic', 'code', 'addons'),
273
+ ];
274
+ for (const root of roots) {
275
+ if (!fs.existsSync(root)) continue;
276
+ for (const componentEntry of fs.readdirSync(root, { withFileTypes: true })) {
277
+ if (!componentEntry.isDirectory()) continue;
278
+ const skillsDir = path.join(root, componentEntry.name, 'skills');
279
+ if (!fs.existsSync(skillsDir)) continue;
280
+ for (const skillEntry of fs.readdirSync(skillsDir, { withFileTypes: true })) {
281
+ if (!skillEntry.isDirectory()) continue;
282
+ const fullPath = path.join(skillsDir, skillEntry.name);
283
+ if (isKernelSkill(fullPath)) names.add(skillEntry.name);
284
+ }
285
+ }
286
+ }
287
+ return Array.from(names);
288
+ }
289
+
290
+
291
+ /**
292
+ * Holistic post-deploy cleanup of stale AIWG-managed skills.
293
+ *
294
+ * Run this AFTER all `deploySkills` invocations have completed for a
295
+ * given provider so the desired-name set reflects every kernel skill
296
+ * deployed across all frameworks/addons. Per-call cleanup races because
297
+ * `deploySkills` may be invoked multiple times in one orchestration —
298
+ * this function does the cleanup once at the end.
299
+ *
300
+ * Identifies AIWG-managed skills via:
301
+ * 1. `.aiwg-managed` marker file (preferred — set by `deploySkillDir`)
302
+ * 2. Frontmatter `namespace: aiwg` (migration fallback for pre-marker
303
+ * deploys; stops firing after one redeploy)
304
+ *
305
+ * Bounded to entries identified above, so user-authored skills next to
306
+ * AIWG-managed ones are never touched.
307
+ *
308
+ * @param {string} kernelDestDir absolute path to the platform's kernel
309
+ * skills dir (e.g. `<project>/.claude/skills/`)
310
+ * @param {string[]|null} desiredKernelNames names of every kernel skill that
311
+ * SHOULD remain (basenames of source dirs). When `null` (no AIWG tree
312
+ * located — see `computeAllKernelNames`), pruning is skipped entirely so a
313
+ * project-local-bundle deploy without AIWG_ROOT never empties the kernel
314
+ * skills directory (#123).
315
+ * @param {object} opts `{ dryRun, verbose, artifactExtensions }`
316
+ * @returns {number} count of pruned entries
317
+ */
318
+ export function pruneStaleAiwgSkills(kernelDestDir, desiredKernelNames, opts = {}) {
319
+ if (!kernelDestDir || !fs.existsSync(kernelDestDir)) return 0;
320
+ // No global desired set — skip pruning rather than delete everything (#123).
321
+ if (desiredKernelNames == null) return 0;
322
+ if (opts.dryRun) return 0;
323
+ const desired = new Set(desiredKernelNames);
324
+ let pruned = 0;
325
+ for (const entry of fs.readdirSync(kernelDestDir, { withFileTypes: true })) {
326
+ if (!entry.isDirectory()) continue;
327
+ if (desired.has(entry.name)) continue;
328
+
329
+ const skillMd = path.join(kernelDestDir, entry.name, 'SKILL.md');
330
+ if (!fs.existsSync(skillMd)) continue;
331
+
332
+ const marker = path.join(kernelDestDir, entry.name, '.aiwg-managed');
333
+ let isAiwgManaged = fs.existsSync(marker);
334
+ if (!isAiwgManaged) {
335
+ try {
336
+ const content = fs.readFileSync(skillMd, 'utf8');
337
+ const fmMatch = content.match(/^---\n([\s\S]*?)\n---/);
338
+ if (fmMatch && /^\s*namespace:\s*["']?aiwg["']?\s*$/m.test(fmMatch[1])) {
339
+ isAiwgManaged = true;
340
+ }
341
+ } catch { /* unreadable — leave alone */ }
342
+ }
343
+ if (!isAiwgManaged) continue;
344
+
345
+ try {
346
+ fs.rmSync(path.join(kernelDestDir, entry.name), { recursive: true, force: true });
347
+ pruned++;
348
+ if (opts.verbose) console.log(`pruned stale AIWG skill: ${entry.name}`);
349
+ } catch (err) {
350
+ if (opts.verbose) console.warn(`Warning: could not prune ${entry.name}: ${err.message}`);
351
+ }
352
+ }
353
+ return pruned;
354
+ }