@aiwg/cli 2026.10.16 → 2026.10.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/dist/src/artifacts/corpus-tools/resolve.js +21 -4
  2. package/dist/src/artifacts/query-engine-corpus.js +217 -0
  3. package/dist/src/artifacts/query-engine-discover-output.js +229 -0
  4. package/dist/src/artifacts/query-engine-discover.js +285 -0
  5. package/dist/src/artifacts/query-engine-entries.js +188 -0
  6. package/dist/src/artifacts/query-engine-index.js +249 -0
  7. package/dist/src/artifacts/query-engine-matching.js +143 -0
  8. package/dist/src/artifacts/query-engine-options.js +2 -0
  9. package/dist/src/artifacts/query-engine-rules.js +202 -0
  10. package/dist/src/artifacts/query-engine-scoring.js +436 -0
  11. package/dist/src/artifacts/query-engine-show-card.js +194 -0
  12. package/dist/src/artifacts/query-engine-show-load.js +211 -0
  13. package/dist/src/artifacts/query-engine-show.js +300 -0
  14. package/dist/src/artifacts/query-engine.js +7 -2576
  15. package/dist/src/cli/handlers/mc-agents.js +111 -0
  16. package/dist/src/cli/handlers/mc-args.js +54 -0
  17. package/dist/src/cli/handlers/mc-control.js +227 -0
  18. package/dist/src/cli/handlers/mc-dispatch.js +203 -0
  19. package/dist/src/cli/handlers/mc-help.js +171 -0
  20. package/dist/src/cli/handlers/mc-run.js +343 -0
  21. package/dist/src/cli/handlers/mc-session.js +138 -0
  22. package/dist/src/cli/handlers/mc-status.js +258 -0
  23. package/dist/src/cli/handlers/mc-summary.js +43 -0
  24. package/dist/src/cli/handlers/mc-types.js +3 -0
  25. package/dist/src/cli/handlers/mc-worker.js +205 -0
  26. package/dist/src/cli/handlers/mc.js +12 -1665
  27. package/dist/src/cli/handlers/models-refusal.js +13 -0
  28. package/dist/src/cli/handlers/models.js +2 -1
  29. package/dist/src/cli/handlers/remove-bundled.js +133 -0
  30. package/dist/src/cli/handlers/remove-options.js +31 -0
  31. package/dist/src/cli/handlers/remove-user.js +174 -0
  32. package/dist/src/cli/handlers/remove.js +201 -0
  33. package/dist/src/cli/handlers/subcommands-bundles.js +257 -0
  34. package/dist/src/cli/handlers/subcommands-discovery.js +165 -0
  35. package/dist/src/cli/handlers/subcommands-list-format.js +129 -0
  36. package/dist/src/cli/handlers/subcommands-list.js +250 -0
  37. package/dist/src/cli/handlers/subcommands-plugins.js +213 -0
  38. package/dist/src/cli/handlers/subcommands-quickref.js +58 -0
  39. package/dist/src/cli/handlers/subcommands-rlm.js +113 -0
  40. package/dist/src/cli/handlers/subcommands-services.js +66 -0
  41. package/dist/src/cli/handlers/subcommands-storage.js +259 -0
  42. package/dist/src/cli/handlers/subcommands.js +18 -1984
  43. package/dist/src/cli/scope-resolver.js +1 -142
  44. package/dist/src/cli/user-scope-mirror.js +173 -0
  45. package/dist/src/config/dispatch-host-thresholds.js +2 -0
  46. package/dist/src/config/dispatch-thresholds-runtime.mjs +4 -0
  47. package/dist/src/config/host-resource-report.d.mts +5 -0
  48. package/dist/src/config/host-resource-report.mjs +36 -6
  49. package/dist/src/config/host-resource-runtime.d.mts +3 -0
  50. package/dist/src/config/host-resource-runtime.mjs +9 -6
  51. package/dist/src/decision/ensemble-study/artifacts.js +7 -0
  52. package/dist/src/decision/ensemble-study/gate-policy.js +58 -0
  53. package/dist/src/decision/ensemble-study/gates.js +78 -0
  54. package/dist/src/decision/ensemble-study/protocol.js +18 -21
  55. package/dist/src/decision/ensemble-study/score.js +3 -2
  56. package/dist/src/decision/ensemble-study/statistics.js +7 -26
  57. package/dist/src/decision/sensitivity/comparative-gates.js +135 -0
  58. package/dist/src/decision/sensitivity/comparative.js +18 -41
  59. package/dist/src/extensions/claude-hooks-installer.js +18 -0
  60. package/dist/src/gates/evaluate.js +2 -358
  61. package/dist/src/gates/observations.js +363 -0
  62. package/dist/src/gates/pack-composition.js +270 -0
  63. package/dist/src/gates/pack-tightening.js +197 -0
  64. package/dist/src/gates/pack-validation.js +262 -0
  65. package/dist/src/gates/registry-error.js +5 -0
  66. package/dist/src/gates/registry.js +13 -685
  67. package/dist/src/mcp/json-document.mjs +29 -0
  68. package/dist/src/mcp/muse-native-config.mjs +1 -28
  69. package/dist/src/mission-protocol/worker-review-gate.js +7 -0
  70. package/dist/src/models/worker-plan.js +5 -5
  71. package/dist/src/plugin/command-ownership.js +34 -0
  72. package/dist/src/plugin/skill-command-frontmatter.js +197 -0
  73. package/dist/src/plugin/skill-command-translator.js +6 -232
  74. package/dist/src/providers/context-output-ownership.js +26 -0
  75. package/dist/src/providers/deployment-ownership.d.mts +19 -0
  76. package/dist/src/providers/deployment-ownership.mjs +226 -0
  77. package/dist/src/providers/deployment-removal.js +200 -0
  78. package/dist/src/providers/removal-transaction.js +86 -0
  79. package/dist/src/providers/settings-document.d.mts +3 -0
  80. package/dist/src/providers/settings-document.mjs +47 -0
  81. package/dist/src/providers/settings-removal.js +190 -0
  82. package/dist/src/providers/skill-ownership.d.mts +19 -2
  83. package/dist/src/providers/skill-ownership.mjs +12 -4
  84. package/dist/src/providers/transformation-receipt-integration.js +15 -271
  85. package/dist/src/providers/transformation-receipt-outputs.js +99 -0
  86. package/dist/src/providers/transformation-receipt-source.js +194 -0
  87. package/dist/src/research/identity.js +8 -2
  88. package/dist/src/research/reference-match.js +42 -7
  89. package/dist/src/rules/activation.mjs +15 -6
  90. package/dist/src/rules/core-startup.mjs +2 -2
  91. package/dist/src/serve/mission-conductor.js +4 -0
  92. package/dist/src/serve/mission-summary.js +56 -0
  93. package/dist/src/smiths/context-pipeline/aiwg-md.js +23 -0
  94. package/dist/src/smiths/context-pipeline/context-file-safety.js +3 -0
  95. package/dist/src/smiths/context-pipeline/generator.js +1 -1
  96. package/dist/src/smiths/hook-bridge/index.js +9 -0
  97. package/package.json +4 -1
  98. package/schemas/decision/D17StudyProtocol.v1.schema.json +39 -67
  99. package/tools/agents/deploy-agents.mjs +16 -677
  100. package/tools/agents/deploy-command-mirrors.mjs +229 -0
  101. package/tools/agents/deploy-options.mjs +258 -0
  102. package/tools/agents/deploy-support.mjs +165 -0
  103. package/tools/agents/providers/base-addon-discovery.mjs +139 -0
  104. package/tools/agents/providers/base-behaviors.mjs +168 -0
  105. package/tools/agents/providers/base-context.mjs +205 -0
  106. package/tools/agents/providers/base-contract.mjs +116 -0
  107. package/tools/agents/providers/base-files.mjs +252 -0
  108. package/tools/agents/providers/base-flat-artifacts.mjs +233 -0
  109. package/tools/agents/providers/base-framework-discovery.mjs +309 -0
  110. package/tools/agents/providers/base-frontmatter.mjs +196 -0
  111. package/tools/agents/providers/base-inventory.mjs +269 -0
  112. package/tools/agents/providers/base-kernel-skills.mjs +354 -0
  113. package/tools/agents/providers/base-migrations.mjs +258 -0
  114. package/tools/agents/providers/base-models-platforms.mjs +273 -0
  115. package/tools/agents/providers/base-rule-index.mjs +450 -0
  116. package/tools/agents/providers/base-runtime.mjs +60 -0
  117. package/tools/agents/providers/base-skill-copy.mjs +273 -0
  118. package/tools/agents/providers/base.mjs +16 -3364
  119. package/tools/agents/providers/claude-post-deploy.mjs +10 -2
  120. package/tools/agents/providers/hermes-startup.mjs +0 -5
  121. package/tools/agents/providers/muse.mjs +7 -2
  122. package/tools/agents/providers/rule-delivery-surface.mjs +31 -4
  123. package/tools/agents/providers/rule-deployment-commit.mjs +19 -15
  124. package/tools/agents/providers/rule-deployment-prepare.mjs +11 -2
  125. package/tools/agents/providers/rule-projection.mjs +3 -0
  126. package/tools/ralph-external/lib/worker-invocation-processes.mjs +4 -2
  127. package/tools/ralph-external/lib/worker-termination.mjs +15 -8
  128. package/vscode-extension/schemas/aiwg.config.v1.json +2 -4
@@ -0,0 +1,171 @@
1
+ // Mission Control help operations, extracted from the shared handler.
2
+ import * as ui from '../ui.js';
3
+ /**
4
+ * Per-subcommand usage strings (#1440).
5
+ *
6
+ * `aiwg mc <subcommand> --help` MUST print this text and exit before any
7
+ * side-effecting logic. The previous behavior — running `aiwg mc start --help`
8
+ * actually created a session — violated the universal `--help` convention.
9
+ */
10
+ export const subcommandUsage = {
11
+ summary: `Usage: aiwg mc summary --ledger <path> [--json]
12
+
13
+ Read an existing Mission conductor ledger without syncing or writing it.
14
+ Accepted requires an independent review result with evidence references.
15
+ Completed means worker execution finished without independent acceptance.
16
+ Routed, plan-only and unmeasured work remain unknown.
17
+
18
+ --ledger <path> Existing conductor ledger JSON (relative to the working directory)
19
+ --json Emit cycle classifications, reasons, evidence and counts`,
20
+ start: `Usage: aiwg mc start [--name "<label>"] [--max-missions N]
21
+
22
+ Create a new Mission Control session for tracking background missions.
23
+
24
+ --name <label> Human-readable session name (default: "Mission YYYY-MM-DD")
25
+ --max-missions N Capacity limit for queued missions (default: 10)
26
+
27
+ Note: 'start' only creates the session. Use 'dispatch' to queue missions and
28
+ 'run' to drain the queue.`,
29
+ dispatch: `Usage: aiwg mc dispatch <session-id> "<objective>" [options]
30
+
31
+ Queue a mission onto a session. Does NOT execute — use 'aiwg mc run' to launch.
32
+
33
+ --completion "<criteria>" Verifiable completion criteria (required for 'mc run')
34
+ --priority <level> Priority hint (default: normal)
35
+ --max-iterations N Ralph iteration cap when launched (default: 10)
36
+ --max-total-tokens N Hard cumulative token ceiling when observable
37
+ --max-output-tokens N Hard cumulative output-token ceiling
38
+ --max-tool-calls N Hard cumulative tool-call ceiling
39
+ --max-total-cost USD Hard cumulative provider-reported spend ceiling
40
+ --max-wall-clock-minutes N Hard cumulative runtime ceiling
41
+ --exploration-quota K Require structural variant after K flat cycles
42
+ (off unless declared; no default K)
43
+ --budget-stop-policy P completion-wins (default) | budget-wins
44
+ --mode pty-orchestrator PTY-orchestrator mode (requires --target-agent)
45
+ --target-agent <id> Required for --mode pty-orchestrator
46
+ --worker-dispatch <path> Prepared managed worker dispatch JSON (queues only)
47
+ --expected-updated-at <time> Reject stale state with exit 3
48
+ --request-id <id> Idempotent dispatch key`,
49
+ run: `Usage: aiwg mc run [<session-id>] [--accept-cost]
50
+
51
+ Drain queued missions in a session by launching each as a ralph loop. Missions
52
+ without --completion criteria are skipped with a warning.
53
+
54
+ --accept-cost Skip the cost-warning gate (required for non-TTY contexts
55
+ when estimated cumulative cost exceeds $5). See #1450.
56
+
57
+ The estimate is the cumulative iteration floor (missions x max-iterations x
58
+ ~$1.60 cache cost per headless iteration). A mission's --max-total-cost caps its
59
+ share of that estimate only on a provider that reports spend; on a provider that
60
+ reports none the ceiling is inert (#1766), so it is reported but not subtracted.
61
+ See #2522.`,
62
+ status: `Usage: aiwg mc status [<session-id>] [--json]
63
+
64
+ Show mission status for a session. Auto-syncs from ralph loop state files.
65
+
66
+ --json Emit JSON instead of human-readable table`,
67
+ watch: `Usage: aiwg mc watch [<session-id>]
68
+
69
+ Live-monitor mission progress (non-interactive context prints status once).`,
70
+ abort: `Usage: aiwg mc abort <session-id> <mission-id>
71
+
72
+ Mark a specific mission as aborted.
73
+
74
+ --expected-updated-at <timestamp> Reject stale state with exit 3
75
+ --request-id <id> Idempotent mutation key`,
76
+ pause: `Usage: aiwg mc pause [<session-id>]
77
+
78
+ Pause an active session; running missions transition to 'paused' status.
79
+
80
+ --expected-updated-at <timestamp> Reject stale state with exit 3
81
+ --request-id <id> Idempotent mutation key`,
82
+ resume: `Usage: aiwg mc resume [<session-id>]
83
+
84
+ Resume a paused session; paused missions transition back to 'running'.
85
+
86
+ --expected-updated-at <timestamp> Reject stale state with exit 3
87
+ --request-id <id> Idempotent mutation key`,
88
+ stop: `Usage: aiwg mc stop [<session-id>] [--drain]
89
+
90
+ Shut down a session.
91
+
92
+ --drain Cancel queued, let running finish (default: abort all non-completed)`,
93
+ list: `Usage: aiwg mc list [--json]
94
+
95
+ List all Mission Control sessions.`,
96
+ agents: `Usage: aiwg mc agents [filters] [--json]
97
+
98
+ Query routable agents from a local 'aiwg serve' instance.
99
+
100
+ --framework <name> Require an AIWG framework (repeatable)
101
+ --sandbox <id> Restrict to a sandbox
102
+ --agent <id> Restrict to a specific agent ID
103
+ --name <n> Match by logical name
104
+ --max-cpu <pct> Reject agents above this CPU %
105
+ --min-memory <gb> Reject agents below this memory threshold
106
+ --json Output raw JSON`,
107
+ };
108
+ export function printSubcommandHelp(name) {
109
+ const text = subcommandUsage[name];
110
+ ui.blank();
111
+ if (text) {
112
+ console.log(` ${text}`);
113
+ }
114
+ else {
115
+ console.log(` No detailed help for 'aiwg mc ${name}'. Run 'aiwg mc --help' for the full reference.`);
116
+ }
117
+ ui.blank();
118
+ }
119
+ export function showMcHelp() {
120
+ ui.blank();
121
+ console.log(` ${ui.brandMark()} ${ui.bold('Mission Control')} — multi-loop background orchestration`);
122
+ ui.rule();
123
+ console.log(`
124
+ ${ui.bold('Usage:')} aiwg mc <subcommand> [options]
125
+
126
+ ${ui.bold('Lifecycle:')}
127
+ 1. start — create a session (state-tracking only)
128
+ 2. dispatch — queue one or more missions onto a session
129
+ 3. run — drain the queue by launching each mission as a ralph loop
130
+ 4. status — view progress (auto-syncs from ralph loop state)
131
+ 5. watch — live tail of progress
132
+ 6. stop — shut down the session
133
+
134
+ ${ui.bold('Subcommands:')}
135
+ start Start a new Mission Control session
136
+ dispatch <id> "<objective>" Queue a mission on the session (does NOT execute)
137
+ [--completion "<criteria>"] [--max-iterations N]
138
+ [--max-total-tokens N] [--max-output-tokens N]
139
+ [--max-tool-calls N] [--max-total-cost USD]
140
+ [--max-wall-clock-minutes N] [--exploration-quota N]
141
+ [--mode pty-orchestrator] [--target-agent <id>]
142
+ run <id> [--accept-cost] Launch queued missions as ralph loops (#1439)
143
+ Cost gate warns/refuses above ~$5 estimate
144
+ status [<id>] [--json] View mission status dashboard
145
+ summary --ledger <path> [--json] Read accepted, completed, failed and unknown work
146
+ watch [<id>] Live monitor (streaming)
147
+ abort|cancel <session> <mission> Abort a specific mission
148
+ pause [<id>] Pause active session
149
+ resume [<id>] Resume paused session
150
+ stop [<id>] [--drain] Shut down session
151
+ list [--json] List all sessions
152
+ agents [--filter] [--json] Query routable agents from aiwg serve (#916)
153
+ ${ui.bold('Examples:')}
154
+ aiwg mc start --name "Sprint 4"
155
+ aiwg mc dispatch mc-abc123 "Fix auth" --completion "tests pass"
156
+ aiwg mc dispatch mc-abc123 "Fix auth" --completion "tests pass" --max-total-tokens 5000 --exploration-quota 2
157
+ aiwg mc dispatch mc-abc123 "Refactor users" --completion "npm test passes"
158
+ aiwg mc run mc-abc123 # launches queued missions
159
+ aiwg mc status mc-abc123 # syncs progress from ralph loops
160
+ aiwg mc dispatch mc-abc123 "Supervise agent-01" --mode pty-orchestrator --target-agent agent-01 --completion "migration complete"
161
+ aiwg mc stop mc-abc123 --drain
162
+ aiwg mc agents --framework sdlc-complete --max-cpu 80
163
+
164
+ ${ui.bold('A2A route for new sandbox work:')}
165
+ GET /api/v2/admin/instances
166
+ GET /agents/{instance_id}/.well-known/agent-card.json
167
+ GET /agents/{instance_id}/v1/extendedAgentCard
168
+ POST /agents/{instance_id}/v1/messages:send
169
+ `);
170
+ }
171
+ //# sourceMappingURL=mc-help.js.map
@@ -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