@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
@@ -1,1981 +1,23 @@
1
- /**
2
- * Subcommand Handlers
3
- *
4
- * Handlers for MCP, catalog, plugin, and other subcommands.
5
- * Handles CLI subcommand routing.
6
- *
7
- * @implements @.aiwg/architecture/decisions/ADR-001-unified-extension-system.md
8
- * @implements #56, #57
9
- * @source @src/cli/router.ts
10
- * @tests @test/unit/cli/handlers/subcommands.test.ts
11
- * @issue #33
12
- */
13
- import { createScriptRunner } from "./script-runner.js";
14
- import { getFrameworkRoot } from "../../channel/manager.mjs";
15
- import { getRegistry } from "../../extensions/registry.js";
16
- import { registerDeployedExtensions } from "../../extensions/deployment-registration.js";
17
- import { discoverProjectLocalBundles } from "../../extensions/project-local-discovery.js";
18
- import { buildUpstreamRegistry } from "../../extensions/upstream-registry.js";
19
- import { resolveShadows } from "../../extensions/shadow-resolver.js";
20
1
  import { sessionHandler } from "./session.js";
21
2
  import { feedbackHandler } from "./feedback.js";
22
- import { handlerResultFromError } from "../errors.js";
23
- import { getProjectDir } from "../../config/aiwg-config.js";
24
- import { deployedSkillRoots } from "../../providers/deployed-skill-roots.js";
25
- import { releaseSkillOwnership } from "../../providers/skill-ownership.mjs";
26
- import { formatDeployedWorkspaceSignalPlan, readWorkspaceSignalPlan } from "../workspace-signals.js";
27
- import * as path from "node:path";
28
- import * as fsSync from "node:fs";
29
- import { pathToFileURL } from "node:url";
30
- /** Generate or deploy the canonical project quickref. */
31
- export const quickrefHandler = {
32
- id: 'quickref',
33
- name: 'Project Quickref',
34
- description: 'Generate and deploy an always-visible project quickref',
35
- category: 'project',
36
- aliases: [],
37
- async help() {
38
- return { exitCode: 0, message: 'Usage: aiwg quickref generate|deploy --project [--provider <id>] [--dry-run]', rawOutput: true };
39
- },
40
- async execute(ctx) {
41
- const action = ctx.args.find(arg => !arg.startsWith('-')) ?? 'generate';
42
- if (!ctx.args.includes('--project')) {
43
- return { exitCode: 1, message: 'Error: project quickrefs require --project\n\nUsage: aiwg quickref generate|deploy --project [--provider <id>] [--dry-run]' };
44
- }
45
- if (!['generate', 'deploy'].includes(action)) {
46
- return { exitCode: 1, message: `Error: unknown quickref action '${action}' (expected generate or deploy)` };
47
- }
48
- const { generateProjectQuickref, deployProjectQuickref, } = await import('../../extensions/project-quickref.js');
49
- try {
50
- if (action === 'generate') {
51
- const result = await generateProjectQuickref(ctx.cwd, { dryRun: ctx.dryRun });
52
- const verb = ctx.dryRun ? 'Would generate' : result.changed ? 'Generated' : 'Unchanged';
53
- console.log(`${verb} ${result.skillName}`);
54
- console.log(` Source: ${result.sourcePath}`);
55
- console.log(` Output: ${result.outputPath}`);
56
- for (const warning of result.warnings)
57
- console.log(` Warning: ${warning}`);
58
- if (ctx.dryRun) {
59
- console.log('\n--- preview ---\n');
60
- console.log(result.content);
61
- }
62
- return { exitCode: 0 };
63
- }
64
- const providerIndex = ctx.args.indexOf('--provider');
65
- const explicitProvider = providerIndex >= 0 ? ctx.args[providerIndex + 1] : undefined;
66
- const { readAiwgConfig } = await import('../../config/aiwg-config.js');
67
- const config = await readAiwgConfig(ctx.cwd);
68
- const providers = explicitProvider ? [explicitProvider] : (config?.providers ?? []);
69
- if (providers.length === 0) {
70
- return { exitCode: 1, message: 'No providers configured. Pass --provider <id> or add providers to .aiwg/aiwg.config.' };
71
- }
72
- for (const provider of providers) {
73
- const result = await deployProjectQuickref(ctx.cwd, provider, { dryRun: ctx.dryRun });
74
- const verb = ctx.dryRun ? 'Would deploy' : result.changed ? 'Deployed' : 'Unchanged';
75
- console.log(`${verb} ${result.skillName} -> ${result.provider}: ${result.targetPath}${result.emulated ? ' (emulated skill surface)' : ''}`);
76
- for (const stale of result.pruned) {
77
- console.log(` ${ctx.dryRun ? 'Would prune' : 'Pruned'} stale managed quickref: ${stale}`);
78
- }
79
- }
80
- return { exitCode: 0 };
81
- }
82
- catch (error) {
83
- return { exitCode: 1, message: `Project quickref failed: ${error.message}` };
84
- }
85
- },
86
- };
87
- const LIST_PROVIDER_TARGETS = [
88
- { name: 'claude', root: '.claude', agentsPath: '.claude/agents', skillsPath: '.claude/skills', commandsPath: '.claude/commands' },
89
- { name: 'codex', root: '.codex', agentsPath: '.codex/agents', skillsPath: '.codex/skills', commandsPath: '.codex/commands' },
90
- { name: 'copilot', root: '.github', agentsPath: '.github/agents', skillsPath: '.github/skills', commandsPath: '.github/prompts' },
91
- { name: 'cursor', root: '.cursor', agentsPath: '.cursor/agents', skillsPath: '.cursor/skills', commandsPath: '.cursor/commands' },
92
- { name: 'opencode', root: '.opencode', agentsPath: '.opencode/agent', skillsPath: '.opencode/skill', commandsPath: '.opencode/command' },
93
- { name: 'warp', root: '.warp', agentsPath: '.warp/agents', skillsPath: '.warp/skills', commandsPath: '.warp/commands' },
94
- { name: 'factory', root: '.factory', agentsPath: '.factory/droids', skillsPath: '.factory/skills', commandsPath: '.factory/commands' },
95
- { name: 'windsurf', root: '.windsurf', agentsPath: '.windsurf/agents', skillsPath: '.windsurf/skills', commandsPath: '.windsurf/workflows' },
96
- { name: 'universal', root: '.agents', agentsPath: '.agents/agents', skillsPath: '.agents/skills', commandsPath: '.agents/commands' },
97
- ];
98
- function hasAnyPopulated(cwd, p) {
99
- const candidates = [p.agentsPath, p.skillsPath, p.commandsPath];
100
- for (const rel of candidates) {
101
- const abs = path.join(cwd, rel);
102
- try {
103
- if (fsSync.statSync(abs).isDirectory() && fsSync.readdirSync(abs).length > 0)
104
- return true;
105
- }
106
- catch {
107
- // dir doesn't exist or unreadable — skip
108
- }
109
- }
110
- return false;
111
- }
112
- function detectDeployedProviders(cwd) {
113
- return LIST_PROVIDER_TARGETS.filter(p => hasAnyPopulated(cwd, p));
114
- }
115
- const REMOVE_FLAGS_WITH_VALUES = new Set([
116
- '--provider',
117
- '--platform',
118
- '--scope',
119
- '--target',
120
- ]);
121
- function firstRemovePositional(args) {
122
- for (let i = 0; i < args.length; i += 1) {
123
- const arg = args[i];
124
- if (REMOVE_FLAGS_WITH_VALUES.has(arg)) {
125
- i += 1;
126
- continue;
127
- }
128
- if (!arg.startsWith('-'))
129
- return arg;
130
- }
131
- return undefined;
132
- }
133
- function parseRemoveProvider(args) {
134
- const idx = args.findIndex(a => a === '--provider' || a === '--platform');
135
- if (idx < 0)
136
- return {};
137
- const provider = args[idx + 1];
138
- if (!provider || provider.startsWith('-')) {
139
- return { error: 'Error: --provider requires a provider name' };
140
- }
141
- return { provider };
142
- }
143
- /**
144
- * MCP server command handler
145
- *
146
- * Dynamically imports and delegates to src/mcp/cli.mjs.
147
- * Handles subcommands: serve, install, info
148
- */
149
- export const mcpHandler = {
150
- id: "aiwg-mcp-server",
151
- name: "AIWG MCP Server",
152
- description: "AIWG MCP server commands (serve, install, add, remove, update, list, inject, info)",
153
- category: "mcp",
154
- aliases: ["mcp", "aiwg-mcp"],
155
- async help() {
156
- const { main } = await import("../../mcp/cli.mjs");
157
- await main(["--help"]);
158
- return { exitCode: 0 };
159
- },
160
- async execute(ctx) {
161
- try {
162
- // Dynamic import to avoid loading MCP dependencies unless needed
163
- const { main } = await import("../../mcp/cli.mjs");
164
- await main(ctx.args);
165
- return {
166
- exitCode: 0,
167
- };
168
- }
169
- catch (error) {
170
- const result = handlerResultFromError(error);
171
- return { ...result, message: `MCP command failed: ${result.message}` };
172
- }
173
- },
174
- };
175
- /**
176
- * Model catalog command handler
177
- *
178
- * Dynamically imports and delegates to src/catalog/cli.mjs.
179
- * Handles subcommands: list, info, search
180
- */
181
- export const catalogHandler = {
182
- id: "catalog",
183
- name: "Model Catalog",
184
- description: "Model catalog commands (list, info, search)",
185
- category: "catalog",
186
- aliases: [],
187
- async help() {
188
- const { printCatalogHelp } = await import("../../catalog/cli.mjs");
189
- printCatalogHelp();
190
- return { exitCode: 0 };
191
- },
192
- async execute(ctx) {
193
- try {
194
- // Dynamic import to avoid loading catalog dependencies unless needed
195
- const { main } = await import("../../catalog/cli.mjs");
196
- await main(ctx.args);
197
- return {
198
- exitCode: 0,
199
- };
200
- }
201
- catch (error) {
202
- const result = handlerResultFromError(error);
203
- return { ...result, message: `Catalog command failed: ${result.message}` };
204
- }
205
- },
206
- };
207
- /**
208
- * List frameworks handler
209
- *
210
- * Lists deployed extensions from the registry.
211
- * Falls back to legacy plugin-status script if needed.
212
- */
213
- export const listHandler = {
214
- id: "list",
215
- name: "List Frameworks",
216
- description: "List installed frameworks and plugins",
217
- category: "framework",
218
- aliases: ["ls"],
219
- async execute(ctx) {
220
- // Filter args: positional type filter, plus --project-local flag (#1034)
221
- const projectLocalOnly = ctx.args.includes('--project-local');
222
- const shadowsOnly = ctx.args.includes('--shadows');
223
- const deployedOnly = ctx.args.includes('--deployed');
224
- const filterType = ctx.args.find((a) => !a.startsWith('--')); // 'agents'|'skills'|'commands'|'all'|undefined
225
- // #1156 Phase 1 — --scope user / --user surfaces the per-user registry
226
- // (~/.aiwg/installed.json) instead of the project-scope deployed-extensions
227
- // registry. Works from any cwd; does not require a project to be present.
228
- const userScopeRequested = ctx.args.includes('--user') || isScopeUser(ctx.args);
229
- if (userScopeRequested) {
230
- return await formatUserScopeRegistry();
231
- }
232
- // Project-local bundle discovery (#1034) — read-only scan, no deploy
233
- const projectLocal = await discoverProjectLocalBundles(ctx.cwd);
234
- if (shadowsOnly) {
235
- // #1036 — surface only artifacts that shadow upstream
236
- return await formatShadowsOnly(projectLocal);
237
- }
238
- if (projectLocalOnly) {
239
- // --project-local: only show project-local bundles; skip the deployed-
240
- // extension registry read entirely
241
- return formatProjectLocalOnly(projectLocal);
242
- }
243
- // Ensure registry is populated with deployed extensions
244
- const registry = getRegistry();
245
- // If registry is empty, try to populate it from EVERY deployed provider
246
- // in the workspace (not just claude). Fixes #1530: in a Codex-only
247
- // workspace the legacy hard-coded `.claude/...` lookup reported zero
248
- // extensions even though `.codex/` was populated. Detection mirrors
249
- // `tools/cli/workspace-status.mjs` so `aiwg list` and `aiwg status`
250
- // agree on what counts as deployed.
251
- //
252
- // `--provider <name>` narrows registration to one provider; otherwise
253
- // we register the union of everything detected so a multi-provider
254
- // workspace shows everything in a single inventory.
255
- if (registry.size === 0) {
256
- try {
257
- const provIdx = ctx.args.findIndex((a) => a === '--provider' || a === '--platform');
258
- const requestedProvider = provIdx >= 0 ? ctx.args[provIdx + 1] : undefined;
259
- let targets = detectDeployedProviders(ctx.cwd);
260
- if (requestedProvider) {
261
- targets = targets.filter((p) => p.name === requestedProvider);
262
- if (targets.length === 0) {
263
- return {
264
- exitCode: 1,
265
- message: `Error: provider '${requestedProvider}' is not deployed in this workspace.\n\nRun 'aiwg status' to see deployed providers.`,
266
- };
267
- }
268
- }
269
- if (targets.length === 0) {
270
- // No deployed providers detected → return a clean empty-inventory
271
- // message rather than dispatching to the legacy script (which
272
- // requires a path argument it doesn't get here). Matches the
273
- // legacy script's helpful guidance from #1530.
274
- return {
275
- exitCode: 0,
276
- message: 'No agents, skills, or commands deployed in this workspace.\n\n' +
277
- 'Tip: Deploy a framework with "aiwg use sdlc" (or another framework) to get started.\n' +
278
- 'Run "aiwg status" for workspace health detail.\n',
279
- };
280
- }
281
- for (const target of targets) {
282
- await registerDeployedExtensions(registry, {
283
- agentsPath: target.agentsPath,
284
- skillsPath: target.skillsPath,
285
- commandsPath: target.commandsPath,
286
- provider: target.name,
287
- cwd: ctx.cwd,
288
- });
289
- }
290
- }
291
- catch (error) {
292
- // If registry population fails, fall back to legacy script
293
- const frameworkRoot = await getFrameworkRoot();
294
- const runner = createScriptRunner(frameworkRoot);
295
- return runner.run("tools/plugin/plugin-status-cli.mjs", ctx.args, {
296
- cwd: ctx.cwd,
297
- });
298
- }
299
- }
300
- // Determine what to show
301
- const showAgents = !filterType || filterType === 'agents' || filterType === 'all';
302
- const showSkills = !filterType || filterType === 'skills' || filterType === 'all';
303
- const showCommands = !filterType || filterType === 'commands' || filterType === 'all';
304
- let output = '';
305
- if (showAgents) {
306
- const agents = registry.getByType('agent');
307
- output += `\nAgents (${agents.length}):\n`;
308
- output += '─'.repeat(60) + '\n';
309
- if (agents.length === 0) {
310
- output += ' No agents deployed\n';
311
- }
312
- else {
313
- for (const agent of agents.slice(0, 20)) { // Limit to 20 for readability
314
- output += ` ${agent.name}\n`;
315
- output += ` ID: ${agent.id}\n`;
316
- output += ` Description: ${agent.description.slice(0, 80)}${agent.description.length > 80 ? '...' : ''}\n`;
317
- if (agent.installation) {
318
- output += ` Path: ${agent.installation.installedPath}\n`;
319
- }
320
- output += '\n';
321
- }
322
- if (agents.length > 20) {
323
- output += ` ... and ${agents.length - 20} more\n`;
324
- }
325
- }
326
- }
327
- if (showSkills) {
328
- const skills = registry.getByType('skill');
329
- output += `\nSkills (${skills.length}):\n`;
330
- output += '─'.repeat(60) + '\n';
331
- if (skills.length === 0) {
332
- output += ' No skills deployed\n';
333
- }
334
- else {
335
- for (const skill of skills.slice(0, 20)) {
336
- output += ` ${skill.name}\n`;
337
- output += ` ID: ${skill.id}\n`;
338
- output += ` Description: ${skill.description.slice(0, 80)}${skill.description.length > 80 ? '...' : ''}\n`;
339
- if (skill.installation) {
340
- output += ` Path: ${skill.installation.installedPath}\n`;
341
- }
342
- output += '\n';
343
- }
344
- if (skills.length > 20) {
345
- output += ` ... and ${skills.length - 20} more\n`;
346
- }
347
- }
348
- }
349
- if (showCommands) {
350
- const commands = registry.getByType('command');
351
- output += `\nCommands (${commands.length}):\n`;
352
- output += '─'.repeat(60) + '\n';
353
- if (commands.length === 0) {
354
- output += ' No commands registered\n';
355
- }
356
- else {
357
- for (const command of commands.slice(0, 20)) {
358
- output += ` ${command.name}\n`;
359
- output += ` ID: ${command.id}\n`;
360
- output += ` Description: ${command.description.slice(0, 80)}${command.description.length > 80 ? '...' : ''}\n`;
361
- output += '\n';
362
- }
363
- if (commands.length > 20) {
364
- output += ` ... and ${commands.length - 20} more\n`;
365
- }
366
- }
367
- }
368
- // Project-local bundles (#1034) — surfaced as a separate section with
369
- // [project] source label
370
- const totalProjectLocal = projectLocal.counts.extension +
371
- projectLocal.counts.addon +
372
- projectLocal.counts.framework +
373
- projectLocal.counts.plugin;
374
- if (totalProjectLocal > 0 || projectLocal.errors.length > 0) {
375
- output += `\nProject-local bundles (${totalProjectLocal}):\n`;
376
- output += '─'.repeat(60) + '\n';
377
- for (const b of projectLocal.bundles) {
378
- output += ` ${b.id} [project] [${b.type}]\n`;
379
- output += ` Path: ${b.localPath}\n`;
380
- output += ` Description: ${b.manifest.description.slice(0, 80)}${b.manifest.description.length > 80 ? '...' : ''}\n\n`;
381
- }
382
- if (projectLocal.errors.length > 0) {
383
- output += ` ⚠ ${projectLocal.errors.length} validation error(s) — see "aiwg doctor" for details\n`;
384
- }
385
- }
386
- // Summary
387
- const totalAgents = registry.getByType('agent').length;
388
- const totalSkills = registry.getByType('skill').length;
389
- const totalCommands = registry.getByType('command').length;
390
- const total = totalAgents + totalSkills + totalCommands;
391
- output += '\n' + '═'.repeat(60) + '\n';
392
- output += `Total: ${total} extensions (${totalAgents} agents, ${totalSkills} skills, ${totalCommands} commands)`;
393
- if (totalProjectLocal > 0) {
394
- output += ` + ${totalProjectLocal} project-local`;
395
- }
396
- output += '\n';
397
- if (total === 0 && totalProjectLocal === 0) {
398
- output += '\nTip: Deploy a framework with "aiwg use sdlc" to get started\n';
399
- }
400
- else if (totalCommands === 0 && totalAgents > 0) {
401
- // Skill-only model (Claude Code default): commands aren't deployed as
402
- // slash commands; capabilities reach the agent via natural language or
403
- // `aiwg discover` (#1228). Surface this so 0 commands doesn't look like
404
- // a deploy failure.
405
- output += '\nNote: 0 commands is expected on Claude Code — capabilities are reached via natural language or `aiwg discover "<phrase>"`.\n';
406
- }
407
- if (deployedOnly) {
408
- const projectDir = getProjectDir(ctx, ctx.args);
409
- const plan = await readWorkspaceSignalPlan(projectDir);
410
- if (plan) {
411
- output += formatDeployedWorkspaceSignalPlan(plan);
412
- }
413
- else {
414
- output += '\nWorkspace skill filter: no recorded plan found.\n';
415
- output += 'Run `aiwg use --profile <name>` to record workspace-aware include/exclude reasons.\n';
416
- }
417
- }
418
- return {
419
- exitCode: 0,
420
- message: output,
421
- };
422
- },
423
- };
424
- /**
425
- * Format `aiwg list --project-local` output: only project-local bundles, with
426
- * per-type breakdown and any validation errors surfaced. (#1034)
427
- */
428
- function formatProjectLocalOnly(result) {
429
- let output = '';
430
- const total = result.counts.extension +
431
- result.counts.addon +
432
- result.counts.framework +
433
- result.counts.plugin;
434
- if (total === 0 && result.errors.length === 0) {
435
- output += '\nNo project-local bundles found.\n';
436
- output += '\nTip: place a manifest.json under the configured AIWG artifact root at {extensions,addons,frameworks,plugins,providers}/<name>/ to author a project-local artifact.\n';
437
- return { exitCode: 0, message: output };
438
- }
439
- output += `\nProject-local bundles (${total}):\n`;
440
- output += '─'.repeat(60) + '\n';
441
- for (const b of result.bundles) {
442
- output += ` ${b.id} [project] [${b.type}] v${b.manifest.version}\n`;
443
- output += ` Path: ${b.localPath}\n`;
444
- output += ` Description: ${b.manifest.description.slice(0, 80)}${b.manifest.description.length > 80 ? '...' : ''}\n\n`;
445
- }
446
- if (result.errors.length > 0) {
447
- output += '\nValidation errors:\n';
448
- output += '─'.repeat(60) + '\n';
449
- for (const e of result.errors.slice(0, 10)) {
450
- output += ` [${e.severity}] ${e.path}\n`;
451
- output += ` ${e.field}: expected ${e.expected}, got ${e.actual}\n`;
452
- if (e.hint)
453
- output += ` hint: ${e.hint}\n`;
454
- }
455
- if (result.errors.length > 10) {
456
- output += ` ... and ${result.errors.length - 10} more\n`;
457
- }
458
- }
459
- output += '\n' + '═'.repeat(60) + '\n';
460
- output += `Counts by type: extension=${result.counts.extension} addon=${result.counts.addon} framework=${result.counts.framework} plugin=${result.counts.plugin}\n`;
461
- return { exitCode: 0, message: output };
462
- }
463
- /**
464
- * Format `aiwg list --shadows` output: only artifacts that currently shadow
465
- * an upstream artifact, with safety-critical and override status. (#1036)
466
- */
467
- async function formatShadowsOnly(projectLocal) {
468
- let output = '';
469
- if (projectLocal.bundles.length === 0) {
470
- output += '\nNo project-local bundles — no shadows possible.\n';
471
- return { exitCode: 0, message: output };
472
- }
473
- const { getFrameworkRoot: gfr } = await import('../../channel/manager.mjs');
474
- const frameworkRoot = await gfr();
475
- const upstream = await buildUpstreamRegistry({ frameworkRoot });
476
- const result = await resolveShadows(projectLocal.bundles, upstream);
477
- if (result.shadows.length === 0) {
478
- output += '\nNo active shadows.\n';
479
- output += '\nProject-local bundles deploy alongside upstream without collision.\n';
480
- return { exitCode: 0, message: output };
481
- }
482
- output += `\nActive shadows (${result.shadows.length}):\n`;
483
- output += '─'.repeat(60) + '\n';
484
- for (const r of result.shadows) {
485
- const sc = r.upstream?.safetyCritical ? ' [SAFETY-CRITICAL]' : '';
486
- output += ` ${r.artifactType}/${r.artifactId}${sc}\n`;
487
- output += ` Bundle: ${r.bundleId} (${r.bundleLocalPath})\n`;
488
- output += ` Project-local: ${r.artifactSourcePath}\n`;
489
- if (r.upstream) {
490
- output += ` Shadows ${r.upstream.source}: ${r.upstream.sourcePath}\n`;
491
- }
492
- output += ` Verdict: ${r.verdict}\n\n`;
493
- }
494
- if (result.blockedBundleIds.size > 0) {
495
- output += `\n⚠ ${result.blockedBundleIds.size} bundle(s) blocked from deployment due to unsafe shadows.\n`;
496
- }
497
- return { exitCode: 0, message: output };
498
- }
499
- /**
500
- * #1156 Phase 1 — `--scope user` detection. Mirrors `detectScope()` from
501
- * scope-resolver but tolerates the absence of the flag (no throw on absent).
502
- * Returns true when args contain `--scope user`.
503
- */
504
- function isScopeUser(args) {
505
- const idx = args.findIndex((a) => a === '--scope');
506
- if (idx === -1)
507
- return false;
508
- return args[idx + 1] === 'user';
509
- }
510
- /**
511
- * #1156 Phase 1 — Format the per-user registry (~/.aiwg/installed.json) as a
512
- * human-readable inventory. Used by `aiwg list --scope user` / `aiwg list
513
- * --user`. Independent of any project — works from any cwd.
514
- */
515
- async function formatUserScopeRegistry() {
516
- const { readUserRegistry, userRegistryPath } = await import('../../config/user-registry.js');
517
- const registry = await readUserRegistry();
518
- const frameworks = Object.entries(registry.installed);
519
- let output = '';
520
- if (frameworks.length === 0) {
521
- output += '\nNo frameworks deployed at user scope.\n';
522
- output += `\nRegistry path: ${userRegistryPath()}\n`;
523
- output += '\nTip: run `aiwg use <framework> --provider <p> --scope user` to install at user scope.\n';
524
- return { exitCode: 0, message: output };
525
- }
526
- output += `\nUser-scope deployments (${frameworks.length}):\n`;
527
- output += '─'.repeat(60) + '\n';
528
- for (const [name, entry] of frameworks) {
529
- output += ` ${name} v${entry.version} [${entry.source}]\n`;
530
- output += ` Installed: ${entry.installedAt}\n`;
531
- const providers = Object.entries(entry.deployedTo);
532
- for (const [provider, counts] of providers) {
533
- const parts = [];
534
- if (counts.agents > 0)
535
- parts.push(`${counts.agents} agents`);
536
- if (counts.commands > 0)
537
- parts.push(`${counts.commands} commands`);
538
- if (counts.skills > 0)
539
- parts.push(`${counts.skills} skills`);
540
- if (counts.rules > 0)
541
- parts.push(`${counts.rules} rules`);
542
- output += ` ${provider}: ${parts.length > 0 ? parts.join(', ') : '(empty)'}\n`;
543
- }
544
- output += '\n';
545
- }
546
- output += '═'.repeat(60) + '\n';
547
- output += `Registry path: ${userRegistryPath()}\n`;
548
- return { exitCode: 0, message: output };
549
- }
550
- /**
551
- * #1156 Phase 1 — Revert a user-scope mirror.
552
- *
553
- * Reads `~/.aiwg/installed.json`, looks up the framework + provider entry,
554
- * and deletes the specific artifact entries this deploy created (recorded
555
- * by the mirror in Cycle 3). With `--dry-run`, lists what would be removed
556
- * without touching the filesystem.
557
- *
558
- * Back-compat: registry entries written before Cycle 3 lack the `entries`
559
- * snapshot. For those, the handler falls back to the conservative
560
- * registry-only revert and tells the operator to clean up manually.
561
- *
562
- * Multi-provider: if `--provider` is omitted, all of the framework's
563
- * provider deployments are reverted in one pass.
564
- */
565
- async function removeUserScopeDeploy(args) {
566
- const positional = firstRemovePositional(args);
567
- if (!positional) {
568
- return {
569
- exitCode: 1,
570
- message: 'Error: framework name required\n\nUsage: aiwg remove <framework> --scope user [--provider <p>] [--dry-run]',
571
- };
572
- }
573
- const dryRun = args.includes('--dry-run');
574
- const providerParse = parseRemoveProvider(args);
575
- if (providerParse.error) {
576
- return {
577
- exitCode: 1,
578
- message: `${providerParse.error}\n\nUsage: aiwg remove <framework> --scope user [--provider <p>] [--dry-run]`,
579
- };
580
- }
581
- const provider = providerParse.provider;
582
- const { readUserRegistry, removeUserDeploy } = await import('../../config/user-registry.js');
583
- const { USER_SCOPE_PATHS } = await import('../scope-resolver.js');
584
- const registry = await readUserRegistry();
585
- const entry = registry.installed[positional];
586
- if (!entry) {
587
- return {
588
- exitCode: 1,
589
- message: `Error: framework '${positional}' is not deployed at user scope.\n\nRun 'aiwg list --scope user' to see installed frameworks.`,
590
- };
591
- }
592
- const providersToRevert = provider ? [provider] : Object.keys(entry.deployedTo);
593
- if (provider && !entry.deployedTo[provider]) {
594
- return {
595
- exitCode: 1,
596
- message: `Error: framework '${positional}' is not deployed at user scope for provider '${provider}'.\n\nDeployed providers: ${Object.keys(entry.deployedTo).join(', ') || '(none)'}`,
597
- };
598
- }
599
- const fs = await import('node:fs/promises');
600
- const path = await import('node:path');
601
- const linesOut = [];
602
- if (dryRun)
603
- linesOut.push(`[dry-run] Plan for user-scope remove of '${positional}':`);
604
- else
605
- linesOut.push(`Removing user-scope mirror of '${positional}':`);
606
- let totalDeleted = 0;
607
- let conservativeFallbackUsed = false;
608
- for (const p of providersToRevert) {
609
- const userPaths = USER_SCOPE_PATHS[p];
610
- if (!userPaths) {
611
- linesOut.push(` ⚠ ${p}: no user-scope paths registered — skipping (manual cleanup may be needed)`);
612
- continue;
613
- }
614
- // Cast through unknown to access the optional `entries` snapshot recorded
615
- // by the Cycle 3 mirror. Older registry entries won't have it.
616
- const providerEntry = entry.deployedTo[p];
617
- const recorded = providerEntry?.entries;
618
- if (!recorded) {
619
- // Pre-Cycle-3 entry: surface the deploy paths and let the operator
620
- // clean them up manually. We can't safely auto-delete because the dirs
621
- // are shared with other frameworks.
622
- conservativeFallbackUsed = true;
623
- const existingDirs = [
624
- { type: 'agents', path: userPaths.agents },
625
- { type: 'commands', path: userPaths.commands },
626
- { type: 'skills', path: userPaths.skills },
627
- { type: 'rules', path: userPaths.rules },
628
- { type: 'behaviors', path: userPaths.behaviors },
629
- ].filter(t => t.path);
630
- linesOut.push(` ⚠ ${p}: registry entry has no per-artifact manifest (deployed before Cycle 3). Manual cleanup of these dirs may be needed:`);
631
- for (const t of existingDirs) {
632
- const stat = await fs.stat(t.path).catch(() => null);
633
- if (stat && stat.isDirectory()) {
634
- linesOut.push(` - ${t.path}`);
635
- }
636
- }
637
- continue;
638
- }
639
- // Precise revert — walk the recorded entry names and delete each one
640
- // from its corresponding user-scope dir.
641
- const sets = [
642
- ['agents', userPaths.agents, recorded.agents],
643
- ['commands', userPaths.commands, recorded.commands],
644
- ['skills', userPaths.skills, recorded.skills],
645
- ['rules', userPaths.rules, recorded.rules],
646
- ['behaviors', userPaths.behaviors, recorded.behaviors],
647
- ];
648
- for (const [type, dir, names] of sets) {
649
- if (!dir || !names || names.length === 0)
650
- continue;
651
- let deletedHere = 0;
652
- for (const name of names) {
653
- const target = path.join(dir, name);
654
- if (dryRun) {
655
- linesOut.push(` · ${p} ${type}: ${target}`);
656
- deletedHere++;
657
- continue;
658
- }
659
- try {
660
- if (type === 'skills') {
661
- const { resolveFrameworkDir } = await import('./use.js');
662
- const released = releaseSkillOwnership(target, { frameworkSlug: resolveFrameworkDir(positional) ?? positional });
663
- if (released === null)
664
- continue;
665
- }
666
- else {
667
- await fs.rm(target, { recursive: true, force: true });
668
- }
669
- deletedHere++;
670
- totalDeleted++;
671
- }
672
- catch (err) {
673
- linesOut.push(` ⚠ ${p} ${type}: failed to remove ${target}: ${err instanceof Error ? err.message : String(err)}`);
674
- }
675
- }
676
- if (!dryRun && deletedHere > 0) {
677
- linesOut.push(` ✓ ${p} ${type}: removed ${deletedHere} entry/entries from ${dir}`);
678
- }
679
- else if (dryRun) {
680
- linesOut.push(` (${deletedHere} ${type} would be removed from ${dir})`);
681
- }
682
- }
683
- }
684
- if (!dryRun) {
685
- if (provider) {
686
- await removeUserDeploy({ framework: positional, provider });
687
- }
688
- else {
689
- await removeUserDeploy({ framework: positional });
690
- }
691
- linesOut.push('');
692
- if (conservativeFallbackUsed) {
693
- linesOut.push('Registry updated. Some providers had no per-artifact manifest (pre-Cycle-3 deploys); inspect the dirs listed above and clean up manually if needed.');
694
- }
695
- else {
696
- linesOut.push(`Registry updated. ${totalDeleted} artifact entry/entries removed.`);
697
- }
698
- }
699
- return {
700
- exitCode: 0,
701
- message: linesOut.join('\n') + '\n',
702
- };
703
- }
704
- /** List only unrecorded paths; recorded decisions come from the ownership plan. */
705
- function previewUnrecordedSkillFiles(skillDir, owned, plan, skillRoots) {
706
- // Some adapters (Hermes) put the bulk root directly inside the kernel root.
707
- if (skillRoots.includes(skillDir))
708
- return;
709
- const recorded = new Set(plan.map(entry => entry.path));
710
- const visit = (target) => {
711
- if (recorded.has(path.resolve(target)))
712
- return;
713
- let reason = owned ? 'unrecorded operator file' : 'foreign or unverifiable ownership receipt';
714
- try {
715
- const stat = fsSync.lstatSync(target);
716
- if (stat.isDirectory()) {
717
- for (const name of fsSync.readdirSync(target).sort())
718
- visit(path.join(target, name));
719
- return;
720
- }
721
- if (owned && stat.isSymbolicLink())
722
- reason = 'symlink preserved';
723
- }
724
- catch {
725
- reason = 'missing or unreadable path; cannot verify';
726
- }
727
- plan.push({ path: path.resolve(target), action: 'preserve', reason });
728
- };
729
- visit(skillDir);
730
- }
731
- /**
732
- * Remove framework handler
733
- *
734
- * Delegates to tools/plugin/plugin-uninstaller-cli.mjs
735
- */
736
- export const removeHandler = {
737
- id: "remove",
738
- name: "Remove Framework",
739
- description: "Remove installed framework, plugin, or project-local bundle",
740
- category: "framework",
741
- aliases: [],
742
- async help() {
743
- return { exitCode: 0, rawOutput: true, message: [
744
- 'Usage: aiwg remove <id> [options]',
745
- '',
746
- 'Remove an installed framework, plugin, or project-local bundle by id (for example all or sdlc).',
747
- 'Project scope is the default; without --provider, process all recorded provider deployments.',
748
- '"all" is an installed bundle id, not a wildcard for every installed entry.',
749
- 'Bundled deployments release skill ownership receipts and delete only unchanged recorded files.',
750
- 'Project-local removal reverts deployed artifacts using recorded hashes; bundle source is preserved.',
751
- '',
752
- 'Options:',
753
- ' --dry-run List planned removals and preserved paths with reasons; write nothing.',
754
- ' --provider <p> Select one recorded provider deployment.',
755
- ' --keep-registry Keep project installed/deployedTo records after removal. By default,',
756
- ' remove selected deployment records and drop the id when none remain.',
757
- ' Project-local partial reverts retain their registry records.',
758
- ' --force Override project-local mutation refusal or legacy plugin dependency checks;',
759
- ' does not override bundled skill hash/ownership preservation.',
760
- ' --scope user Remove the user-scope mirror using ~/.aiwg/installed.json instead.',
761
- ' --user Alias for --scope user; user mirror removal updates its own registry.',
762
- ' --target <d> Target a project directory (alias: --prefix; default: cwd).',
763
- ' --help, -h Show this help.',
764
- '',
765
- 'Bundled skill removal preserves modified files, unrecorded operator files, foreign skills,',
766
- 'and symlinks inside skill directories. Project-local bundle source is never deleted.',
767
- 'User-scope legacy records without artifact manifests require manual file cleanup.',
768
- 'Unregistered ids fall back to the legacy plugin uninstaller (also supports --keep-data).',
769
- '',
770
- 'Examples:',
771
- ' aiwg remove all --dry-run',
772
- ' aiwg remove sdlc --provider claude --dry-run',
773
- ' aiwg remove my-bundle --keep-registry',
774
- ' aiwg remove sdlc --scope user --provider codex --dry-run',
775
- ].join('\n') };
776
- },
777
- async execute(ctx) {
778
- // Explicit provider removal is separate from framework removal. The native
779
- // adapter validates receipt hashes and preserves operator modifications.
780
- const nativeRemovalProvider = parseRemoveProvider(ctx.args);
781
- if (firstRemovePositional(ctx.args) === 'omp' && nativeRemovalProvider.provider === 'omp') {
782
- // Loaded from the package root, not by a path relative to this file: the
783
- // compiled handler sits one directory deeper than its source.
784
- const { uninstall } = (await import(pathToFileURL(path.join(await getFrameworkRoot(), 'tools/agents/providers/omp.mjs')).href));
785
- const { getProjectDir } = await import('../../config/aiwg-config.js');
786
- const dryRun = ctx.args.includes('--dry-run');
787
- const scope = ctx.args.includes('--user') || isScopeUser(ctx.args) ? 'user' : 'project';
788
- const count = uninstall(getProjectDir({ cwd: ctx.cwd }, ctx.args), { dryRun, scope });
789
- return { exitCode: 0, message: `${dryRun ? 'Would remove' : 'Removed'} ${count} unchanged OMP-owned files; operator files preserved.` };
790
- }
791
- // #1156 Phase 1 — `--scope user` / `--user`: revert the user-scope mirror
792
- // for the given framework. Independent of any project; reads the per-user
793
- // registry at ~/.aiwg/installed.json to find what was deployed, deletes
794
- // the mirrored artifacts under the provider's USER_SCOPE_PATHS, and
795
- // updates the registry.
796
- if (ctx.args.includes('--user') || isScopeUser(ctx.args)) {
797
- return await removeUserScopeDeploy(ctx.args);
798
- }
799
- if (firstRemovePositional(ctx.args) === 'grok-build') {
800
- const providerParse = parseRemoveProvider(ctx.args);
801
- if (providerParse.provider !== 'grok-build' || providerParse.error) {
802
- return { exitCode: 1, message: 'Use aiwg remove grok-build --provider grok-build [--dry-run] for reviewed project-scope removal.' };
803
- }
804
- const frameworkRoot = await getFrameworkRoot();
805
- const { uninstall } = (await import(pathToFileURL(path.join(frameworkRoot, 'tools/agents/providers/grok-build.mjs')).href));
806
- const { readAiwgConfig, writeAiwgConfig } = await import('../../config/aiwg-config.js');
807
- const target = getProjectDir({ cwd: ctx.cwd }, ctx.args);
808
- const dryRun = ctx.args.includes('--dry-run');
809
- const report = uninstall(target, { dryRun, srcRoot: frameworkRoot });
810
- if (!dryRun && report.skipped.length === 0) {
811
- const config = await readAiwgConfig(target);
812
- if (config) {
813
- for (const [name, entry] of Object.entries(config.installed ?? {})) {
814
- delete entry.deployedTo?.['grok-build'];
815
- if (Object.keys(entry.deployedTo ?? {}).length === 0)
816
- delete config.installed[name];
817
- }
818
- await writeAiwgConfig(target, config);
819
- }
820
- }
821
- const lines = [
822
- `${dryRun ? 'Would remove' : 'Removed'} ${dryRun ? report.planned.length : report.removed.length} unchanged AIWG-owned Grok Build artifact(s).`,
823
- ...report.planned.map(relative => ` ${relative}`),
824
- ...report.skipped.map(relative => ` Preserved modified or unverifiable: ${relative}`),
825
- 'Operator-owned Grok content and shared context files are preserved.',
826
- ];
827
- return { exitCode: report.skipped.length ? 1 : 0, message: lines.join('\n') };
828
- }
829
- // #1037 — Project-local-aware remove. If the first positional arg matches
830
- // a project-local entry in `installed`, route to the new handler.
831
- // Otherwise fall through to the existing plugin-uninstaller flow.
832
- const positionalArg = firstRemovePositional(ctx.args);
833
- const providerParse = parseRemoveProvider(ctx.args);
834
- if (providerParse.error) {
835
- return {
836
- exitCode: 1,
837
- message: `${providerParse.error}\n\nUsage: aiwg remove <id> [--force] [--dry-run] [--provider <p>] [--keep-registry]`,
838
- };
839
- }
840
- if (!positionalArg) {
841
- return {
842
- exitCode: 1,
843
- message: 'Error: framework or bundle id required\n\nUsage: aiwg remove <id> [--force] [--dry-run] [--provider <p>] [--keep-registry]',
844
- };
845
- }
846
- if (positionalArg) {
847
- try {
848
- const { readAiwgConfig, writeAiwgConfig, getProjectDir } = await import('../../config/aiwg-config.js');
849
- const { removeProjectLocalBundle } = await import('../../extensions/project-local-remove.js');
850
- const projectDir = getProjectDir({ cwd: ctx.cwd }, ctx.args);
851
- const config = await readAiwgConfig(projectDir);
852
- const entry = config?.installed?.[positionalArg];
853
- if (config && entry && entry.source !== 'project-local') {
854
- const fs = await import('node:fs/promises');
855
- const { resolveFrameworkDir } = await import('./use.js');
856
- const frameworkSlug = resolveFrameworkDir(positionalArg) ?? positionalArg;
857
- const dryRun = ctx.args.includes('--dry-run');
858
- const providers = Object.keys(entry.deployedTo).filter(p => !providerParse.provider || p === providerParse.provider);
859
- if (providerParse.provider && providers.length === 0) {
860
- return { exitCode: 1, message: `Error: '${positionalArg}' is not deployed for provider '${providerParse.provider}'.` };
861
- }
862
- let released = 0;
863
- const lines = [];
864
- for (const provider of providers) {
865
- if (dryRun)
866
- lines.push(` Provider ${provider}:`);
867
- const providerStart = lines.length;
868
- const skillRoots = deployedSkillRoots(projectDir, provider);
869
- for (const root of skillRoots) {
870
- for (const name of (await fs.readdir(root).catch(() => [])).sort()) {
871
- const skillDir = path.join(root, name);
872
- const plan = [];
873
- const owned = releaseSkillOwnership(skillDir, { frameworkSlug }, { dryRun, plan }) !== null;
874
- if (owned)
875
- released++;
876
- if (dryRun) {
877
- previewUnrecordedSkillFiles(skillDir, owned, plan, skillRoots);
878
- for (const entry of plan) {
879
- lines.push(` Would ${entry.action} ${path.relative(projectDir, entry.path)} — ${entry.reason}`);
880
- }
881
- }
882
- }
883
- }
884
- if (dryRun && lines.length === providerStart)
885
- lines.push(' No deployed skill files found.');
886
- if (!dryRun && !ctx.args.includes('--keep-registry'))
887
- delete entry.deployedTo[provider];
888
- }
889
- if (!dryRun && !ctx.args.includes('--keep-registry')) {
890
- if (Object.keys(entry.deployedTo).length === 0)
891
- delete config.installed[positionalArg];
892
- await writeAiwgConfig(projectDir, config);
893
- }
894
- if (dryRun) {
895
- lines.push(ctx.args.includes('--keep-registry')
896
- ? ' Registry preserved (--keep-registry).'
897
- : ` Would update .aiwg/aiwg.config: release ${providers.join(', ')} deployment record(s) for '${positionalArg}'; drop the id if none remain.`);
898
- }
899
- lines.push(`${dryRun ? 'Would release' : 'Released'} ${released} skill ownership receipt(s); operator files preserved.`);
900
- return { exitCode: 0, message: lines.join('\n') };
901
- }
902
- if (config && entry?.source === 'project-local') {
903
- const force = ctx.args.includes('--force');
904
- const dryRun = ctx.args.includes('--dry-run');
905
- const keepRegistry = ctx.args.includes('--keep-registry');
906
- const provider = providerParse.provider;
907
- const result = await removeProjectLocalBundle(config, projectDir, positionalArg, { force, dryRun, keepRegistry, provider });
908
- // Print outcome summary
909
- const lines = [];
910
- if (dryRun)
911
- lines.push(`[dry-run] Plan for project-local '${positionalArg}':`);
912
- for (const o of result.outcomes) {
913
- const marker = o.reverted ? '✓' : '⚠';
914
- lines.push(` ${marker} ${o.provider} :: ${o.artifactPath} [${o.case}] ${o.message}`);
915
- }
916
- if (result.revertedProviders.length > 0) {
917
- lines.push(`Fully reverted: ${result.revertedProviders.join(', ')}`);
918
- }
919
- if (result.partialProviders.length > 0) {
920
- lines.push(`Partial (registry preserved): ${result.partialProviders.join(', ')}`);
921
- }
922
- if (lines.length > 0)
923
- console.log(lines.join('\n'));
924
- if (!dryRun) {
925
- await writeAiwgConfig(projectDir, config);
926
- }
927
- // Note: source under .aiwg/<type>/<name>/ is intentionally NOT
928
- // deleted (load-bearing invariant from #1048 design).
929
- return {
930
- exitCode: result.partialProviders.length > 0 ? 1 : 0,
931
- message: result.partialProviders.length > 0
932
- ? `Some artifacts skipped (see above). Use --force to override mutation refusal.`
933
- : '',
934
- };
935
- }
936
- }
937
- catch (err) {
938
- // Fall through to upstream remove on any error in the project-local path
939
- const msg = err instanceof Error ? err.message : String(err);
940
- process.stderr.write(`project-local remove pre-check failed (falling through): ${msg}\n`);
941
- }
942
- }
943
- if (providerParse.provider) {
944
- return {
945
- exitCode: 1,
946
- message: `Error: --provider is only supported for project-local or user-scope remove. '${positionalArg}' is not a project-local bundle.\n\nUse 'aiwg remove ${positionalArg}' without --provider, or 'aiwg remove ${positionalArg} --scope user --provider ${providerParse.provider}' for a user-scope mirror. Refs #1610.`,
947
- };
948
- }
949
- const frameworkRoot = await getFrameworkRoot();
950
- const runner = createScriptRunner(frameworkRoot);
951
- return runner.run("tools/plugin/plugin-uninstaller-cli.mjs", ctx.args, {
952
- cwd: ctx.cwd,
953
- });
954
- },
955
- };
956
- /**
957
- * Promote handler — graduate a project-local bundle to upstream or to a
958
- * private corpus path. Implements the design at
959
- * @.aiwg/architecture/design-doctor-log-promote.md (#1049).
960
- *
961
- * Usage:
962
- * aiwg promote <name> # default: --to upstream
963
- * aiwg promote <name> --to upstream
964
- * aiwg promote <name> --to corpus <path>
965
- * aiwg promote <name> --dry-run
966
- * aiwg promote <name> --cleanup
967
- * aiwg promote <name> --force
968
- *
969
- * @implements #1037
970
- */
971
- export const promoteHandler = {
972
- id: 'promote',
973
- name: 'Promote',
974
- description: 'Graduate a project-local bundle to upstream or a corpus path',
975
- category: 'framework',
976
- aliases: ['-promote', '--promote', 'graduate'],
977
- async execute(ctx) {
978
- const args = ctx.args;
979
- const positional = args.find(a => !a.startsWith('-'));
980
- if (!positional) {
981
- return { exitCode: 1, message: 'Error: bundle name required\n\nUsage: aiwg promote <name> [--to upstream|corpus <path>] [--dry-run] [--cleanup] [--force]' };
982
- }
983
- const toIdx = args.findIndex(a => a === '--to');
984
- const toValue = toIdx >= 0 ? args[toIdx + 1] : 'upstream';
985
- let corpusPath;
986
- if (toValue === 'corpus') {
987
- // The argument *after* "corpus" is the path
988
- corpusPath = args[toIdx + 2];
989
- if (!corpusPath || corpusPath.startsWith('-')) {
990
- return { exitCode: 1, message: 'Error: --to corpus requires a path argument' };
991
- }
992
- }
993
- else if (toValue !== 'upstream') {
994
- return { exitCode: 1, message: `Error: --to must be 'upstream' or 'corpus' (got '${toValue}')` };
995
- }
996
- const dryRun = args.includes('--dry-run');
997
- const cleanup = args.includes('--cleanup');
998
- const force = args.includes('--force');
999
- try {
1000
- const { readAiwgConfig, writeAiwgConfig, getProjectDir } = await import('../../config/aiwg-config.js');
1001
- const { promoteProjectLocalBundle } = await import('../../extensions/project-local-promote.js');
1002
- const projectDir = getProjectDir({ cwd: ctx.cwd }, args);
1003
- const config = await readAiwgConfig(projectDir);
1004
- if (!config) {
1005
- return { exitCode: 1, message: 'Error: no .aiwg/aiwg.config found — run `aiwg init` first' };
1006
- }
1007
- const fr = await getFrameworkRoot();
1008
- const result = await promoteProjectLocalBundle(config, projectDir, positional, {
1009
- to: toValue,
1010
- corpusPath,
1011
- dryRun,
1012
- cleanup,
1013
- force,
1014
- frameworkRoot: fr,
1015
- });
1016
- if (!result.ok) {
1017
- return { exitCode: 1, message: `Error: ${result.message ?? result.failureReason}` };
1018
- }
1019
- if (dryRun && result.plan) {
1020
- console.log('[dry-run] Would copy:');
1021
- console.log(` ${result.plan.source} → ${result.plan.destination}`);
1022
- console.log(` Files: ${result.plan.files.length}, ${result.plan.totalBytes} bytes`);
1023
- console.log(' Pre-flight: ✓ manifest valid ✓ destination clean');
1024
- console.log(' Hash verification: skipped (dry-run)');
1025
- console.log(` Registry update: source: project-local → ${toValue === 'upstream' ? 'bundled' : 'corpus'}`);
1026
- console.log(` Cleanup: ${cleanup ? 'will remove .aiwg source after copy' : 'skipped (--cleanup not set)'}`);
1027
- return { exitCode: 0 };
1028
- }
1029
- await writeAiwgConfig(projectDir, config);
1030
- console.log(`✓ Promoted '${positional}' → ${result.plan?.destination}`);
1031
- if (cleanup) {
1032
- console.log(' Source removed from .aiwg/');
1033
- try {
1034
- const { deployProjectQuickref, generateProjectQuickref, hasProjectQuickref } = await import('../../extensions/project-quickref.js');
1035
- if (await hasProjectQuickref(projectDir)) {
1036
- if (config.providers.length > 0) {
1037
- for (const provider of config.providers)
1038
- await deployProjectQuickref(projectDir, provider);
1039
- console.log(` Managed project quickref refreshed for: ${config.providers.join(', ')}.`);
1040
- }
1041
- else {
1042
- await generateProjectQuickref(projectDir);
1043
- console.log(' Managed project quickref generated; no providers are configured for deployment.');
1044
- }
1045
- }
1046
- else {
1047
- console.log(' Managed project quickref is now empty; run `aiwg doctor --project-local` to inspect deployed stale copies.');
1048
- }
1049
- }
1050
- catch (error) {
1051
- console.log(` Managed project quickref refresh failed: ${error.message}`);
1052
- }
1053
- }
1054
- return { exitCode: 0 };
1055
- }
1056
- catch (err) {
1057
- const msg = err instanceof Error ? err.message : String(err);
1058
- return { exitCode: 1, message: `promote failed: ${msg}` };
1059
- }
1060
- },
1061
- };
1062
- /**
1063
- * New bundle handler — scaffolds a project-local bundle under the configured
1064
- * AIWG artifact root with a valid manifest, starter artifact, and a
1065
- * README that includes the identical-form portability reminder.
1066
- *
1067
- * Usage:
1068
- * aiwg new-bundle <name> # default: --type extension --starter skill
1069
- * aiwg new-bundle <name> --type addon
1070
- * aiwg new-bundle <name> --type framework --starter minimal
1071
- * aiwg new-bundle <name> --starter rule --description "Custom rule"
1072
- *
1073
- * @implements #1050
1074
- */
1075
- export const newBundleHandler = {
1076
- id: 'new-bundle',
1077
- name: 'New Bundle',
1078
- description: 'Scaffold a project-local bundle under the configured AIWG artifact root',
1079
- category: 'scaffolding',
1080
- aliases: ['new-extension', 'new-addon', 'new-framework', 'new-plugin', 'new-provider'],
1081
- async execute(ctx) {
1082
- const args = ctx.args;
1083
- const positional = args.find(a => !a.startsWith('-'));
1084
- if (!positional) {
1085
- return {
1086
- exitCode: 1,
1087
- message: 'Error: bundle name required\n\nUsage: aiwg new-bundle <name> [--type extension|addon|framework|plugin|provider] [--starter skill|rule|agent|minimal] [--description "..."]',
1088
- };
1089
- }
1090
- // Type can be inferred from the alias used to invoke (new-extension etc.)
1091
- const aliasMap = {
1092
- 'new-extension': 'extension',
1093
- 'new-addon': 'addon',
1094
- 'new-framework': 'framework',
1095
- 'new-plugin': 'plugin',
1096
- 'new-provider': 'provider',
1097
- };
1098
- const invoked = ctx.rawArgs[0] ?? '';
1099
- const aliasType = aliasMap[invoked];
1100
- const typeIdx = args.findIndex(a => a === '--type');
1101
- const typeFlag = typeIdx >= 0 ? args[typeIdx + 1] : undefined;
1102
- const type = (typeFlag ?? aliasType ?? 'extension');
1103
- if (!['extension', 'addon', 'framework', 'plugin', 'provider'].includes(type)) {
1104
- return { exitCode: 1, message: `Error: --type must be one of extension|addon|framework|plugin|provider (got '${type}')` };
1105
- }
1106
- const starterIdx = args.findIndex(a => a === '--starter');
1107
- const starter = starterIdx >= 0 ? args[starterIdx + 1] : undefined;
1108
- if (starter && !['skill', 'rule', 'agent', 'minimal'].includes(starter)) {
1109
- return { exitCode: 1, message: `Error: --starter must be one of skill|rule|agent|minimal (got '${starter}')` };
1110
- }
1111
- const descIdx = args.findIndex(a => a === '--description');
1112
- const description = descIdx >= 0 ? args[descIdx + 1] : undefined;
1113
- const dryRun = args.includes('--dry-run');
1114
- const { scaffoldProjectLocalBundle } = await import('../../extensions/project-local-scaffold.js');
1115
- try {
1116
- const result = await scaffoldProjectLocalBundle({
1117
- type,
1118
- name: positional,
1119
- description,
1120
- starter,
1121
- projectDir: ctx.cwd,
1122
- dryRun,
1123
- });
1124
- if (result.alreadyExists) {
1125
- return {
1126
- exitCode: 1,
1127
- message: `Refused: bundle already exists at ${result.bundlePath}. Remove it first or pick a different name.`,
1128
- };
1129
- }
1130
- if (dryRun) {
1131
- console.log(`[DRY RUN] Would scaffold project-local ${type} '${positional}' at ${result.bundlePath}`);
1132
- console.log(' Files that would be created:');
1133
- for (const f of result.filesCreated)
1134
- console.log(` + ${f}`);
1135
- console.log('');
1136
- console.log('No files written. Re-run without --dry-run to create.');
1137
- return { exitCode: 0 };
1138
- }
1139
- console.log(`✓ Scaffolded project-local ${type} '${positional}' at ${result.bundlePath}`);
1140
- console.log(' Files created:');
1141
- for (const f of result.filesCreated)
1142
- console.log(` + ${f}`);
1143
- // #1085 — when the project blanket-ignores .aiwg/, the new bundle's
1144
- // source would be silently dropped from version control. Detect and
1145
- // self-heal idempotently.
1146
- try {
1147
- const { appendAiwgSourceTrackBlock } = await import('../../extensions/project-local-gitignore.js');
1148
- const ig = await appendAiwgSourceTrackBlock(ctx.cwd);
1149
- if (ig.added) {
1150
- console.log('');
1151
- console.log(` → ${ig.reason}`);
1152
- console.log(' .aiwg/{addons,extensions,frameworks,plugins,providers}/ now tracked by git.');
1153
- console.log(' Generated state under .aiwg/ (working/, ralph/, research/, ...) stays ignored.');
1154
- }
1155
- }
1156
- catch {
1157
- // .gitignore management is best-effort; don't fail the scaffold
1158
- }
1159
- try {
1160
- const { generateProjectQuickref } = await import('../../extensions/project-quickref.js');
1161
- await generateProjectQuickref(ctx.cwd);
1162
- console.log(' → Managed project quickref refreshed from discovered capabilities.');
1163
- }
1164
- catch (error) {
1165
- console.log(` → Managed project quickref refresh deferred: ${error.message}`);
1166
- }
1167
- // #1235 / #1758 — auto-rebuild the project graph and refresh the
1168
- // Fortemi Core static cache so the new bundle is immediately
1169
- // discoverable via top-level `aiwg discover` / `aiwg show`.
1170
- // Best-effort: don't fail the scaffold if indexing hiccups.
1171
- let indexedOk = false;
1172
- let fortemiSyncedOk = false;
1173
- try {
1174
- const { buildIndex } = await import('../../artifacts/index-builder.js');
1175
- await buildIndex(ctx.cwd, { graph: 'project', force: false, explicit: true });
1176
- indexedOk = true;
1177
- const { syncFortemiCoreIndex } = await import('../../artifacts/fortemi-core-sync.js');
1178
- syncFortemiCoreIndex(ctx.cwd, { graph: 'project' });
1179
- fortemiSyncedOk = true;
1180
- }
1181
- catch {
1182
- // ignore — surface via next-steps hint instead
1183
- }
1184
- console.log('');
1185
- console.log('Next steps:');
1186
- console.log(` 1. Edit manifest.json (description, version, keywords)`);
1187
- console.log(` 2. Customize the starter artifact under ${result.bundlePath}/`);
1188
- if (indexedOk && fortemiSyncedOk) {
1189
- console.log(` 3. Discoverable now via: aiwg discover "${positional}"`);
1190
- }
1191
- else if (indexedOk) {
1192
- console.log(` 3. Sync project search cache: aiwg index sync --graph project`);
1193
- console.log(` then: aiwg discover "${positional}"`);
1194
- }
1195
- else {
1196
- console.log(` 3. Rebuild project index: aiwg index build --graph project`);
1197
- console.log(` then sync search cache: aiwg index sync --graph project`);
1198
- console.log(` then: aiwg discover "${positional}"`);
1199
- }
1200
- console.log(` 4. Deploy: aiwg use ${positional}`);
1201
- console.log(` 5. Inspect: aiwg doctor --project-local`);
1202
- console.log(` 6. When mature, promote: aiwg promote ${positional}`);
1203
- return { exitCode: 0 };
1204
- }
1205
- catch (err) {
1206
- const msg = err instanceof Error ? err.message : String(err);
1207
- return { exitCode: 1, message: `Error: ${msg}` };
1208
- }
1209
- },
1210
- };
1211
- /**
1212
- * New project handler
1213
- *
1214
- * Delegates to tools/install/new-project.mjs
1215
- */
1216
- export const newProjectHandler = {
1217
- id: "new",
1218
- name: "New Project",
1219
- description: "Scaffold a new project with AIWG",
1220
- category: "project",
1221
- aliases: ["-new", "--new"],
1222
- async execute(ctx) {
1223
- const frameworkRoot = await getFrameworkRoot();
1224
- const runner = createScriptRunner(frameworkRoot);
1225
- const result = await runner.run("tools/install/new-project.mjs", ctx.args, {
1226
- cwd: ctx.cwd,
1227
- });
1228
- if (result.exitCode === 0) {
1229
- // The real scaffolder always runs in an existing target directory. Keep
1230
- // mocked/script-runner-only calls side-effect free when their synthetic
1231
- // cwd does not exist.
1232
- const { access } = await import('node:fs/promises');
1233
- const { constants } = await import('node:fs');
1234
- try {
1235
- await access(ctx.cwd, constants.W_OK);
1236
- const { ensureWorkspaceContext } = await import('../../smiths/context-pipeline/workspace-context.js');
1237
- await ensureWorkspaceContext(ctx.cwd);
1238
- }
1239
- catch (error) {
1240
- if (!['ENOENT', 'EACCES'].includes(error.code ?? ''))
1241
- throw error;
1242
- }
1243
- const { formatStarNudge } = await import("../../community/links.js");
1244
- const { markNudgeShown, shouldShowNudge } = await import("../../community/nudge-policy.js");
1245
- if (shouldShowNudge('intake')) {
1246
- const nudge = formatStarNudge();
1247
- if (nudge) {
1248
- console.log('');
1249
- console.log(nudge);
1250
- markNudgeShown('intake');
1251
- }
1252
- }
1253
- }
1254
- return result;
1255
- },
1256
- };
1257
- /**
1258
- * Install plugin handler
1259
- *
1260
- * Delegates to tools/plugin/plugin-installer-cli.mjs
1261
- */
1262
- export const installPluginHandler = {
1263
- id: "install-plugin",
1264
- name: "Install Plugin",
1265
- description: "Install a plugin from the registry",
1266
- category: "plugin",
1267
- aliases: ["-install-plugin", "--install-plugin"],
1268
- async execute(ctx) {
1269
- const frameworkRoot = await getFrameworkRoot();
1270
- const runner = createScriptRunner(frameworkRoot);
1271
- return runner.run("tools/plugin/plugin-installer-cli.mjs", ctx.args, {
1272
- cwd: ctx.cwd,
1273
- env: { AIWG_ROOT: frameworkRoot },
1274
- });
1275
- },
1276
- };
1277
- /**
1278
- * Uninstall plugin handler
1279
- *
1280
- * Delegates to tools/plugin/plugin-uninstaller-cli.mjs
1281
- */
1282
- export const uninstallPluginHandler = {
1283
- id: "uninstall-plugin",
1284
- name: "Uninstall Plugin",
1285
- description: "Uninstall a plugin",
1286
- category: "plugin",
1287
- aliases: ["-uninstall-plugin", "--uninstall-plugin"],
1288
- async execute(ctx) {
1289
- const frameworkRoot = await getFrameworkRoot();
1290
- const runner = createScriptRunner(frameworkRoot);
1291
- return runner.run("tools/plugin/plugin-uninstaller-cli.mjs", ctx.args, {
1292
- cwd: ctx.cwd,
1293
- });
1294
- },
1295
- };
1296
- /**
1297
- * Plugin status handler
1298
- *
1299
- * Delegates to tools/plugin/plugin-status-cli.mjs
1300
- */
1301
- export const pluginStatusHandler = {
1302
- id: "plugin-status",
1303
- name: "Plugin Status",
1304
- description: "Show plugin status and installation details",
1305
- category: "plugin",
1306
- aliases: ["-plugin-status", "--plugin-status"],
1307
- async execute(ctx) {
1308
- const frameworkRoot = await getFrameworkRoot();
1309
- const runner = createScriptRunner(frameworkRoot);
1310
- return runner.run("tools/plugin/plugin-status-cli.mjs", ctx.args, {
1311
- cwd: ctx.cwd,
1312
- });
1313
- },
1314
- };
1315
- /**
1316
- * Package plugin handler
1317
- *
1318
- * Delegates to tools/plugin/package-plugins.mjs
1319
- */
1320
- function packagePluginHelp() {
1321
- return {
1322
- exitCode: 0,
1323
- message: [
1324
- "aiwg package-plugin — package a project-local or built-in marketplace wrapper",
1325
- "",
1326
- "Usage:",
1327
- " aiwg package-plugin <name> [--source <path>] [--output <path>] [--provider <name>] [--clean] [--dry-run]",
1328
- " aiwg package-plugin --plugin <name> [options] # compatibility form",
1329
- "",
1330
- "Options:",
1331
- " --source <path> explicit project-local wrapper source (must stay inside the project)",
1332
- " --output <path> standalone archive output (default: dist/plugins)",
1333
- " --provider <name> claude, codex, or all for standalone wrappers; built-ins retain all formats",
1334
- " --clean clean generated plugin output before packaging",
1335
- " --dry-run, -n preview without writing",
1336
- " --help, -h show this help",
1337
- "",
1338
- "Project-local wrappers are discovered under .aiwg/plugins and packaged as deterministic archives.",
1339
- ].join("\n"),
1340
- };
1341
- }
1342
- export const packagePluginHandler = {
1343
- id: "package-plugin",
1344
- name: "Package Plugin",
1345
- description: "Package a plugin for distribution",
1346
- category: "plugin",
1347
- aliases: ["-package-plugin", "--package-plugin"],
1348
- async help() {
1349
- return packagePluginHelp();
1350
- },
1351
- async execute(ctx) {
1352
- if (ctx.args.includes("--help") || ctx.args.includes("-h")) {
1353
- return packagePluginHelp();
1354
- }
1355
- const hasExplicitPlugin = ctx.args.includes("--plugin") || ctx.args.includes("-p");
1356
- const positional = ctx.args[0] && !ctx.args[0].startsWith("-")
1357
- ? ctx.args[0]
1358
- : undefined;
1359
- if (!hasExplicitPlugin && !positional) {
1360
- return {
1361
- exitCode: 1,
1362
- message: "Error: plugin name is required.\n\nRun `aiwg package-plugin --help` for usage.",
1363
- };
1364
- }
1365
- const positionalSource = positional && (positional.includes('/') || positional.includes('\\'))
1366
- ? positional
1367
- : undefined;
1368
- const normalizedArgs = hasExplicitPlugin
1369
- ? ctx.args
1370
- : positionalSource
1371
- ? [
1372
- "--plugin", path.basename(path.resolve(ctx.cwd, positionalSource)),
1373
- "--source", positionalSource,
1374
- ...ctx.args.slice(1),
1375
- ]
1376
- : ["--plugin", positional, ...ctx.args.slice(1)];
1377
- const frameworkRoot = await getFrameworkRoot();
1378
- const runner = createScriptRunner(frameworkRoot);
1379
- return runner.run("tools/plugin/package-plugins.mjs", normalizedArgs, {
1380
- cwd: ctx.cwd,
1381
- });
1382
- },
1383
- };
1384
- /**
1385
- * Package all plugins handler
1386
- *
1387
- * Delegates to tools/plugin/package-plugins.mjs with --all flag
1388
- */
1389
- export const packageAllPluginsHandler = {
1390
- id: "package-all-plugins",
1391
- name: "Package All Plugins",
1392
- description: "Package all plugins for distribution",
1393
- category: "plugin",
1394
- aliases: ["-package-all-plugins", "--package-all-plugins"],
1395
- async execute(ctx) {
1396
- if (ctx.args.includes("--help") || ctx.args.includes("-h")) {
1397
- return {
1398
- exitCode: 0,
1399
- message: [
1400
- "aiwg package-all-plugins — package every built-in marketplace wrapper",
1401
- "",
1402
- "Usage:",
1403
- " aiwg package-all-plugins [--provider <name>] [--clean] [--dry-run]",
1404
- "",
1405
- "Options:",
1406
- " --provider <name> claude, codex, cursor, factory, openclaw, or all",
1407
- " --clean clean generated plugin output before packaging",
1408
- " --dry-run, -n preview without writing",
1409
- " --help, -h show this help",
1410
- ].join("\n"),
1411
- };
1412
- }
1413
- const frameworkRoot = await getFrameworkRoot();
1414
- const runner = createScriptRunner(frameworkRoot);
1415
- return runner.run("tools/plugin/package-plugins.mjs", ["--all", ...ctx.args], {
1416
- cwd: ctx.cwd,
1417
- });
1418
- },
1419
- };
1420
- /**
1421
- * Artifact index command handler
1422
- *
1423
- * Dynamically imports and delegates to src/artifacts/cli.mjs.
1424
- * Handles subcommands: build, query, deps, stats
1425
- *
1426
- * @implements #420
1427
- */
1428
- export const indexHandler = {
1429
- id: "index",
1430
- name: "Artifact Index",
1431
- description: "Artifact index commands (build, query, deps, stats)",
1432
- category: "index",
1433
- aliases: [],
1434
- async help() {
1435
- const { printIndexUsage } = await import("../../artifacts/cli.js");
1436
- printIndexUsage();
1437
- return { exitCode: 0 };
1438
- },
1439
- async execute(ctx) {
1440
- try {
1441
- const { main } = await import("../../artifacts/cli.js");
1442
- await main(ctx.args);
1443
- return {
1444
- exitCode: Number(process.exitCode ?? 0),
1445
- };
1446
- }
1447
- catch (error) {
1448
- const result = handlerResultFromError(error);
1449
- return { ...result, message: `Index command failed: ${result.message}` };
1450
- }
1451
- },
1452
- };
1453
- /**
1454
- * `aiwg corpus` — research-corpus tools (radar/freshness subsystem, #1498).
1455
- * Delegates to the corpus-tools router, mirroring indexHandler.
1456
- */
1457
- export const corpusHandler = {
1458
- id: "corpus",
1459
- name: "Research Corpus Tools",
1460
- description: "Research-corpus tools (radar-init, radar-status, radar-report)",
1461
- category: "index",
1462
- aliases: [],
1463
- async help() {
1464
- const { corpusMain } = await import("../../artifacts/corpus-tools/cli.js");
1465
- await corpusMain(["--help"]);
1466
- return { exitCode: 0 };
1467
- },
1468
- async execute(ctx) {
1469
- try {
1470
- const { corpusMain } = await import("../../artifacts/corpus-tools/cli.js");
1471
- await corpusMain(ctx.args, ctx.cwd);
1472
- return { exitCode: 0 };
1473
- }
1474
- catch (error) {
1475
- const result = handlerResultFromError(error);
1476
- return { ...result, message: `Corpus command failed: ${result.message}` };
1477
- }
1478
- },
1479
- };
1480
- /**
1481
- * Discovery command handler — first-class top-level verb (#1212).
1482
- *
1483
- * Forwards to the same implementation as `aiwg index discover` but
1484
- * exposes discovery as its own command so agents don't conflate it
1485
- * with the project's general-purpose artifact graph indices.
1486
- *
1487
- * aiwg discover "<phrase>" [--limit N] [--type skill,agent,...] [--json]
1488
- * [--resource-source local|web|auto] [--aiwg-version <version|range|digest|channel>] [--offline]
1489
- */
1490
- export const discoverHandler = {
1491
- id: "discover",
1492
- name: "Discover",
1493
- description: "Find AIWG operational assets by capability — index-driven on-demand discovery",
1494
- category: "index",
1495
- aliases: [],
1496
- async execute(ctx) {
1497
- try {
1498
- // Delegate to the same handler `aiwg index discover` uses, by
1499
- // prepending the `discover` subcommand and reusing the artifacts
1500
- // CLI router. This keeps a single implementation path.
1501
- const { main } = await import("../../artifacts/cli.js");
1502
- await main(["discover", ...ctx.args]);
1503
- return { exitCode: 0 };
1504
- }
1505
- catch (error) {
1506
- const result = handlerResultFromError(error);
1507
- return { ...result, message: `Discover command failed: ${result.message}` };
1508
- }
1509
- },
1510
- };
1511
- /**
1512
- * Features command handler — manage AIWG's optional runtime features (#1219).
1513
- *
1514
- * Subcommands: status / info / install / remove. Native feature installs use
1515
- * a user-owned package root with explicit package-level script approval.
1516
- */
1517
- export const featuresHandler = {
1518
- id: "features",
1519
- name: "Features",
1520
- description: "List, inspect, and install AIWG's optional runtime features",
1521
- category: "maintenance",
1522
- aliases: [],
1523
- async execute(ctx) {
1524
- try {
1525
- const { main } = await import("../../features/cli.js");
1526
- await main(ctx.args);
1527
- return { exitCode: 0 };
1528
- }
1529
- catch (error) {
1530
- const result = handlerResultFromError(error);
1531
- return { ...result, message: `Features command failed: ${result.message}` };
1532
- }
1533
- },
1534
- };
1535
- /**
1536
- * Show command handler — fetch the full text of a specific artifact (#1218).
1537
- *
1538
- * Forwards to the same implementation as `aiwg index show`. Companion to
1539
- * `aiwg discover`: where discover ranks candidates, show fetches the body
1540
- * so consumers don't need to navigate AIWG's storage paths themselves.
1541
- *
1542
- * aiwg show <name> [--type skill,agent,...] [--json] [--first]
1543
- * [--resource-source local|web|auto] [--aiwg-version <version|range|digest|channel>] [--offline]
1544
- */
1545
- export const showHandler = {
1546
- id: "show",
1547
- name: "Show",
1548
- description: "Show an AIWG metadata card; --section or --body fetches content",
1549
- category: "index",
1550
- aliases: [],
1551
- async execute(ctx) {
1552
- try {
1553
- const { main } = await import("../../artifacts/cli.js");
1554
- await main(["show", ...ctx.args]);
1555
- return { exitCode: 0 };
1556
- }
1557
- catch (error) {
1558
- const result = handlerResultFromError(error);
1559
- return { ...result, message: `Show command failed: ${result.message}` };
1560
- }
1561
- },
1562
- };
1563
- /**
1564
- * Skills command handler
1565
- *
1566
- * Dynamically imports and delegates to src/skills/cli.ts.
1567
- * Handles subcommands: search, info, list, install, publish
1568
- *
1569
- * @implements #539
1570
- */
1571
- export const skillsHandler = {
1572
- id: "skills",
1573
- name: "Skills Registry",
1574
- description: "Skill commands (search, info, list, install, publish)",
1575
- category: "catalog",
1576
- aliases: [],
1577
- async execute(ctx) {
1578
- try {
1579
- const { main } = await import("../../skills/cli.js");
1580
- await main(ctx.args);
1581
- return {
1582
- exitCode: 0,
1583
- };
1584
- }
1585
- catch (error) {
1586
- const result = handlerResultFromError(error);
1587
- return { ...result, message: `Skills command failed: ${result.message}` };
1588
- }
1589
- },
1590
- };
1591
- /**
1592
- * Config command handler
1593
- *
1594
- * Dynamically imports and delegates to src/config/cli.ts.
1595
- * Handles subcommands: get, set, list, validate, reset, path, edit
1596
- *
1597
- * @implements #545
1598
- */
1599
- export const configHandler = {
1600
- id: "config",
1601
- name: "Config",
1602
- description: "User config commands (get, set, list, validate, reset, path, edit)",
1603
- category: "config",
1604
- aliases: [],
1605
- async execute(ctx) {
1606
- try {
1607
- const { main } = await import("../../config/cli.js");
1608
- await main(ctx.args);
1609
- return {
1610
- exitCode: 0,
1611
- };
1612
- }
1613
- catch (error) {
1614
- const result = handlerResultFromError(error);
1615
- return { ...result, message: `Config command failed: ${result.message}` };
1616
- }
1617
- },
1618
- };
1619
- /**
1620
- * Ops command handler
1621
- *
1622
- * Dynamically imports and delegates to src/ops/cli.ts.
1623
- * Handles subcommands: init, status, use, list, push
1624
- *
1625
- * @implements #544
1626
- */
1627
- export const opsHandler = {
1628
- id: "ops",
1629
- name: "Ops",
1630
- description: "Ops ecosystem commands (init, status, use, list, push)",
1631
- category: "ops",
1632
- aliases: [],
1633
- async execute(ctx) {
1634
- try {
1635
- const { main } = await import("../../ops/cli.js");
1636
- await main(ctx.args);
1637
- return {
1638
- exitCode: 0,
1639
- };
1640
- }
1641
- catch (error) {
1642
- const result = handlerResultFromError(error);
1643
- return { ...result, message: `Ops command failed: ${result.message}` };
1644
- }
1645
- },
1646
- };
1647
- /**
1648
- * Activity-log command handler
1649
- *
1650
- * Dynamically imports and delegates to src/activity-log/cli.ts.
1651
- * Handles subcommands: show, append, stats. Persistence routes through
1652
- * resolveStorage('activity_log') so the log honors any storage.config
1653
- * override (#934).
1654
- *
1655
- * @implements #934
1656
- * @implements #964
1657
- */
1658
- export const activityLogHandler = {
1659
- id: 'activity-log',
1660
- name: 'Activity Log',
1661
- description: 'Query and manage .aiwg/activity.log (show, append, stats)',
1662
- category: 'utility',
1663
- aliases: [],
1664
- async execute(ctx) {
1665
- try {
1666
- const { main } = await import('../../activity-log/cli.js');
1667
- await main(ctx.args);
1668
- return { exitCode: 0 };
1669
- }
1670
- catch (error) {
1671
- const result = handlerResultFromError(error);
1672
- return { ...result, message: `activity-log command failed: ${result.message}` };
1673
- }
1674
- },
1675
- };
1676
- /**
1677
- * Provenance command handler — routes \`aiwg provenance\` through
1678
- * resolveStorage('provenance') for provenance-* skills (#968).
1679
- *
1680
- * @implements #934
1681
- * @implements #968
1682
- */
1683
- export const provenanceHandler = {
1684
- id: 'provenance',
1685
- name: 'Provenance',
1686
- description: 'Provenance subsystem storage operations (path, list, get, put, delete, append-log)',
1687
- category: 'utility',
1688
- aliases: [],
1689
- async execute(ctx) {
1690
- try {
1691
- const { main } = await import('../../provenance/cli.js');
1692
- await main(ctx.args);
1693
- return { exitCode: 0 };
1694
- }
1695
- catch (error) {
1696
- const result = handlerResultFromError(error);
1697
- return { ...result, message: `provenance command failed: ${result.message}` };
1698
- }
1699
- },
1700
- };
1701
- /**
1702
- * Research storage command handler — routes \`aiwg research-store\`
1703
- * through resolveStorage('research') for research-acquire / corpus-*
1704
- * skills (#968). Disambiguated from existing research-* workflow
1705
- * commands by the \`-store\` suffix.
1706
- *
1707
- * @implements #934
1708
- * @implements #968
1709
- */
1710
- export const researchStoreHandler = {
1711
- id: 'research-store',
1712
- name: 'Research Store',
1713
- description: 'Research subsystem storage operations (path, list, get, put, delete, append-log)',
1714
- category: 'utility',
1715
- aliases: [],
1716
- async execute(ctx) {
1717
- try {
1718
- const { main } = await import('../../research/storage-cli.js');
1719
- await main(ctx.args);
1720
- return { exitCode: 0 };
1721
- }
1722
- catch (error) {
1723
- const result = handlerResultFromError(error);
1724
- return { ...result, message: `research-store command failed: ${result.message}` };
1725
- }
1726
- },
1727
- };
1728
- /** Executable source-selection companion to the research-query skill. */
1729
- export const researchQueryHandler = {
1730
- id: 'research-query',
1731
- name: 'Research Query',
1732
- description: 'Select research sources for a question with local or Fortemi Core retrieval',
1733
- category: 'index',
1734
- aliases: [],
1735
- async execute(ctx) {
1736
- try {
1737
- const { main } = await import('../../research/query-cli.js');
1738
- await main(ctx.args, ctx.cwd);
1739
- return { exitCode: 0 };
1740
- }
1741
- catch (error) {
1742
- const result = handlerResultFromError(error);
1743
- return { ...result, message: `research-query command failed: ${result.message}` };
1744
- }
1745
- },
1746
- };
1747
- /**
1748
- * Reflections command handler
1749
- *
1750
- * Routes \`aiwg reflections <subcommand>\` through resolveStorage('reflections')
1751
- * for ralph-reflect / reflection-injection skills (#967).
1752
- *
1753
- * @implements #934
1754
- * @implements #967
1755
- */
1756
- export const reflectionsHandler = {
1757
- id: 'reflections',
1758
- name: 'Reflections',
1759
- description: 'Reflections subsystem storage operations (path, list, get, put, delete, append-log)',
1760
- category: 'utility',
1761
- aliases: [],
1762
- async execute(ctx) {
1763
- try {
1764
- const { main } = await import('../../reflections/cli.js');
1765
- await main(ctx.args);
1766
- return { exitCode: 0 };
1767
- }
1768
- catch (error) {
1769
- const result = handlerResultFromError(error);
1770
- return { ...result, message: `reflections command failed: ${result.message}` };
1771
- }
1772
- },
1773
- };
1774
- /**
1775
- * Memory command handler
1776
- *
1777
- * Routes \`aiwg memory <subcommand>\` through resolveStorage('memory') so
1778
- * the four memory skills (memory-ingest, memory-lint, memory-log-append,
1779
- * memory-query-capture) honor any storage.config redirection.
1780
- *
1781
- * @implements #934
1782
- * @implements #966
1783
- */
1784
- export const memoryHandler = {
1785
- id: 'memory',
1786
- name: 'Memory',
1787
- description: 'Memory storage, project registry, read-only audit/cost/recommendations, and reviewed lifecycle operations',
1788
- category: 'utility',
1789
- aliases: [],
1790
- async help(ctx) {
1791
- if (ctx.args[0] === 'cost') {
1792
- const { MEMORY_COST_USAGE } = await import('../../memory/cli.js');
1793
- return { exitCode: 0, message: MEMORY_COST_USAGE, rawOutput: true };
1794
- }
1795
- if (ctx.args[0] === 'recommend') {
1796
- const { MEMORY_RECOMMEND_USAGE } = await import('../../memory/recommend-cli.js');
1797
- return { exitCode: 0, message: MEMORY_RECOMMEND_USAGE, rawOutput: true };
1798
- }
1799
- if (['plan', 'apply', 'verify', 'restore'].includes(ctx.args[0])) {
1800
- const { MEMORY_MAINTENANCE_USAGE } = await import('../../memory/maintenance-cli.js');
1801
- return { exitCode: 0, message: MEMORY_MAINTENANCE_USAGE, rawOutput: true };
1802
- }
1803
- const { MEMORY_AUDIT_USAGE } = await import('../../memory/cli.js');
1804
- return { exitCode: 0, message: MEMORY_AUDIT_USAGE, rawOutput: true };
1805
- },
1806
- async execute(ctx) {
1807
- try {
1808
- const { main } = await import('../../memory/cli.js');
1809
- return { exitCode: (await main(ctx.args)) ?? 0 };
1810
- }
1811
- catch (error) {
1812
- const result = handlerResultFromError(error);
1813
- if (['audit', 'cost', 'recommend', 'plan', 'apply', 'verify', 'restore'].includes(ctx.args[0])) {
1814
- const { isAiwgError } = await import('../errors.js');
1815
- const exitCode = isAiwgError(error) ? error.exitCode : 3;
1816
- const receipt = error && typeof error === 'object' && 'receipt' in error ? error.receipt : undefined;
1817
- if (ctx.args.includes('--json')) {
1818
- console.log(JSON.stringify({ error: result.message, exitCode,
1819
- ...(receipt !== undefined ? { receipt } : {}) }, null, 2));
1820
- return { exitCode };
1821
- }
1822
- return { ...result, exitCode, message: `memory command failed: ${result.message}${receipt !== undefined ? `\n${JSON.stringify({ receipt }, null, 2)}` : ''}` };
1823
- }
1824
- return { ...result, message: `memory command failed: ${result.message}` };
1825
- }
1826
- },
1827
- };
1828
- /**
1829
- * Knowledge-base command handler
1830
- *
1831
- * Routes \`aiwg kb <subcommand>\` through resolveStorage('kb') so the KB
1832
- * honors any storage.config redirection without each kb skill
1833
- * hardcoding `.aiwg/kb/`.
1834
- *
1835
- * @implements #934
1836
- * @implements #965
1837
- */
1838
- export const kbHandler = {
1839
- id: 'kb',
1840
- name: 'Knowledge Base',
1841
- description: 'Knowledge base storage operations (path, list, get, put, delete)',
1842
- category: 'utility',
1843
- aliases: [],
1844
- async execute(ctx) {
1845
- try {
1846
- const { main } = await import('../../kb/cli.js');
1847
- await main(ctx.args);
1848
- return { exitCode: 0 };
1849
- }
1850
- catch (error) {
1851
- const result = handlerResultFromError(error);
1852
- return { ...result, message: `kb command failed: ${result.message}` };
1853
- }
1854
- },
1855
- };
1856
- /**
1857
- * Storage command handler
1858
- *
1859
- * Dynamically imports and delegates to src/storage/cli.ts.
1860
- * Handles subcommands: show, list-backends, test
1861
- *
1862
- * @implements #934
1863
- * @implements #954
1864
- */
1865
- export const storageHandler = {
1866
- id: 'storage',
1867
- name: 'Storage',
1868
- description: 'Storage adapter commands (show, list-backends, test)',
1869
- category: 'utility',
1870
- aliases: [],
1871
- async execute(ctx) {
1872
- try {
1873
- const { main } = await import('../../storage/cli.js');
1874
- await main(ctx.args);
1875
- return { exitCode: 0 };
1876
- }
1877
- catch (error) {
1878
- const result = handlerResultFromError(error);
1879
- return { ...result, message: `Storage command failed: ${result.message}` };
1880
- }
1881
- },
1882
- };
1883
- /**
1884
- * RLM agentic tools handler
1885
- *
1886
- * Routes `aiwg chunk`, `aiwg fanout`, `aiwg rlm-prep`, `aiwg rlm-search`,
1887
- * and `aiwg rlm-status` to src/rlm/cli.ts.
1888
- *
1889
- * These are support tools for agentic sessions — callable by users but
1890
- * primarily used by RLM agents during recursive and fanout operations.
1891
- *
1892
- * @implements #559
1893
- */
1894
- export const rlmToolsHandler = {
1895
- id: 'rlm-tools',
1896
- name: 'RLM Tools',
1897
- description: 'Agentic support tools for RLM operations (chunk, fanout, rlm-prep, rlm-search, rlm-status)',
1898
- category: 'agentic-tools',
1899
- aliases: [],
1900
- async execute(ctx) {
1901
- try {
1902
- const { main } = await import('../../rlm/cli.js');
1903
- await main(ctx.args);
1904
- return {
1905
- exitCode: 0,
1906
- };
1907
- }
1908
- catch (error) {
1909
- const result = handlerResultFromError(error);
1910
- return { ...result, message: `RLM tools command failed: ${result.message}` };
1911
- }
1912
- },
1913
- };
1914
- // Individual handlers that delegate to rlmToolsHandler with their command prepended
1915
- export const chunkHandler = {
1916
- id: 'chunk',
1917
- name: 'Chunk',
1918
- description: 'Split a file into overlapping chunks for parallel fanout processing',
1919
- category: 'agentic-tools',
1920
- aliases: [],
1921
- async execute(ctx) {
1922
- return rlmToolsHandler.execute({ ...ctx, args: ['chunk', ...ctx.args] });
1923
- },
1924
- };
1925
- export const fanoutHandler = {
1926
- id: 'fanout',
1927
- name: 'Fanout',
1928
- description: 'Dispatch parallel subagent queries across a chunk manifest',
1929
- category: 'agentic-tools',
1930
- aliases: [],
1931
- async execute(ctx) {
1932
- return rlmToolsHandler.execute({ ...ctx, args: ['fanout', ...ctx.args] });
1933
- },
1934
- };
1935
- export const rlmPrepHandler = {
1936
- id: 'rlm-prep',
1937
- name: 'RLM Prep',
1938
- description: 'Prepare source content for RLM processing (chunk + index + manifest)',
1939
- category: 'agentic-tools',
1940
- aliases: [],
1941
- async execute(ctx) {
1942
- return rlmToolsHandler.execute({ ...ctx, args: ['rlm-prep', ...ctx.args] });
1943
- },
1944
- };
1945
- export const rlmSearchHandler = {
1946
- id: 'rlm-search',
1947
- name: 'RLM Search',
1948
- description: 'Full recursive search pipeline: decompose source, fanout query, synthesize results',
1949
- category: 'agentic-tools',
1950
- aliases: [],
1951
- async execute(ctx) {
1952
- return rlmToolsHandler.execute({ ...ctx, args: ['rlm-search', ...ctx.args] });
1953
- },
1954
- };
1955
- export const rlmStatusCliHandler = {
1956
- id: 'rlm-status',
1957
- name: 'RLM Status',
1958
- description: 'Show active RLM task tree, progress, and cost breakdown',
1959
- category: 'agentic-tools',
1960
- aliases: [],
1961
- async execute(ctx) {
1962
- return rlmToolsHandler.execute({ ...ctx, args: ['rlm-status', ...ctx.args] });
1963
- },
1964
- };
1965
- /** RLM result cache (#1203). */
1966
- export const rlmCacheHandler = {
1967
- id: 'rlm-cache',
1968
- name: 'RLM Cache',
1969
- description: 'Manage cached RLM results (list, stats, evict, clear) — keyed by index content-hash',
1970
- category: 'agentic-tools',
1971
- aliases: [],
1972
- async execute(ctx) {
1973
- return rlmToolsHandler.execute({ ...ctx, args: ['rlm-cache', ...ctx.args] });
1974
- },
1975
- };
1976
- /**
1977
- * All subcommand handlers
1978
- */
3
+ import { quickrefHandler } from "./subcommands-quickref.js";
4
+ export { quickrefHandler };
5
+ import { listHandler } from "./subcommands-list.js";
6
+ export { listHandler };
7
+ import { removeHandler } from "./remove.js";
8
+ export { removeHandler };
9
+ import { promoteHandler, newBundleHandler } from "./subcommands-bundles.js";
10
+ export { promoteHandler, newBundleHandler };
11
+ import { newProjectHandler, installPluginHandler, uninstallPluginHandler, pluginStatusHandler, packagePluginHandler, packageAllPluginsHandler } from "./subcommands-plugins.js";
12
+ export { newProjectHandler, installPluginHandler, uninstallPluginHandler, pluginStatusHandler, packagePluginHandler, packageAllPluginsHandler };
13
+ import { indexHandler, corpusHandler, discoverHandler, featuresHandler, showHandler, skillsHandler } from "./subcommands-discovery.js";
14
+ export { indexHandler, corpusHandler, discoverHandler, featuresHandler, showHandler, skillsHandler };
15
+ import { configHandler, opsHandler, activityLogHandler, provenanceHandler, researchStoreHandler, researchQueryHandler, reflectionsHandler, memoryHandler, kbHandler } from "./subcommands-storage.js";
16
+ export { configHandler, opsHandler, activityLogHandler, provenanceHandler, researchStoreHandler, researchQueryHandler, reflectionsHandler, memoryHandler, kbHandler };
17
+ import { storageHandler, rlmToolsHandler, chunkHandler, fanoutHandler, rlmPrepHandler, rlmSearchHandler, rlmStatusCliHandler, rlmCacheHandler } from "./subcommands-rlm.js";
18
+ export { storageHandler, rlmToolsHandler, chunkHandler, fanoutHandler, rlmPrepHandler, rlmSearchHandler, rlmStatusCliHandler, rlmCacheHandler };
19
+ import { mcpHandler, catalogHandler } from "./subcommands-services.js";
20
+ export { mcpHandler, catalogHandler };
1979
21
  export const subcommandHandlers = [
1980
22
  mcpHandler,
1981
23
  catalogHandler,