@aiwg/cli 2026.10.15 → 2026.10.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (286) hide show
  1. package/agentic/code/providers/pi/aiwg-bridge.ts +45 -7
  2. package/dist/src/artifacts/citation-parser.js +7 -6
  3. package/dist/src/artifacts/corpus-tools/citation-densify.js +4 -2
  4. package/dist/src/artifacts/corpus-tools/cli.js +8 -3
  5. package/dist/src/artifacts/corpus-tools/discovery-log.js +26 -24
  6. package/dist/src/artifacts/corpus-tools/expand-cli.js +3 -2
  7. package/dist/src/artifacts/corpus-tools/expand-dates.js +107 -0
  8. package/dist/src/artifacts/corpus-tools/expand-queue.js +4 -1
  9. package/dist/src/artifacts/corpus-tools/expand-review.js +104 -0
  10. package/dist/src/artifacts/corpus-tools/expand-state.js +17 -1
  11. package/dist/src/artifacts/corpus-tools/expand.js +16 -17
  12. package/dist/src/artifacts/corpus-tools/induction-audit.js +7 -6
  13. package/dist/src/artifacts/corpus-tools/integrity-scan.js +3 -3
  14. package/dist/src/artifacts/corpus-tools/radar-shared.js +7 -9
  15. package/dist/src/artifacts/corpus-tools/ref-files.js +11 -0
  16. package/dist/src/artifacts/corpus-tools/resolve-cli.js +11 -3
  17. package/dist/src/artifacts/corpus-tools/resolve.js +42 -11
  18. package/dist/src/artifacts/corpus-tools/retrieval-lab.js +2 -1
  19. package/dist/src/artifacts/corpus-tools/sidecar-lint.js +4 -4
  20. package/dist/src/artifacts/corpus-tools/sidecar-repair.js +2 -1
  21. package/dist/src/artifacts/corpus-views/ref-parser.js +3 -17
  22. package/dist/src/artifacts/graph-query.js +5 -3
  23. package/dist/src/artifacts/hybrid-query.js +11 -2
  24. package/dist/src/artifacts/index-refresh.js +2 -0
  25. package/dist/src/artifacts/query-engine-corpus.js +217 -0
  26. package/dist/src/artifacts/query-engine-discover-output.js +229 -0
  27. package/dist/src/artifacts/query-engine-discover.js +285 -0
  28. package/dist/src/artifacts/query-engine-entries.js +188 -0
  29. package/dist/src/artifacts/query-engine-index.js +249 -0
  30. package/dist/src/artifacts/query-engine-matching.js +143 -0
  31. package/dist/src/artifacts/query-engine-options.js +2 -0
  32. package/dist/src/artifacts/query-engine-rules.js +202 -0
  33. package/dist/src/artifacts/query-engine-scoring.js +436 -0
  34. package/dist/src/artifacts/query-engine-show-card.js +194 -0
  35. package/dist/src/artifacts/query-engine-show-load.js +211 -0
  36. package/dist/src/artifacts/query-engine-show.js +300 -0
  37. package/dist/src/artifacts/query-engine.js +7 -2576
  38. package/dist/src/cli/handlers/daemon.js +17 -1
  39. package/dist/src/cli/handlers/doctor-args.js +10 -5
  40. package/dist/src/cli/handlers/doctor-help.js +4 -1
  41. package/dist/src/cli/handlers/index.js +2 -2
  42. package/dist/src/cli/handlers/mc-agents.js +111 -0
  43. package/dist/src/cli/handlers/mc-args.js +54 -0
  44. package/dist/src/cli/handlers/mc-control.js +227 -0
  45. package/dist/src/cli/handlers/mc-dispatch.js +203 -0
  46. package/dist/src/cli/handlers/mc-help.js +171 -0
  47. package/dist/src/cli/handlers/mc-run.js +343 -0
  48. package/dist/src/cli/handlers/mc-session.js +138 -0
  49. package/dist/src/cli/handlers/mc-status.js +258 -0
  50. package/dist/src/cli/handlers/mc-summary.js +43 -0
  51. package/dist/src/cli/handlers/mc-types.js +3 -0
  52. package/dist/src/cli/handlers/mc-worker.js +205 -0
  53. package/dist/src/cli/handlers/mc.js +12 -1665
  54. package/dist/src/cli/handlers/models-refusal.js +13 -0
  55. package/dist/src/cli/handlers/models-resource-sample.js +10 -0
  56. package/dist/src/cli/handlers/models.js +5 -3
  57. package/dist/src/cli/handlers/regenerate.js +8 -16
  58. package/dist/src/cli/handlers/remove-bundled.js +133 -0
  59. package/dist/src/cli/handlers/remove-options.js +31 -0
  60. package/dist/src/cli/handlers/remove-user.js +174 -0
  61. package/dist/src/cli/handlers/remove.js +201 -0
  62. package/dist/src/cli/handlers/sessions.js +7 -7
  63. package/dist/src/cli/handlers/subcommands-bundles.js +257 -0
  64. package/dist/src/cli/handlers/subcommands-discovery.js +165 -0
  65. package/dist/src/cli/handlers/subcommands-list-format.js +129 -0
  66. package/dist/src/cli/handlers/subcommands-list.js +250 -0
  67. package/dist/src/cli/handlers/subcommands-plugins.js +213 -0
  68. package/dist/src/cli/handlers/subcommands-quickref.js +58 -0
  69. package/dist/src/cli/handlers/subcommands-rlm.js +113 -0
  70. package/dist/src/cli/handlers/subcommands-services.js +66 -0
  71. package/dist/src/cli/handlers/subcommands-storage.js +259 -0
  72. package/dist/src/cli/handlers/subcommands.js +18 -1976
  73. package/dist/src/cli/handlers/update.js +157 -0
  74. package/dist/src/cli/handlers/use.js +14 -4
  75. package/dist/src/cli/handlers/utilities.js +3 -560
  76. package/dist/src/cli/handlers/utility-doctor.js +412 -0
  77. package/dist/src/cli/scope-resolver.js +1 -142
  78. package/dist/src/cli/services/deployment-verification.js +0 -1
  79. package/dist/src/cli/user-scope-mirror.js +173 -0
  80. package/dist/src/config/aiwg-config.js +2 -1
  81. package/dist/src/config/authorization-cli.js +7 -3
  82. package/dist/src/config/dispatch-host-thresholds.js +2 -0
  83. package/dist/src/config/dispatch-thresholds-runtime.d.mts +3 -2
  84. package/dist/src/config/dispatch-thresholds-runtime.mjs +21 -7
  85. package/dist/src/config/framework-aliases.js +12 -0
  86. package/dist/src/config/host-resource-report.d.mts +24 -0
  87. package/dist/src/config/host-resource-report.mjs +110 -0
  88. package/dist/src/config/host-resource-runtime.d.mts +37 -0
  89. package/dist/src/config/host-resource-runtime.mjs +296 -0
  90. package/dist/src/config/installed-selection.js +22 -0
  91. package/dist/src/config/worker-invocation-marker.d.mts +1 -0
  92. package/dist/src/config/worker-invocation-marker.mjs +2 -0
  93. package/dist/src/decision/ensemble-study/artifacts.js +7 -0
  94. package/dist/src/decision/ensemble-study/gate-policy.js +58 -0
  95. package/dist/src/decision/ensemble-study/gates.js +78 -0
  96. package/dist/src/decision/ensemble-study/protocol.js +18 -21
  97. package/dist/src/decision/ensemble-study/score.js +3 -2
  98. package/dist/src/decision/ensemble-study/statistics.js +7 -26
  99. package/dist/src/decision/heldout/access.js +74 -0
  100. package/dist/src/decision/heldout/calibration.js +1 -0
  101. package/dist/src/decision/heldout/collector.js +8 -1
  102. package/dist/src/decision/sensitivity/comparative-gates.js +135 -0
  103. package/dist/src/decision/sensitivity/comparative.js +18 -41
  104. package/dist/src/effects/verifiers/file.js +22 -5
  105. package/dist/src/extensions/claude-attribution.js +82 -0
  106. package/dist/src/extensions/claude-hooks-installer.js +133 -69
  107. package/dist/src/extensions/commands/daemon.js +109 -0
  108. package/dist/src/extensions/commands/definitions.js +5 -89
  109. package/dist/src/gates/evaluate.js +2 -358
  110. package/dist/src/gates/heldout.js +17 -7
  111. package/dist/src/gates/observations.js +363 -0
  112. package/dist/src/gates/pack-composition.js +270 -0
  113. package/dist/src/gates/pack-tightening.js +197 -0
  114. package/dist/src/gates/pack-validation.js +262 -0
  115. package/dist/src/gates/registry-error.js +5 -0
  116. package/dist/src/gates/registry.js +13 -685
  117. package/dist/src/lint/check-patterns.js +163 -0
  118. package/dist/src/lint/checks.js +268 -0
  119. package/dist/src/lint/reference-resolution.js +54 -0
  120. package/dist/src/lint/runner.js +3 -465
  121. package/dist/src/mcp/helpers.mjs +11 -1
  122. package/dist/src/mcp/json-document.mjs +29 -0
  123. package/dist/src/mcp/muse-native-config.mjs +1 -28
  124. package/dist/src/memory/project-registry.js +44 -4
  125. package/dist/src/mission-protocol/worker-review-gate.js +7 -0
  126. package/dist/src/models/worker-plan.js +36 -5
  127. package/dist/src/models/wrapper-deployment.js +25 -12
  128. package/dist/src/models/wrapper-enforcement.js +47 -7
  129. package/dist/src/network-analysis/research.js +2 -1
  130. package/dist/src/plugin/command-ownership.js +34 -0
  131. package/dist/src/plugin/skill-command-frontmatter.js +197 -0
  132. package/dist/src/plugin/skill-command-translator.js +6 -232
  133. package/dist/src/policy/hitl-check.js +14 -4
  134. package/dist/src/policy/hitl-consume.js +54 -0
  135. package/dist/src/policy/hitl-receipt.js +2 -0
  136. package/dist/src/policy/hitl.js +11 -3
  137. package/dist/src/providers/context-output-ownership.js +26 -0
  138. package/dist/src/providers/deployment-ownership.d.mts +19 -0
  139. package/dist/src/providers/deployment-ownership.mjs +226 -0
  140. package/dist/src/providers/deployment-removal.js +200 -0
  141. package/dist/src/providers/provider-context-contracts.js +162 -0
  142. package/dist/src/providers/provider-definition-schema.js +136 -0
  143. package/dist/src/providers/provider-definitions.js +8 -1298
  144. package/dist/src/providers/provider-seeds-1.js +360 -0
  145. package/dist/src/providers/provider-seeds-2.js +387 -0
  146. package/dist/src/providers/provider-seeds-3.js +262 -0
  147. package/dist/src/providers/removal-transaction.js +86 -0
  148. package/dist/src/providers/settings-document.d.mts +3 -0
  149. package/dist/src/providers/settings-document.mjs +47 -0
  150. package/dist/src/providers/settings-removal.js +190 -0
  151. package/dist/src/providers/skill-ownership.d.mts +19 -2
  152. package/dist/src/providers/skill-ownership.mjs +12 -4
  153. package/dist/src/providers/transformation-receipt-integration.js +15 -271
  154. package/dist/src/providers/transformation-receipt-outputs.js +99 -0
  155. package/dist/src/providers/transformation-receipt-source.js +194 -0
  156. package/dist/src/research/clients/arxiv.js +4 -30
  157. package/dist/src/research/clients/base.js +48 -22
  158. package/dist/src/research/identity.js +42 -4
  159. package/dist/src/research/query-cli.js +3 -87
  160. package/dist/src/research/query-options.js +87 -0
  161. package/dist/src/research/reference-match.js +105 -24
  162. package/dist/src/research/services/acquisition.js +9 -7
  163. package/dist/src/research/services/citation.js +5 -2
  164. package/dist/src/research/types.js +2 -0
  165. package/dist/src/rules/activation.mjs +15 -6
  166. package/dist/src/rules/core-startup.mjs +2 -2
  167. package/dist/src/serve/mission-conductor.js +52 -4
  168. package/dist/src/serve/mission-summary.js +56 -0
  169. package/dist/src/sessions/adapters/grok-build-native.js +23 -0
  170. package/dist/src/sessions/adapters/grok-build.js +14 -7
  171. package/dist/src/sessions/workspace-discovery.js +5 -5
  172. package/dist/src/smiths/context-pipeline/aiwg-md.js +39 -46
  173. package/dist/src/smiths/context-pipeline/claude-hook.js +1 -1
  174. package/dist/src/smiths/context-pipeline/code-regions.js +28 -0
  175. package/dist/src/smiths/context-pipeline/context-file-safety.js +3 -0
  176. package/dist/src/smiths/context-pipeline/finalization.js +81 -51
  177. package/dist/src/smiths/context-pipeline/generator.js +10 -11
  178. package/dist/src/smiths/context-pipeline/managed-hook.js +1 -1
  179. package/dist/src/smiths/context-pipeline/muse-bridge.js +2 -2
  180. package/dist/src/smiths/context-pipeline/provider-policy.js +6 -12
  181. package/dist/src/smiths/context-pipeline/workspace-audit.js +299 -0
  182. package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +148 -0
  183. package/dist/src/smiths/context-pipeline/workspace-context-shared.js +111 -0
  184. package/dist/src/smiths/context-pipeline/workspace-context.js +8 -1373
  185. package/dist/src/smiths/context-pipeline/workspace-doctor.js +192 -0
  186. package/dist/src/smiths/context-pipeline/workspace-document.js +201 -0
  187. package/dist/src/smiths/context-pipeline/workspace-extraction.js +205 -0
  188. package/dist/src/smiths/context-pipeline/workspace-migration.js +250 -0
  189. package/dist/src/smiths/hook-bridge/index.js +9 -0
  190. package/package.json +13 -1
  191. package/schemas/decision/D17StudyProtocol.v1.schema.json +39 -67
  192. package/schemas/decision/D29Study.v10.schema.json +65 -0
  193. package/tools/agents/deploy-agents.mjs +24 -675
  194. package/tools/agents/deploy-command-mirrors.mjs +229 -0
  195. package/tools/agents/deploy-options.mjs +258 -0
  196. package/tools/agents/deploy-support.mjs +165 -0
  197. package/tools/agents/providers/base-addon-discovery.mjs +139 -0
  198. package/tools/agents/providers/base-behaviors.mjs +168 -0
  199. package/tools/agents/providers/base-context.mjs +205 -0
  200. package/tools/agents/providers/base-contract.mjs +116 -0
  201. package/tools/agents/providers/base-files.mjs +252 -0
  202. package/tools/agents/providers/base-flat-artifacts.mjs +233 -0
  203. package/tools/agents/providers/base-framework-discovery.mjs +309 -0
  204. package/tools/agents/providers/base-frontmatter.mjs +196 -0
  205. package/tools/agents/providers/base-inventory.mjs +269 -0
  206. package/tools/agents/providers/base-kernel-skills.mjs +354 -0
  207. package/tools/agents/providers/base-migrations.mjs +258 -0
  208. package/tools/agents/providers/base-models-platforms.mjs +273 -0
  209. package/tools/agents/providers/base-rule-index.mjs +450 -0
  210. package/tools/agents/providers/base-runtime.mjs +60 -0
  211. package/tools/agents/providers/base-skill-copy.mjs +273 -0
  212. package/tools/agents/providers/base.mjs +16 -3364
  213. package/tools/agents/providers/claude-post-deploy.mjs +20 -1
  214. package/tools/agents/providers/context-write.mjs +4 -0
  215. package/tools/agents/providers/hermes-startup.mjs +0 -5
  216. package/tools/agents/providers/muse.mjs +7 -2
  217. package/tools/agents/providers/pi.mjs +3 -1
  218. package/tools/agents/providers/rule-delivery-surface.mjs +359 -0
  219. package/tools/agents/providers/rule-delivery.mjs +20 -1144
  220. package/tools/agents/providers/rule-deployment-commit.mjs +148 -0
  221. package/tools/agents/providers/rule-deployment-prepare.mjs +461 -0
  222. package/tools/agents/providers/rule-deployment-state.mjs +300 -0
  223. package/tools/agents/providers/rule-projection.mjs +3 -0
  224. package/tools/daemon/README.md +511 -0
  225. package/tools/daemon/adapters/base-adapter.mjs +84 -0
  226. package/tools/daemon/adapters/webhook-adapter.mjs +107 -0
  227. package/tools/daemon/agent-supervisor.mjs +299 -0
  228. package/tools/daemon/automation-engine.mjs +310 -0
  229. package/tools/daemon/autonomous-engine.mjs +346 -0
  230. package/tools/daemon/behavior-loader.mjs +316 -0
  231. package/tools/daemon/behavior.mjs +174 -0
  232. package/tools/daemon/concierge/intent-router.mjs +401 -0
  233. package/tools/daemon/concierge/orchestrator.mjs +272 -0
  234. package/tools/daemon/concierge/response-translator.mjs +462 -0
  235. package/tools/daemon/config.mjs +377 -0
  236. package/tools/daemon/cron-scheduler.mjs +178 -0
  237. package/tools/daemon/daemon-main.mjs +1169 -0
  238. package/tools/daemon/event-router.mjs +84 -0
  239. package/tools/daemon/file-watcher.mjs +383 -0
  240. package/tools/daemon/index.mjs +1181 -0
  241. package/tools/daemon/init-profile.mjs +124 -0
  242. package/tools/daemon/ipc-client.mjs +197 -0
  243. package/tools/daemon/ipc-ops-handlers.mjs +236 -0
  244. package/tools/daemon/ipc-server.mjs +275 -0
  245. package/tools/daemon/maintenance-owner.mjs +79 -0
  246. package/tools/daemon/memory-manager.mjs +386 -0
  247. package/tools/daemon/message-router.mjs +194 -0
  248. package/tools/daemon/provider-watcher.mjs +585 -0
  249. package/tools/daemon/pty-adapter.mjs +420 -0
  250. package/tools/daemon/repl-chat.mjs +359 -0
  251. package/tools/daemon/resource-bounds.mjs +88 -0
  252. package/tools/daemon/sandbox-transport.mjs +295 -0
  253. package/tools/daemon/scheduled-task-runner.mjs +535 -0
  254. package/tools/daemon/task-store.mjs +450 -0
  255. package/tools/daemon/tmux-manager.mjs +324 -0
  256. package/tools/daemon/update-policy.mjs +517 -0
  257. package/tools/daemon/web-server.mjs +399 -0
  258. package/tools/daemon/web-ui/index.html +585 -0
  259. package/tools/daemon/web-ui/styles.css +156 -0
  260. package/tools/docker/Dockerfile.daemon +35 -0
  261. package/tools/docker/container-manager.mjs +291 -0
  262. package/tools/messaging/adapter-registry.mjs +230 -0
  263. package/tools/messaging/adapters/base.mjs +326 -0
  264. package/tools/messaging/adapters/discord.mjs +462 -0
  265. package/tools/messaging/adapters/slack.mjs +402 -0
  266. package/tools/messaging/adapters/telegram.mjs +552 -0
  267. package/tools/messaging/chat-handler.mjs +297 -0
  268. package/tools/messaging/command-router.mjs +269 -0
  269. package/tools/messaging/event-bus.mjs +199 -0
  270. package/tools/messaging/index.mjs +456 -0
  271. package/tools/messaging/message-formatter.mjs +320 -0
  272. package/tools/messaging/room-manager.mjs +277 -0
  273. package/tools/messaging/types.mjs +94 -0
  274. package/tools/providers/pi-bridge-policy.mjs +4 -0
  275. package/tools/ralph-external/daemon-supervisor.mjs +394 -0
  276. package/tools/ralph-external/lib/behavior-registry.mjs +270 -0
  277. package/tools/ralph-external/lib/worker-invocation-processes.mjs +7 -4
  278. package/tools/ralph-external/lib/worker-isolation-args.mjs +217 -0
  279. package/tools/ralph-external/lib/worker-isolation-status.mjs +19 -0
  280. package/tools/ralph-external/lib/worker-isolation.mjs +11 -237
  281. package/tools/ralph-external/lib/worker-overflow.mjs +10 -2
  282. package/tools/ralph-external/lib/worker-termination.mjs +15 -8
  283. package/tools/ralph-external/lib/worker-unit-cleanup.mjs +72 -0
  284. package/tools/ralph-external/session-launcher.mjs +7 -7
  285. package/tools/scripts/resource-preflight.mjs +3 -242
  286. package/vscode-extension/schemas/aiwg.config.v1.json +2 -4
@@ -0,0 +1,343 @@
1
+ import * as ui from '../ui.js';
2
+ import { promises as fs } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { assertMissionWorkerHandoff } from '../../mission-protocol/codecs.js';
5
+ import { createMcAdmissionScheduler } from './mc-admission.js';
6
+ import { SESSIONS_DIR, writeSession, appendLog, findActiveSession } from './mc-session.js';
7
+ import { hasFlag, getPositionalArgs } from './mc-args.js';
8
+ import { readAdmissionConfig, mcWorkerSupport, workerDispatch, resolveMcWorker } from './mc-worker.js';
9
+ import { managedControlFailure, cancelManagedMission } from './mc-control.js';
10
+ /**
11
+ * Drain queued missions in a session by launching each as a ralph loop (#1439).
12
+ *
13
+ * Before this command existed, missions sat in `queued` status forever because
14
+ * no supervisor process drained the queue. `mc run` is the explicit supervisor
15
+ * step: for every queued direct-mode mission, spawn a detached ralph process
16
+ * via launchExternalRalph(), record the resulting loopId + pid on the mission,
17
+ * and flip the mission to `running`.
18
+ *
19
+ * Status sync back from ralph to mc happens lazily via syncMissionsFromRalph()
20
+ * called from `mc status` and `mc watch` — no separate daemon needed.
21
+ *
22
+ * Limitations of cycle 1:
23
+ * - pty-orchestrator missions are skipped with a warning (separate codepath)
24
+ * - missions launch sequentially (each call to launchExternalRalph spawns a
25
+ * detached process, so they DO run in parallel after launch — the loop here
26
+ * is just for orderly dispatch, not for parallel scheduling)
27
+ */
28
+ /**
29
+ * Per-iteration cache-creation floor for a headless claude session (sonnet
30
+ * baseline; opus is ~$3.90).
31
+ */
32
+ export const SONNET_CACHE_USD = 1.60;
33
+ /** Estimate at or above which `mc run` warns and refuses in non-TTY contexts. */
34
+ export const COST_WARNING_THRESHOLD_USD = 5.0;
35
+ /**
36
+ * Providers whose headless stream reports spend, so a declared `--max-total-cost`
37
+ * ceiling can actually fire mid-loop.
38
+ *
39
+ * Only `claude` emits cost on its stream-json events, which is what
40
+ * `SessionLauncher._extractUsageStats` reads. Adapters without stream-json
41
+ * (codex, factory, opencode, deepseek) emit no usage events at all — #1766
42
+ * recorded that a spend ceiling on those is inert and never fires. Adapters that
43
+ * do stream JSON but have not been observed carrying cost fields (omp, pi) stay
44
+ * out of this set deliberately: assuming an observability we have not seen would
45
+ * weaken the gate in exactly the case where the operator has least protection.
46
+ */
47
+ export const COST_REPORTING_PROVIDERS = new Set(['claude']);
48
+ /**
49
+ * Estimate cumulative spend for a set of queued missions (#2522).
50
+ *
51
+ * The floor for each mission is `maxIterations × SONNET_CACHE_USD`. A declared
52
+ * `maxTotalCost` bounds that floor **only** when the target provider reports
53
+ * spend — on a provider that reports none, the ceiling is inert (#1766), so
54
+ * subtracting it would make the warning weaker precisely where the operator has
55
+ * no enforced protection. Those ceilings are counted and surfaced instead.
56
+ */
57
+ export function estimateMissionRunCost(missions, provider) {
58
+ const spendObservable = COST_REPORTING_PROVIDERS.has(provider);
59
+ let estimateUsd = 0;
60
+ let iterationFloorUsd = 0;
61
+ let declaredCeilingUsd = 0;
62
+ let cappedMissions = 0;
63
+ let inertCeilingMissions = 0;
64
+ for (const mission of missions) {
65
+ const floor = mission.maxIterations * SONNET_CACHE_USD;
66
+ iterationFloorUsd += floor;
67
+ const ceiling = typeof mission.maxTotalCost === 'number' && Number.isFinite(mission.maxTotalCost)
68
+ ? mission.maxTotalCost
69
+ : undefined;
70
+ if (ceiling === undefined) {
71
+ estimateUsd += floor;
72
+ continue;
73
+ }
74
+ declaredCeilingUsd += ceiling;
75
+ if (spendObservable) {
76
+ cappedMissions += 1;
77
+ estimateUsd += Math.min(floor, ceiling);
78
+ }
79
+ else {
80
+ inertCeilingMissions += 1;
81
+ estimateUsd += floor;
82
+ }
83
+ }
84
+ return {
85
+ estimateUsd,
86
+ iterationFloorUsd,
87
+ declaredCeilingUsd,
88
+ cappedMissions,
89
+ inertCeilingMissions,
90
+ spendObservable,
91
+ };
92
+ }
93
+ export async function mcRun(ctx) {
94
+ const positional = getPositionalArgs(ctx.args);
95
+ const sessionId = positional[0];
96
+ const acceptCost = hasFlag(ctx.args, '--accept-cost');
97
+ const session = await findActiveSession(sessionId);
98
+ if (!session) {
99
+ ui.error(sessionId ? `Session not found: ${sessionId}` : 'No active session. Run `aiwg mc start` first.');
100
+ return { exitCode: 1 };
101
+ }
102
+ const queued = session.missions.filter((m) => m.status === 'queued');
103
+ let cfg;
104
+ try {
105
+ cfg = await readAdmissionConfig(ctx.cwd || process.cwd());
106
+ const support = cfg?.parallelism?.worker_dispatch && cfg.parallelism.worker_mode === 'managed' ? mcWorkerSupport() : undefined;
107
+ assertMissionWorkerHandoff(session, 'mc-cli', support);
108
+ for (const mission of queued)
109
+ assertMissionWorkerHandoff(mission, 'mc-cli', support);
110
+ }
111
+ catch (error) {
112
+ const message = error instanceof Error ? error.message : String(error);
113
+ ui.error(message);
114
+ return { exitCode: 1, message };
115
+ }
116
+ if (queued.length === 0) {
117
+ ui.info(`No queued missions in session ${session.id}. Run \`aiwg mc dispatch ${session.id} "<objective>"\` to add one.`);
118
+ return { exitCode: 0 };
119
+ }
120
+ // #1450 P0: cost warning gate, with declared ceilings honored (#2522).
121
+ //
122
+ // Each headless claude session pays a ~$1.60 cache-creation cost on iteration
123
+ // 1 before any user-meaningful work (sonnet baseline; opus is ~$3.90). Across
124
+ // N missions × M iterations the floor compounds quickly. Warn before launch
125
+ // and refuse in non-TTY contexts unless --accept-cost is set.
126
+ const eligible = queued.filter(m => m.mode !== 'pty-orchestrator' && !!m.completion);
127
+ const projectRoot = ctx.cwd || process.cwd();
128
+ const frameworkRoot = ctx.frameworkRoot;
129
+ let scheduler;
130
+ try {
131
+ scheduler = await createMcAdmissionScheduler(projectRoot, cfg);
132
+ }
133
+ catch (error) {
134
+ const message = error instanceof Error ? error.message : String(error);
135
+ ui.error(message);
136
+ return { exitCode: 1, message };
137
+ }
138
+ const provider = cfg?.providers[0] ?? 'unknown';
139
+ const estimate = estimateMissionRunCost(eligible, provider);
140
+ if (estimate.estimateUsd >= COST_WARNING_THRESHOLD_USD && !acceptCost) {
141
+ ui.blank();
142
+ ui.warn(`Cost estimate: ~$${estimate.estimateUsd.toFixed(2)} (${eligible.length} missions × iteration floors × ~$${SONNET_CACHE_USD.toFixed(2)} cache cost per claude headless iter).`);
143
+ if (estimate.cappedMissions > 0) {
144
+ ui.warn(`Declared ceilings: $${estimate.declaredCeilingUsd.toFixed(2)} across ${estimate.cappedMissions} mission(s) — counted toward the estimate because ${provider} reports spend.`);
145
+ }
146
+ if (estimate.inertCeilingMissions > 0) {
147
+ ui.warn(`${estimate.inertCeilingMissions} mission(s) declare --max-total-cost totalling $${estimate.declaredCeilingUsd.toFixed(2)}, but ${provider} does not report spend — those ceilings cannot fire and are NOT subtracted from this estimate (#1766).`);
148
+ }
149
+ ui.warn('Actual spend may be lower if missions complete early, higher if model is opus or context grows.');
150
+ if (!process.stdout.isTTY) {
151
+ ui.error('Refusing to launch in non-interactive context. Re-run with `--accept-cost` to proceed.');
152
+ return { exitCode: 1 };
153
+ }
154
+ // TTY path: surface the warning and continue. A future revision should
155
+ // prompt y/N here; for now the warning is informational and the operator
156
+ // can Ctrl+C before launches actually begin.
157
+ ui.info('Continuing (TTY). Use Ctrl+C to abort within the next 2 seconds.');
158
+ await new Promise((resolve) => setTimeout(resolve, 2000));
159
+ }
160
+ ui.blank();
161
+ console.log(` ${ui.brandMark()} ${ui.bold('Mission Control')} — running ${queued.length} queued mission(s) in ${ui.accent(session.id)}`);
162
+ ui.rule();
163
+ // Lazy import — ralph-launcher pulls in node:child_process and other heavy
164
+ // deps we don't want to pay for on every mc subcommand.
165
+ const { launchExternalRalph } = await import('./ralph-launcher.js');
166
+ let launched = 0;
167
+ let skipped = 0;
168
+ let failed = 0;
169
+ const managed = cfg?.parallelism?.worker_dispatch && cfg.parallelism.worker_mode === 'managed';
170
+ const allowanceOwner = managed ? await import('../../serve/shared-host-scheduler.js') : null;
171
+ // Qualify every worker before admission; one parent retains completion gates.
172
+ const workers = new Map();
173
+ try {
174
+ for (const mission of queued)
175
+ if (workerDispatch(mission))
176
+ workers.set(mission.id, await resolveMcWorker(ctx, session, mission));
177
+ }
178
+ catch (error) {
179
+ return managedControlFailure(error);
180
+ }
181
+ for (const mission of queued) {
182
+ const worker = workers.get(mission.id);
183
+ if (mission.mode === 'pty-orchestrator') {
184
+ ui.warn(`Mission ${mission.id} mode=pty-orchestrator is not yet wired to mc run; skipping. Use 'aiwg ralph' directly for PTY-orchestrator workflows.`);
185
+ skipped += 1;
186
+ continue;
187
+ }
188
+ if (!mission.completion) {
189
+ ui.warn(`Mission ${mission.id} has no --completion criteria; ralph requires one. Skipping. Re-dispatch with --completion "<criteria>" to include this mission.`);
190
+ skipped += 1;
191
+ continue;
192
+ }
193
+ const admissionRequestId = mission.admissionState === 'released'
194
+ ? `${session.id}.${mission.id}.${Date.now().toString(36)}`
195
+ : mission.admissionRequestId ?? worker?.dispatch.requestId ?? `${session.id}.${mission.id}`;
196
+ const admissionSubmittedAt = mission.admissionState === 'released'
197
+ ? new Date().toISOString()
198
+ : mission.admissionSubmittedAt ?? new Date().toISOString();
199
+ const admission = scheduler.submit({
200
+ requestId: admissionRequestId,
201
+ orchestratorId: session.id,
202
+ environment: process.env.AIWG_ENVIRONMENT ?? 'default',
203
+ provider: worker?.plan.invocation?.selected.inferenceProvider ?? provider,
204
+ runtimeKind: 'host',
205
+ priority: mission.priority === 'critical' ? 100 : mission.priority === 'high' ? 50 : mission.priority === 'low' ? 0 : 10,
206
+ submittedAt: admissionSubmittedAt,
207
+ queueTimeoutMs: managed ? (cfg?.parallelism?.admission?.queueTimeoutSeconds ?? 300) * 1000 : 24 * 60 * 60_000,
208
+ preemptible: false,
209
+ metadata: { missionId: mission.id, ...(worker ? { invocationId: worker.dispatch.invocationId } : {}) },
210
+ ...(managed ? { managed: worker ? { kind: 'external', group: worker.plan.selected.group,
211
+ member: worker.plan.selected.member, cli: worker.plan.selected.cli, model: worker.plan.selected.modelKey,
212
+ quotaScope: cfg.parallelism.clis[worker.plan.selected.cli].quotaScope } : { kind: 'native' },
213
+ allowance: worker ? { runId: session.id, taskId: worker.intent.taskId,
214
+ taskBudgets: { maxAttempts: Math.min(worker.intent.limits.maxAttempts, mission.maxIterations),
215
+ maxTokens: Math.min(worker.intent.limits.tokens, mission.maxTotalTokens ?? Infinity),
216
+ maxCostUsd: worker.intent.limits.costUsd === null ? mission.maxTotalCost
217
+ : Math.min(worker.intent.limits.costUsd, mission.maxTotalCost ?? Infinity),
218
+ timeoutSeconds: Math.min(worker.intent.limits.wallSeconds, (mission.maxWallClockMinutes ?? Infinity) * 60) },
219
+ reservation: { tokens: worker.plan.invocation.limits.tokens, costUsd: worker.plan.invocation.limits.costUsd },
220
+ } : allowanceOwner.managedAllowanceFromOwner(session.id, mission.id, {
221
+ kind: 'ralph', maxIterations: mission.maxIterations, maxTotalTokens: mission.maxTotalTokens,
222
+ maxTotalCost: mission.maxTotalCost, maxWallClockMinutes: mission.maxWallClockMinutes,
223
+ }),
224
+ } : {}),
225
+ });
226
+ mission.admissionRequestId = admissionRequestId;
227
+ mission.admissionSubmittedAt = admissionSubmittedAt;
228
+ mission.admissionState = admission.state;
229
+ mission.admissionLeaseExpiresAt = admission.leaseExpiresAt;
230
+ if (managed)
231
+ mission.admissionGeneration = admission.leaseGeneration;
232
+ await writeSession(session);
233
+ if (admission.state !== 'admitted') {
234
+ await appendLog(session.id, {
235
+ event: 'mission_admission_queued',
236
+ missionId: mission.id,
237
+ admissionRequestId,
238
+ reason: admission.reason,
239
+ });
240
+ ui.info(`Queued ${mission.id}: ${admission.reason}`);
241
+ skipped += 1;
242
+ continue;
243
+ }
244
+ try {
245
+ let maxWallClockMinutes = mission.maxWallClockMinutes;
246
+ if (managed) {
247
+ const scopes = scheduler.snapshot().allowances;
248
+ const deadlines = [scopes[admission.accounting.runKey].deadlineAt, scopes[admission.accounting.taskKey].deadlineAt]
249
+ .filter((value) => value !== undefined).map(Date.parse);
250
+ const remainingMs = Math.min(...deadlines) - Date.now();
251
+ if (remainingMs <= 0)
252
+ throw new Error('cumulative allowance deadline elapsed before launch');
253
+ maxWallClockMinutes = deadlines.length ? remainingMs / 60_000 : undefined;
254
+ }
255
+ if (worker) {
256
+ if (worker.brief.lease.generation !== mission.admissionGeneration || worker.brief.lease.reservationId !== admissionRequestId
257
+ || worker.brief.lease.authorityRef !== 'project')
258
+ throw new Error('Managed brief lease differs from current admission');
259
+ const invocationPath = join(projectRoot, SESSIONS_DIR, session.id, `${mission.id}.invocation.json`);
260
+ const runDir = join(projectRoot, SESSIONS_DIR, session.id, `${mission.id}.run`);
261
+ await fs.writeFile(invocationPath, JSON.stringify(worker.plan), { mode: 0o600 });
262
+ mission.managedWorker = { invocationPath, runDir };
263
+ }
264
+ if (managed) {
265
+ scheduler.claimLaunch(admissionRequestId, mission.admissionGeneration);
266
+ mission.admissionLaunchClaimed = true;
267
+ await writeSession(session);
268
+ }
269
+ const result = await launchExternalRalph(frameworkRoot, projectRoot, {
270
+ objective: mission.objective,
271
+ completionCriteria: mission.completion,
272
+ maxIterations: managed ? admission.accounting.attemptCount : mission.maxIterations,
273
+ maxTotalTokens: managed ? admission.accounting.reservation.tokens ?? undefined : mission.maxTotalTokens,
274
+ maxOutputTokens: mission.maxOutputTokens,
275
+ maxToolCalls: mission.maxToolCalls,
276
+ maxTotalCost: managed ? admission.accounting.reservation.costUsd ?? undefined : mission.maxTotalCost,
277
+ maxWallClockMinutes,
278
+ explorationQuota: mission.explorationQuota,
279
+ budgetStopPolicy: mission.budgetStopPolicy,
280
+ // Defaults for cycle 1; advanced options can be added per-mission later.
281
+ verbose: false,
282
+ ...(managed ? { managedAdmission: { requestId: admissionRequestId, generation: mission.admissionGeneration } } : {}),
283
+ ...(worker ? { managedWorker: mission.managedWorker } : {}),
284
+ });
285
+ if (managed) {
286
+ if (!result.execution || result.execution.pid !== result.pid)
287
+ throw new Error('managed launch requires its OS process birth identity');
288
+ scheduler.bindExecution(admissionRequestId, mission.admissionGeneration, result.execution);
289
+ mission.admissionExecution = result.execution;
290
+ mission.ralphLoopId = result.loopId;
291
+ mission.ralphPid = result.pid;
292
+ const current = scheduler.renew(admissionRequestId, mission.admissionGeneration);
293
+ if (current.state !== 'admitted') {
294
+ await cancelManagedMission(ctx, scheduler, mission);
295
+ throw new Error('managed launch lost admission during execution checkpoint; reconcile uncertain work');
296
+ }
297
+ }
298
+ mission.status = 'running';
299
+ if (worker)
300
+ worker.dispatch.state = 'running';
301
+ mission.startedAt = new Date().toISOString();
302
+ mission.ralphLoopId = result.loopId;
303
+ mission.ralphPid = result.pid;
304
+ await writeSession(session);
305
+ await appendLog(session.id, {
306
+ event: 'mission_started',
307
+ missionId: mission.id,
308
+ loopId: result.loopId,
309
+ pid: result.pid,
310
+ });
311
+ ui.success(`Started ${mission.id} → ralph loop ${result.loopId} (PID ${result.pid})`);
312
+ launched += 1;
313
+ }
314
+ catch (err) {
315
+ const msg = err instanceof Error ? err.message : String(err);
316
+ mission.status = 'failed';
317
+ mission.error = msg;
318
+ mission.completedAt = new Date().toISOString();
319
+ if (managed)
320
+ mission.admissionState = scheduler.stop(admissionRequestId, mission.admissionGeneration, 'observer-loss').state;
321
+ else {
322
+ scheduler.release(admissionRequestId);
323
+ mission.admissionState = 'released';
324
+ }
325
+ mission.admissionLeaseExpiresAt = undefined;
326
+ await writeSession(session);
327
+ await appendLog(session.id, {
328
+ event: 'mission_launch_failed',
329
+ missionId: mission.id,
330
+ error: msg,
331
+ });
332
+ ui.error(`Failed to start ${mission.id}: ${msg}`);
333
+ failed += 1;
334
+ }
335
+ }
336
+ ui.blank();
337
+ ui.info(`Launched: ${launched} | Skipped: ${skipped} | Failed: ${failed}`);
338
+ if (launched > 0) {
339
+ ui.info(`Monitor: \`aiwg mc status ${session.id}\` or \`aiwg mc watch ${session.id}\``);
340
+ }
341
+ return { exitCode: failed > 0 && launched === 0 ? 1 : 0 };
342
+ }
343
+ //# sourceMappingURL=mc-run.js.map
@@ -0,0 +1,138 @@
1
+ import * as ui from '../ui.js';
2
+ import { promises as fs } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { randomBytes } from 'node:crypto';
5
+ import { parseFlag } from './mc-args.js';
6
+ // ── Constants ────────────────────────────────────────────────
7
+ export const MC_ROOT = '.aiwg/ralph-external/mc';
8
+ export const SESSIONS_DIR = join(MC_ROOT, 'sessions');
9
+ export const CONTROL_ID_RE = /^[a-zA-Z0-9._-]+$/;
10
+ // ── Helpers ──────────────────────────────────────────────────
11
+ export function genId(prefix) {
12
+ return `${prefix}-${Date.now().toString(36)}-${randomBytes(3).toString('hex')}`;
13
+ }
14
+ export async function ensureDir(dir) {
15
+ await fs.mkdir(dir, { recursive: true });
16
+ }
17
+ export async function readSession(sessionId) {
18
+ if (!CONTROL_ID_RE.test(sessionId))
19
+ return null;
20
+ const path = join(SESSIONS_DIR, sessionId, 'session.json');
21
+ try {
22
+ const raw = await fs.readFile(path, 'utf-8');
23
+ return JSON.parse(raw);
24
+ }
25
+ catch {
26
+ return null;
27
+ }
28
+ }
29
+ export async function writeSession(session, { touch = true } = {}) {
30
+ const dir = join(SESSIONS_DIR, session.id);
31
+ await ensureDir(dir);
32
+ if (touch)
33
+ session.updatedAt = new Date().toISOString();
34
+ const destination = join(dir, 'session.json');
35
+ const temporary = join(dir, `.session.${process.pid}.${randomBytes(4).toString('hex')}.tmp`);
36
+ await fs.writeFile(temporary, JSON.stringify(session, null, 2));
37
+ await fs.rename(temporary, destination);
38
+ }
39
+ export async function appendLog(sessionId, event) {
40
+ const logPath = join(SESSIONS_DIR, sessionId, 'log.jsonl');
41
+ const entry = JSON.stringify({ ...event, ts: new Date().toISOString() });
42
+ await fs.appendFile(logPath, entry + '\n');
43
+ }
44
+ /**
45
+ * Apply one durable Mission Control mutation under a cross-process lock.
46
+ * `expectedUpdatedAt` provides optimistic concurrency and `requestId` makes
47
+ * retries idempotent across CLI/Cockpit reconnects.
48
+ */
49
+ export async function mutateSession(sessionId, action, target, expectedUpdatedAt, requestId, mutate) {
50
+ if (!CONTROL_ID_RE.test(sessionId) || !CONTROL_ID_RE.test(target)) {
51
+ return { ok: false, code: 'target_not_found', message: 'invalid Mission control identifier' };
52
+ }
53
+ const dir = join(SESSIONS_DIR, sessionId);
54
+ await ensureDir(dir);
55
+ const lockPath = join(dir, '.control.lock');
56
+ let lock;
57
+ try {
58
+ lock = await fs.open(lockPath, 'wx', 0o600);
59
+ }
60
+ catch (error) {
61
+ if (error.code === 'EEXIST') {
62
+ return { ok: false, code: 'mission_conflict', message: 'another Mission control mutation is in progress' };
63
+ }
64
+ throw error;
65
+ }
66
+ try {
67
+ const session = await readSession(sessionId);
68
+ if (!session)
69
+ return { ok: false, code: 'session_not_found', message: `Session not found: ${sessionId}` };
70
+ if (expectedUpdatedAt && session.updatedAt !== expectedUpdatedAt) {
71
+ return { ok: false, code: 'mission_conflict', message: `expected revision ${expectedUpdatedAt}; current revision is ${session.updatedAt}` };
72
+ }
73
+ if (requestId && session.mutationKeys?.[requestId]) {
74
+ const prior = session.mutationKeys[requestId];
75
+ if (prior.action !== action || prior.target !== target) {
76
+ return { ok: false, code: 'mission_conflict', message: `request id '${requestId}' was already used for another mutation` };
77
+ }
78
+ return { ok: true, session, replayed: true };
79
+ }
80
+ const errorCode = mutate(session);
81
+ if (errorCode === 'target_not_found')
82
+ return { ok: false, code: errorCode, message: `Mission not found: ${target}` };
83
+ if (errorCode === 'invalid_state')
84
+ return { ok: false, code: errorCode, message: `Mutation '${action}' is invalid from state '${session.state}'` };
85
+ if (errorCode === 'capacity')
86
+ return { ok: false, code: errorCode, message: `Session at capacity (${session.maxMissions} missions)` };
87
+ const nextUpdatedAt = new Date().toISOString();
88
+ session.updatedAt = nextUpdatedAt;
89
+ if (requestId) {
90
+ session.mutationKeys = { ...(session.mutationKeys ?? {}), [requestId]: { action, target, updatedAt: nextUpdatedAt } };
91
+ }
92
+ await writeSession(session, { touch: false });
93
+ await appendLog(session.id, { event: `control_${action}`, target, requestId: requestId ?? null, replayed: false, revision: session.updatedAt });
94
+ return { ok: true, session, replayed: false };
95
+ }
96
+ finally {
97
+ await lock.close();
98
+ await fs.unlink(lockPath).catch(() => undefined);
99
+ }
100
+ }
101
+ export function mutationFlags(args) {
102
+ return {
103
+ expectedUpdatedAt: parseFlag(args, '--expected-updated-at'),
104
+ requestId: parseFlag(args, '--request-id'),
105
+ };
106
+ }
107
+ export function mutationFailure(result) {
108
+ ui.error(`${result.code}: ${result.message}`);
109
+ return { exitCode: result.code === 'mission_conflict' ? 3 : 1, message: `${result.code}: ${result.message}` };
110
+ }
111
+ export async function listSessions() {
112
+ try {
113
+ const entries = await fs.readdir(SESSIONS_DIR, { withFileTypes: true });
114
+ const sessions = [];
115
+ for (const entry of entries) {
116
+ if (entry.isDirectory()) {
117
+ const s = await readSession(entry.name);
118
+ if (s)
119
+ sessions.push(s);
120
+ }
121
+ }
122
+ return sessions;
123
+ }
124
+ catch {
125
+ return [];
126
+ }
127
+ }
128
+ export async function findActiveSession(sessionIdArg) {
129
+ if (sessionIdArg)
130
+ return readSession(sessionIdArg);
131
+ // Find latest active session
132
+ const sessions = await listSessions();
133
+ const active = sessions
134
+ .filter(s => s.state === 'active' || s.state === 'paused')
135
+ .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
136
+ return active[0] || null;
137
+ }
138
+ //# sourceMappingURL=mc-session.js.map