@aiwg/cli 2026.10.15 → 2026.10.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (286) hide show
  1. package/agentic/code/providers/pi/aiwg-bridge.ts +45 -7
  2. package/dist/src/artifacts/citation-parser.js +7 -6
  3. package/dist/src/artifacts/corpus-tools/citation-densify.js +4 -2
  4. package/dist/src/artifacts/corpus-tools/cli.js +8 -3
  5. package/dist/src/artifacts/corpus-tools/discovery-log.js +26 -24
  6. package/dist/src/artifacts/corpus-tools/expand-cli.js +3 -2
  7. package/dist/src/artifacts/corpus-tools/expand-dates.js +107 -0
  8. package/dist/src/artifacts/corpus-tools/expand-queue.js +4 -1
  9. package/dist/src/artifacts/corpus-tools/expand-review.js +104 -0
  10. package/dist/src/artifacts/corpus-tools/expand-state.js +17 -1
  11. package/dist/src/artifacts/corpus-tools/expand.js +16 -17
  12. package/dist/src/artifacts/corpus-tools/induction-audit.js +7 -6
  13. package/dist/src/artifacts/corpus-tools/integrity-scan.js +3 -3
  14. package/dist/src/artifacts/corpus-tools/radar-shared.js +7 -9
  15. package/dist/src/artifacts/corpus-tools/ref-files.js +11 -0
  16. package/dist/src/artifacts/corpus-tools/resolve-cli.js +11 -3
  17. package/dist/src/artifacts/corpus-tools/resolve.js +42 -11
  18. package/dist/src/artifacts/corpus-tools/retrieval-lab.js +2 -1
  19. package/dist/src/artifacts/corpus-tools/sidecar-lint.js +4 -4
  20. package/dist/src/artifacts/corpus-tools/sidecar-repair.js +2 -1
  21. package/dist/src/artifacts/corpus-views/ref-parser.js +3 -17
  22. package/dist/src/artifacts/graph-query.js +5 -3
  23. package/dist/src/artifacts/hybrid-query.js +11 -2
  24. package/dist/src/artifacts/index-refresh.js +2 -0
  25. package/dist/src/artifacts/query-engine-corpus.js +217 -0
  26. package/dist/src/artifacts/query-engine-discover-output.js +229 -0
  27. package/dist/src/artifacts/query-engine-discover.js +285 -0
  28. package/dist/src/artifacts/query-engine-entries.js +188 -0
  29. package/dist/src/artifacts/query-engine-index.js +249 -0
  30. package/dist/src/artifacts/query-engine-matching.js +143 -0
  31. package/dist/src/artifacts/query-engine-options.js +2 -0
  32. package/dist/src/artifacts/query-engine-rules.js +202 -0
  33. package/dist/src/artifacts/query-engine-scoring.js +436 -0
  34. package/dist/src/artifacts/query-engine-show-card.js +194 -0
  35. package/dist/src/artifacts/query-engine-show-load.js +211 -0
  36. package/dist/src/artifacts/query-engine-show.js +300 -0
  37. package/dist/src/artifacts/query-engine.js +7 -2576
  38. package/dist/src/cli/handlers/daemon.js +17 -1
  39. package/dist/src/cli/handlers/doctor-args.js +10 -5
  40. package/dist/src/cli/handlers/doctor-help.js +4 -1
  41. package/dist/src/cli/handlers/index.js +2 -2
  42. package/dist/src/cli/handlers/mc-agents.js +111 -0
  43. package/dist/src/cli/handlers/mc-args.js +54 -0
  44. package/dist/src/cli/handlers/mc-control.js +227 -0
  45. package/dist/src/cli/handlers/mc-dispatch.js +203 -0
  46. package/dist/src/cli/handlers/mc-help.js +171 -0
  47. package/dist/src/cli/handlers/mc-run.js +343 -0
  48. package/dist/src/cli/handlers/mc-session.js +138 -0
  49. package/dist/src/cli/handlers/mc-status.js +258 -0
  50. package/dist/src/cli/handlers/mc-summary.js +43 -0
  51. package/dist/src/cli/handlers/mc-types.js +3 -0
  52. package/dist/src/cli/handlers/mc-worker.js +205 -0
  53. package/dist/src/cli/handlers/mc.js +12 -1665
  54. package/dist/src/cli/handlers/models-refusal.js +13 -0
  55. package/dist/src/cli/handlers/models-resource-sample.js +10 -0
  56. package/dist/src/cli/handlers/models.js +5 -3
  57. package/dist/src/cli/handlers/regenerate.js +8 -16
  58. package/dist/src/cli/handlers/remove-bundled.js +133 -0
  59. package/dist/src/cli/handlers/remove-options.js +31 -0
  60. package/dist/src/cli/handlers/remove-user.js +174 -0
  61. package/dist/src/cli/handlers/remove.js +201 -0
  62. package/dist/src/cli/handlers/sessions.js +7 -7
  63. package/dist/src/cli/handlers/subcommands-bundles.js +257 -0
  64. package/dist/src/cli/handlers/subcommands-discovery.js +165 -0
  65. package/dist/src/cli/handlers/subcommands-list-format.js +129 -0
  66. package/dist/src/cli/handlers/subcommands-list.js +250 -0
  67. package/dist/src/cli/handlers/subcommands-plugins.js +213 -0
  68. package/dist/src/cli/handlers/subcommands-quickref.js +58 -0
  69. package/dist/src/cli/handlers/subcommands-rlm.js +113 -0
  70. package/dist/src/cli/handlers/subcommands-services.js +66 -0
  71. package/dist/src/cli/handlers/subcommands-storage.js +259 -0
  72. package/dist/src/cli/handlers/subcommands.js +18 -1976
  73. package/dist/src/cli/handlers/update.js +157 -0
  74. package/dist/src/cli/handlers/use.js +14 -4
  75. package/dist/src/cli/handlers/utilities.js +3 -560
  76. package/dist/src/cli/handlers/utility-doctor.js +412 -0
  77. package/dist/src/cli/scope-resolver.js +1 -142
  78. package/dist/src/cli/services/deployment-verification.js +0 -1
  79. package/dist/src/cli/user-scope-mirror.js +173 -0
  80. package/dist/src/config/aiwg-config.js +2 -1
  81. package/dist/src/config/authorization-cli.js +7 -3
  82. package/dist/src/config/dispatch-host-thresholds.js +2 -0
  83. package/dist/src/config/dispatch-thresholds-runtime.d.mts +3 -2
  84. package/dist/src/config/dispatch-thresholds-runtime.mjs +21 -7
  85. package/dist/src/config/framework-aliases.js +12 -0
  86. package/dist/src/config/host-resource-report.d.mts +24 -0
  87. package/dist/src/config/host-resource-report.mjs +110 -0
  88. package/dist/src/config/host-resource-runtime.d.mts +37 -0
  89. package/dist/src/config/host-resource-runtime.mjs +296 -0
  90. package/dist/src/config/installed-selection.js +22 -0
  91. package/dist/src/config/worker-invocation-marker.d.mts +1 -0
  92. package/dist/src/config/worker-invocation-marker.mjs +2 -0
  93. package/dist/src/decision/ensemble-study/artifacts.js +7 -0
  94. package/dist/src/decision/ensemble-study/gate-policy.js +58 -0
  95. package/dist/src/decision/ensemble-study/gates.js +78 -0
  96. package/dist/src/decision/ensemble-study/protocol.js +18 -21
  97. package/dist/src/decision/ensemble-study/score.js +3 -2
  98. package/dist/src/decision/ensemble-study/statistics.js +7 -26
  99. package/dist/src/decision/heldout/access.js +74 -0
  100. package/dist/src/decision/heldout/calibration.js +1 -0
  101. package/dist/src/decision/heldout/collector.js +8 -1
  102. package/dist/src/decision/sensitivity/comparative-gates.js +135 -0
  103. package/dist/src/decision/sensitivity/comparative.js +18 -41
  104. package/dist/src/effects/verifiers/file.js +22 -5
  105. package/dist/src/extensions/claude-attribution.js +82 -0
  106. package/dist/src/extensions/claude-hooks-installer.js +133 -69
  107. package/dist/src/extensions/commands/daemon.js +109 -0
  108. package/dist/src/extensions/commands/definitions.js +5 -89
  109. package/dist/src/gates/evaluate.js +2 -358
  110. package/dist/src/gates/heldout.js +17 -7
  111. package/dist/src/gates/observations.js +363 -0
  112. package/dist/src/gates/pack-composition.js +270 -0
  113. package/dist/src/gates/pack-tightening.js +197 -0
  114. package/dist/src/gates/pack-validation.js +262 -0
  115. package/dist/src/gates/registry-error.js +5 -0
  116. package/dist/src/gates/registry.js +13 -685
  117. package/dist/src/lint/check-patterns.js +163 -0
  118. package/dist/src/lint/checks.js +268 -0
  119. package/dist/src/lint/reference-resolution.js +54 -0
  120. package/dist/src/lint/runner.js +3 -465
  121. package/dist/src/mcp/helpers.mjs +11 -1
  122. package/dist/src/mcp/json-document.mjs +29 -0
  123. package/dist/src/mcp/muse-native-config.mjs +1 -28
  124. package/dist/src/memory/project-registry.js +44 -4
  125. package/dist/src/mission-protocol/worker-review-gate.js +7 -0
  126. package/dist/src/models/worker-plan.js +36 -5
  127. package/dist/src/models/wrapper-deployment.js +25 -12
  128. package/dist/src/models/wrapper-enforcement.js +47 -7
  129. package/dist/src/network-analysis/research.js +2 -1
  130. package/dist/src/plugin/command-ownership.js +34 -0
  131. package/dist/src/plugin/skill-command-frontmatter.js +197 -0
  132. package/dist/src/plugin/skill-command-translator.js +6 -232
  133. package/dist/src/policy/hitl-check.js +14 -4
  134. package/dist/src/policy/hitl-consume.js +54 -0
  135. package/dist/src/policy/hitl-receipt.js +2 -0
  136. package/dist/src/policy/hitl.js +11 -3
  137. package/dist/src/providers/context-output-ownership.js +26 -0
  138. package/dist/src/providers/deployment-ownership.d.mts +19 -0
  139. package/dist/src/providers/deployment-ownership.mjs +226 -0
  140. package/dist/src/providers/deployment-removal.js +200 -0
  141. package/dist/src/providers/provider-context-contracts.js +162 -0
  142. package/dist/src/providers/provider-definition-schema.js +136 -0
  143. package/dist/src/providers/provider-definitions.js +8 -1298
  144. package/dist/src/providers/provider-seeds-1.js +360 -0
  145. package/dist/src/providers/provider-seeds-2.js +387 -0
  146. package/dist/src/providers/provider-seeds-3.js +262 -0
  147. package/dist/src/providers/removal-transaction.js +86 -0
  148. package/dist/src/providers/settings-document.d.mts +3 -0
  149. package/dist/src/providers/settings-document.mjs +47 -0
  150. package/dist/src/providers/settings-removal.js +190 -0
  151. package/dist/src/providers/skill-ownership.d.mts +19 -2
  152. package/dist/src/providers/skill-ownership.mjs +12 -4
  153. package/dist/src/providers/transformation-receipt-integration.js +15 -271
  154. package/dist/src/providers/transformation-receipt-outputs.js +99 -0
  155. package/dist/src/providers/transformation-receipt-source.js +194 -0
  156. package/dist/src/research/clients/arxiv.js +4 -30
  157. package/dist/src/research/clients/base.js +48 -22
  158. package/dist/src/research/identity.js +42 -4
  159. package/dist/src/research/query-cli.js +3 -87
  160. package/dist/src/research/query-options.js +87 -0
  161. package/dist/src/research/reference-match.js +105 -24
  162. package/dist/src/research/services/acquisition.js +9 -7
  163. package/dist/src/research/services/citation.js +5 -2
  164. package/dist/src/research/types.js +2 -0
  165. package/dist/src/rules/activation.mjs +15 -6
  166. package/dist/src/rules/core-startup.mjs +2 -2
  167. package/dist/src/serve/mission-conductor.js +52 -4
  168. package/dist/src/serve/mission-summary.js +56 -0
  169. package/dist/src/sessions/adapters/grok-build-native.js +23 -0
  170. package/dist/src/sessions/adapters/grok-build.js +14 -7
  171. package/dist/src/sessions/workspace-discovery.js +5 -5
  172. package/dist/src/smiths/context-pipeline/aiwg-md.js +39 -46
  173. package/dist/src/smiths/context-pipeline/claude-hook.js +1 -1
  174. package/dist/src/smiths/context-pipeline/code-regions.js +28 -0
  175. package/dist/src/smiths/context-pipeline/context-file-safety.js +3 -0
  176. package/dist/src/smiths/context-pipeline/finalization.js +81 -51
  177. package/dist/src/smiths/context-pipeline/generator.js +10 -11
  178. package/dist/src/smiths/context-pipeline/managed-hook.js +1 -1
  179. package/dist/src/smiths/context-pipeline/muse-bridge.js +2 -2
  180. package/dist/src/smiths/context-pipeline/provider-policy.js +6 -12
  181. package/dist/src/smiths/context-pipeline/workspace-audit.js +299 -0
  182. package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +148 -0
  183. package/dist/src/smiths/context-pipeline/workspace-context-shared.js +111 -0
  184. package/dist/src/smiths/context-pipeline/workspace-context.js +8 -1373
  185. package/dist/src/smiths/context-pipeline/workspace-doctor.js +192 -0
  186. package/dist/src/smiths/context-pipeline/workspace-document.js +201 -0
  187. package/dist/src/smiths/context-pipeline/workspace-extraction.js +205 -0
  188. package/dist/src/smiths/context-pipeline/workspace-migration.js +250 -0
  189. package/dist/src/smiths/hook-bridge/index.js +9 -0
  190. package/package.json +13 -1
  191. package/schemas/decision/D17StudyProtocol.v1.schema.json +39 -67
  192. package/schemas/decision/D29Study.v10.schema.json +65 -0
  193. package/tools/agents/deploy-agents.mjs +24 -675
  194. package/tools/agents/deploy-command-mirrors.mjs +229 -0
  195. package/tools/agents/deploy-options.mjs +258 -0
  196. package/tools/agents/deploy-support.mjs +165 -0
  197. package/tools/agents/providers/base-addon-discovery.mjs +139 -0
  198. package/tools/agents/providers/base-behaviors.mjs +168 -0
  199. package/tools/agents/providers/base-context.mjs +205 -0
  200. package/tools/agents/providers/base-contract.mjs +116 -0
  201. package/tools/agents/providers/base-files.mjs +252 -0
  202. package/tools/agents/providers/base-flat-artifacts.mjs +233 -0
  203. package/tools/agents/providers/base-framework-discovery.mjs +309 -0
  204. package/tools/agents/providers/base-frontmatter.mjs +196 -0
  205. package/tools/agents/providers/base-inventory.mjs +269 -0
  206. package/tools/agents/providers/base-kernel-skills.mjs +354 -0
  207. package/tools/agents/providers/base-migrations.mjs +258 -0
  208. package/tools/agents/providers/base-models-platforms.mjs +273 -0
  209. package/tools/agents/providers/base-rule-index.mjs +450 -0
  210. package/tools/agents/providers/base-runtime.mjs +60 -0
  211. package/tools/agents/providers/base-skill-copy.mjs +273 -0
  212. package/tools/agents/providers/base.mjs +16 -3364
  213. package/tools/agents/providers/claude-post-deploy.mjs +20 -1
  214. package/tools/agents/providers/context-write.mjs +4 -0
  215. package/tools/agents/providers/hermes-startup.mjs +0 -5
  216. package/tools/agents/providers/muse.mjs +7 -2
  217. package/tools/agents/providers/pi.mjs +3 -1
  218. package/tools/agents/providers/rule-delivery-surface.mjs +359 -0
  219. package/tools/agents/providers/rule-delivery.mjs +20 -1144
  220. package/tools/agents/providers/rule-deployment-commit.mjs +148 -0
  221. package/tools/agents/providers/rule-deployment-prepare.mjs +461 -0
  222. package/tools/agents/providers/rule-deployment-state.mjs +300 -0
  223. package/tools/agents/providers/rule-projection.mjs +3 -0
  224. package/tools/daemon/README.md +511 -0
  225. package/tools/daemon/adapters/base-adapter.mjs +84 -0
  226. package/tools/daemon/adapters/webhook-adapter.mjs +107 -0
  227. package/tools/daemon/agent-supervisor.mjs +299 -0
  228. package/tools/daemon/automation-engine.mjs +310 -0
  229. package/tools/daemon/autonomous-engine.mjs +346 -0
  230. package/tools/daemon/behavior-loader.mjs +316 -0
  231. package/tools/daemon/behavior.mjs +174 -0
  232. package/tools/daemon/concierge/intent-router.mjs +401 -0
  233. package/tools/daemon/concierge/orchestrator.mjs +272 -0
  234. package/tools/daemon/concierge/response-translator.mjs +462 -0
  235. package/tools/daemon/config.mjs +377 -0
  236. package/tools/daemon/cron-scheduler.mjs +178 -0
  237. package/tools/daemon/daemon-main.mjs +1169 -0
  238. package/tools/daemon/event-router.mjs +84 -0
  239. package/tools/daemon/file-watcher.mjs +383 -0
  240. package/tools/daemon/index.mjs +1181 -0
  241. package/tools/daemon/init-profile.mjs +124 -0
  242. package/tools/daemon/ipc-client.mjs +197 -0
  243. package/tools/daemon/ipc-ops-handlers.mjs +236 -0
  244. package/tools/daemon/ipc-server.mjs +275 -0
  245. package/tools/daemon/maintenance-owner.mjs +79 -0
  246. package/tools/daemon/memory-manager.mjs +386 -0
  247. package/tools/daemon/message-router.mjs +194 -0
  248. package/tools/daemon/provider-watcher.mjs +585 -0
  249. package/tools/daemon/pty-adapter.mjs +420 -0
  250. package/tools/daemon/repl-chat.mjs +359 -0
  251. package/tools/daemon/resource-bounds.mjs +88 -0
  252. package/tools/daemon/sandbox-transport.mjs +295 -0
  253. package/tools/daemon/scheduled-task-runner.mjs +535 -0
  254. package/tools/daemon/task-store.mjs +450 -0
  255. package/tools/daemon/tmux-manager.mjs +324 -0
  256. package/tools/daemon/update-policy.mjs +517 -0
  257. package/tools/daemon/web-server.mjs +399 -0
  258. package/tools/daemon/web-ui/index.html +585 -0
  259. package/tools/daemon/web-ui/styles.css +156 -0
  260. package/tools/docker/Dockerfile.daemon +35 -0
  261. package/tools/docker/container-manager.mjs +291 -0
  262. package/tools/messaging/adapter-registry.mjs +230 -0
  263. package/tools/messaging/adapters/base.mjs +326 -0
  264. package/tools/messaging/adapters/discord.mjs +462 -0
  265. package/tools/messaging/adapters/slack.mjs +402 -0
  266. package/tools/messaging/adapters/telegram.mjs +552 -0
  267. package/tools/messaging/chat-handler.mjs +297 -0
  268. package/tools/messaging/command-router.mjs +269 -0
  269. package/tools/messaging/event-bus.mjs +199 -0
  270. package/tools/messaging/index.mjs +456 -0
  271. package/tools/messaging/message-formatter.mjs +320 -0
  272. package/tools/messaging/room-manager.mjs +277 -0
  273. package/tools/messaging/types.mjs +94 -0
  274. package/tools/providers/pi-bridge-policy.mjs +4 -0
  275. package/tools/ralph-external/daemon-supervisor.mjs +394 -0
  276. package/tools/ralph-external/lib/behavior-registry.mjs +270 -0
  277. package/tools/ralph-external/lib/worker-invocation-processes.mjs +7 -4
  278. package/tools/ralph-external/lib/worker-isolation-args.mjs +217 -0
  279. package/tools/ralph-external/lib/worker-isolation-status.mjs +19 -0
  280. package/tools/ralph-external/lib/worker-isolation.mjs +11 -237
  281. package/tools/ralph-external/lib/worker-overflow.mjs +10 -2
  282. package/tools/ralph-external/lib/worker-termination.mjs +15 -8
  283. package/tools/ralph-external/lib/worker-unit-cleanup.mjs +72 -0
  284. package/tools/ralph-external/session-launcher.mjs +7 -7
  285. package/tools/scripts/resource-preflight.mjs +3 -242
  286. package/vscode-extension/schemas/aiwg.config.v1.json +2 -4
@@ -0,0 +1,258 @@
1
+ // Shared provider migrations utilities.
2
+ import { fs, path } from './base-runtime.mjs';
3
+ import { MANAGED_MARKER_RE, MANIFEST_FILENAME, readSidecarManifest, writeSidecarManifest } from './base-files.mjs';
4
+
5
+
6
+ /**
7
+ * Clean up old individually-deployed rule files from target directory.
8
+ * Removes any .md files that are NOT RULES-INDEX.md.
9
+ *
10
+ * @param {string} rulesDir - Target rules directory
11
+ * @param {object} opts - Options
12
+ * @param {boolean} opts.dryRun - If true, log but don't delete
13
+ * @returns {string[]} - List of removed (or would-be-removed) file paths
14
+ */
15
+ /**
16
+ * Remove stale rule files from a deploy directory before writing fresh ones.
17
+ *
18
+ * Per #1143 + #1117: addon deploys run as separate `deploy-agents.mjs`
19
+ * invocations after the main framework, and the previous "wipe all non-index
20
+ * .md before writing" behavior caused the main framework's rules to be
21
+ * silently destroyed by every subsequent addon deploy (whether or not the
22
+ * addon shipped any rules of its own).
23
+ *
24
+ * The fix: cleanup only fires when the operator explicitly asks via
25
+ * `opts.cleanRules: true`. The deploy-time cleanup is replaced by a
26
+ * dedicated `aiwg refresh --clean-rules` operator flow (follow-up issue).
27
+ *
28
+ * Existing callers that pass `incomingFiles: []` still get a no-op; existing
29
+ * callers that pass nothing get the legacy (now-disabled) cleanup as a no-op
30
+ * by default.
31
+ *
32
+ * @param {string} rulesDir
33
+ * @param {object} opts
34
+ * @param {boolean} [opts.dryRun]
35
+ * @param {boolean} [opts.cleanRules] explicit opt-in to remove stale files
36
+ * @param {string[]} [opts.incomingFiles] when cleanRules=true, only files NOT
37
+ * in this list are removed
38
+ */
39
+ export function cleanupOldRuleFiles(rulesDir, opts = {}) {
40
+ const { dryRun = false, cleanRules = false, incomingFiles } = opts;
41
+ const removed = [];
42
+
43
+ if (!fs.existsSync(rulesDir)) return removed;
44
+ if (!cleanRules) return removed;
45
+ if (Array.isArray(incomingFiles) && incomingFiles.length === 0) return removed;
46
+
47
+ // Only `.md` rules are eligible for generic cleanup — `.mdc` (native Cursor
48
+ // rules) and non-rule files (config.json, …) are preserved. AIWG's own legacy
49
+ // `.md`→`.mdc` migration is handled explicitly by the Cursor provider's
50
+ // deployRulesInline (marker-gated), not here, so operator `.mdc` stay safe.
51
+ const incomingBasenames = new Set(
52
+ Array.isArray(incomingFiles)
53
+ ? incomingFiles.map((f) => path.basename(f))
54
+ : []
55
+ );
56
+
57
+ // Ownership gate (#1627): only AIWG-managed rule files are eligible for
58
+ // removal. A rule the operator dropped into the dir (no sidecar entry, no
59
+ // `aiwg:managed` marker) is preserved even when cleanRules is on.
60
+ const sidecarManaged = readSidecarManifest(rulesDir)?.managed || {};
61
+
62
+ const entries = fs.readdirSync(rulesDir, { withFileTypes: true });
63
+ for (const entry of entries) {
64
+ if (!entry.isFile()) continue;
65
+ if (!entry.name.toLowerCase().endsWith('.md')) continue;
66
+ if (entry.name === 'RULES-INDEX.md') continue;
67
+ if (entry.name === 'RULES-ONDEMAND.md') continue; // generated on-demand index (#1675) — protected like RULES-INDEX
68
+ if (incomingBasenames.has(entry.name)) continue;
69
+
70
+ const filePath = path.join(rulesDir, entry.name);
71
+
72
+ let owned = Object.prototype.hasOwnProperty.call(sidecarManaged, entry.name);
73
+ if (!owned) {
74
+ try {
75
+ owned = MANAGED_MARKER_RE.test(fs.readFileSync(filePath, 'utf8'));
76
+ } catch {
77
+ owned = false; // unreadable → leave it alone
78
+ }
79
+ }
80
+ if (!owned) continue; // user-authored rule — preserve
81
+
82
+ removed.push(filePath);
83
+
84
+ if (dryRun) {
85
+ console.log(`[dry-run] would remove old rule: ${entry.name}`);
86
+ } else {
87
+ fs.unlinkSync(filePath);
88
+ console.log(`removed old rule: ${entry.name}`);
89
+ }
90
+ }
91
+
92
+ if (removed.length > 0) {
93
+ console.log(`cleaned up ${removed.length} old rule file(s) from ${rulesDir}`);
94
+ }
95
+
96
+ return removed;
97
+ }
98
+
99
+
100
+ /**
101
+ * Migrate commands directory by removing stale AIWG command files before
102
+ * skills deployment.
103
+ *
104
+ * AIWG migrated from commands to skills. If old AIWG command files are left
105
+ * in place alongside newly deployed skills, the provider TUI (e.g. Claude
106
+ * Code's command palette) shows duplicate entries — one from the stale
107
+ * command file and one from the skill. This removes those duplicates.
108
+ *
109
+ * Removal is bounded to AIWG-managed command files (#1627): a command the
110
+ * operator authored (no sidecar entry, no `aiwg:managed` marker) is preserved.
111
+ * Subdirectories and non-command files are left untouched. The directory is
112
+ * removed only if it ends up empty after pruning AIWG files.
113
+ *
114
+ * Home-directory providers (codex, openclaw) are excluded by the caller: their
115
+ * commands paths are shared across all projects and must not be touched.
116
+ *
117
+ * @param {string} commandsDir - Full path to the provider's commands directory
118
+ * @param {object} opts
119
+ * @param {boolean} opts.dryRun - Log but don't delete
120
+ * @param {boolean} opts.skipCommandsMigration - User opted out; warn about duplicates instead
121
+ * @returns {boolean} true if any AIWG command file was removed (or would be in dry-run)
122
+ */
123
+ /**
124
+ * Commands directories already warned about this process. The stale-command
125
+ * condition belongs to the directory, not to each deployed framework/addon, so
126
+ * `aiwg use all` must not repeat it once per unit (#2541).
127
+ */
128
+ export const warnedCommandsDirs = new Set();
129
+
130
+
131
+ /**
132
+ * AIWG-managed command filenames in a directory — sidecar entries or files
133
+ * carrying the managed marker. Operator-authored commands and current
134
+ * skill-command wrappers are excluded.
135
+ */
136
+ export function listManagedCommandFiles(commandsDir) {
137
+ let entries;
138
+ try {
139
+ entries = fs.readdirSync(commandsDir, { withFileTypes: true });
140
+ } catch {
141
+ return [];
142
+ }
143
+ const sidecar = readSidecarManifest(commandsDir) || { managed: {} };
144
+ const managed = sidecar.managed || {};
145
+ const names = [];
146
+ for (const entry of entries) {
147
+ if (!entry.isFile()) continue;
148
+ if (!entry.name.toLowerCase().endsWith('.md')) continue;
149
+ if (managed[entry.name]?.kind === 'skill-command') continue;
150
+ let owned = Object.prototype.hasOwnProperty.call(managed, entry.name);
151
+ if (!owned) {
152
+ try {
153
+ owned = MANAGED_MARKER_RE.test(fs.readFileSync(path.join(commandsDir, entry.name), 'utf8'));
154
+ } catch {
155
+ owned = false;
156
+ }
157
+ }
158
+ if (owned) names.push(entry.name);
159
+ }
160
+ return names;
161
+ }
162
+
163
+
164
+ export function migrateCommandsDirectory(commandsDir, opts = {}) {
165
+ const { dryRun = false, skipCommandsMigration = false, verbose = false, warnOnSkip = true } = opts;
166
+
167
+ if (!fs.existsSync(commandsDir)) return false;
168
+
169
+ const entries = fs.readdirSync(commandsDir, { withFileTypes: true });
170
+ if (entries.length === 0) return false;
171
+
172
+ if (skipCommandsMigration) {
173
+ // Structural opt-outs (project-local addon bundles) skip the migration because
174
+ // it does not apply to them, not because the operator declined it. Warning
175
+ // there is noise, and it fired once per bundle (#2541).
176
+ if (!warnOnSkip) return false;
177
+
178
+ const rel = path.relative(process.cwd(), commandsDir);
179
+ // The condition is a property of the directory, not of each deployed unit;
180
+ // emit it once per run no matter how many units pass through.
181
+ const warned = opts.warnedCommandsDirs || warnedCommandsDirs;
182
+ if (warned.has(commandsDir)) return false;
183
+ warned.add(commandsDir);
184
+
185
+ const stale = listManagedCommandFiles(commandsDir);
186
+ if (stale.length === 0) return false;
187
+
188
+ console.warn(`\nWarning: commands migration skipped for ${rel}`);
189
+ console.warn(' Duplicate entries may appear in the command palette because these old');
190
+ console.warn(' AIWG command files overlap with newly deployed skills:');
191
+ for (const name of stale) console.warn(` ${path.join(rel, name)}`);
192
+ console.warn(' Resolve automatically by re-running without --skip-commands-migration,');
193
+ console.warn(' or remove them directly:');
194
+ console.warn(` rm ${stale.map((name) => path.join(rel, name)).join(' ')}`);
195
+ return false;
196
+ }
197
+
198
+ // Bound removal to AIWG-managed command files; preserve operator files.
199
+ const sidecar = readSidecarManifest(commandsDir) || { managed: {} };
200
+ const managed = sidecar.managed || {};
201
+ let sidecarDirty = false;
202
+ const rel = path.relative(process.cwd(), commandsDir);
203
+
204
+ const managedNames = [];
205
+ for (const entry of entries) {
206
+ if (!entry.isFile()) continue;
207
+ const lower = entry.name.toLowerCase();
208
+ if (!lower.endsWith('.md')) continue; // only command markdown files
209
+ const filePath = path.join(commandsDir, entry.name);
210
+ // Skill-command wrappers ARE the current skill surface, not legacy command
211
+ // files superseded by it. Migrating them away deletes what the same deploy
212
+ // just wrote — and on a kernel-only run, which does not re-translate, they
213
+ // are never restored (#2507).
214
+ if (managed[entry.name]?.kind === 'skill-command') continue;
215
+ let owned = Object.prototype.hasOwnProperty.call(managed, entry.name);
216
+ if (!owned) {
217
+ try {
218
+ owned = MANAGED_MARKER_RE.test(fs.readFileSync(filePath, 'utf8'));
219
+ } catch {
220
+ owned = false;
221
+ }
222
+ }
223
+ if (owned) managedNames.push(entry.name);
224
+ }
225
+
226
+ if (managedNames.length === 0) return false;
227
+
228
+ if (dryRun) {
229
+ console.log(`[dry-run] would remove ${managedNames.length} AIWG command file(s) from ${rel}`);
230
+ return true;
231
+ }
232
+
233
+ for (const name of managedNames) {
234
+ try {
235
+ fs.unlinkSync(path.join(commandsDir, name));
236
+ if (Object.prototype.hasOwnProperty.call(managed, name)) {
237
+ delete managed[name];
238
+ sidecarDirty = true;
239
+ }
240
+ if (verbose) console.log(` removed AIWG command file: ${name}`);
241
+ } catch (err) {
242
+ if (verbose) console.warn(` Warning: could not remove ${name}: ${err.message}`);
243
+ }
244
+ }
245
+
246
+ if (sidecarDirty) writeSidecarManifest(commandsDir, sidecar, dryRun);
247
+ console.log(` Removed ${managedNames.length} old AIWG command file(s) from ${rel} (now served as skills)`);
248
+
249
+ // Remove the directory only if AIWG files were the only contents.
250
+ try {
251
+ const remaining = fs.readdirSync(commandsDir).filter((n) => n !== MANIFEST_FILENAME);
252
+ if (remaining.length === 0) {
253
+ fs.rmSync(commandsDir, { recursive: true, force: true });
254
+ }
255
+ } catch { /* non-fatal */ }
256
+
257
+ return true;
258
+ }
@@ -0,0 +1,273 @@
1
+ // Shared provider models platforms utilities.
2
+ import { resolveAiwgRoot } from './base-inventory.mjs';
3
+ import { fs, os, path, yaml } from './base-runtime.mjs';
4
+
5
+
6
+ // ============================================================================
7
+ // Model Configuration
8
+ // ============================================================================
9
+
10
+ /**
11
+ * Load model configuration from models.json
12
+ * Priority: Project models.json > User ~/.config/aiwg/models.json > AIWG defaults
13
+ */
14
+ export function loadModelConfig(srcRoot) {
15
+ // An addon/framework/bundle `--source` is not the AIWG root, so resolve the
16
+ // shipped defaults through the corpus root; otherwise addon deploys fell
17
+ // through to the hardcoded fallback and deployed bare aliases (#2563).
18
+ const aiwgRoot = (srcRoot && resolveAiwgRoot(srcRoot)) || srcRoot;
19
+ const locations = [
20
+ { path: path.join(process.cwd(), 'models.json'), label: 'project' },
21
+ { path: path.join(process.env.HOME || process.env.USERPROFILE, '.config', 'aiwg', 'models.json'), label: 'user' },
22
+ { path: path.join(aiwgRoot, 'agentic', 'code', 'frameworks', 'sdlc-complete', 'config', 'models.json'), label: 'AIWG defaults' }
23
+ ];
24
+
25
+ for (const loc of locations) {
26
+ if (fs.existsSync(loc.path)) {
27
+ try {
28
+ const config = JSON.parse(fs.readFileSync(loc.path, 'utf8'));
29
+ config._source = `${loc.label} (${loc.path})`;
30
+ return config;
31
+ } catch (err) {
32
+ console.warn(`Warning: Could not parse models.json at ${loc.path}: ${err.message}`);
33
+ }
34
+ }
35
+ }
36
+
37
+ // Fallback to hardcoded defaults if no config found
38
+ return {
39
+ claude: {
40
+ reasoning: { model: 'claude-opus-5' },
41
+ coding: { model: 'claude-sonnet-5' },
42
+ efficiency: { model: 'claude-haiku-4-5' }
43
+ },
44
+ factory: {
45
+ reasoning: { model: 'heavy' },
46
+ coding: { model: 'medium' },
47
+ efficiency: { model: 'light' }
48
+ },
49
+ shorthand: {
50
+ 'opus': 'claude-opus-5',
51
+ 'sonnet': 'claude-sonnet-5',
52
+ 'haiku': 'claude-haiku-4-5',
53
+ 'inherit': 'inherit'
54
+ },
55
+ claude_shorthand: {
56
+ 'opus': 'opus',
57
+ 'opus-1m': 'opus[1m]',
58
+ 'opus[1m]': 'opus[1m]',
59
+ 'sonnet': 'sonnet',
60
+ 'sonnet-1m': 'sonnet[1m]',
61
+ 'sonnet[1m]': 'sonnet[1m]',
62
+ 'haiku': 'haiku',
63
+ 'inherit': 'inherit'
64
+ }
65
+ };
66
+ }
67
+
68
+
69
+ /**
70
+ * Load a fresh dynamically-discovered model catalog when available, otherwise
71
+ * use the committed catalog supplied by the caller. Refresh is performed by
72
+ * `aiwg models refresh`; deployment itself never performs network access.
73
+ */
74
+ export function loadRuntimeModelCatalog(staticCatalog, options = {}) {
75
+ if (process.env.VITEST && !options.cacheFile && !options.homeDir) return staticCatalog;
76
+ const homeDir = options.homeDir || os.homedir();
77
+ const cacheFile = options.cacheFile || path.join(homeDir, '.cache', 'aiwg', 'model-catalog.v1.json');
78
+ const ttlMs = options.ttlMs ?? 24 * 60 * 60 * 1000;
79
+ try {
80
+ const cached = JSON.parse(fs.readFileSync(cacheFile, 'utf8'));
81
+ const fetchedAt = Date.parse(cached?.discovery?.fetchedAt || '');
82
+ const age = Date.now() - fetchedAt;
83
+ if (
84
+ cached?.providers &&
85
+ Number.isFinite(age) &&
86
+ age >= 0 &&
87
+ age <= ttlMs
88
+ ) {
89
+ return cached;
90
+ }
91
+ } catch {
92
+ // Missing, stale, or malformed cache: deterministic static fallback.
93
+ }
94
+ return staticCatalog;
95
+ }
96
+
97
+
98
+ // ============================================================================
99
+ // Frontmatter Utilities
100
+ // ============================================================================
101
+
102
+ /**
103
+ * Maps provider names to the platform identifiers used in skill platforms: fields.
104
+ * Skills use descriptive names (e.g. "claude-code") while providers use short names (e.g. "claude").
105
+ */
106
+ export const PROVIDER_TO_PLATFORM = {
107
+ 'claude': 'claude-code'
108
+ };
109
+
110
+
111
+ /**
112
+ * Parse the platforms: field from a SKILL.md frontmatter block.
113
+ * Accepts a string or a list of strings; all alone means unrestricted.
114
+ * Returns null if platforms is missing, or no frontmatter is present.
115
+ * Returns an empty array for malformed frontmatter or invalid platforms.
116
+ */
117
+ export function parseSkillPlatforms(content) {
118
+ // A leading UTF-8 BOM must not hide the frontmatter (and its restrictions).
119
+ if (content.charCodeAt(0) === 0xfeff) content = content.slice(1);
120
+ const fmMatch = content.match(/^---\r?\n([\s\S]*?)^---[ \t]*(?:\r?\n|$)/m);
121
+ if (!fmMatch || fmMatch.index !== 0) {
122
+ return /^---[ \t]*(?:\r?\n|$)/.test(content) ? [] : null;
123
+ }
124
+
125
+ let metadata;
126
+ try {
127
+ const document = yaml.parseDocument(fmMatch[1]);
128
+ if (document.errors.length > 0) return [];
129
+ if (!document.contents) return null; // Empty frontmatter has no restrictions.
130
+ metadata = document.toJS();
131
+ } catch {
132
+ return [];
133
+ }
134
+ if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) return [];
135
+ // The yaml package leaves merge keys unresolved, so platforms could arrive only
136
+ // through `<<`; without an explicit key that is ambiguous, so fail closed.
137
+ if (!Object.hasOwn(metadata, 'platforms')) return Object.hasOwn(metadata, '<<') ? [] : null;
138
+
139
+ const platforms = metadata.platforms;
140
+ const items = typeof platforms === 'string' ? [platforms] : platforms;
141
+ if (!Array.isArray(items) || !items.every(item => typeof item === 'string')) return [];
142
+ const normalized = items.map(item => item.trim());
143
+ if (normalized.some(item => !item)) return [];
144
+ return normalized.length === 1 && normalized[0] === 'all' ? null : normalized;
145
+ }
146
+
147
+
148
+ /**
149
+ * Returns true if a skill (given its source content) should be deployed to the given provider.
150
+ * If no provider is specified, always returns true.
151
+ */
152
+ export function skillMatchesProvider(content, provider) {
153
+ if (!provider) return true;
154
+
155
+ const platforms = parseSkillPlatforms(content);
156
+ if (!platforms) return true; // No restriction
157
+
158
+ const platformName = PROVIDER_TO_PLATFORM[provider] || provider;
159
+ return platforms.includes(platformName) || platforms.includes(provider);
160
+ }
161
+
162
+
163
+ /**
164
+ * Inject the target platform name into a SKILL.md frontmatter block.
165
+ *
166
+ * Source skills use platforms: [all] as a deployment token.
167
+ * At deploy time this function replaces [all] with [<targetPlatform>] so
168
+ * each deployed copy accurately reflects where it was installed.
169
+ *
170
+ * Explicit restriction lists (not [all]) are preserved as-is.
171
+ * If no platforms: field is present, one is added.
172
+ */
173
+ export function injectPlatformInContent(content, targetPlatform) {
174
+ if (!targetPlatform) return content;
175
+
176
+ const fmMatch = content.match(/^(---\n)([\s\S]*?)(\n---\n?)([\s\S]*)$/);
177
+ if (!fmMatch) return content;
178
+
179
+ const [, open, fm, close, body] = fmMatch;
180
+
181
+ const injected = `platforms: [${targetPlatform}]`;
182
+
183
+ // Case 1: inline [all] token → replace with target platform
184
+ let updated = fm.replace(/^platforms:\s*\[all\]\n?/m, injected + '\n');
185
+ if (updated !== fm) return open + updated + close + body;
186
+
187
+ // Case 2: inline explicit restriction (not [all]) → leave as-is, do not inject
188
+ if (/^platforms:\s*\[(?!all\])[^\]]+\]/m.test(fm)) {
189
+ return content;
190
+ }
191
+
192
+ // Case 3: multi-line list → replace entire block with injected value
193
+ updated = fm.replace(/^platforms:\s*\n(?:[ \t]+-[ \t]+\S[^\n]*\n?)*/m, injected + '\n');
194
+ if (updated !== fm) return open + updated + close + body;
195
+
196
+ // Case 4: bare `platforms:` with no value → replace
197
+ updated = fm.replace(/^platforms:\s*$/m, injected);
198
+ if (updated !== fm) return open + updated + close + body;
199
+
200
+ // Case 5: no platforms: field at all → insert after the first frontmatter line
201
+ const fmLines = fm.split('\n');
202
+ fmLines.splice(1, 0, injected);
203
+ return open + fmLines.join('\n') + close + body;
204
+ }
205
+
206
+
207
+ /**
208
+ * Remove the `platforms:` field from a SKILL.md frontmatter block.
209
+ *
210
+ * Hermes (and other providers that treat `platforms:` as an OS gate —
211
+ * linux / macos / windows) hide any skill whose value isn't a recognized
212
+ * OS. AIWG source skills use the field as a *provider* restriction token
213
+ * (`[all]`, provider names), which is the opposite meaning, so deployed
214
+ * copies destined for such providers must drop the field entirely. An
215
+ * absent field is the documented "compatible with all platforms" default.
216
+ */
217
+ /**
218
+ * Remove the `triggers:` field from a deployed rule's frontmatter.
219
+ *
220
+ * Rules declare trigger phrases so `aiwg discover` can reach them by the
221
+ * question an agent asks rather than by their policy name (#2544). That is
222
+ * index-time metadata: no provider matches a *rule* by trigger, and the agent
223
+ * reading the deployed rule gains nothing from the list. Shipping it spends
224
+ * startup context on noise, which is exactly the budget #2540 is defending —
225
+ * ~2KB across the 16 rules covered today, and ~16KB if every rule adopts.
226
+ *
227
+ * Skills are untouched: several providers do match skills by trigger.
228
+ */
229
+ export function stripTriggersFromContent(content) {
230
+ const fmMatch = content.match(/^(---\r?\n)([\s\S]*?)(\r?\n---(?:\r?\n|$))([\s\S]*)$/);
231
+ if (!fmMatch) return content;
232
+
233
+ const [, open, fm, close, body] = fmMatch;
234
+ // Block list form:
235
+ // triggers:
236
+ // - "am I allowed to do this"
237
+ let updated = fm.replace(
238
+ /^triggers:[ \t]*\r?\n(?:[ \t]+-[ \t]+\S[^\r\n]*(?:\r?\n|$))*/m,
239
+ '',
240
+ );
241
+ // Inline form: triggers: ["a", "b"]
242
+ if (updated === fm) updated = fm.replace(/^triggers:[^\r\n]*(?:\r?\n|$)/m, '');
243
+
244
+ if (updated === fm) return content;
245
+ // An otherwise-empty frontmatter block is dropped rather than left as `---\n---`.
246
+ if (updated.trim().length === 0) return body.replace(/^\r?\n/, '');
247
+ // Removing a block mid-frontmatter can leave a trailing blank line before the
248
+ // closing fence; the deployed file should not carry it.
249
+ return open + updated.replace(/\s+$/, '') + close + body;
250
+ }
251
+
252
+
253
+ export function stripPlatformsFromContent(content) {
254
+ const fmMatch = content.match(/^(---\r?\n)([\s\S]*?)(\r?\n---(?:\r?\n|$))([\s\S]*)$/);
255
+ if (!fmMatch) return content;
256
+
257
+ const [, open, fm, close, body] = fmMatch;
258
+ let updated = fm.replace(/^platforms:[^\r\n]*(?:\r?\n|$)/m, '');
259
+
260
+ // Multi-line list form:
261
+ // platforms:
262
+ // - claude-code
263
+ // - hermes
264
+ if (updated === fm) {
265
+ updated = fm.replace(
266
+ /^platforms:[ \t]*\r?\n(?:[ \t]+-[ \t]+\S[^\r\n]*(?:\r?\n|$))*/m,
267
+ '',
268
+ );
269
+ }
270
+
271
+ if (updated === fm) return content;
272
+ return open + updated + close + body;
273
+ }