@aiwg/cli 2026.10.16 → 2026.10.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. package/agentic/code/providers/capability-matrix.yaml +51 -0
  2. package/agentic/code/providers/flue/README.md +62 -0
  3. package/agentic/code/providers/flue/templates/aiwg/tools.ts +120 -0
  4. package/agentic/code/providers/model-capabilities.v1.json +23 -0
  5. package/agentic/code/providers/model-catalog.v1.json +9 -0
  6. package/dist/src/artifacts/corpus-tools/resolve.js +28 -6
  7. package/dist/src/artifacts/query-engine-corpus.js +217 -0
  8. package/dist/src/artifacts/query-engine-discover-output.js +229 -0
  9. package/dist/src/artifacts/query-engine-discover.js +285 -0
  10. package/dist/src/artifacts/query-engine-entries.js +188 -0
  11. package/dist/src/artifacts/query-engine-index.js +249 -0
  12. package/dist/src/artifacts/query-engine-matching.js +143 -0
  13. package/dist/src/artifacts/query-engine-options.js +2 -0
  14. package/dist/src/artifacts/query-engine-rules.js +202 -0
  15. package/dist/src/artifacts/query-engine-scoring.js +436 -0
  16. package/dist/src/artifacts/query-engine-show-card.js +194 -0
  17. package/dist/src/artifacts/query-engine-show-load.js +211 -0
  18. package/dist/src/artifacts/query-engine-show.js +300 -0
  19. package/dist/src/artifacts/query-engine.js +7 -2576
  20. package/dist/src/cli/handlers/help.js +1 -1
  21. package/dist/src/cli/handlers/init.js +1 -0
  22. package/dist/src/cli/handlers/mc-agents.js +111 -0
  23. package/dist/src/cli/handlers/mc-args.js +54 -0
  24. package/dist/src/cli/handlers/mc-control.js +227 -0
  25. package/dist/src/cli/handlers/mc-dispatch.js +203 -0
  26. package/dist/src/cli/handlers/mc-help.js +171 -0
  27. package/dist/src/cli/handlers/mc-run.js +343 -0
  28. package/dist/src/cli/handlers/mc-session.js +138 -0
  29. package/dist/src/cli/handlers/mc-status.js +258 -0
  30. package/dist/src/cli/handlers/mc-summary.js +43 -0
  31. package/dist/src/cli/handlers/mc-types.js +3 -0
  32. package/dist/src/cli/handlers/mc-worker.js +205 -0
  33. package/dist/src/cli/handlers/mc.js +12 -1665
  34. package/dist/src/cli/handlers/models-refusal.js +13 -0
  35. package/dist/src/cli/handlers/models.js +2 -1
  36. package/dist/src/cli/handlers/remove-bundled.js +133 -0
  37. package/dist/src/cli/handlers/remove-options.js +31 -0
  38. package/dist/src/cli/handlers/remove-user.js +174 -0
  39. package/dist/src/cli/handlers/remove.js +201 -0
  40. package/dist/src/cli/handlers/subcommands-bundles.js +257 -0
  41. package/dist/src/cli/handlers/subcommands-discovery.js +165 -0
  42. package/dist/src/cli/handlers/subcommands-list-format.js +129 -0
  43. package/dist/src/cli/handlers/subcommands-list.js +250 -0
  44. package/dist/src/cli/handlers/subcommands-plugins.js +213 -0
  45. package/dist/src/cli/handlers/subcommands-quickref.js +58 -0
  46. package/dist/src/cli/handlers/subcommands-rlm.js +113 -0
  47. package/dist/src/cli/handlers/subcommands-services.js +66 -0
  48. package/dist/src/cli/handlers/subcommands-storage.js +259 -0
  49. package/dist/src/cli/handlers/subcommands.js +18 -1984
  50. package/dist/src/cli/handlers/use.js +11 -5
  51. package/dist/src/cli/scope-resolver.js +1 -142
  52. package/dist/src/cli/services/deployment-verification.js +3 -0
  53. package/dist/src/cli/user-scope-mirror.js +173 -0
  54. package/dist/src/config/dispatch-host-thresholds.js +2 -0
  55. package/dist/src/config/dispatch-thresholds-runtime.mjs +4 -0
  56. package/dist/src/config/host-resource-report.d.mts +5 -0
  57. package/dist/src/config/host-resource-report.mjs +36 -6
  58. package/dist/src/config/host-resource-runtime.d.mts +3 -0
  59. package/dist/src/config/host-resource-runtime.mjs +9 -6
  60. package/dist/src/decision/ensemble-study/artifacts.js +7 -0
  61. package/dist/src/decision/ensemble-study/gate-policy.js +58 -0
  62. package/dist/src/decision/ensemble-study/gates.js +78 -0
  63. package/dist/src/decision/ensemble-study/protocol.js +18 -21
  64. package/dist/src/decision/ensemble-study/score.js +3 -2
  65. package/dist/src/decision/ensemble-study/statistics.js +7 -26
  66. package/dist/src/decision/sensitivity/comparative-gates.js +135 -0
  67. package/dist/src/decision/sensitivity/comparative.js +18 -41
  68. package/dist/src/extensions/claude-hooks-installer.js +18 -0
  69. package/dist/src/gates/evaluate.js +2 -358
  70. package/dist/src/gates/observations.js +363 -0
  71. package/dist/src/gates/pack-composition.js +270 -0
  72. package/dist/src/gates/pack-tightening.js +197 -0
  73. package/dist/src/gates/pack-validation.js +262 -0
  74. package/dist/src/gates/registry-error.js +5 -0
  75. package/dist/src/gates/registry.js +13 -685
  76. package/dist/src/mcp/json-document.mjs +29 -0
  77. package/dist/src/mcp/muse-native-config.mjs +1 -28
  78. package/dist/src/memory/provider-memory-adapter.js +1 -0
  79. package/dist/src/mission-protocol/worker-review-gate.js +7 -0
  80. package/dist/src/models/model-capabilities.v1.json +23 -0
  81. package/dist/src/models/model-catalog.v1.json +9 -0
  82. package/dist/src/models/policy-resources.js +1 -1
  83. package/dist/src/models/worker-plan.js +5 -5
  84. package/dist/src/plugin/command-ownership.js +34 -0
  85. package/dist/src/plugin/skill-command-frontmatter.js +197 -0
  86. package/dist/src/plugin/skill-command-translator.js +6 -232
  87. package/dist/src/providers/capability-matrix.yaml +51 -0
  88. package/dist/src/providers/context-output-ownership.js +26 -0
  89. package/dist/src/providers/deployment-ownership.d.mts +20 -0
  90. package/dist/src/providers/deployment-ownership.mjs +236 -0
  91. package/dist/src/providers/deployment-removal.js +222 -0
  92. package/dist/src/providers/provider-context-contracts.js +8 -0
  93. package/dist/src/providers/provider-definition-schema.js +1 -0
  94. package/dist/src/providers/provider-definitions.js +1 -0
  95. package/dist/src/providers/provider-seeds-3.js +18 -0
  96. package/dist/src/providers/removal-transaction.js +86 -0
  97. package/dist/src/providers/settings-document.d.mts +3 -0
  98. package/dist/src/providers/settings-document.mjs +47 -0
  99. package/dist/src/providers/settings-removal.js +190 -0
  100. package/dist/src/providers/skill-ownership.d.mts +20 -2
  101. package/dist/src/providers/skill-ownership.mjs +12 -4
  102. package/dist/src/providers/transformation-receipt-integration.js +15 -271
  103. package/dist/src/providers/transformation-receipt-outputs.js +99 -0
  104. package/dist/src/providers/transformation-receipt-source.js +194 -0
  105. package/dist/src/research/identity.js +8 -2
  106. package/dist/src/research/reference-match.js +66 -8
  107. package/dist/src/rules/activation.mjs +15 -6
  108. package/dist/src/rules/core-startup.mjs +2 -2
  109. package/dist/src/serve/mission-conductor.js +4 -0
  110. package/dist/src/serve/mission-summary.js +56 -0
  111. package/dist/src/skills/deployment-ownership.js +2 -2
  112. package/dist/src/skills/deployment-policy.js +9 -0
  113. package/dist/src/smiths/context-pipeline/aiwg-md.js +23 -0
  114. package/dist/src/smiths/context-pipeline/context-file-safety.js +3 -0
  115. package/dist/src/smiths/context-pipeline/flue-context.js +25 -0
  116. package/dist/src/smiths/context-pipeline/generator.js +7 -2
  117. package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +9 -7
  118. package/dist/src/smiths/hook-bridge/index.js +9 -0
  119. package/package.json +5 -1
  120. package/schemas/decision/D17StudyProtocol.v1.schema.json +39 -67
  121. package/tools/agents/deploy-agents.mjs +21 -680
  122. package/tools/agents/deploy-command-mirrors.mjs +229 -0
  123. package/tools/agents/deploy-options.mjs +267 -0
  124. package/tools/agents/deploy-support.mjs +165 -0
  125. package/tools/agents/providers/base-addon-discovery.mjs +139 -0
  126. package/tools/agents/providers/base-behaviors.mjs +168 -0
  127. package/tools/agents/providers/base-context.mjs +205 -0
  128. package/tools/agents/providers/base-contract.mjs +116 -0
  129. package/tools/agents/providers/base-files.mjs +252 -0
  130. package/tools/agents/providers/base-flat-artifacts.mjs +233 -0
  131. package/tools/agents/providers/base-framework-discovery.mjs +309 -0
  132. package/tools/agents/providers/base-frontmatter.mjs +196 -0
  133. package/tools/agents/providers/base-inventory.mjs +269 -0
  134. package/tools/agents/providers/base-kernel-skills.mjs +354 -0
  135. package/tools/agents/providers/base-migrations.mjs +258 -0
  136. package/tools/agents/providers/base-models-platforms.mjs +273 -0
  137. package/tools/agents/providers/base-rule-index.mjs +450 -0
  138. package/tools/agents/providers/base-runtime.mjs +60 -0
  139. package/tools/agents/providers/base-skill-copy.mjs +273 -0
  140. package/tools/agents/providers/base.mjs +16 -3364
  141. package/tools/agents/providers/claude-post-deploy.mjs +10 -2
  142. package/tools/agents/providers/flue-project.mjs +79 -0
  143. package/tools/agents/providers/flue-specialists.mjs +64 -0
  144. package/tools/agents/providers/flue.mjs +50 -0
  145. package/tools/agents/providers/hermes-startup.mjs +0 -5
  146. package/tools/agents/providers/muse.mjs +7 -2
  147. package/tools/agents/providers/rule-delivery-surface.mjs +33 -5
  148. package/tools/agents/providers/rule-deployment-commit.mjs +19 -15
  149. package/tools/agents/providers/rule-deployment-prepare.mjs +13 -3
  150. package/tools/agents/providers/rule-projection.mjs +3 -0
  151. package/tools/agents/providers/rule-startup.mjs +3 -3
  152. package/tools/agents/use-rule-selection.mjs +17 -0
  153. package/tools/ralph-external/lib/worker-invocation-processes.mjs +4 -2
  154. package/tools/ralph-external/lib/worker-termination.mjs +15 -8
  155. package/vscode-extension/schemas/aiwg.config.v1.json +2 -4
@@ -1,1620 +1,18 @@
1
- /**
2
- * Mission Control Command Handler
3
- *
4
- * Multi-loop background orchestration dashboard. Lets an orchestrator
5
- * spawn multiple long-running agent loops, monitor all simultaneously,
6
- * and react to completions or failures without blocking the primary session.
7
- *
8
- * Subcommands: start, dispatch, status, watch, abort, pause, resume, stop, list
9
- *
10
- * @implements @agentic/code/frameworks/sdlc-complete/rules/self-maintenance.md
11
- * @source @src/cli/router.ts
12
- * @issue #483
13
- */
14
1
  import * as ui from '../ui.js';
15
- import { constants as fsConstants, promises as fs } from 'node:fs';
16
- import { isAbsolute, join, relative } from 'node:path';
17
- import { fileURLToPath, pathToFileURL } from 'node:url';
18
- import { createHash, randomBytes } from 'node:crypto';
19
- import { assertMissionWorkerHandoff, assertValidWorkerPayload, validateWorkerPayload, workerConsumerSupport } from '../../mission-protocol/codecs.js';
20
- import { WORKER_BASELINE_FEATURES } from '../../mission-protocol/types.js';
21
- // ── Constants ────────────────────────────────────────────────
22
- const MC_ROOT = '.aiwg/ralph-external/mc';
23
- const SESSIONS_DIR = join(MC_ROOT, 'sessions');
24
- const CONTROL_ID_RE = /^[a-zA-Z0-9._-]+$/;
25
- /** Managed callers fail closed on invalid configuration; legacy reads keep their
26
- * historical best-effort behavior. No activation is installed by a caller. */
27
- async function readAdmissionConfig(projectRoot) {
28
- const { readAiwgConfig, readAiwgConfigCandidate } = await import('../../config/aiwg-config.js');
29
- try {
30
- return await readAiwgConfig(projectRoot);
31
- }
32
- catch (error) {
33
- const candidate = await readAiwgConfigCandidate(projectRoot);
34
- if (candidate?.parallelism?.worker_mode === 'managed')
35
- throw error;
36
- return null;
37
- }
38
- }
39
- import { createMcAdmissionScheduler } from './mc-admission.js';
2
+ import { wantsHelp } from './mc-args.js';
3
+ import { printSubcommandHelp, showMcHelp } from './mc-help.js';
4
+ import { mcStart, mcDispatch } from './mc-dispatch.js';
5
+ import { mcRun } from './mc-run.js';
6
+ import { mcStatus, mcList, mcWatch } from './mc-status.js';
7
+ import { mcAbort, mcPause, mcResume, mcStop } from './mc-control.js';
8
+ import { mcAgents } from './mc-agents.js';
40
9
  export { createMcAdmissionScheduler } from './mc-admission.js';
41
- const mcWorkerSupport = () => workerConsumerSupport([...WORKER_BASELINE_FEATURES, 'worker-health.v1']);
42
- function workerDispatch(mission) {
43
- const bindings = new Set();
44
- const seen = new Set();
45
- function visit(value) {
46
- if (!value || typeof value !== 'object' || seen.has(value))
47
- return;
48
- seen.add(value);
49
- const record = value;
50
- if (record['aiwg.worker-dispatch'])
51
- bindings.add(record['aiwg.worker-dispatch']);
52
- visit(record.extensions);
53
- visit(record.metadata);
54
- for (const [key, child] of Object.entries(record))
55
- if (key.startsWith('aiwg.source.'))
56
- visit(child);
57
- }
58
- visit(mission);
59
- if (bindings.size > 1)
60
- throw new Error('Managed task contains multiple dispatch bindings');
61
- return [...bindings][0];
62
- }
63
- async function readWorkerArtifact(artifact, projectRoot) {
64
- const filename = artifact.ref.startsWith('file:') ? fileURLToPath(artifact.ref) : artifact.ref;
65
- const inside = relative(projectRoot, filename);
66
- if (!isAbsolute(filename) || inside.startsWith('..') || isAbsolute(inside))
67
- throw new Error('Managed worker artifacts must be inside the project');
68
- const bytes = await readWorkerBytes(filename);
69
- if (`sha256:${createHash('sha256').update(bytes).digest('hex')}` !== artifact.digest)
70
- throw new Error('Managed worker artifact digest changed');
71
- return JSON.parse(bytes.toString('utf8'));
72
- }
73
- async function readWorkerBytes(filename) {
74
- const { inspectWorkerPath } = await import('../../serve/worker-invocation.js');
75
- if (!await inspectWorkerPath(filename, 'file'))
76
- throw Object.assign(new Error('Managed worker artifact is missing'), { code: 'ENOENT' });
77
- const handle = await fs.open(filename, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
78
- try {
79
- const stat = await handle.stat();
80
- if (!stat.isFile() || stat.nlink !== 1 || stat.size > 1048576)
81
- throw new Error('Invalid managed worker artifact');
82
- const bytes = Buffer.alloc(1048577);
83
- const { bytesRead } = await handle.read(bytes, 0, bytes.length, 0);
84
- if (bytesRead > 1048576)
85
- throw new Error('Managed worker artifact exceeds its size bound');
86
- return bytes.subarray(0, bytesRead);
87
- }
88
- finally {
89
- await handle.close();
90
- }
91
- }
92
- async function readWorkerJson(filename) {
93
- return JSON.parse((await readWorkerBytes(filename)).toString('utf8'));
94
- }
95
- async function resolveMcWorker(ctx, session, mission, parentKind = 'mission') {
96
- const dispatch = workerDispatch(mission);
97
- if (!dispatch)
98
- return undefined;
99
- const projectRoot = ctx.cwd || process.cwd();
100
- const intent = await readWorkerArtifact(dispatch.intent, projectRoot);
101
- assertValidWorkerPayload('workerSelectionIntent', intent);
102
- if (!dispatch.brief)
103
- throw new Error('Managed worker requires a prepared brief');
104
- const brief = await readWorkerArtifact(dispatch.brief, projectRoot);
105
- assertValidWorkerPayload('workerBrief', brief);
106
- const { workerConfigDigest } = await import('../../config/aiwg-config.js');
107
- if (intent.parent.kind !== parentKind || intent.parent.id !== session.id || intent.objective !== mission.objective
108
- || intent.taskId !== dispatch.taskId || intent.requestId !== dispatch.requestId
109
- || brief.invocationId !== dispatch.invocationId || workerConfigDigest(brief.intent) !== workerConfigDigest(intent)
110
- || brief.intentDigest !== workerConfigDigest(intent))
111
- throw new Error('Managed worker task authority differs from its parent');
112
- const { loadWorkerInputs } = await import('./models.js');
113
- const { resolveWorkerInvocation } = await import('../../serve/worker-invocation.js');
114
- const inputs = await loadWorkerInputs(ctx);
115
- const plan = await resolveWorkerInvocation(inputs.snapshot, { role: intent.role, task: intent.taskClass, group: intent.group,
116
- brief: dispatch.brief.ref.startsWith('file:') ? fileURLToPath(dispatch.brief.ref) : dispatch.brief.ref,
117
- workdir: brief.workspace.path, final_output: brief.output.resultPath, managedIntent: intent }, inputs.drivers);
118
- if (!plan.invocation || plan.status !== 'eligible' || plan.invocation.readiness !== 'launchable') {
119
- throw new Error(`Managed worker is ineligible: ${plan.diagnostics.map(item => item.message).join('; ')}`);
120
- }
121
- if (parentKind === 'mission' && plan.invocation.transport !== 'shell')
122
- throw new Error('Managed Ralph capture requires a qualified shell transport');
123
- return { dispatch, intent, brief, plan };
124
- }
125
- /** Flow adapters use the same eligibility, project authority and allowance owner. */
126
- export async function createMcFlowAdapter(ctx, bindings) {
127
- const cfg = await readAdmissionConfig(ctx.cwd);
128
- if (!cfg?.parallelism?.worker_dispatch || cfg.parallelism.worker_mode !== 'managed') {
129
- throw new Error('OG_CONTRACT_UNSUPPORTED: Flow shared dispatch requires managed mode');
130
- }
131
- const scheduler = await createMcAdmissionScheduler(ctx.cwd, cfg);
132
- const { managedAllowanceFromOwner } = await import('../../serve/shared-host-scheduler.js');
133
- const { createManagedCompositionAdapter } = await import(join(ctx.frameworkRoot, 'agentic/code/addons/composition-engine/lib/runtime.mjs'));
134
- return createManagedCompositionAdapter({ scheduler, allowanceFromOwner: managedAllowanceFromOwner,
135
- invokeNode: bindings.invokeNode,
136
- prepareNode: async (request) => {
137
- const binding = await bindings.prepareNode(request);
138
- const worker = await resolveMcWorker(ctx, { id: request.runId }, {
139
- id: request.node.id, objective: binding.objective, status: 'queued', loop: 0,
140
- maxIterations: 1, priority: 'normal', mode: 'direct', extensions: { 'aiwg.worker-dispatch': binding.dispatch },
141
- }, 'flow');
142
- if (!worker || worker.intent.taskId !== request.node.id)
143
- throw new Error('Flow task authority differs from node identity');
144
- const selected = worker.plan.selected;
145
- return { invocation: worker.plan.invocation, plan: worker.plan, brief: worker.brief,
146
- admission: { requestId: worker.dispatch.requestId, orchestratorId: request.runId,
147
- environment: process.env.AIWG_ENVIRONMENT ?? 'default', provider: selected.inferenceProvider, runtimeKind: 'host',
148
- priority: 10, submittedAt: new Date().toISOString(), queueTimeoutMs: (cfg.parallelism.admission?.queueTimeoutSeconds ?? 300) * 1000,
149
- preemptible: false, metadata: { nodeId: request.node.id, invocationId: worker.dispatch.invocationId },
150
- managed: { kind: 'external', group: selected.group, member: selected.member, cli: selected.cli,
151
- model: selected.modelKey, quotaScope: cfg.parallelism.clis[selected.cli].quotaScope },
152
- allowance: { runId: request.runId, taskId: request.node.id,
153
- taskBudgets: { maxAttempts: worker.intent.limits.maxAttempts, maxTokens: worker.intent.limits.tokens,
154
- maxCostUsd: worker.intent.limits.costUsd ?? undefined, timeoutSeconds: worker.intent.limits.wallSeconds },
155
- reservation: { tokens: worker.plan.invocation.limits.tokens, costUsd: worker.plan.invocation.limits.costUsd } },
156
- } };
157
- },
158
- });
159
- }
160
- /** Capture completion is evidence for the parent, never an independent gate. */
161
- async function readManagedWorkerState(mission, scheduler) {
162
- const binding = mission.managedWorker;
163
- const observation = await readWorkerJson(join(binding.runDir, 'health.json'));
164
- assertValidWorkerPayload('workerHealthSummary', observation.health);
165
- const dispatch = workerDispatch(mission);
166
- if (observation.invocationId !== dispatch.invocationId || observation.health.observerGeneration !== mission.admissionGeneration) {
167
- throw new Error('Stale managed worker observation');
168
- }
169
- let exit;
170
- try {
171
- exit = await readWorkerJson(join(binding.runDir, 'exit.json'));
172
- }
173
- catch (error) {
174
- if (error.code !== 'ENOENT')
175
- throw error;
176
- }
177
- if (!exit)
178
- return { status: 'running', health: observation.health };
179
- if (exit.invocationId !== dispatch.invocationId || exit.managedAdmission?.requestId !== mission.admissionRequestId
180
- || exit.managedAdmission?.generation !== mission.admissionGeneration)
181
- throw new Error('Stale managed worker exit evidence');
182
- const record = scheduler.snapshot().records[mission.admissionRequestId];
183
- const usage = { inputTokens: null, outputTokens: null, cacheTokens: null, reasoningTokens: null,
184
- costUsd: null, quality: 'unknown', reservedTokens: record.accounting.reservation.tokens,
185
- reservedUsd: record.accounting.reservation.costUsd };
186
- const plan = await readWorkerJson(binding.invocationPath);
187
- const succeeded = exit.exitCode === 0 && !exit.errorCode && !exit.timedOut && !exit.cancelled;
188
- const result = { version: 1, taskId: dispatch.taskId, invocationId: dispatch.invocationId,
189
- briefDigest: plan.invocation.briefDigest, worker: null,
190
- execution: { status: succeeded ? 'completed' : 'failed', exitCode: exit.exitCode,
191
- requested: plan.invocation.selected, observedModel: null, observedFamily: null, observedEffort: null,
192
- identityEvidence: [], identityQuality: 'unavailable', startedAt: mission.startedAt, endedAt: exit.endedAt,
193
- termination: exit.termination, usage, failure: null, health: observation.health },
194
- verification: { status: 'pending', verifierId: null, runnerRef: null, artifactDigest: null, evidence: [], findings: [] } };
195
- try {
196
- const claims = await readWorkerJson(plan.invocation.finalPath);
197
- assertValidWorkerPayload('workerClaims', claims);
198
- result.worker = claims;
199
- }
200
- catch { /* Invalid or absent claims remain separate from execution evidence. */ }
201
- assertValidWorkerPayload('workerResult', result);
202
- // Use the checkpoint's own directory; request IDs need not contain a session ID.
203
- const destination = `${binding.invocationPath}.result.json`;
204
- const bytes = JSON.stringify(result);
205
- await fs.writeFile(destination, bytes, { mode: 0o600 });
206
- dispatch.result = { ref: pathToFileURL(destination).href, digest: `sha256:${createHash('sha256').update(bytes).digest('hex')}` };
207
- scheduler.acceptFinal(mission.admissionRequestId, mission.admissionGeneration, observation.health, usage);
208
- // A surviving or unobservable outer supervisor cannot prove its own stop.
209
- let supervisorGone = false;
210
- try {
211
- process.kill(mission.admissionExecution.pid, 0);
212
- }
213
- catch (error) {
214
- supervisorGone = error.code === 'ESRCH';
215
- }
216
- if (supervisorGone && exit.termination === 'confirmed' && exit.descendants === 'stopped') {
217
- const settled = scheduler.settle(mission.admissionRequestId, mission.admissionGeneration, observation.health, usage, undefined, mission.admissionExecution);
218
- mission.admissionState = settled.state;
219
- }
220
- dispatch.state = mission.admissionState === 'settled' ? succeeded ? 'completed' : 'failed' : 'uncertain';
221
- // Verification and original completion criteria remain with the parent.
222
- return { status: succeeded && result.worker?.status === 'completed' ? 'paused' : 'failed', health: observation.health };
223
- }
224
- // ── Helpers ──────────────────────────────────────────────────
225
- function genId(prefix) {
226
- return `${prefix}-${Date.now().toString(36)}-${randomBytes(3).toString('hex')}`;
227
- }
228
- async function ensureDir(dir) {
229
- await fs.mkdir(dir, { recursive: true });
230
- }
231
- async function readSession(sessionId) {
232
- if (!CONTROL_ID_RE.test(sessionId))
233
- return null;
234
- const path = join(SESSIONS_DIR, sessionId, 'session.json');
235
- try {
236
- const raw = await fs.readFile(path, 'utf-8');
237
- return JSON.parse(raw);
238
- }
239
- catch {
240
- return null;
241
- }
242
- }
243
- async function writeSession(session, { touch = true } = {}) {
244
- const dir = join(SESSIONS_DIR, session.id);
245
- await ensureDir(dir);
246
- if (touch)
247
- session.updatedAt = new Date().toISOString();
248
- const destination = join(dir, 'session.json');
249
- const temporary = join(dir, `.session.${process.pid}.${randomBytes(4).toString('hex')}.tmp`);
250
- await fs.writeFile(temporary, JSON.stringify(session, null, 2));
251
- await fs.rename(temporary, destination);
252
- }
253
- async function appendLog(sessionId, event) {
254
- const logPath = join(SESSIONS_DIR, sessionId, 'log.jsonl');
255
- const entry = JSON.stringify({ ...event, ts: new Date().toISOString() });
256
- await fs.appendFile(logPath, entry + '\n');
257
- }
258
- /**
259
- * Apply one durable Mission Control mutation under a cross-process lock.
260
- * `expectedUpdatedAt` provides optimistic concurrency and `requestId` makes
261
- * retries idempotent across CLI/Cockpit reconnects.
262
- */
263
- async function mutateSession(sessionId, action, target, expectedUpdatedAt, requestId, mutate) {
264
- if (!CONTROL_ID_RE.test(sessionId) || !CONTROL_ID_RE.test(target)) {
265
- return { ok: false, code: 'target_not_found', message: 'invalid Mission control identifier' };
266
- }
267
- const dir = join(SESSIONS_DIR, sessionId);
268
- await ensureDir(dir);
269
- const lockPath = join(dir, '.control.lock');
270
- let lock;
271
- try {
272
- lock = await fs.open(lockPath, 'wx', 0o600);
273
- }
274
- catch (error) {
275
- if (error.code === 'EEXIST') {
276
- return { ok: false, code: 'mission_conflict', message: 'another Mission control mutation is in progress' };
277
- }
278
- throw error;
279
- }
280
- try {
281
- const session = await readSession(sessionId);
282
- if (!session)
283
- return { ok: false, code: 'session_not_found', message: `Session not found: ${sessionId}` };
284
- if (expectedUpdatedAt && session.updatedAt !== expectedUpdatedAt) {
285
- return { ok: false, code: 'mission_conflict', message: `expected revision ${expectedUpdatedAt}; current revision is ${session.updatedAt}` };
286
- }
287
- if (requestId && session.mutationKeys?.[requestId]) {
288
- const prior = session.mutationKeys[requestId];
289
- if (prior.action !== action || prior.target !== target) {
290
- return { ok: false, code: 'mission_conflict', message: `request id '${requestId}' was already used for another mutation` };
291
- }
292
- return { ok: true, session, replayed: true };
293
- }
294
- const errorCode = mutate(session);
295
- if (errorCode === 'target_not_found')
296
- return { ok: false, code: errorCode, message: `Mission not found: ${target}` };
297
- if (errorCode === 'invalid_state')
298
- return { ok: false, code: errorCode, message: `Mutation '${action}' is invalid from state '${session.state}'` };
299
- if (errorCode === 'capacity')
300
- return { ok: false, code: errorCode, message: `Session at capacity (${session.maxMissions} missions)` };
301
- const nextUpdatedAt = new Date().toISOString();
302
- session.updatedAt = nextUpdatedAt;
303
- if (requestId) {
304
- session.mutationKeys = { ...(session.mutationKeys ?? {}), [requestId]: { action, target, updatedAt: nextUpdatedAt } };
305
- }
306
- await writeSession(session, { touch: false });
307
- await appendLog(session.id, { event: `control_${action}`, target, requestId: requestId ?? null, replayed: false, revision: session.updatedAt });
308
- return { ok: true, session, replayed: false };
309
- }
310
- finally {
311
- await lock.close();
312
- await fs.unlink(lockPath).catch(() => undefined);
313
- }
314
- }
315
- function mutationFlags(args) {
316
- return {
317
- expectedUpdatedAt: parseFlag(args, '--expected-updated-at'),
318
- requestId: parseFlag(args, '--request-id'),
319
- };
320
- }
321
- function mutationFailure(result) {
322
- ui.error(`${result.code}: ${result.message}`);
323
- return { exitCode: result.code === 'mission_conflict' ? 3 : 1, message: `${result.code}: ${result.message}` };
324
- }
325
- async function listSessions() {
326
- try {
327
- const entries = await fs.readdir(SESSIONS_DIR, { withFileTypes: true });
328
- const sessions = [];
329
- for (const entry of entries) {
330
- if (entry.isDirectory()) {
331
- const s = await readSession(entry.name);
332
- if (s)
333
- sessions.push(s);
334
- }
335
- }
336
- return sessions;
337
- }
338
- catch {
339
- return [];
340
- }
341
- }
342
- async function findActiveSession(sessionIdArg) {
343
- if (sessionIdArg)
344
- return readSession(sessionIdArg);
345
- // Find latest active session
346
- const sessions = await listSessions();
347
- const active = sessions
348
- .filter(s => s.state === 'active' || s.state === 'paused')
349
- .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
350
- return active[0] || null;
351
- }
352
- function parseFlag(args, flag) {
353
- for (let i = 0; i < args.length; i++) {
354
- if (args[i] === flag) {
355
- return i + 1 < args.length ? args[i + 1] : undefined;
356
- }
357
- // Support --flag=value — previously silently ignored, which for budget
358
- // flags meant an unbounded loop the operator believed was capped (#1770)
359
- if (args[i].startsWith(`${flag}=`)) {
360
- return args[i].slice(flag.length + 1);
361
- }
362
- }
363
- return undefined;
364
- }
365
- function hasFlag(args, flag) {
366
- return args.includes(flag);
367
- }
368
- /**
369
- * Parse a numeric flag. A flag that is PRESENT but not a positive number is a
370
- * usage error collected into `invalidSink` — silently dropping it used to
371
- * dispatch missions with no ceiling while the operator believed one applied
372
- * (#1770).
373
- */
374
- function parseNumberFlag(args, flag, invalidSink, integer = false) {
375
- if (!args.some(arg => arg === flag || arg.startsWith(`${flag}=`)))
376
- return undefined;
377
- const raw = parseFlag(args, flag);
378
- // Presence and validity are distinct: a trailing flag must not silently
379
- // disappear, and counter limits must not accept fractional/unsafe values.
380
- const decimal = typeof raw === 'string' && /^[+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(raw);
381
- const value = decimal ? Number(raw) : NaN;
382
- if (!Number.isFinite(value) || value <= 0 || (integer && !Number.isSafeInteger(value))) {
383
- invalidSink?.push(`${flag} (got '${raw}')`);
384
- return undefined;
385
- }
386
- return value;
387
- }
388
- function wantsHelp(args) {
389
- return args.includes('--help') || args.includes('-h');
390
- }
391
- /**
392
- * Per-subcommand usage strings (#1440).
393
- *
394
- * `aiwg mc <subcommand> --help` MUST print this text and exit before any
395
- * side-effecting logic. The previous behavior — running `aiwg mc start --help`
396
- * actually created a session — violated the universal `--help` convention.
397
- */
398
- const subcommandUsage = {
399
- start: `Usage: aiwg mc start [--name "<label>"] [--max-missions N]
400
-
401
- Create a new Mission Control session for tracking background missions.
402
-
403
- --name <label> Human-readable session name (default: "Mission YYYY-MM-DD")
404
- --max-missions N Capacity limit for queued missions (default: 10)
405
-
406
- Note: 'start' only creates the session. Use 'dispatch' to queue missions and
407
- 'run' to drain the queue.`,
408
- dispatch: `Usage: aiwg mc dispatch <session-id> "<objective>" [options]
409
-
410
- Queue a mission onto a session. Does NOT execute — use 'aiwg mc run' to launch.
411
-
412
- --completion "<criteria>" Verifiable completion criteria (required for 'mc run')
413
- --priority <level> Priority hint (default: normal)
414
- --max-iterations N Ralph iteration cap when launched (default: 10)
415
- --max-total-tokens N Hard cumulative token ceiling when observable
416
- --max-output-tokens N Hard cumulative output-token ceiling
417
- --max-tool-calls N Hard cumulative tool-call ceiling
418
- --max-total-cost USD Hard cumulative provider-reported spend ceiling
419
- --max-wall-clock-minutes N Hard cumulative runtime ceiling
420
- --exploration-quota K Require structural variant after K flat cycles
421
- (off unless declared; no default K)
422
- --budget-stop-policy P completion-wins (default) | budget-wins
423
- --mode pty-orchestrator PTY-orchestrator mode (requires --target-agent)
424
- --target-agent <id> Required for --mode pty-orchestrator
425
- --worker-dispatch <path> Prepared managed worker dispatch JSON (queues only)
426
- --expected-updated-at <time> Reject stale state with exit 3
427
- --request-id <id> Idempotent dispatch key`,
428
- run: `Usage: aiwg mc run [<session-id>] [--accept-cost]
429
-
430
- Drain queued missions in a session by launching each as a ralph loop. Missions
431
- without --completion criteria are skipped with a warning.
432
-
433
- --accept-cost Skip the cost-warning gate (required for non-TTY contexts
434
- when estimated cumulative cost exceeds $5). See #1450.
435
-
436
- The estimate is the cumulative iteration floor (missions x max-iterations x
437
- ~$1.60 cache cost per headless iteration). A mission's --max-total-cost caps its
438
- share of that estimate only on a provider that reports spend; on a provider that
439
- reports none the ceiling is inert (#1766), so it is reported but not subtracted.
440
- See #2522.`,
441
- status: `Usage: aiwg mc status [<session-id>] [--json]
442
-
443
- Show mission status for a session. Auto-syncs from ralph loop state files.
444
-
445
- --json Emit JSON instead of human-readable table`,
446
- watch: `Usage: aiwg mc watch [<session-id>]
447
-
448
- Live-monitor mission progress (non-interactive context prints status once).`,
449
- abort: `Usage: aiwg mc abort <session-id> <mission-id>
450
-
451
- Mark a specific mission as aborted.
452
-
453
- --expected-updated-at <timestamp> Reject stale state with exit 3
454
- --request-id <id> Idempotent mutation key`,
455
- pause: `Usage: aiwg mc pause [<session-id>]
456
-
457
- Pause an active session; running missions transition to 'paused' status.
458
-
459
- --expected-updated-at <timestamp> Reject stale state with exit 3
460
- --request-id <id> Idempotent mutation key`,
461
- resume: `Usage: aiwg mc resume [<session-id>]
462
-
463
- Resume a paused session; paused missions transition back to 'running'.
464
-
465
- --expected-updated-at <timestamp> Reject stale state with exit 3
466
- --request-id <id> Idempotent mutation key`,
467
- stop: `Usage: aiwg mc stop [<session-id>] [--drain]
468
-
469
- Shut down a session.
470
-
471
- --drain Cancel queued, let running finish (default: abort all non-completed)`,
472
- list: `Usage: aiwg mc list [--json]
473
-
474
- List all Mission Control sessions.`,
475
- agents: `Usage: aiwg mc agents [filters] [--json]
476
-
477
- Query routable agents from a local 'aiwg serve' instance.
478
-
479
- --framework <name> Require an AIWG framework (repeatable)
480
- --sandbox <id> Restrict to a sandbox
481
- --agent <id> Restrict to a specific agent ID
482
- --name <n> Match by logical name
483
- --max-cpu <pct> Reject agents above this CPU %
484
- --min-memory <gb> Reject agents below this memory threshold
485
- --json Output raw JSON`,
486
- };
487
- function printSubcommandHelp(name) {
488
- const text = subcommandUsage[name];
489
- ui.blank();
490
- if (text) {
491
- console.log(` ${text}`);
492
- }
493
- else {
494
- console.log(` No detailed help for 'aiwg mc ${name}'. Run 'aiwg mc --help' for the full reference.`);
495
- }
496
- ui.blank();
497
- }
498
- function getPositionalArgs(args) {
499
- const positional = [];
500
- for (let i = 0; i < args.length; i++) {
501
- if (args[i].startsWith('--')) {
502
- // Skip flag and its value if it has one
503
- if (i + 1 < args.length && !args[i + 1].startsWith('--'))
504
- i++;
505
- continue;
506
- }
507
- positional.push(args[i]);
508
- }
509
- return positional;
510
- }
511
- // ── Subcommand handlers ──────────────────────────────────────
512
- async function mcStart(ctx) {
513
- const name = parseFlag(ctx.args, '--name') || `Mission ${new Date().toISOString().slice(0, 10)}`;
514
- const maxMissions = parseInt(parseFlag(ctx.args, '--max-missions') || '10', 10);
515
- const session = {
516
- id: genId('mc'),
517
- name,
518
- state: 'active',
519
- maxMissions,
520
- createdAt: new Date().toISOString(),
521
- updatedAt: new Date().toISOString(),
522
- missions: [],
523
- };
524
- await writeSession(session);
525
- await appendLog(session.id, { event: 'session_started', name, maxMissions });
526
- ui.blank();
527
- console.log(` ${ui.brandMark()} ${ui.bold('Mission Control')} — ${ui.accent(name)}`);
528
- ui.rule();
529
- ui.success(`Session started: ${session.id}`);
530
- ui.info(`Max missions: ${maxMissions}`);
531
- // #1439: the lifecycle is start → dispatch → run → status. State this
532
- // up-front so users don't get stuck wondering why missions never execute.
533
- ui.info(`Next: \`aiwg mc dispatch ${session.id} "<objective>" --completion "<criteria>"\``);
534
- ui.info(`Then: \`aiwg mc run ${session.id}\` to drain the queue (missions stay 'queued' until you do).`);
535
- ui.blank();
536
- return { exitCode: 0, message: session.id };
537
- }
538
- async function mcDispatch(ctx) {
539
- const positional = getPositionalArgs(ctx.args);
540
- const sessionId = positional[0];
541
- const objective = positional.slice(1).join(' ') || parseFlag(ctx.args, '--objective');
542
- const completion = parseFlag(ctx.args, '--completion');
543
- const priority = parseFlag(ctx.args, '--priority') || 'normal';
544
- const invalidFlags = [];
545
- const maxIterations = parseNumberFlag(ctx.args, '--max-iterations', invalidFlags, true) ?? 10;
546
- const maxTotalTokens = parseNumberFlag(ctx.args, '--max-total-tokens', invalidFlags, true);
547
- const maxOutputTokens = parseNumberFlag(ctx.args, '--max-output-tokens', invalidFlags, true);
548
- const maxToolCalls = parseNumberFlag(ctx.args, '--max-tool-calls', invalidFlags, true);
549
- const maxTotalCost = parseNumberFlag(ctx.args, '--max-total-cost', invalidFlags);
550
- const maxWallClockMinutes = parseNumberFlag(ctx.args, '--max-wall-clock-minutes', invalidFlags);
551
- const explorationQuota = parseNumberFlag(ctx.args, '--exploration-quota', invalidFlags, true);
552
- const budgetStopPolicyRaw = parseFlag(ctx.args, '--budget-stop-policy');
553
- let budgetStopPolicy;
554
- if (budgetStopPolicyRaw !== undefined) {
555
- if (budgetStopPolicyRaw === 'completion-wins' || budgetStopPolicyRaw === 'budget-wins') {
556
- budgetStopPolicy = budgetStopPolicyRaw;
557
- }
558
- else {
559
- invalidFlags.push(`--budget-stop-policy (got '${budgetStopPolicyRaw}', expected completion-wins|budget-wins)`);
560
- }
561
- }
562
- const modeRaw = parseFlag(ctx.args, '--mode') || 'direct';
563
- const mode = modeRaw === 'pty-orchestrator' ? 'pty-orchestrator' : 'direct';
564
- const targetAgent = parseFlag(ctx.args, '--target-agent');
565
- if (!objective) {
566
- // #1438: keep this in sync with subcommandUsage.dispatch above so 'mc
567
- // dispatch' with bad args and 'mc dispatch --help' agree on flags.
568
- ui.error('Usage: aiwg mc dispatch <session-id> "<objective>" [--completion "<criteria>"] [--max-iterations N] [--priority <level>] [--mode pty-orchestrator] [--target-agent <agent-id>]');
569
- return { exitCode: 1 };
570
- }
571
- if (invalidFlags.length > 0) {
572
- ui.error(`Invalid numeric flag value(s): ${invalidFlags.join(', ')}. Budget/quota flags require positive numbers. Mission not dispatched.`);
573
- return { exitCode: 1 };
574
- }
575
- if (mode === 'pty-orchestrator' && !targetAgent) {
576
- ui.error('--mode pty-orchestrator requires --target-agent <agent-id>');
577
- return { exitCode: 1 };
578
- }
579
- const selected = await findActiveSession(sessionId);
580
- if (!selected) {
581
- ui.error(sessionId ? `Session not found: ${sessionId}` : 'No active session. Run `aiwg mc start` first.');
582
- return { exitCode: 1 };
583
- }
584
- // mission-dispatch accepts only the frozen objective envelope. Worker
585
- // bindings can arrive through its existing session, so inspect that payload.
586
- try {
587
- const cfg = await readAdmissionConfig(ctx.cwd || process.cwd());
588
- const support = cfg?.parallelism?.worker_dispatch && cfg.parallelism.worker_mode === 'managed' ? mcWorkerSupport() : undefined;
589
- assertMissionWorkerHandoff(selected, 'mc-cli', support);
590
- for (const mission of selected.missions)
591
- assertMissionWorkerHandoff(mission, 'mc-cli', support);
592
- }
593
- catch (error) {
594
- const message = error instanceof Error ? error.message : String(error);
595
- ui.error(message);
596
- return { exitCode: 1, message };
597
- }
598
- // #1361: Check project-level parallelism cap. Active missions = running or
599
- // queued; if at cap, warn but still queue (FIFO behavior — the mission goes
600
- // into the session as 'queued' and will run when a slot frees up).
601
- let capWarning;
602
- try {
603
- const { readAiwgConfig, resolveParallelism } = await import('../../config/aiwg-config.js');
604
- const cfg = await readAiwgConfig(ctx.cwd || process.cwd());
605
- if (cfg) {
606
- const resolved = resolveParallelism(cfg.parallelism, cfg.providers[0]);
607
- const activeCount = selected.missions.filter(m => m.status === 'running' || m.status === 'queued' || m.status === 'paused').length;
608
- if (activeCount >= resolved.max_parallel_mc_missions) {
609
- capWarning = `Active missions (${activeCount}) at or above project parallelism cap (${resolved.max_parallel_mc_missions}). Mission will queue; bump via 'aiwg config set --project parallelism.max_parallel_mc_missions N'.`;
610
- }
611
- }
612
- }
613
- catch {
614
- // Non-fatal — config read failure doesn't block dispatch
615
- }
616
- const flags = mutationFlags(ctx.args);
617
- const mission = {
618
- id: flags.requestId
619
- ? `m-${createHash('sha256').update(flags.requestId).digest('hex').slice(0, 16)}`
620
- : genId('m'),
621
- objective,
622
- completion,
623
- status: 'queued',
624
- loop: 0,
625
- maxIterations,
626
- maxTotalTokens,
627
- maxOutputTokens,
628
- maxToolCalls,
629
- maxTotalCost,
630
- maxWallClockMinutes,
631
- explorationQuota,
632
- budgetStopPolicy,
633
- priority,
634
- mode,
635
- targetAgent: targetAgent || undefined,
636
- };
637
- const dispatchPath = parseFlag(ctx.args, '--worker-dispatch');
638
- if (dispatchPath) {
639
- try {
640
- const cfg = await readAdmissionConfig(ctx.cwd || process.cwd());
641
- if (!cfg?.parallelism?.worker_dispatch || cfg.parallelism.worker_mode !== 'managed' || mode !== 'direct') {
642
- throw new Error('OG_CONTRACT_UNSUPPORTED: worker dispatch requires the managed MC caller');
643
- }
644
- if (!isAbsolute(dispatchPath) || relative(ctx.cwd, dispatchPath).startsWith('..'))
645
- throw new Error('Worker dispatch path must be inside the project');
646
- const dispatch = await readWorkerJson(dispatchPath);
647
- mission.extensions = { 'aiwg.worker-dispatch': dispatch };
648
- assertMissionWorkerHandoff(mission, 'mc-cli', mcWorkerSupport());
649
- await resolveMcWorker(ctx, selected, mission);
650
- }
651
- catch (error) {
652
- return managedControlFailure(error);
653
- }
654
- }
655
- const result = await mutateSession(selected.id, 'dispatch', mission.id, flags.expectedUpdatedAt, flags.requestId, session => {
656
- if (session.state !== 'active')
657
- return 'invalid_state';
658
- if (session.missions.length >= session.maxMissions)
659
- return 'capacity';
660
- session.missions.push(mission);
661
- return undefined;
662
- });
663
- if (!result.ok)
664
- return mutationFailure(result);
665
- if (!result.replayed) {
666
- await appendLog(selected.id, {
667
- event: 'mission_dispatched',
668
- missionId: mission.id,
669
- objective,
670
- priority,
671
- mode,
672
- targetAgent,
673
- requestId: flags.requestId ?? null,
674
- lfdBudgets: {
675
- maxTotalTokens,
676
- maxOutputTokens,
677
- maxToolCalls,
678
- maxTotalCost,
679
- maxWallClockMinutes,
680
- explorationQuota,
681
- },
682
- });
683
- }
684
- if (capWarning)
685
- ui.warn(capWarning);
686
- ui.success(`${result.replayed ? 'Replayed dispatch for' : 'Dispatched mission'} ${mission.id}: ${objective}`);
687
- const modeLabel = mode === 'pty-orchestrator' ? ` | Mode: PTY orchestrator → ${targetAgent}` : '';
688
- ui.info(`Priority: ${priority} | Max iterations: ${maxIterations}${modeLabel}`);
689
- const lfdLimits = [
690
- maxTotalTokens ? `total tokens ${maxTotalTokens}` : null,
691
- maxOutputTokens ? `output tokens ${maxOutputTokens}` : null,
692
- maxToolCalls ? `tool calls ${maxToolCalls}` : null,
693
- maxTotalCost ? `total cost $${maxTotalCost}` : null,
694
- maxWallClockMinutes ? `wall clock ${maxWallClockMinutes}m` : null,
695
- explorationQuota ? `exploration quota ${explorationQuota}` : null,
696
- ].filter(Boolean);
697
- if (lfdLimits.length > 0) {
698
- ui.info(`LFD limits: ${lfdLimits.join(' | ')}`);
699
- }
700
- // #1439: dispatch alone does NOT execute the mission. Surface the next step
701
- // so the user knows the queue won't drain on its own.
702
- ui.info(`Next: run \`aiwg mc run ${selected.id}\` to launch queued missions as ralph loops.`);
703
- return { exitCode: 0, message: mission.id };
704
- }
705
- /**
706
- * Drain queued missions in a session by launching each as a ralph loop (#1439).
707
- *
708
- * Before this command existed, missions sat in `queued` status forever because
709
- * no supervisor process drained the queue. `mc run` is the explicit supervisor
710
- * step: for every queued direct-mode mission, spawn a detached ralph process
711
- * via launchExternalRalph(), record the resulting loopId + pid on the mission,
712
- * and flip the mission to `running`.
713
- *
714
- * Status sync back from ralph to mc happens lazily via syncMissionsFromRalph()
715
- * called from `mc status` and `mc watch` — no separate daemon needed.
716
- *
717
- * Limitations of cycle 1:
718
- * - pty-orchestrator missions are skipped with a warning (separate codepath)
719
- * - missions launch sequentially (each call to launchExternalRalph spawns a
720
- * detached process, so they DO run in parallel after launch — the loop here
721
- * is just for orderly dispatch, not for parallel scheduling)
722
- */
723
- /**
724
- * Per-iteration cache-creation floor for a headless claude session (sonnet
725
- * baseline; opus is ~$3.90).
726
- */
727
- export const SONNET_CACHE_USD = 1.60;
728
- /** Estimate at or above which `mc run` warns and refuses in non-TTY contexts. */
729
- export const COST_WARNING_THRESHOLD_USD = 5.0;
730
- /**
731
- * Providers whose headless stream reports spend, so a declared `--max-total-cost`
732
- * ceiling can actually fire mid-loop.
733
- *
734
- * Only `claude` emits cost on its stream-json events, which is what
735
- * `SessionLauncher._extractUsageStats` reads. Adapters without stream-json
736
- * (codex, factory, opencode, deepseek) emit no usage events at all — #1766
737
- * recorded that a spend ceiling on those is inert and never fires. Adapters that
738
- * do stream JSON but have not been observed carrying cost fields (omp, pi) stay
739
- * out of this set deliberately: assuming an observability we have not seen would
740
- * weaken the gate in exactly the case where the operator has least protection.
741
- */
742
- export const COST_REPORTING_PROVIDERS = new Set(['claude']);
743
- /**
744
- * Estimate cumulative spend for a set of queued missions (#2522).
745
- *
746
- * The floor for each mission is `maxIterations × SONNET_CACHE_USD`. A declared
747
- * `maxTotalCost` bounds that floor **only** when the target provider reports
748
- * spend — on a provider that reports none, the ceiling is inert (#1766), so
749
- * subtracting it would make the warning weaker precisely where the operator has
750
- * no enforced protection. Those ceilings are counted and surfaced instead.
751
- */
752
- export function estimateMissionRunCost(missions, provider) {
753
- const spendObservable = COST_REPORTING_PROVIDERS.has(provider);
754
- let estimateUsd = 0;
755
- let iterationFloorUsd = 0;
756
- let declaredCeilingUsd = 0;
757
- let cappedMissions = 0;
758
- let inertCeilingMissions = 0;
759
- for (const mission of missions) {
760
- const floor = mission.maxIterations * SONNET_CACHE_USD;
761
- iterationFloorUsd += floor;
762
- const ceiling = typeof mission.maxTotalCost === 'number' && Number.isFinite(mission.maxTotalCost)
763
- ? mission.maxTotalCost
764
- : undefined;
765
- if (ceiling === undefined) {
766
- estimateUsd += floor;
767
- continue;
768
- }
769
- declaredCeilingUsd += ceiling;
770
- if (spendObservable) {
771
- cappedMissions += 1;
772
- estimateUsd += Math.min(floor, ceiling);
773
- }
774
- else {
775
- inertCeilingMissions += 1;
776
- estimateUsd += floor;
777
- }
778
- }
779
- return {
780
- estimateUsd,
781
- iterationFloorUsd,
782
- declaredCeilingUsd,
783
- cappedMissions,
784
- inertCeilingMissions,
785
- spendObservable,
786
- };
787
- }
788
- async function mcRun(ctx) {
789
- const positional = getPositionalArgs(ctx.args);
790
- const sessionId = positional[0];
791
- const acceptCost = hasFlag(ctx.args, '--accept-cost');
792
- const session = await findActiveSession(sessionId);
793
- if (!session) {
794
- ui.error(sessionId ? `Session not found: ${sessionId}` : 'No active session. Run `aiwg mc start` first.');
795
- return { exitCode: 1 };
796
- }
797
- const queued = session.missions.filter((m) => m.status === 'queued');
798
- let cfg;
799
- try {
800
- cfg = await readAdmissionConfig(ctx.cwd || process.cwd());
801
- const support = cfg?.parallelism?.worker_dispatch && cfg.parallelism.worker_mode === 'managed' ? mcWorkerSupport() : undefined;
802
- assertMissionWorkerHandoff(session, 'mc-cli', support);
803
- for (const mission of queued)
804
- assertMissionWorkerHandoff(mission, 'mc-cli', support);
805
- }
806
- catch (error) {
807
- const message = error instanceof Error ? error.message : String(error);
808
- ui.error(message);
809
- return { exitCode: 1, message };
810
- }
811
- if (queued.length === 0) {
812
- ui.info(`No queued missions in session ${session.id}. Run \`aiwg mc dispatch ${session.id} "<objective>"\` to add one.`);
813
- return { exitCode: 0 };
814
- }
815
- // #1450 P0: cost warning gate, with declared ceilings honored (#2522).
816
- //
817
- // Each headless claude session pays a ~$1.60 cache-creation cost on iteration
818
- // 1 before any user-meaningful work (sonnet baseline; opus is ~$3.90). Across
819
- // N missions × M iterations the floor compounds quickly. Warn before launch
820
- // and refuse in non-TTY contexts unless --accept-cost is set.
821
- const eligible = queued.filter(m => m.mode !== 'pty-orchestrator' && !!m.completion);
822
- const projectRoot = ctx.cwd || process.cwd();
823
- const frameworkRoot = ctx.frameworkRoot;
824
- let scheduler;
825
- try {
826
- scheduler = await createMcAdmissionScheduler(projectRoot, cfg);
827
- }
828
- catch (error) {
829
- const message = error instanceof Error ? error.message : String(error);
830
- ui.error(message);
831
- return { exitCode: 1, message };
832
- }
833
- const provider = cfg?.providers[0] ?? 'unknown';
834
- const estimate = estimateMissionRunCost(eligible, provider);
835
- if (estimate.estimateUsd >= COST_WARNING_THRESHOLD_USD && !acceptCost) {
836
- ui.blank();
837
- ui.warn(`Cost estimate: ~$${estimate.estimateUsd.toFixed(2)} (${eligible.length} missions × iteration floors × ~$${SONNET_CACHE_USD.toFixed(2)} cache cost per claude headless iter).`);
838
- if (estimate.cappedMissions > 0) {
839
- ui.warn(`Declared ceilings: $${estimate.declaredCeilingUsd.toFixed(2)} across ${estimate.cappedMissions} mission(s) — counted toward the estimate because ${provider} reports spend.`);
840
- }
841
- if (estimate.inertCeilingMissions > 0) {
842
- 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).`);
843
- }
844
- ui.warn('Actual spend may be lower if missions complete early, higher if model is opus or context grows.');
845
- if (!process.stdout.isTTY) {
846
- ui.error('Refusing to launch in non-interactive context. Re-run with `--accept-cost` to proceed.');
847
- return { exitCode: 1 };
848
- }
849
- // TTY path: surface the warning and continue. A future revision should
850
- // prompt y/N here; for now the warning is informational and the operator
851
- // can Ctrl+C before launches actually begin.
852
- ui.info('Continuing (TTY). Use Ctrl+C to abort within the next 2 seconds.');
853
- await new Promise((resolve) => setTimeout(resolve, 2000));
854
- }
855
- ui.blank();
856
- console.log(` ${ui.brandMark()} ${ui.bold('Mission Control')} — running ${queued.length} queued mission(s) in ${ui.accent(session.id)}`);
857
- ui.rule();
858
- // Lazy import — ralph-launcher pulls in node:child_process and other heavy
859
- // deps we don't want to pay for on every mc subcommand.
860
- const { launchExternalRalph } = await import('./ralph-launcher.js');
861
- let launched = 0;
862
- let skipped = 0;
863
- let failed = 0;
864
- const managed = cfg?.parallelism?.worker_dispatch && cfg.parallelism.worker_mode === 'managed';
865
- const allowanceOwner = managed ? await import('../../serve/shared-host-scheduler.js') : null;
866
- // Qualify every worker before admission; one parent retains completion gates.
867
- const workers = new Map();
868
- try {
869
- for (const mission of queued)
870
- if (workerDispatch(mission))
871
- workers.set(mission.id, await resolveMcWorker(ctx, session, mission));
872
- }
873
- catch (error) {
874
- return managedControlFailure(error);
875
- }
876
- for (const mission of queued) {
877
- const worker = workers.get(mission.id);
878
- if (mission.mode === 'pty-orchestrator') {
879
- ui.warn(`Mission ${mission.id} mode=pty-orchestrator is not yet wired to mc run; skipping. Use 'aiwg ralph' directly for PTY-orchestrator workflows.`);
880
- skipped += 1;
881
- continue;
882
- }
883
- if (!mission.completion) {
884
- ui.warn(`Mission ${mission.id} has no --completion criteria; ralph requires one. Skipping. Re-dispatch with --completion "<criteria>" to include this mission.`);
885
- skipped += 1;
886
- continue;
887
- }
888
- const admissionRequestId = mission.admissionState === 'released'
889
- ? `${session.id}.${mission.id}.${Date.now().toString(36)}`
890
- : mission.admissionRequestId ?? worker?.dispatch.requestId ?? `${session.id}.${mission.id}`;
891
- const admissionSubmittedAt = mission.admissionState === 'released'
892
- ? new Date().toISOString()
893
- : mission.admissionSubmittedAt ?? new Date().toISOString();
894
- const admission = scheduler.submit({
895
- requestId: admissionRequestId,
896
- orchestratorId: session.id,
897
- environment: process.env.AIWG_ENVIRONMENT ?? 'default',
898
- provider: worker?.plan.invocation?.selected.inferenceProvider ?? provider,
899
- runtimeKind: 'host',
900
- priority: mission.priority === 'critical' ? 100 : mission.priority === 'high' ? 50 : mission.priority === 'low' ? 0 : 10,
901
- submittedAt: admissionSubmittedAt,
902
- queueTimeoutMs: managed ? (cfg?.parallelism?.admission?.queueTimeoutSeconds ?? 300) * 1000 : 24 * 60 * 60_000,
903
- preemptible: false,
904
- metadata: { missionId: mission.id, ...(worker ? { invocationId: worker.dispatch.invocationId } : {}) },
905
- ...(managed ? { managed: worker ? { kind: 'external', group: worker.plan.selected.group,
906
- member: worker.plan.selected.member, cli: worker.plan.selected.cli, model: worker.plan.selected.modelKey,
907
- quotaScope: cfg.parallelism.clis[worker.plan.selected.cli].quotaScope } : { kind: 'native' },
908
- allowance: worker ? { runId: session.id, taskId: worker.intent.taskId,
909
- taskBudgets: { maxAttempts: Math.min(worker.intent.limits.maxAttempts, mission.maxIterations),
910
- maxTokens: Math.min(worker.intent.limits.tokens, mission.maxTotalTokens ?? Infinity),
911
- maxCostUsd: worker.intent.limits.costUsd === null ? mission.maxTotalCost
912
- : Math.min(worker.intent.limits.costUsd, mission.maxTotalCost ?? Infinity),
913
- timeoutSeconds: Math.min(worker.intent.limits.wallSeconds, (mission.maxWallClockMinutes ?? Infinity) * 60) },
914
- reservation: { tokens: worker.plan.invocation.limits.tokens, costUsd: worker.plan.invocation.limits.costUsd },
915
- } : allowanceOwner.managedAllowanceFromOwner(session.id, mission.id, {
916
- kind: 'ralph', maxIterations: mission.maxIterations, maxTotalTokens: mission.maxTotalTokens,
917
- maxTotalCost: mission.maxTotalCost, maxWallClockMinutes: mission.maxWallClockMinutes,
918
- }),
919
- } : {}),
920
- });
921
- mission.admissionRequestId = admissionRequestId;
922
- mission.admissionSubmittedAt = admissionSubmittedAt;
923
- mission.admissionState = admission.state;
924
- mission.admissionLeaseExpiresAt = admission.leaseExpiresAt;
925
- if (managed)
926
- mission.admissionGeneration = admission.leaseGeneration;
927
- await writeSession(session);
928
- if (admission.state !== 'admitted') {
929
- await appendLog(session.id, {
930
- event: 'mission_admission_queued',
931
- missionId: mission.id,
932
- admissionRequestId,
933
- reason: admission.reason,
934
- });
935
- ui.info(`Queued ${mission.id}: ${admission.reason}`);
936
- skipped += 1;
937
- continue;
938
- }
939
- try {
940
- let maxWallClockMinutes = mission.maxWallClockMinutes;
941
- if (managed) {
942
- const scopes = scheduler.snapshot().allowances;
943
- const deadlines = [scopes[admission.accounting.runKey].deadlineAt, scopes[admission.accounting.taskKey].deadlineAt]
944
- .filter((value) => value !== undefined).map(Date.parse);
945
- const remainingMs = Math.min(...deadlines) - Date.now();
946
- if (remainingMs <= 0)
947
- throw new Error('cumulative allowance deadline elapsed before launch');
948
- maxWallClockMinutes = deadlines.length ? remainingMs / 60_000 : undefined;
949
- }
950
- if (worker) {
951
- if (worker.brief.lease.generation !== mission.admissionGeneration || worker.brief.lease.reservationId !== admissionRequestId
952
- || worker.brief.lease.authorityRef !== 'project')
953
- throw new Error('Managed brief lease differs from current admission');
954
- const invocationPath = join(projectRoot, SESSIONS_DIR, session.id, `${mission.id}.invocation.json`);
955
- const runDir = join(projectRoot, SESSIONS_DIR, session.id, `${mission.id}.run`);
956
- await fs.writeFile(invocationPath, JSON.stringify(worker.plan), { mode: 0o600 });
957
- mission.managedWorker = { invocationPath, runDir };
958
- }
959
- if (managed) {
960
- scheduler.claimLaunch(admissionRequestId, mission.admissionGeneration);
961
- mission.admissionLaunchClaimed = true;
962
- await writeSession(session);
963
- }
964
- const result = await launchExternalRalph(frameworkRoot, projectRoot, {
965
- objective: mission.objective,
966
- completionCriteria: mission.completion,
967
- maxIterations: managed ? admission.accounting.attemptCount : mission.maxIterations,
968
- maxTotalTokens: managed ? admission.accounting.reservation.tokens ?? undefined : mission.maxTotalTokens,
969
- maxOutputTokens: mission.maxOutputTokens,
970
- maxToolCalls: mission.maxToolCalls,
971
- maxTotalCost: managed ? admission.accounting.reservation.costUsd ?? undefined : mission.maxTotalCost,
972
- maxWallClockMinutes,
973
- explorationQuota: mission.explorationQuota,
974
- budgetStopPolicy: mission.budgetStopPolicy,
975
- // Defaults for cycle 1; advanced options can be added per-mission later.
976
- verbose: false,
977
- ...(managed ? { managedAdmission: { requestId: admissionRequestId, generation: mission.admissionGeneration } } : {}),
978
- ...(worker ? { managedWorker: mission.managedWorker } : {}),
979
- });
980
- if (managed) {
981
- if (!result.execution || result.execution.pid !== result.pid)
982
- throw new Error('managed launch requires its OS process birth identity');
983
- scheduler.bindExecution(admissionRequestId, mission.admissionGeneration, result.execution);
984
- mission.admissionExecution = result.execution;
985
- mission.ralphLoopId = result.loopId;
986
- mission.ralphPid = result.pid;
987
- const current = scheduler.renew(admissionRequestId, mission.admissionGeneration);
988
- if (current.state !== 'admitted') {
989
- await cancelManagedMission(ctx, scheduler, mission);
990
- throw new Error('managed launch lost admission during execution checkpoint; reconcile uncertain work');
991
- }
992
- }
993
- mission.status = 'running';
994
- if (worker)
995
- worker.dispatch.state = 'running';
996
- mission.startedAt = new Date().toISOString();
997
- mission.ralphLoopId = result.loopId;
998
- mission.ralphPid = result.pid;
999
- await writeSession(session);
1000
- await appendLog(session.id, {
1001
- event: 'mission_started',
1002
- missionId: mission.id,
1003
- loopId: result.loopId,
1004
- pid: result.pid,
1005
- });
1006
- ui.success(`Started ${mission.id} → ralph loop ${result.loopId} (PID ${result.pid})`);
1007
- launched += 1;
1008
- }
1009
- catch (err) {
1010
- const msg = err instanceof Error ? err.message : String(err);
1011
- mission.status = 'failed';
1012
- mission.error = msg;
1013
- mission.completedAt = new Date().toISOString();
1014
- if (managed)
1015
- mission.admissionState = scheduler.stop(admissionRequestId, mission.admissionGeneration, 'observer-loss').state;
1016
- else {
1017
- scheduler.release(admissionRequestId);
1018
- mission.admissionState = 'released';
1019
- }
1020
- mission.admissionLeaseExpiresAt = undefined;
1021
- await writeSession(session);
1022
- await appendLog(session.id, {
1023
- event: 'mission_launch_failed',
1024
- missionId: mission.id,
1025
- error: msg,
1026
- });
1027
- ui.error(`Failed to start ${mission.id}: ${msg}`);
1028
- failed += 1;
1029
- }
1030
- }
1031
- ui.blank();
1032
- ui.info(`Launched: ${launched} | Skipped: ${skipped} | Failed: ${failed}`);
1033
- if (launched > 0) {
1034
- ui.info(`Monitor: \`aiwg mc status ${session.id}\` or \`aiwg mc watch ${session.id}\``);
1035
- }
1036
- return { exitCode: failed > 0 && launched === 0 ? 1 : 0 };
1037
- }
1038
- /**
1039
- * Sync mission statuses from their backing ralph loop state files (#1439).
1040
- *
1041
- * Each mission launched by `mc run` carries a `ralphLoopId`. The ralph loop
1042
- * writes its own session-state.json with a `status` field
1043
- * (running|completed|failed|paused|aborted). This helper polls those files
1044
- * and reflects the truth back into the mc session.json so `mc status` and
1045
- * `mc watch` show actual progress without manual intervention.
1046
- *
1047
- * Sync is best-effort — a missing or unreadable ralph state file leaves the
1048
- * mission status unchanged (typically 'running' until the ralph process
1049
- * actually writes state).
1050
- */
1051
- async function syncMissionsFromRalph(session, projectRoot) {
1052
- let mutated = false;
1053
- const cfg = await readAdmissionConfig(projectRoot);
1054
- const scheduler = await createMcAdmissionScheduler(projectRoot, cfg);
1055
- const managed = cfg?.parallelism?.worker_dispatch && cfg.parallelism.worker_mode === 'managed';
1056
- for (const mission of session.missions) {
1057
- const wasRunning = mission.status === 'running';
1058
- if (!wasRunning && !(managed && mission.managedWorker && mission.admissionState === 'uncertain'))
1059
- continue;
1060
- if (!mission.ralphLoopId)
1061
- continue;
1062
- const ralphStatePath = join(projectRoot, '.aiwg', 'ralph-external', 'loops', mission.ralphLoopId, 'session-state.json');
1063
- if (managed) {
1064
- const current = mission.admissionRequestId ? scheduler.snapshot().records[mission.admissionRequestId] : undefined;
1065
- if (!current || !mission.admissionGeneration || current.leaseGeneration !== mission.admissionGeneration)
1066
- continue;
1067
- }
1068
- try {
1069
- const state = managed && mission.managedWorker
1070
- ? await readManagedWorkerState(mission, scheduler)
1071
- : JSON.parse(await fs.readFile(ralphStatePath, 'utf-8'));
1072
- const ralphStatus = String(state.status || '').toLowerCase();
1073
- if (managed && mission.admissionRequestId && state.health !== undefined) {
1074
- if (!validateWorkerPayload('workerHealthSummary', state.health).valid)
1075
- throw new Error('invalid Ralph worker health');
1076
- const observed = scheduler.observeHealth(mission.admissionRequestId, mission.admissionGeneration, state.health);
1077
- mission.admissionState = observed.state;
1078
- mutated = true;
1079
- }
1080
- // Map ralph status → mc mission status
1081
- let nextStatus = null;
1082
- if (ralphStatus === 'completed')
1083
- nextStatus = 'done';
1084
- else if (ralphStatus === 'failed' || ralphStatus === 'crashed')
1085
- nextStatus = 'failed';
1086
- else if (ralphStatus === 'aborted')
1087
- nextStatus = 'aborted';
1088
- else if (ralphStatus === 'paused')
1089
- nextStatus = 'paused';
1090
- if (!wasRunning)
1091
- nextStatus = null;
1092
- // 'running' stays running
1093
- // Reflect iteration count if available
1094
- const iter = typeof state.iteration === 'number' ? state.iteration : (typeof state.currentIteration === 'number' ? state.currentIteration : null);
1095
- if (iter !== null && iter !== mission.loop) {
1096
- mission.loop = iter;
1097
- mutated = true;
1098
- }
1099
- // mission.status is narrowed to 'running' by the early-continue above,
1100
- // and nextStatus is one of {done, failed, aborted, paused}. So the
1101
- // transition is always real when nextStatus is set — no equality
1102
- // check needed.
1103
- if (nextStatus) {
1104
- mission.status = nextStatus;
1105
- mission.completedAt = new Date().toISOString();
1106
- if (nextStatus === 'failed' && typeof state.error === 'string') {
1107
- mission.error = state.error;
1108
- }
1109
- mutated = true;
1110
- if (mission.admissionRequestId) {
1111
- if (managed) {
1112
- if (!mission.managedWorker) {
1113
- if (state.health)
1114
- scheduler.acceptFinal(mission.admissionRequestId, mission.admissionGeneration, state.health);
1115
- }
1116
- if (mission.admissionState !== 'settled')
1117
- mission.admissionState = scheduler.stop(mission.admissionRequestId, mission.admissionGeneration, 'observer-loss').state;
1118
- }
1119
- else {
1120
- try {
1121
- scheduler.release(mission.admissionRequestId);
1122
- }
1123
- catch { /* already expired or released */ }
1124
- mission.admissionState = 'released';
1125
- }
1126
- mission.admissionLeaseExpiresAt = undefined;
1127
- }
1128
- }
1129
- else if (mission.admissionRequestId) {
1130
- try {
1131
- const renewed = managed
1132
- ? scheduler.renew(mission.admissionRequestId, mission.admissionGeneration)
1133
- : scheduler.renew(mission.admissionRequestId);
1134
- mission.admissionState = renewed.state;
1135
- mission.admissionLeaseExpiresAt = renewed.leaseExpiresAt;
1136
- mutated = true;
1137
- }
1138
- catch {
1139
- // An expired lease is reconciled on the next run; status remains best-effort.
1140
- }
1141
- }
1142
- }
1143
- catch {
1144
- if (managed && mission.admissionRequestId) {
1145
- mission.admissionState = scheduler.disconnect(mission.admissionRequestId, mission.admissionGeneration).state;
1146
- mission.admissionLeaseExpiresAt = undefined;
1147
- mutated = true;
1148
- }
1149
- // Missing supervision preserves the last task status and all artifacts.
1150
- }
1151
- }
1152
- if (mutated) {
1153
- session.updatedAt = new Date().toISOString();
1154
- await writeSession(session);
1155
- }
1156
- return mutated;
1157
- }
1158
- async function mcStatus(ctx) {
1159
- const positional = getPositionalArgs(ctx.args);
1160
- const sessionId = positional[0];
1161
- const json = hasFlag(ctx.args, '--json');
1162
- const session = await findActiveSession(sessionId);
1163
- if (!session) {
1164
- if (json) {
1165
- console.log(JSON.stringify({ error: 'no_active_session' }));
1166
- }
1167
- else {
1168
- ui.error(sessionId ? `Session not found: ${sessionId}` : 'No active session.');
1169
- }
1170
- return { exitCode: 1 };
1171
- }
1172
- // #1439: Sync mission statuses from ralph loop state files BEFORE display
1173
- // so 'mc status' reflects the true state of any in-flight ralph processes
1174
- // (otherwise missions launched by 'mc run' stay 'running' in mc.session.json
1175
- // even after the ralph loop has completed).
1176
- await syncMissionsFromRalph(session, ctx.cwd || process.cwd());
1177
- if (json) {
1178
- console.log(JSON.stringify(session, null, 2));
1179
- return { exitCode: 0 };
1180
- }
1181
- const statusIcons = {
1182
- done: '✓',
1183
- running: '⏳',
1184
- queued: '⏺',
1185
- failed: '✗',
1186
- aborted: '⊘',
1187
- paused: '⏸',
1188
- };
1189
- ui.blank();
1190
- console.log(` ${ui.brandMark()} ${ui.bold('MISSION CONTROL')} — ${ui.accent(session.name)} [${session.id}]`);
1191
- ui.rule(60);
1192
- // Header
1193
- // #1441: ui.dim() returns void (it prints) — wrapping in console.log emitted
1194
- // a literal "undefined" between the header and the separator. Use dimText()
1195
- // (returns a string) for inline styling.
1196
- const header = ` ${'#'.padEnd(4)} ${'Mission'.padEnd(32)} ${'Mode'.padEnd(6)} ${'Status'.padEnd(12)} ${'Loop'.padEnd(8)} ${'Started'.padEnd(8)}`;
1197
- console.log(ui.dimText(header));
1198
- ui.rule(68);
1199
- for (let i = 0; i < session.missions.length; i++) {
1200
- const m = session.missions[i];
1201
- const icon = statusIcons[m.status] || '?';
1202
- const num = String(i + 1).padEnd(4);
1203
- const obj = m.objective.length > 30 ? m.objective.slice(0, 27) + '...' : m.objective.padEnd(32);
1204
- const modeTag = m.mode === 'pty-orchestrator' ? 'PTY'.padEnd(6) : '—'.padEnd(6);
1205
- const status = `${icon} ${m.status.toUpperCase()}`.padEnd(12);
1206
- const loop = m.status === 'queued' ? '—'.padEnd(8) : `${m.loop}/${m.maxIterations}`.padEnd(8);
1207
- const started = m.startedAt ? new Date(m.startedAt).toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: false }) : '—';
1208
- console.log(` ${num} ${obj} ${modeTag} ${status} ${loop} ${started}`);
1209
- // Show last action for PTY-orchestrated missions
1210
- if (m.mode === 'pty-orchestrator' && m.lastAction && m.status === 'running') {
1211
- console.log(ui.dimText(` └─ Last: ${m.lastAction}`));
1212
- }
1213
- }
1214
- ui.rule(68);
1215
- const counts = {
1216
- done: session.missions.filter(m => m.status === 'done').length,
1217
- running: session.missions.filter(m => m.status === 'running').length,
1218
- queued: session.missions.filter(m => m.status === 'queued').length,
1219
- failed: session.missions.filter(m => m.status === 'failed').length,
1220
- };
1221
- console.log(` ${session.missions.length} missions | ${counts.done} done | ${counts.running} running | ${counts.queued} queued | ${counts.failed} failed`);
1222
- // #1361: Show project parallelism cap when one is configured.
1223
- try {
1224
- const { readAiwgConfig, resolveParallelism } = await import('../../config/aiwg-config.js');
1225
- const cfg = await readAiwgConfig(ctx.cwd || process.cwd());
1226
- if (cfg) {
1227
- const resolved = resolveParallelism(cfg.parallelism, cfg.providers[0]);
1228
- const active = counts.running + counts.queued;
1229
- const cap = resolved.max_parallel_mc_missions;
1230
- const overCap = active > cap ? ` ${ui.dim(`(${active - cap} over cap — queued)`)}` : '';
1231
- console.log(` Parallelism cap: ${active}/${cap} active${overCap}`);
1232
- }
1233
- }
1234
- catch {
1235
- // Non-fatal
1236
- }
1237
- ui.blank();
1238
- return { exitCode: 0 };
1239
- }
1240
- async function managedControlScheduler(ctx, missions) {
1241
- const projectRoot = ctx.cwd || process.cwd();
1242
- const cfg = await readAdmissionConfig(projectRoot);
1243
- if (!cfg?.parallelism?.worker_dispatch || cfg.parallelism.worker_mode !== 'managed')
1244
- return undefined;
1245
- const scheduler = await createMcAdmissionScheduler(projectRoot, cfg);
1246
- const snapshot = scheduler.snapshot();
1247
- for (const mission of missions) {
1248
- if (!mission.admissionRequestId)
1249
- continue;
1250
- const record = snapshot.records[mission.admissionRequestId];
1251
- if (!record || !mission.admissionGeneration || record.leaseGeneration !== mission.admissionGeneration) {
1252
- throw new Error('stale managed Mission checkpoint generation');
1253
- }
1254
- }
1255
- return scheduler;
1256
- }
1257
- function managedControlFailure(error) {
1258
- const message = error instanceof Error ? error.message : String(error);
1259
- ui.error(message);
1260
- return { exitCode: 1, message };
1261
- }
1262
- async function cancelManagedMission(ctx, scheduler, mission) {
1263
- if (!mission.admissionRequestId)
1264
- return;
1265
- const cancelled = scheduler.cancel(mission.admissionRequestId, mission.admissionGeneration);
1266
- mission.admissionState = cancelled.state;
1267
- mission.admissionLeaseExpiresAt = undefined;
1268
- if (cancelled.state !== 'uncertain' || !mission.ralphLoopId || !mission.admissionExecution)
1269
- return;
1270
- try {
1271
- const { cancelManagedRalph } = await import('./ralph-launcher.js');
1272
- await cancelManagedRalph(ctx.frameworkRoot, ctx.cwd || process.cwd(), mission.ralphLoopId, {
1273
- requestId: mission.admissionRequestId, generation: mission.admissionGeneration, execution: mission.admissionExecution,
1274
- });
1275
- }
1276
- catch {
1277
- // Reservation is already uncertain; unavailable signalling cannot release it.
1278
- }
1279
- }
1280
- async function mcAbort(ctx) {
1281
- const positional = getPositionalArgs(ctx.args);
1282
- const sessionId = positional[0];
1283
- const missionId = positional[1];
1284
- if (!sessionId || !missionId) {
1285
- ui.error('Usage: aiwg mc abort <session-id> <mission-id>');
1286
- return { exitCode: 1 };
1287
- }
1288
- let managedScheduler;
1289
- try {
1290
- const selected = await readSession(sessionId);
1291
- managedScheduler = await managedControlScheduler(ctx, selected?.missions.filter(mission => mission.id === missionId) ?? []);
1292
- }
1293
- catch (error) {
1294
- return managedControlFailure(error);
1295
- }
1296
- const flags = mutationFlags(ctx.args);
1297
- const result = await mutateSession(sessionId, 'cancel', missionId, flags.expectedUpdatedAt, flags.requestId, session => {
1298
- const mission = session.missions.find(m => m.id === missionId);
1299
- if (!mission)
1300
- return 'target_not_found';
1301
- if (mission.status === 'done' || mission.status === 'failed' || mission.status === 'aborted')
1302
- return 'invalid_state';
1303
- mission.status = 'aborted';
1304
- mission.completedAt = new Date().toISOString();
1305
- return undefined;
1306
- });
1307
- if (!result.ok)
1308
- return mutationFailure(result);
1309
- if (!result.replayed) {
1310
- const mission = result.session.missions.find(candidate => candidate.id === missionId);
1311
- if (mission?.admissionRequestId) {
1312
- try {
1313
- if (managedScheduler) {
1314
- await cancelManagedMission(ctx, managedScheduler, mission);
1315
- await writeSession(result.session);
1316
- }
1317
- else {
1318
- const projectRoot = ctx.cwd || process.cwd();
1319
- const cfg = await readAdmissionConfig(projectRoot);
1320
- const scheduler = await createMcAdmissionScheduler(projectRoot, cfg);
1321
- scheduler.cancel(mission.admissionRequestId);
1322
- }
1323
- }
1324
- catch (error) {
1325
- if (managedScheduler)
1326
- return managedControlFailure(error);
1327
- // Legacy leases keep their existing best-effort cancellation behavior.
1328
- }
1329
- }
1330
- }
1331
- ui.success(`${result.replayed ? 'Replayed' : 'Aborted'} mission: ${missionId}`);
1332
- return { exitCode: 0, message: JSON.stringify({ ok: true, replayed: result.replayed, updated_at: result.session.updatedAt }) };
1333
- }
1334
- async function mcPause(ctx) {
1335
- const positional = getPositionalArgs(ctx.args);
1336
- const sessionId = positional[0];
1337
- const selected = await findActiveSession(sessionId);
1338
- if (!selected) {
1339
- ui.error('No active session to pause.');
1340
- return { exitCode: 1 };
1341
- }
1342
- let managedScheduler;
1343
- try {
1344
- managedScheduler = await managedControlScheduler(ctx, selected.missions.filter(mission => mission.status === 'running'));
1345
- }
1346
- catch (error) {
1347
- return managedControlFailure(error);
1348
- }
1349
- const flags = mutationFlags(ctx.args);
1350
- const result = await mutateSession(selected.id, 'pause', selected.id, flags.expectedUpdatedAt, flags.requestId, session => {
1351
- if (session.state !== 'active')
1352
- return 'invalid_state';
1353
- session.state = 'paused';
1354
- for (const mission of session.missions)
1355
- if (mission.status === 'running')
1356
- mission.status = 'paused';
1357
- return undefined;
1358
- });
1359
- if (!result.ok)
1360
- return mutationFailure(result);
1361
- if (!result.replayed && managedScheduler) {
1362
- for (const mission of result.session.missions) {
1363
- if (mission.status === 'paused')
1364
- await cancelManagedMission(ctx, managedScheduler, mission);
1365
- }
1366
- await writeSession(result.session);
1367
- }
1368
- ui.success(`${result.replayed ? 'Replayed pause for' : 'Paused'} session: ${selected.id}`);
1369
- return { exitCode: 0, message: JSON.stringify({ ok: true, replayed: result.replayed, updated_at: result.session.updatedAt }) };
1370
- }
1371
- async function mcResume(ctx) {
1372
- const positional = getPositionalArgs(ctx.args);
1373
- const sessionId = positional[0];
1374
- const selected = await findActiveSession(sessionId);
1375
- if (!selected || selected.state !== 'paused') {
1376
- ui.error('No paused session to resume.');
1377
- return { exitCode: 1 };
1378
- }
1379
- try {
1380
- const cfg = await readAdmissionConfig(ctx.cwd || process.cwd());
1381
- if (cfg?.parallelism?.worker_dispatch && cfg.parallelism.worker_mode === 'managed') {
1382
- const scheduler = await createMcAdmissionScheduler(ctx.cwd || process.cwd(), cfg);
1383
- const snapshot = scheduler.snapshot();
1384
- for (const mission of selected.missions.filter(candidate => candidate.status === 'paused')) {
1385
- if (!mission.admissionRequestId)
1386
- continue;
1387
- const record = snapshot.records[mission.admissionRequestId];
1388
- if (!record || record.leaseGeneration !== mission.admissionGeneration || record.state !== 'admitted') {
1389
- throw new Error('managed resume requires current admission and reconciliation of uncertain work');
1390
- }
1391
- }
1392
- }
1393
- }
1394
- catch (error) {
1395
- const message = error instanceof Error ? error.message : String(error);
1396
- ui.error(message);
1397
- return { exitCode: 1, message };
1398
- }
1399
- const flags = mutationFlags(ctx.args);
1400
- const result = await mutateSession(selected.id, 'resume', selected.id, flags.expectedUpdatedAt, flags.requestId, session => {
1401
- if (session.state !== 'paused')
1402
- return 'invalid_state';
1403
- session.state = 'active';
1404
- for (const mission of session.missions)
1405
- if (mission.status === 'paused')
1406
- mission.status = 'running';
1407
- return undefined;
1408
- });
1409
- if (!result.ok)
1410
- return mutationFailure(result);
1411
- ui.success(`${result.replayed ? 'Replayed resume for' : 'Resumed'} session: ${selected.id}`);
1412
- return { exitCode: 0, message: JSON.stringify({ ok: true, replayed: result.replayed, updated_at: result.session.updatedAt }) };
1413
- }
1414
- async function mcStop(ctx) {
1415
- const positional = getPositionalArgs(ctx.args);
1416
- const sessionId = positional[0];
1417
- const drain = hasFlag(ctx.args, '--drain');
1418
- const session = await findActiveSession(sessionId);
1419
- if (!session) {
1420
- ui.error('No active session to stop.');
1421
- return { exitCode: 1 };
1422
- }
1423
- let managedScheduler;
1424
- try {
1425
- managedScheduler = await managedControlScheduler(ctx, session.missions.filter(mission => mission.status === 'queued' || (!drain && (mission.status === 'running' || mission.status === 'paused'))));
1426
- }
1427
- catch (error) {
1428
- return managedControlFailure(error);
1429
- }
1430
- if (drain) {
1431
- // Mark queued missions as aborted, let running finish
1432
- for (const m of session.missions) {
1433
- if (m.status === 'queued') {
1434
- m.status = 'aborted';
1435
- m.completedAt = new Date().toISOString();
1436
- }
1437
- }
1438
- ui.info('Draining: queued missions cancelled, running missions will complete.');
1439
- }
1440
- else {
1441
- // Abort all non-completed missions
1442
- for (const m of session.missions) {
1443
- if (m.status === 'running' || m.status === 'queued' || m.status === 'paused') {
1444
- m.status = 'aborted';
1445
- m.completedAt = new Date().toISOString();
1446
- }
1447
- }
1448
- }
1449
- if (managedScheduler) {
1450
- for (const mission of session.missions) {
1451
- if (mission.status === 'aborted')
1452
- await cancelManagedMission(ctx, managedScheduler, mission);
1453
- }
1454
- }
1455
- session.state = 'stopped';
1456
- await writeSession(session);
1457
- await appendLog(session.id, { event: 'session_stopped', drain });
1458
- ui.success(`Stopped session: ${session.id}`);
1459
- return { exitCode: 0 };
1460
- }
1461
- async function mcList(ctx) {
1462
- const json = hasFlag(ctx.args, '--json');
1463
- const sessions = await listSessions();
1464
- if (json) {
1465
- console.log(JSON.stringify(sessions.map(s => ({
1466
- id: s.id,
1467
- name: s.name,
1468
- state: s.state,
1469
- missions: s.missions.length,
1470
- created: s.createdAt,
1471
- updated: s.updatedAt,
1472
- })), null, 2));
1473
- return { exitCode: 0 };
1474
- }
1475
- if (sessions.length === 0) {
1476
- ui.info('No Mission Control sessions. Run `aiwg mc start` to create one.');
1477
- return { exitCode: 0 };
1478
- }
1479
- ui.blank();
1480
- console.log(` ${ui.brandMark()} ${ui.bold('Mission Control Sessions')}`);
1481
- ui.rule();
1482
- for (const s of sessions) {
1483
- const stateIcon = s.state === 'active' ? '●' : s.state === 'paused' ? '⏸' : '○';
1484
- const missionCount = s.missions.length;
1485
- const done = s.missions.filter(m => m.status === 'done').length;
1486
- console.log(` ${stateIcon} ${s.id} ${ui.accent(s.name)} (${done}/${missionCount} done) [${s.state}]`);
1487
- }
1488
- ui.blank();
1489
- return { exitCode: 0 };
1490
- }
1491
- async function mcWatch(ctx) {
1492
- const positional = getPositionalArgs(ctx.args);
1493
- const sessionId = positional[0];
1494
- const session = await findActiveSession(sessionId);
1495
- if (!session) {
1496
- ui.error('No active session to watch.');
1497
- return { exitCode: 1 };
1498
- }
1499
- // For non-interactive contexts, show status once with a note
1500
- // Real streaming would use fs.watch on the session file
1501
- ui.info(`Watch mode: polling session ${session.id}`);
1502
- ui.info('Press Ctrl+C to stop watching.');
1503
- ui.blank();
1504
- // Show current status
1505
- ctx.args = [session.id];
1506
- return mcStatus(ctx);
1507
- }
1508
- // ── Agent routing query ──────────────────────────────────────
1509
- /**
1510
- * aiwg mc agents [--filter key=value...] [--json]
1511
- *
1512
- * Queries GET /api/agents/candidates on the local aiwg serve instance and
1513
- * prints a table of agents that match the given routing filter. This is a thin
1514
- * CLI wrapper over the #916 routing endpoint so operators can check routing
1515
- * from a terminal without opening the dashboard.
1516
- *
1517
- * Filter flags:
1518
- * --framework <name> Require a specific AIWG framework (repeatable)
1519
- * --sandbox <id> Restrict to a specific sandbox
1520
- * --agent <id> Restrict to a specific agent ID
1521
- * --name <n> Match by logical name
1522
- * --max-cpu <pct> Reject agents above this CPU %
1523
- * --min-memory <gb> Reject agents below this memory threshold
1524
- * --json Output raw JSON
1525
- */
1526
- async function mcAgents(ctx) {
1527
- const args = ctx.args;
1528
- const json = hasFlag(args, '--json');
1529
- const port = process.env['AIWG_SERVE_PORT'] ?? '7337';
1530
- const base = `http://127.0.0.1:${port}`;
1531
- const params = new URLSearchParams();
1532
- for (let i = 0; i < args.length; i++) {
1533
- const a = args[i];
1534
- if (a === '--framework' && args[i + 1]) {
1535
- params.append('frameworks', args[++i]);
1536
- }
1537
- else if (a === '--sandbox' && args[i + 1]) {
1538
- params.set('sandbox_id', args[++i]);
1539
- }
1540
- else if (a === '--agent' && args[i + 1]) {
1541
- params.set('agent_id', args[++i]);
1542
- }
1543
- else if (a === '--name' && args[i + 1]) {
1544
- params.set('agent_name', args[++i]);
1545
- }
1546
- else if (a === '--max-cpu' && args[i + 1]) {
1547
- params.set('max_cpu_percent', args[++i]);
1548
- }
1549
- else if (a === '--min-memory' && args[i + 1]) {
1550
- params.set('min_memory_gb', args[++i]);
1551
- }
1552
- }
1553
- // 5s timeout so a wedged serve cannot hang the CLI. Override with
1554
- // AIWG_FETCH_TIMEOUT_MS for slow local environments or integration tests.
1555
- const fetchTimeoutMs = (() => {
1556
- const raw = process.env['AIWG_FETCH_TIMEOUT_MS'];
1557
- const n = raw ? parseInt(raw, 10) : NaN;
1558
- return Number.isFinite(n) && n > 0 ? n : 5_000;
1559
- })();
1560
- let result;
1561
- try {
1562
- // Combine user-cancel (Ctrl-C) with the per-call timeout so the fetch
1563
- // aborts on either. `AbortSignal.any` requires Node 20+.
1564
- const signal = ctx.signal
1565
- ? AbortSignal.any([ctx.signal, AbortSignal.timeout(fetchTimeoutMs)])
1566
- : AbortSignal.timeout(fetchTimeoutMs);
1567
- const resp = await fetch(`${base}/api/agents/candidates?${params.toString()}`, {
1568
- signal,
1569
- });
1570
- if (!resp.ok) {
1571
- ui.error(`aiwg serve returned ${resp.status} — is it running on port ${port}?`);
1572
- return { exitCode: 1 };
1573
- }
1574
- result = await resp.json();
1575
- }
1576
- catch (err) {
1577
- if (err instanceof Error && err.name === 'TimeoutError') {
1578
- ui.error(`aiwg serve on port ${port} timed out after ${fetchTimeoutMs}ms. Is it wedged?`);
1579
- }
1580
- else {
1581
- ui.error(`Cannot reach aiwg serve on port ${port}. Start it with: aiwg serve`);
1582
- }
1583
- return { exitCode: 1 };
1584
- }
1585
- if (json) {
1586
- console.log(JSON.stringify(result, null, 2));
1587
- return { exitCode: 0 };
1588
- }
1589
- ui.blank();
1590
- console.log(` ${ui.brandMark()} ${ui.bold('Agent Routing Candidates')}`);
1591
- ui.rule();
1592
- if (result.candidates.length === 0) {
1593
- ui.info('No matching agents found for the given filter.');
1594
- return { exitCode: 0 };
1595
- }
1596
- for (const c of result.candidates) {
1597
- const agent = c['agent'];
1598
- const agentId = agent?.['agentId'] ?? '?';
1599
- const logicalName = agent?.['logicalName'];
1600
- const sandboxName = c['sandboxName'] ?? '';
1601
- const cpu = agent?.['latestMetrics']?.['cpu_percent'];
1602
- const status = agent?.['status'] ?? '';
1603
- const isSelected = result.selected?.['sandboxName'] === sandboxName &&
1604
- result.selected?.['agent']?.['agentId'] === agentId;
1605
- const label = logicalName ? `${logicalName} (${agentId})` : agentId;
1606
- const cpuStr = cpu !== undefined ? ` cpu:${cpu.toFixed(0)}%` : '';
1607
- const selectedMark = isSelected ? ' ← selected' : '';
1608
- console.log(` • ${ui.bold(label)} sandbox:${sandboxName} status:${status}${cpuStr}${selectedMark}`);
1609
- const reason = c['matchReason'];
1610
- if (reason)
1611
- console.log(` reason: ${reason}`);
1612
- }
1613
- ui.blank();
1614
- return { exitCode: 0 };
1615
- }
10
+ export { createMcFlowAdapter } from './mc-worker.js';
11
+ export { SONNET_CACHE_USD, COST_WARNING_THRESHOLD_USD, COST_REPORTING_PROVIDERS, estimateMissionRunCost } from './mc-run.js';
1616
12
  // ── Subcommand router ────────────────────────────────────────
1617
- const subcommands = {
13
+ import { mcSummary } from './mc-summary.js';
14
+ export const subcommands = {
15
+ summary: mcSummary,
1618
16
  start: mcStart,
1619
17
  dispatch: mcDispatch,
1620
18
  run: mcRun, // #1439
@@ -1628,57 +26,6 @@ const subcommands = {
1628
26
  list: mcList,
1629
27
  agents: mcAgents,
1630
28
  };
1631
- function showMcHelp() {
1632
- ui.blank();
1633
- console.log(` ${ui.brandMark()} ${ui.bold('Mission Control')} — multi-loop background orchestration`);
1634
- ui.rule();
1635
- console.log(`
1636
- ${ui.bold('Usage:')} aiwg mc <subcommand> [options]
1637
-
1638
- ${ui.bold('Lifecycle:')}
1639
- 1. start — create a session (state-tracking only)
1640
- 2. dispatch — queue one or more missions onto a session
1641
- 3. run — drain the queue by launching each mission as a ralph loop
1642
- 4. status — view progress (auto-syncs from ralph loop state)
1643
- 5. watch — live tail of progress
1644
- 6. stop — shut down the session
1645
-
1646
- ${ui.bold('Subcommands:')}
1647
- start Start a new Mission Control session
1648
- dispatch <id> "<objective>" Queue a mission on the session (does NOT execute)
1649
- [--completion "<criteria>"] [--max-iterations N]
1650
- [--max-total-tokens N] [--max-output-tokens N]
1651
- [--max-tool-calls N] [--max-total-cost USD]
1652
- [--max-wall-clock-minutes N] [--exploration-quota N]
1653
- [--mode pty-orchestrator] [--target-agent <id>]
1654
- run <id> [--accept-cost] Launch queued missions as ralph loops (#1439)
1655
- Cost gate warns/refuses above ~$5 estimate
1656
- status [<id>] [--json] View mission status dashboard
1657
- watch [<id>] Live monitor (streaming)
1658
- abort|cancel <session> <mission> Abort a specific mission
1659
- pause [<id>] Pause active session
1660
- resume [<id>] Resume paused session
1661
- stop [<id>] [--drain] Shut down session
1662
- list [--json] List all sessions
1663
- agents [--filter] [--json] Query routable agents from aiwg serve (#916)
1664
- ${ui.bold('Examples:')}
1665
- aiwg mc start --name "Sprint 4"
1666
- aiwg mc dispatch mc-abc123 "Fix auth" --completion "tests pass"
1667
- aiwg mc dispatch mc-abc123 "Fix auth" --completion "tests pass" --max-total-tokens 5000 --exploration-quota 2
1668
- aiwg mc dispatch mc-abc123 "Refactor users" --completion "npm test passes"
1669
- aiwg mc run mc-abc123 # launches queued missions
1670
- aiwg mc status mc-abc123 # syncs progress from ralph loops
1671
- aiwg mc dispatch mc-abc123 "Supervise agent-01" --mode pty-orchestrator --target-agent agent-01 --completion "migration complete"
1672
- aiwg mc stop mc-abc123 --drain
1673
- aiwg mc agents --framework sdlc-complete --max-cpu 80
1674
-
1675
- ${ui.bold('A2A route for new sandbox work:')}
1676
- GET /api/v2/admin/instances
1677
- GET /agents/{instance_id}/.well-known/agent-card.json
1678
- GET /agents/{instance_id}/v1/extendedAgentCard
1679
- POST /agents/{instance_id}/v1/messages:send
1680
- `);
1681
- }
1682
29
  // ── Exported handler ─────────────────────────────────────────
1683
30
  export const mcHandler = {
1684
31
  id: 'mc',