code60-transmission-server 0.0.0-stage → 0.1.0-staging.12

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 (98) hide show
  1. package/LICENSE +180 -0
  2. package/README.engine.md +463 -0
  3. package/README.md +376 -2
  4. package/dist/src/broker/filesystem.js +385 -0
  5. package/dist/src/broker/index.js +734 -0
  6. package/dist/src/broker/native/README.md +207 -0
  7. package/dist/src/broker/native/build.js +46 -0
  8. package/dist/src/broker/native/command-helper.c +93 -0
  9. package/dist/src/broker/native/fs-helper.c +529 -0
  10. package/dist/src/broker/native/git-helper.c +205 -0
  11. package/dist/src/broker/policy.js +149 -0
  12. package/dist/src/broker/startup-lock.js +14 -0
  13. package/dist/src/broker/types.js +11 -0
  14. package/dist/src/cli/configure.js +208 -0
  15. package/dist/src/cli/daemon.js +369 -0
  16. package/dist/src/cli/helpers.js +112 -0
  17. package/dist/src/cli/main.js +189 -0
  18. package/dist/src/cli/runtime-build.js +38 -0
  19. package/dist/src/config/coding-policy.js +4 -0
  20. package/dist/src/config/deployment.js +183 -0
  21. package/dist/src/config/documents.js +29 -0
  22. package/dist/src/config/profile-validation.js +129 -0
  23. package/dist/src/config/schema-graph.js +237 -0
  24. package/dist/src/config/schema-loader.js +185 -0
  25. package/dist/src/config/validation-pool.js +105 -0
  26. package/dist/src/config/validation-protocol.js +1 -0
  27. package/dist/src/config/validation-worker.js +106 -0
  28. package/dist/src/config/workflow-language.js +9 -0
  29. package/dist/src/config/workflow-schema.json +545 -0
  30. package/dist/src/config/workflow-types.js +1 -0
  31. package/dist/src/config/workflow-validation.js +95 -0
  32. package/dist/src/engine/budgets.js +50 -0
  33. package/dist/src/engine/clocks.js +27 -0
  34. package/dist/src/engine/commands.js +477 -0
  35. package/dist/src/engine/contracts.js +11 -0
  36. package/dist/src/engine/drain-state.js +31 -0
  37. package/dist/src/engine/effective-permissions.js +120 -0
  38. package/dist/src/engine/instruction-pins.js +205 -0
  39. package/dist/src/engine/retries.js +50 -0
  40. package/dist/src/engine/state.js +1 -0
  41. package/dist/src/engine/timing.js +23 -0
  42. package/dist/src/engine/tool-observations.js +87 -0
  43. package/dist/src/engine/workflow-engine.js +1862 -0
  44. package/dist/src/main.js +28 -0
  45. package/dist/src/mcp/catalog.js +71 -0
  46. package/dist/src/mcp/main.js +26 -0
  47. package/dist/src/mcp/server.js +177 -0
  48. package/dist/src/runtime/codex-app-server.js +91 -0
  49. package/dist/src/runtime/codex-executable.js +50 -0
  50. package/dist/src/runtime/containment.js +82 -0
  51. package/dist/src/runtime/engine-driver.js +221 -0
  52. package/dist/src/runtime/json-line-writer.js +192 -0
  53. package/dist/src/runtime/pinned-instruction-sources.js +24 -0
  54. package/dist/src/runtime/protocol-client.js +264 -0
  55. package/dist/src/runtime/protocol-pool.js +183 -0
  56. package/dist/src/runtime/protocol-projection.js +393 -0
  57. package/dist/src/runtime/protocol-types.js +1 -0
  58. package/dist/src/runtime/protocol-worker.js +18 -0
  59. package/dist/src/runtime/provider-bridge.js +290 -0
  60. package/dist/src/runtime/provider-credentials.js +41 -0
  61. package/dist/src/runtime/provider-transport.js +406 -0
  62. package/dist/src/runtime/runtime-broker.js +213 -0
  63. package/dist/src/runtime/workspace-instructions.js +120 -0
  64. package/dist/src/runtime/workspace-view.js +74 -0
  65. package/dist/src/server/api-contract.json +11629 -0
  66. package/dist/src/server/api-types.js +1 -0
  67. package/dist/src/server/application.js +44 -0
  68. package/dist/src/server/auth.js +67 -0
  69. package/dist/src/server/broker-handlers.js +242 -0
  70. package/dist/src/server/coding.js +281 -0
  71. package/dist/src/server/control-plane.js +50 -0
  72. package/dist/src/server/deployment.js +249 -0
  73. package/dist/src/server/errors.js +22 -0
  74. package/dist/src/server/history-handlers.js +127 -0
  75. package/dist/src/server/http.js +124 -0
  76. package/dist/src/server/paging.js +56 -0
  77. package/dist/src/server/publication.js +119 -0
  78. package/dist/src/server/tool-event-handler.js +77 -0
  79. package/dist/src/server/workspace-handlers.js +34 -0
  80. package/dist/src/storage/coordinator.js +224 -0
  81. package/dist/src/storage/startup-lock.js +71 -0
  82. package/dist/src/storage/store.js +167 -0
  83. package/dist/src/tools/check-worker.js +81 -0
  84. package/dist/src/tools/checks.js +117 -0
  85. package/dist/src/tools/command-check.js +34 -0
  86. package/dist/src/tools/commands.js +312 -0
  87. package/dist/src/tools/developer.js +353 -0
  88. package/dist/src/tools/dns.js +248 -0
  89. package/dist/src/tools/http-contract.js +38 -0
  90. package/dist/src/tools/http.js +358 -0
  91. package/dist/src/tools/index.js +194 -0
  92. package/dist/src/tools/worker-check.js +73 -0
  93. package/dist/src/workspaces/git.js +227 -0
  94. package/dist/src/workspaces/index.js +937 -0
  95. package/dist/src/workspaces/source.js +295 -0
  96. package/examples/deployment.local.json +22 -0
  97. package/package.json +71 -4
  98. package/scripts/postinstall.mjs +26 -0
@@ -0,0 +1,1862 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { canonical, digest, jsonCopy } from '../broker/policy.js';
3
+ import { WorkspaceError } from '../workspaces/index.js';
4
+ import { CoordinatorError } from '../storage/coordinator.js';
5
+ import { ApiError, problem } from '../server/errors.js';
6
+ import { RunCommands, terminal } from './commands.js';
7
+ import { checkpoint, consumed, expired, status } from './clocks.js';
8
+ import { durationMs } from './timing.js';
9
+ import { limitsFor, mergeIncrease, validateIncrease } from './budgets.js';
10
+ import { BrokerProjection } from '../server/broker-handlers.js';
11
+ import { approvalWaitFor, brokerWorkId } from './drain-state.js';
12
+ const sha = (text) => `sha256:${createHash('sha256').update(text).digest('hex')}`;
13
+ const held = () => new ApiError(409, 'execution_held', 'Execution is held at a safe boundary.');
14
+ const criterionIds = (criteria) => criteria.map((_criterion, index) => `criterion_${index + 1}`);
15
+ const verifierSchema = {
16
+ type: 'object', required: ['decision', 'criteria'], additionalProperties: false,
17
+ properties: { decision: { enum: ['approve', 'revise'] }, guidance: { type: 'string' }, criteria: { type: 'array', items: {
18
+ type: 'object', required: ['criterionId', 'status', 'explanation'], additionalProperties: false,
19
+ properties: { criterionId: { type: 'string', minLength: 1 }, status: { enum: ['pass', 'fail'] },
20
+ explanation: { type: 'string', minLength: 1 }, evidenceArtifactIds: { type: 'array', items: { type: 'string' } } },
21
+ } } },
22
+ };
23
+ /** Durable single-run actor. Every await is outside SQL, and each run has one
24
+ * active transition. Different workspaces may progress independently. */
25
+ export class WorkflowEngine {
26
+ options;
27
+ commands;
28
+ projection;
29
+ #pending = new Set();
30
+ #running = new Set();
31
+ #actors = new Map();
32
+ #effects = new Map();
33
+ #effectSettlements = new Map();
34
+ #controllers = new Map();
35
+ #stopped = new Set();
36
+ #readProof = new Set();
37
+ #timer;
38
+ #closed = false;
39
+ #fatal;
40
+ constructor(options) {
41
+ this.options = options;
42
+ this.commands = options.commands;
43
+ this.projection = new BrokerProjection(this.commands.store, this.commands.options.broker, { work: id => this.work(id), onRunChangedSql: id => {
44
+ // Final approval release and current role state must commit together,
45
+ // before broker waiters attempt their already-authorized claim.
46
+ if (!this.store.get('runs', id).approvalWait.pendingApprovalIds.length)
47
+ this.approvalDrainSql(id);
48
+ this.updateClocks(id);
49
+ } });
50
+ options.driver.onResult((id, content) => this.result(id, content));
51
+ options.driver.onFailure((id, message) => this.failure(id, message));
52
+ }
53
+ get store() { return this.commands.store; }
54
+ get broker() { return this.commands.options.broker; }
55
+ work(runId) {
56
+ const sessions = this.store.list('sessions', { runId, limit: Number.MAX_SAFE_INTEGER }).map(row => row.value);
57
+ const rows = this.store.coordinator.db.prepare('SELECT id,state FROM broker_work WHERE run_id=?').all(runId);
58
+ const work = rows.map(row => {
59
+ const session = sessions.find(value => row.id.startsWith(`external:${value.id}:${value.epoch}:`));
60
+ return { id: brokerWorkId(row.id), kind: row.id.includes(':runtime-model:') ? 'agent_turn' : 'tool',
61
+ ...(session ? { sessionId: session.id } : {}), description: row.state === 'uncertain' ? 'Work requires physical-stop reconciliation' : 'Broker-managed work' };
62
+ });
63
+ work.push(...[...this.#effects.values()].filter(value => value.runId === runId).map(value => value.value));
64
+ if (this.options.driver.activeWork(runId))
65
+ work.push({ id: 'runtime_process_barrier', kind: 'engine_transition', description: 'Runtime startup or physical-exit barrier' });
66
+ if (this.options.validation.activeWork(runId))
67
+ work.push({ id: 'validation_workers', kind: 'engine_transition', description: 'Pure validation workers awaiting physical exit' });
68
+ if (this.options.checks.activeWork(runId).length)
69
+ work.push({ id: 'trusted_checks', kind: 'engine_transition', description: 'Registered checks still physically active' });
70
+ if (this.options.schemas.activeWork(runId))
71
+ work.push({ id: 'schema_startup', kind: 'engine_transition', description: 'Schema graph startup' });
72
+ for (const job of this.options.workspaces.activeWork(runId))
73
+ if (!(this.#readProof.has(runId) && job.state === 'uncertain'))
74
+ work.push({ id: job.id, kind: 'engine_transition', description: job.state === 'uncertain' ? 'Workspace effect requires read-only reconciliation' : 'Workspace Git effect' });
75
+ if (this.options.additionalWork?.(runId))
76
+ work.push({ id: 'command_processes', kind: 'engine_transition', description: 'Command processes or unresolved command settlement' });
77
+ return work;
78
+ }
79
+ quiet(runId) { return this.work(runId).length === 0; }
80
+ signal(runId) {
81
+ let controller = this.#controllers.get(runId);
82
+ if (!controller) {
83
+ controller = new AbortController();
84
+ this.#controllers.set(runId, controller);
85
+ }
86
+ return controller.signal;
87
+ }
88
+ async effect(runId, description, perform, sessionId) {
89
+ this.store.coordinator.assertOutsideTransaction();
90
+ if (this.#closed)
91
+ throw held();
92
+ const id = randomUUID();
93
+ let settle;
94
+ this.#effectSettlements.set(id, new Promise(resolve => { settle = resolve; }));
95
+ this.#effects.set(id, { runId, value: { id, kind: 'engine_transition', description, ...(sessionId ? { sessionId } : {}) } });
96
+ try {
97
+ return await perform();
98
+ }
99
+ finally {
100
+ this.#effects.delete(id);
101
+ this.#effectSettlements.delete(id);
102
+ settle();
103
+ }
104
+ }
105
+ wake(runId) {
106
+ this.store.coordinator.assertOutsideTransaction();
107
+ if (this.#closed || this.#fatal)
108
+ return;
109
+ const run = this.store.find('runs', runId);
110
+ if (!run)
111
+ return;
112
+ const plan = this.commands.plan(runId);
113
+ if (plan.cancelOperationId || terminal(run)) {
114
+ this.#controllers.get(runId)?.abort();
115
+ void this.stopSessions(runId).catch(error => { this.#fatal = error; });
116
+ }
117
+ this.#pending.add(runId);
118
+ queueMicrotask(() => { void this.pump(); });
119
+ }
120
+ start() {
121
+ this.store.coordinator.assertOutsideTransaction();
122
+ if (this.#timer)
123
+ throw new Error('engine_already_started');
124
+ this.#timer = setInterval(() => {
125
+ if (this.#closed || this.#fatal)
126
+ return;
127
+ try {
128
+ for (const row of this.store.coordinator.db.prepare("SELECT id FROM engine_resources WHERE kind='runs' AND (json_extract(body,'$.state') NOT IN ('succeeded','failed','cancelled') OR json_extract(body,'$.state') IN ('failed','cancelled') AND id NOT IN (SELECT id FROM engine_private WHERE scope='lease_released'))").all()) {
129
+ const run = this.store.get('runs', row.id), plan = this.commands.plan(row.id);
130
+ if (!terminal(run) && !plan.cancelOperationId)
131
+ this.deadlines(row.id);
132
+ if (!plan.cancelOperationId && run.executionControl.status === 'pausing')
133
+ this.pause(row.id);
134
+ this.wake(row.id);
135
+ }
136
+ }
137
+ catch (error) {
138
+ this.#fatal = error;
139
+ }
140
+ }, 100);
141
+ this.#timer.unref();
142
+ }
143
+ async close() {
144
+ this.#closed = true;
145
+ if (this.#timer)
146
+ clearInterval(this.#timer);
147
+ for (const controller of this.#controllers.values())
148
+ controller.abort();
149
+ const ids = this.store.coordinator.db.prepare("SELECT id FROM engine_resources WHERE kind='runs'").all();
150
+ this.store.coordinator.atomic(() => {
151
+ for (const { id } of ids)
152
+ for (const { value: session } of this.store.list('sessions', { runId: id, limit: Number.MAX_SAFE_INTEGER })) {
153
+ const authority = this.store.private('session_authority', session.id);
154
+ // Shutdown destroys the preserved conversation. Revoke unused authority
155
+ // before waiting on runtime invocations; pending approval is not an
156
+ // executing effect. Consumed effects still retain their own barriers.
157
+ if (authority && this.commands.current(session.id, session.epoch))
158
+ this.broker.fenceSession(authority.binding);
159
+ this.commands.options.auth.revokeSession(session.id);
160
+ }
161
+ });
162
+ if (this.options.closeCommands)
163
+ await this.options.closeCommands();
164
+ for (const { id } of ids)
165
+ await this.stopSessions(id);
166
+ await Promise.allSettled([...this.#actors.values()]);
167
+ await Promise.allSettled([...this.#effectSettlements.values()]);
168
+ }
169
+ async pump() {
170
+ for (const runId of this.#pending) {
171
+ if (this.#running.has(runId) || this.#closed || this.#fatal)
172
+ continue;
173
+ this.#pending.delete(runId);
174
+ this.#running.add(runId);
175
+ const actor = this.drive(runId).catch(error => this.handleError(runId, error)).finally(() => {
176
+ this.#running.delete(runId);
177
+ this.#actors.delete(runId);
178
+ if (this.#pending.has(runId) && !this.#closed && !this.#fatal)
179
+ queueMicrotask(() => { void this.pump(); });
180
+ });
181
+ this.#actors.set(runId, actor);
182
+ }
183
+ }
184
+ gate(runId, allowBlocks = false, replaceUnderApprovalWait = false) {
185
+ if (this.#closed)
186
+ throw held();
187
+ const run = this.store.get('runs', runId), plan = this.commands.plan(runId);
188
+ if (terminal(run) || plan.cancelOperationId || run.executionControl.status !== 'running' ||
189
+ !allowBlocks && run.pendingBlockIds.length || run.approvalWait.status !== 'none' &&
190
+ !(replaceUnderApprovalWait && this.quiet(runId)))
191
+ throw held();
192
+ if (expired(plan.clock, this.commands.now()))
193
+ throw new ApiError(409, 'deadline_exceeded', 'Workflow allowance is exhausted.');
194
+ const step = plan.steps[plan.ordinal], stepClock = step && plan.stepClocks[step.id];
195
+ if (stepClock && expired(stepClock, this.commands.now()))
196
+ throw new ApiError(409, 'deadline_exceeded', 'Step allowance is exhausted.');
197
+ }
198
+ absoluteDeadline(plan, stepId = plan.steps[plan.ordinal]?.id) {
199
+ if (stepId !== plan.steps[plan.ordinal]?.id)
200
+ throw new Error('deadline_step_binding_mismatch');
201
+ const run = plan.clock.deadlineAt, step = stepId === undefined ? undefined : plan.stepClocks[stepId]?.deadlineAt;
202
+ return run === undefined ? step ?? null : step === undefined ? run : Math.min(run, step);
203
+ }
204
+ /** Join the clock/ordinal mutation. Only the current step can have live
205
+ * sessions; accept fences the old sessions before advancing. Recompute from
206
+ * absolute clocks, never from the previous gate or a relative role budget. */
207
+ syncBrokerDeadlineSql(runId, plan, stepId = plan.steps[plan.ordinal]?.id) {
208
+ const result = this.store.coordinator.db.prepare("UPDATE broker_runs SET body=json_set(body,'$.deadlineAt',?) WHERE id=?")
209
+ .run(this.absoluteDeadline(plan, stepId), runId);
210
+ if (result.changes !== 1)
211
+ throw new Error('broker_run_gate_missing');
212
+ }
213
+ /** Authority-only resolver also serves already-admitted effects. Admission
214
+ * gates are checked separately before a new trusted tool preparation. */
215
+ context(binding) {
216
+ if (!this.commands.current(binding.sessionId, binding.epoch))
217
+ throw new ApiError(409, 'stale_epoch', 'Session is stale.');
218
+ const authority = this.store.private('session_authority', binding.sessionId);
219
+ const session = this.store.get('sessions', binding.sessionId), lease = this.options.workspaces.lease(binding.runId);
220
+ if (authority.binding.profileVersionId !== binding.profileVersionId || authority.binding.role !== binding.role ||
221
+ session.instructionSnapshotId !== session.effectiveConfiguration.instructionSnapshotId || lease.id !== authority.leaseId || lease.state !== 'active')
222
+ throw new ApiError(409, 'stale_assignment', 'Session assignment is stale.');
223
+ return { binding, leaseId: lease.id, workspaceId: authority.workspaceId, instructionSnapshotId: session.instructionSnapshotId,
224
+ ...(authority.workspaceRevisionId ? { workspaceRevisionId: authority.workspaceRevisionId } : {}) };
225
+ }
226
+ toolAdmission(binding) {
227
+ this.context(binding);
228
+ this.gate(binding.runId);
229
+ const session = this.store.get('sessions', binding.sessionId), authority = this.store.private('session_authority', session.id);
230
+ if (session.state !== 'running' || expired(authority.clock, this.commands.now()) ||
231
+ session.limits.maxSubmissions !== undefined && session.submissionsUsed >= session.limits.maxSubmissions ||
232
+ this.commands.plan(binding.runId).reset && authority.phase === 'work')
233
+ throw held();
234
+ }
235
+ async drive(runId) {
236
+ let run = this.store.get('runs', runId), plan = this.commands.plan(runId);
237
+ if (plan.cancelOperationId) {
238
+ await this.cancel(runId);
239
+ return;
240
+ }
241
+ if (terminal(run)) {
242
+ await this.finish(runId);
243
+ return;
244
+ }
245
+ if (this.deadlines(runId))
246
+ return;
247
+ this.projection.refresh(runId);
248
+ await this.extendGrace(runId);
249
+ this.approvalDrain(runId);
250
+ run = this.store.get('runs', runId);
251
+ if (run.executionControl.status === 'pausing') {
252
+ this.pause(runId);
253
+ return;
254
+ }
255
+ if (run.executionControl.status === 'resuming') {
256
+ await this.resume(runId);
257
+ return;
258
+ }
259
+ if (run.executionControl.status === 'paused')
260
+ return;
261
+ if (plan.recoveryOperationId) {
262
+ await this.recover(runId);
263
+ return;
264
+ }
265
+ if (run.state === 'interrupted')
266
+ return;
267
+ // Explicit continuation may retire the replaced role's unused approvals.
268
+ // Only this quiescent administrative transition can cross the wait; normal
269
+ // agents, tools, Git and unrelated pending approvals keep their gates.
270
+ if (plan.queuedDecisions[0]?.decision.kind === 'replace_profile' && this.quiet(runId)) {
271
+ await this.decisions(runId);
272
+ return;
273
+ }
274
+ if (run.approvalWait.status !== 'none') {
275
+ this.updateClocks(runId);
276
+ return;
277
+ }
278
+ if (plan.queuedDecisions.length) {
279
+ await this.decisions(runId);
280
+ return;
281
+ }
282
+ if (run.pendingBlockIds.length) {
283
+ this.updateClocks(runId);
284
+ return;
285
+ }
286
+ this.gate(runId);
287
+ this.updateClocks(runId);
288
+ plan = this.commands.plan(runId);
289
+ if (plan.stage === 'startup')
290
+ await this.startup(runId);
291
+ else if (plan.stage === 'evaluate')
292
+ await this.evaluate(runId);
293
+ else if (plan.stage === 'accept')
294
+ await this.accept(runId);
295
+ else if (plan.stage === 'reset' || plan.stage === 'handoff')
296
+ await this.reset(runId);
297
+ else if (plan.stage === 'complete')
298
+ await this.finish(runId);
299
+ else if (plan.stage === 'worker' && !plan.steps[plan.ordinal].baselineId)
300
+ await this.startStep(runId);
301
+ else
302
+ await this.agent(runId, plan.stage === 'verify' ? 'verifier' : 'worker');
303
+ }
304
+ async startup(runId) {
305
+ let plan = this.commands.plan(runId);
306
+ this.gate(runId);
307
+ if (!plan.graph) {
308
+ const version = this.store.get('workflow_versions', this.store.get('runs', runId).workflowVersionId), policy = this.store.get('runs', runId).policy;
309
+ const loaded = await this.effect(runId, 'Resolve and pin complete schema graph', () => this.options.schemas.load(version, this.options.checks.list().map(check => check.name), { operationId: runId, signal: this.signal(runId),
310
+ ...(plan.clock.deadlineAt === undefined ? {} : { deadlineAt: plan.clock.deadlineAt }),
311
+ timeout: policy.schemaFetchTimeout ?? '30s', retryDelays: policy.schemaFetchRetryDelays ?? ['1s', '2s'],
312
+ beforeFetch: () => this.gate(runId), onPinnedSql: resource => {
313
+ const id = createHash('sha256').update(`${runId}\0${resource.uri}`).digest('hex');
314
+ this.store.put('artifacts', { id, runId, kind: 'schema_snapshot', document: resource.document,
315
+ contentDigest: sha(resource.document.content), state: 'accepted', createdAt: new Date(this.commands.now()).toISOString() }, { runId, immutable: true });
316
+ this.store.event(runId, 'schema_resolved', 'artifact', id, { uri: resource.uri });
317
+ } }));
318
+ if (!loaded.report.valid || !loaded.graph)
319
+ throw new ApiError(422, 'invalid_schema_graph', 'Complete schema graph validation failed.', false, loaded.report.issues);
320
+ plan = this.commands.plan(runId);
321
+ plan.graph = loaded.graph;
322
+ this.commands.savePlan(runId, plan);
323
+ }
324
+ this.gate(runId);
325
+ if (!plan.workspaceInstructions) {
326
+ this.options.workspaces.assertKnown(runId);
327
+ const snapshots = this.options.pins.assemble(runId, plan.definition, plan.steps), workspace = this.options.workspaceInstructions(runId);
328
+ this.options.workspaces.assertKnown(runId);
329
+ this.store.coordinator.atomic(() => {
330
+ plan = this.commands.plan(runId);
331
+ for (const snapshot of snapshots) {
332
+ this.store.put('snapshots', snapshot, { runId, parentId: snapshot.stepExecutionId, immutable: true });
333
+ plan.steps.find(step => step.id === snapshot.stepExecutionId).profiles[snapshot.role].snapshotId = snapshot.id;
334
+ this.store.event(runId, 'instruction_snapshot_created', 'instruction_snapshot', snapshot.id, { role: snapshot.role, stepExecutionId: snapshot.stepExecutionId });
335
+ }
336
+ plan.workspaceInstructions = workspace;
337
+ this.commands.savePlan(runId, plan);
338
+ });
339
+ }
340
+ plan = this.commands.plan(runId);
341
+ for (const step of plan.steps)
342
+ for (const role of ['worker', 'verifier', 'handoff']) {
343
+ const pin = step.profiles[role];
344
+ if (!pin)
345
+ continue;
346
+ const key = `${step.id}:${role}`;
347
+ if (this.store.private('effective_configuration', key))
348
+ continue;
349
+ this.gate(runId);
350
+ const profile = this.store.get('profile_versions', pin.profileVersionId);
351
+ const result = await this.effect(runId, 'Compile pinned effective permissions', () => this.options.validation.run({
352
+ kind: 'effective_permissions', profile: profile.definition.permissions, deployment: this.options.deploymentPolicy,
353
+ role, configuredTools: profile.definition.tools.map(tool => tool.toolId)
354
+ }, { runId, signal: this.signal(runId) }));
355
+ if (!result.valid || !result.effectivePolicy)
356
+ throw new ApiError(422, 'invalid_effective_permissions', 'Effective permissions cannot be compiled.', false, result.errors);
357
+ const configuration = { profileVersionId: profile.id, role, definition: profile.definition, instructionSnapshotId: pin.snapshotId,
358
+ deploymentPolicyDigest: digest(this.options.deploymentPolicy), effectivePermissions: result.effectivePolicy };
359
+ this.store.setPrivate('effective_configuration', key, { ...configuration, contentDigest: digest(configuration) });
360
+ }
361
+ this.gate(runId);
362
+ if (!this.store.private('run_baseline', runId))
363
+ this.options.workspaces.baseline(runId, 'run_start', undefined, {
364
+ onAdmittedSql: baseline => { this.store.put('baselines', baseline, { runId, immutable: true }); this.store.setPrivate('run_baseline', runId, { id: baseline.id }); }
365
+ });
366
+ await this.startStep(runId);
367
+ }
368
+ async startStep(runId) {
369
+ this.gate(runId);
370
+ let plan = this.commands.plan(runId);
371
+ if (plan.ordinal >= plan.steps.length) {
372
+ plan.stage = 'complete';
373
+ this.commands.savePlan(runId, plan);
374
+ await this.finish(runId);
375
+ return;
376
+ }
377
+ const stepPlan = plan.steps[plan.ordinal], definition = plan.definition.steps[plan.ordinal], now = this.commands.now();
378
+ if (!plan.stepClocks[stepPlan.id])
379
+ plan.stepClocks[stepPlan.id] = { consumedMs: 0, changedAt: now, running: true,
380
+ ...(definition.timeout ? { deadlineAt: now + durationMs(definition.timeout.duration) } : {}) };
381
+ this.store.coordinator.atomic(() => {
382
+ this.commands.savePlan(runId, plan);
383
+ this.syncBrokerDeadlineSql(runId, plan);
384
+ });
385
+ if (!stepPlan.baselineId)
386
+ this.options.workspaces.baseline(runId, 'step_start', stepPlan.id, { onAdmittedSql: baseline => {
387
+ plan = this.commands.plan(runId);
388
+ plan.steps[plan.ordinal].baselineId = baseline.id;
389
+ this.commands.savePlan(runId, plan);
390
+ this.store.put('baselines', baseline, { runId, immutable: true });
391
+ this.store.put('steps', { ...this.store.get('steps', stepPlan.id), baselineId: baseline.id }, { runId });
392
+ } });
393
+ this.store.coordinator.atomic(() => {
394
+ const current = this.commands.plan(runId), step = current.steps[current.ordinal];
395
+ if (step.reentry) {
396
+ current.reset = { ...step.reentry.reset, id: randomUUID(), reason: 'rollback_reentry', role: 'worker',
397
+ ...(step.reentry.oldSessionId ? { oldSessionId: step.reentry.oldSessionId } : {}) };
398
+ if (step.reentry.oldSessionId)
399
+ step.workerSessionId = step.reentry.oldSessionId;
400
+ }
401
+ current.stage = step.reentry ? 'reset' : 'worker';
402
+ this.commands.savePlan(runId, current);
403
+ this.commands.updateRun(runId, { state: step.reentry ? 'resetting' : 'running', currentStepId: stepPlan.id });
404
+ this.stepState(runId, step.reentry ? 'resetting' : 'running');
405
+ });
406
+ this.wake(runId);
407
+ }
408
+ stepState(runId, state) {
409
+ const plan = this.commands.plan(runId), step = this.store.get('steps', plan.steps[plan.ordinal].id);
410
+ if (step.state === state)
411
+ return;
412
+ this.store.put('steps', { ...step, state }, { runId });
413
+ this.store.event(runId, 'step_state_changed', 'step_execution', step.id, { state });
414
+ }
415
+ setSession(sessionId, state) {
416
+ const session = this.store.get('sessions', sessionId), authority = this.store.private('session_authority', sessionId);
417
+ authority.clock = checkpoint(authority.clock, state === 'running', this.commands.now());
418
+ this.store.setPrivate('session_authority', sessionId, authority);
419
+ this.store.put('sessions', { ...session, state, timing: status(authority.clock, ['terminated', 'completed'].includes(state), this.commands.now()) }, { runId: session.runId, parentId: session.stepExecutionId });
420
+ if (state !== session.state)
421
+ this.store.event(session.runId, 'session_state_changed', 'session', sessionId, { state });
422
+ }
423
+ roleLimits(plan, role) {
424
+ const step = plan.steps[plan.ordinal], limits = limitsFor(plan.definition.steps[plan.ordinal], role, plan.budgetOverrides?.[step.id]);
425
+ const charges = role === 'verifier' ? step.verificationCharges : role === 'handoff' ? plan.reset?.handoffCharges ?? 0 : 0;
426
+ const elapsed = role === 'verifier' ? step.verificationConsumedMs : role === 'handoff' ? plan.reset?.handoffConsumedMs ?? 0 : 0;
427
+ if (limits.maxSubmissions !== undefined) {
428
+ if (limits.maxSubmissions <= charges)
429
+ throw new ApiError(409, 'session_budget_exhausted', 'The role episode has no remaining attempts.');
430
+ limits.maxSubmissions -= charges;
431
+ }
432
+ if (limits.executionTimeLimit) {
433
+ const remaining = durationMs(limits.executionTimeLimit) - elapsed;
434
+ if (remaining <= 0)
435
+ throw new ApiError(409, 'session_budget_exhausted', 'The role episode has no remaining execution time.');
436
+ limits.executionTimeLimit = `${Math.ceil(remaining)}ms`;
437
+ }
438
+ return limits;
439
+ }
440
+ async launch(runId, role) {
441
+ this.gate(runId);
442
+ if (!this.quiet(runId))
443
+ throw held();
444
+ const plan = this.commands.plan(runId), step = plan.steps[plan.ordinal], pin = step.profiles[role];
445
+ if (!pin?.snapshotId || !plan.workspaceInstructions)
446
+ throw new Error('profile_or_instruction_pins_missing');
447
+ const effective = this.store.private('effective_configuration', `${step.id}:${role}`);
448
+ if (!effective || effective.profileVersionId !== pin.profileVersionId || effective.instructionSnapshotId !== pin.snapshotId)
449
+ throw new Error('effective_configuration_pin_mismatch');
450
+ const profile = this.store.get('profile_versions', pin.profileVersionId), lease = this.options.workspaces.lease(runId);
451
+ const id = randomUUID(), limits = this.roleLimits(plan, role), now = this.commands.now();
452
+ const binding = { sessionId: id, runId, stepExecutionId: step.id, epoch: 1, role, profileVersionId: profile.id,
453
+ configuredTools: profile.definition.tools.map(tool => tool.toolId), permissions: profile.definition.permissions, deploymentPermissions: jsonCopy(this.options.deploymentPolicy) };
454
+ const candidate = step.candidateId ? this.store.get('submissions', step.candidateId) : undefined;
455
+ const phase = role === 'verifier' ? 'verification' : role === 'handoff' ? 'handoff' : 'work';
456
+ const root = plan.graph.roots.find(value => value.stepId === plan.definition.steps[plan.ordinal].id && value.kind === (role === 'handoff' ? 'handoff' : 'exit'));
457
+ const schema = role === 'verifier' ? verifierSchema : plan.graph.resources.find(value => value.uri === root?.uri)?.schema;
458
+ if (schema === undefined || typeof schema !== 'boolean' && (!schema || typeof schema !== 'object' || Array.isArray(schema)))
459
+ throw new Error('output_schema_pin_missing');
460
+ const inputArtifacts = this.store.coordinator.db.prepare("SELECT id FROM engine_resources WHERE kind='artifacts' AND run_id=? AND json_extract(body,'$.state')='accepted' ORDER BY seq").all(runId);
461
+ const inputArtifactIds = [...new Set([...inputArtifacts.map(value => value.id), ...(candidate ? [candidate.artifactId] : [])])];
462
+ const history = this.store.coordinator.db.prepare("SELECT MAX(seq) AS value FROM engine_resources WHERE kind='tool_history' AND run_id=?").get(runId);
463
+ const through = history.value ?? 0, historyLimit = phase === 'handoff' ? plan.definition.steps[plan.ordinal].handoffArtifact.historyLimit : 100;
464
+ const earliest = this.store.coordinator.db.prepare("SELECT seq FROM engine_resources WHERE kind='tool_history' AND run_id=? ORDER BY seq DESC LIMIT 1 OFFSET ?").get(runId, Math.max(0, historyLimit - 1));
465
+ const sessionClock = { consumedMs: 0, changedAt: now, running: true,
466
+ ...(limits.executionTimeLimit ? { limitMs: durationMs(limits.executionTimeLimit) } : {}) };
467
+ const session = { id, runId, stepExecutionId: step.id, role, state: 'running', epoch: 1, limits, submissionsUsed: 0,
468
+ infrastructureAttemptCharges: 0, timing: status(sessionClock), createdAt: new Date(now).toISOString(), profileVersionId: profile.id,
469
+ instructionSnapshotId: pin.snapshotId, effectiveConfiguration: effective };
470
+ const authority = { binding, workspaceId: lease.workspaceId, leaseId: lease.id, outputSchema: schema,
471
+ inputArtifactIds, phase, clock: sessionClock, logicalOperationId: randomUUID(), infrastructureFailures: 0, lastSubmissionConsumedMs: 0,
472
+ retryEpisodeId: role === 'verifier' ? `verification_${candidate.id}` : role === 'handoff' ? `handoff_${step.id}_${this.store.get('steps', step.id).resetsUsed}` : randomUUID(),
473
+ ...(role === 'verifier' ? { subjectSubmissionId: candidate.id, workspaceRevisionId: candidate.workspaceRevision.id } : {}) };
474
+ const snapshot = this.store.get('snapshots', pin.snapshotId), workspace = this.options.workspaces.get(lease.workspaceId);
475
+ const assignment = { session, workspace, instructions: snapshot.assembledText, inputArtifactIds,
476
+ permissions: { projectWrite: role !== 'verifier', scratchPaths: workspace.scratchPaths }, outputSchema: schema,
477
+ instructionSnapshot: snapshot, executionGate: 'open',
478
+ ...(candidate?.workspaceRevision ? { workspaceRevision: candidate.workspaceRevision } : { workspaceRevision: this.options.workspaces.revision(lease.knownRevisionId) }),
479
+ ...(role === 'verifier' ? { subjectSubmissionId: candidate.id } : {}) };
480
+ this.store.coordinator.atomic(() => {
481
+ this.gate(runId);
482
+ this.broker.registerSession(binding, this.absoluteDeadline(plan, binding.stepExecutionId));
483
+ this.syncBrokerDeadlineSql(runId, plan, binding.stepExecutionId);
484
+ this.store.put('sessions', session, { runId, parentId: step.id });
485
+ this.store.setPrivate('session_authority', id, authority);
486
+ this.commands.retries.begin(authority.retryEpisodeId, authority.logicalOperationId);
487
+ this.store.setPrivate('assignments', id, assignment);
488
+ this.store.setPrivate('session_access', id, { runId, inputArtifactIds, historyAfterSeq: Math.max(0, (earliest?.seq ?? 1) - 1), historyThroughSeq: through });
489
+ const current = this.commands.plan(runId);
490
+ if (role === 'worker') {
491
+ current.steps[current.ordinal].workerSessionId = id;
492
+ if (current.reset?.role === 'worker' && !current.reset.replacementSessionId) {
493
+ const execution = this.store.get('steps', step.id);
494
+ if (execution.resetsUsed >= execution.maxSessionResets)
495
+ throw new ApiError(409, 'session_budget_exhausted', 'The worker reset allowance is exhausted.');
496
+ this.store.put('steps', { ...execution, resetsUsed: execution.resetsUsed + 1 }, { runId });
497
+ current.reset.replacementSessionId = id;
498
+ delete current.steps[current.ordinal].reentry;
499
+ }
500
+ }
501
+ else
502
+ current.steps[current.ordinal].auxiliarySessionId = id;
503
+ this.commands.savePlan(runId, current);
504
+ this.store.put('steps', { ...this.store.get('steps', step.id), activeSessionId: id }, { runId });
505
+ this.store.event(runId, 'session_started', 'session', id, { role, profileVersionId: profile.id, instructionSnapshotId: pin.snapshotId });
506
+ });
507
+ await this.effect(runId, 'Start fresh contained provider conversation', () => this.options.driver.start({
508
+ session, assignment, binding, workspaceInstructions: plan.workspaceInstructions
509
+ }), id);
510
+ return id;
511
+ }
512
+ async agent(runId, role) {
513
+ this.gate(runId);
514
+ let plan = this.commands.plan(runId), step = plan.steps[plan.ordinal];
515
+ if (role === 'verifier' && step.verifierRetirementId) {
516
+ const retiring = step.verifierRetirementId;
517
+ await this.closeSession(retiring);
518
+ this.gate(runId);
519
+ plan = this.commands.plan(runId);
520
+ step = plan.steps[plan.ordinal];
521
+ if (step.auxiliarySessionId === retiring)
522
+ delete step.auxiliarySessionId;
523
+ delete step.verifierRetirementId;
524
+ this.commands.savePlan(runId, plan);
525
+ this.wake(runId);
526
+ return;
527
+ }
528
+ let id = role === 'worker' ? step.workerSessionId : step.auxiliarySessionId;
529
+ if (!id)
530
+ id = await this.launch(runId, role);
531
+ this.gate(runId);
532
+ plan = this.commands.plan(runId);
533
+ step = plan.steps[plan.ordinal];
534
+ const session = this.store.get('sessions', id), authority = this.store.private('session_authority', id);
535
+ if (this.options.driver.active(id)) {
536
+ this.options.driver.flush(id);
537
+ return;
538
+ }
539
+ if (!this.options.driver.alive(id)) {
540
+ this.interrupt(runId);
541
+ return;
542
+ }
543
+ if (expired(authority.clock, this.commands.now()) || session.limits.maxSubmissions !== undefined && session.submissionsUsed >= session.limits.maxSubmissions) {
544
+ this.setSession(id, 'exhausted');
545
+ if (role === 'worker') {
546
+ plan.reset = { reason: 'worker_exhausted', role: 'worker', oldSessionId: id };
547
+ plan.stage = 'reset';
548
+ this.commands.savePlan(runId, plan);
549
+ this.wake(runId);
550
+ }
551
+ else
552
+ this.commands.block(runId, 'verification_failed', 'The verifier episode allowance is exhausted.', ['increase_budgets', 'replace_profile', 'rollback']);
553
+ return;
554
+ }
555
+ if (session.state !== 'running')
556
+ return;
557
+ const prior = this.store.private('execution_failure', authority.logicalOperationId);
558
+ if (role === 'verifier' && prior && !prior.retry) {
559
+ this.commands.block(runId, 'verification_failed', 'The shared verifier execution retry allowance is exhausted.', ['increase_budgets', 'replace_profile', 'rollback']);
560
+ return;
561
+ }
562
+ if (role === 'verifier' && prior?.retry) {
563
+ step.verifierRetirementId = id;
564
+ this.commands.savePlan(runId, plan);
565
+ this.wake(runId);
566
+ return;
567
+ }
568
+ if (this.store.private('execution_completion', authority.logicalOperationId) || prior) {
569
+ if (role === 'worker' && (this.store.private('execution_completion', authority.logicalOperationId) || prior?.chargeAttempt))
570
+ authority.retryEpisodeId = randomUUID();
571
+ authority.logicalOperationId = randomUUID();
572
+ this.store.coordinator.atomic(() => { this.store.setPrivate('session_authority', id, authority); this.commands.retries.begin(authority.retryEpisodeId, authority.logicalOperationId); });
573
+ }
574
+ await this.effect(runId, 'Admit one bounded agent turn', () => this.options.driver.turn(id, this.prompt(id)), id);
575
+ }
576
+ prompt(sessionId) {
577
+ const session = this.store.get('sessions', sessionId), authority = this.store.private('session_authority', sessionId);
578
+ const plan = this.commands.plan(session.runId), step = plan.definition.steps[plan.ordinal];
579
+ const byteCount = this.store.coordinator.db.prepare("SELECT COALESCE(SUM(length(CAST(body AS BLOB))),0) AS n FROM engine_resources WHERE kind='artifacts' AND id IN (SELECT value FROM json_each(?))")
580
+ .get(JSON.stringify(authority.inputArtifactIds));
581
+ if (!authority.binding.configuredTools.includes('get_context') && byteCount.n > (this.options.maxContextBytes ?? 67_108_864))
582
+ throw new ApiError(422, 'assignment_context_limit', 'Assigned artifact context exceeds the configured runtime bound.');
583
+ const artifacts = authority.inputArtifactIds.map(id => this.store.get('artifacts', id));
584
+ const bounded = authority.binding.configuredTools.includes('get_context'), limit = this.options.contextBytes ?? 65_536;
585
+ const selected = [];
586
+ let bytes = 0;
587
+ for (const artifact of [...artifacts].reverse()) {
588
+ const size = Buffer.byteLength(JSON.stringify(artifact));
589
+ if (!bounded || bytes + size < limit / 2) {
590
+ selected.unshift(artifact);
591
+ bytes += size;
592
+ }
593
+ }
594
+ const historyAccess = this.store.private('session_access', sessionId);
595
+ const history = this.store.list('tool_history', { runId: session.runId, ...(historyAccess ? { after: historyAccess.historyAfterSeq, through: historyAccess.historyThroughSeq } : {}), limit: Number.MAX_SAFE_INTEGER }).slice(-20).map(({ value }) => ({ id: value.id, name: value.event.name, status: value.event.status, output: JSON.stringify(value.event.output ?? '').slice(0, 1024) }));
596
+ const messages = this.store.coordinator.db.prepare("SELECT id,body FROM engine_private WHERE scope='task_message' AND json_extract(body,'$.runId')=? AND (json_extract(body,'$.delivered')=0 OR ?=1) ORDER BY rowid").all(session.runId, session.submissionsUsed === 0 ? 1 : 0).map(row => {
597
+ const message = JSON.parse(row.body);
598
+ this.store.setPrivate('task_message', row.id, { ...message, delivered: true });
599
+ return { id: row.id, text: message.text };
600
+ });
601
+ const ids = criterionIds(step.exitCriteria.semantic?.criteria ?? []);
602
+ const format = session.effectiveConfiguration.definition.runtime.options?.artifactFormat === 'yaml' ? 'YAML' : 'JSON';
603
+ const prefix = `Perform only the current assigned ${authority.phase} task. Use only the broker tools. Return ONLY the ${format} output document, without Markdown fences. Do not submit HTTP envelopes or claim Git authority.\n` +
604
+ (authority.phase === 'verification' ? 'Check every assigned criterion against the exact artifact and pinned live workspace revision. approve requires ALL pass. revise requires actionable guidance. Project edits are forbidden.\n' : '') + (bounded ? 'Use get_context to retrieve omitted inputs, schemas, artifacts, or user guidance before completing the task.\n' : '');
605
+ const payload = { workflowStepId: step.id, name: step.name ?? step.id, outputSchema: authority.outputSchema, phase: authority.phase,
606
+ criteria: (step.exitCriteria.semantic?.criteria ?? []).map((description, index) => ({ criterionId: ids[index], description })),
607
+ ...(authority.subjectSubmissionId ? { subjectSubmissionId: authority.subjectSubmissionId, workspaceRevisionId: authority.workspaceRevisionId } : {}),
608
+ inputs: bounded && Buffer.byteLength(JSON.stringify(plan.inputs ?? null)) > limit / 4 ? { retrieve: 'get_context', kind: 'inputs' } : plan.inputs ?? null, inputArtifacts: plan.inputArtifacts ?? [], userMessages: bounded ? messages.slice(-8).map(m => ({ id: m.id, text: m.text.slice(0, 2048), ...(m.text.length > 2048 ? { retrieve: 'get_context', kind: 'messages', truncated: true } : {}) })) : messages,
609
+ capabilities: { tools: authority.binding.configuredTools, permissions: session.effectiveConfiguration.effectivePermissions, limits: session.limits, submissionsUsed: session.submissionsUsed, remainingSubmissions: session.limits.maxSubmissions === undefined ? null : Math.max(0, session.limits.maxSubmissions - session.submissionsUsed), timing: session.timing, commands: this.options.commandCapabilities?.() ?? null },
610
+ recentToolHistory: history, artifactManifest: artifacts.slice(-100).map(a => ({ id: a.id, kind: a.kind, bytes: Buffer.byteLength(a.document.content) })),
611
+ artifacts: selected.map(value => ({ id: value.id, kind: value.kind, document: value.document, contentDigest: value.contentDigest })),
612
+ schemaResources: bounded ? plan.graph.resources.filter(r => JSON.stringify(r.schema).length < 8192).slice(0, 4) : plan.graph.resources };
613
+ if (bounded) {
614
+ const payloadLimit = limit - Buffer.byteLength(prefix);
615
+ payload.guidanceManifest = (plan.workspaceInstructions?.files ?? []).filter(file => file.selected).slice(0, 32).map(file => ({ path: file.path, bytes: Buffer.byteLength(file.content), sha256: file.sha256 }));
616
+ payload.questions = this.store.coordinator.db.prepare("SELECT body FROM engine_private WHERE scope='worker_question' AND json_extract(body,'$.runId')=? ORDER BY rowid DESC LIMIT 8").all(session.runId).map(row => { const q = JSON.parse(row.body); return { id: q.id, state: q.state, question: q.question.slice(0, 2048), answer: q.answer?.slice(0, 2048), retrieve: 'get_context', kind: 'questions' }; });
617
+ payload.contextRetrieval = { tool: 'get_context', artifacts: 'artifacts', priorHistory: 'history', schemas: 'schemas', messages: 'messages', questions: 'questions', guidance: 'guidance' };
618
+ if (Buffer.byteLength(JSON.stringify(payload.outputSchema)) > limit / 4)
619
+ payload.outputSchema = { retrieve: 'get_context', kind: 'schema' };
620
+ for (const key of ['schemaResources', 'recentToolHistory', 'artifacts', 'artifactManifest', 'userMessages', 'questions', 'guidanceManifest']) {
621
+ const items = payload[key];
622
+ while (items.length && Buffer.byteLength(JSON.stringify(payload)) > payloadLimit)
623
+ items.shift();
624
+ }
625
+ if (Buffer.byteLength(JSON.stringify(payload)) > payloadLimit)
626
+ throw new ApiError(422, 'assignment_context_limit', 'Required assignment metadata exceeds contextBytes; increase the bound or simplify the selected profile.');
627
+ }
628
+ return prefix + JSON.stringify(payload);
629
+ }
630
+ adapterContext(sessionId, body, key) {
631
+ const session = this.store.get('sessions', sessionId), authority = this.store.private('session_authority', sessionId);
632
+ return { requestId: key, signal: this.signal(session.runId), principal: { id: `adapter_${sessionId}`, audience: 'adapter', sessionId,
633
+ epoch: session.epoch, role: session.role, workspaceIds: [authority.workspaceId] }, params: { sessionId }, query: {}, body,
634
+ header: name => name === 'idempotency-key' ? key : undefined };
635
+ }
636
+ async result(sessionId, content) {
637
+ if (this.#closed)
638
+ return;
639
+ const session = this.store.get('sessions', sessionId);
640
+ if (!this.commands.current(sessionId, session.epoch))
641
+ return;
642
+ const authority = this.store.private('session_authority', sessionId);
643
+ const mediaType = session.effectiveConfiguration.definition.runtime.options?.artifactFormat === 'yaml' ? 'application/yaml' : 'application/json';
644
+ const document = { mediaType, content }, kind = authority.phase === 'work' ? 'exit' : authority.phase === 'verification' ? 'verdict' : 'handoff';
645
+ const lease = this.options.workspaces.lease(session.runId);
646
+ const body = kind === 'exit' ? { artifact: document, observedHeadCommit: this.options.workspaces.revision(lease.knownRevisionId).headCommit } :
647
+ kind === 'verdict' ? { report: document, subjectSubmissionId: authority.subjectSubmissionId, workspaceRevisionId: authority.workspaceRevisionId } : { artifact: document };
648
+ const envelope = await this.effect(session.runId, 'Validate adapter completion envelope', () => this.options.validation.run({
649
+ kind: 'wire', schema: kind === 'exit' ? 'ExitSubmissionCreate' : kind === 'verdict' ? 'VerificationVerdictCreate' : 'HandoffSubmissionCreate', value: body
650
+ }, { runId: session.runId, signal: this.signal(session.runId) }), sessionId);
651
+ if (!envelope.valid)
652
+ throw new ApiError(400, 'invalid_adapter_envelope', 'Runtime completion envelope is invalid.', false, envelope.errors);
653
+ if (this.#closed)
654
+ return;
655
+ this.commands.submit(this.adapterContext(sessionId, body, `turn_${authority.logicalOperationId}`), kind);
656
+ }
657
+ async failure(sessionId, message) {
658
+ if (this.#closed)
659
+ return;
660
+ const session = this.store.find('sessions', sessionId);
661
+ if (!session || !this.commands.current(sessionId, session.epoch))
662
+ return;
663
+ const authority = this.store.private('session_authority', sessionId);
664
+ this.commands.failure(this.adapterContext(sessionId, { clientFailureId: `failure_${authority.logicalOperationId}`, category: 'runtime', message }, `failure_${authority.logicalOperationId}`));
665
+ if (!this.options.driver.alive(sessionId) && !this.commands.plan(session.runId).cancelOperationId)
666
+ this.interrupt(session.runId);
667
+ }
668
+ async evaluate(runId) {
669
+ this.gate(runId);
670
+ if (!this.quiet(runId))
671
+ return;
672
+ let plan = this.commands.plan(runId);
673
+ const id = plan.pendingSubmissionId;
674
+ if (!id)
675
+ throw new Error('pending_submission_missing');
676
+ let submission = this.store.get('submissions', id);
677
+ const artifact = this.store.get('artifacts', submission.artifactId), step = plan.definition.steps[plan.ordinal];
678
+ const pendingMessages = this.store.coordinator.db.prepare("SELECT id FROM engine_private WHERE scope='task_message' AND json_extract(body,'$.runId')=? AND json_extract(body,'$.delivered')=0").all(runId);
679
+ if (submission.kind === 'exit' && pendingMessages.length) {
680
+ await this.reject(runId, submission, [{ code: 'new_user_guidance', message: 'New user guidance arrived. Read the queued messages before completing the task.' }]);
681
+ return;
682
+ }
683
+ if (submission.kind === 'exit' && !submission.workspaceRevision) {
684
+ const revision = this.options.workspaces.captureRevision(runId);
685
+ submission = { ...submission, workspaceRevision: revision, state: 'validating' };
686
+ this.store.put('submissions', submission, { runId, parentId: submission.sessionId });
687
+ const expected = this.store.private('submission_metadata', id);
688
+ if (revision.headCommit !== expected.observedHeadCommit)
689
+ throw new WorkspaceError('git_expected_head_conflict');
690
+ }
691
+ const decoded = artifact.document.mediaType === 'text/plain' ? { valid: true, value: artifact.document.content, errors: [] } :
692
+ await this.effect(runId, 'Decode admitted artifact', () => this.options.validation.run({ kind: 'decode', content: artifact.document.content,
693
+ format: artifact.document.mediaType === 'application/json' ? 'json' : 'yaml' }, { runId, signal: this.signal(runId) }));
694
+ this.gate(runId);
695
+ if (!decoded.valid) {
696
+ await this.reject(runId, submission, decoded.errors);
697
+ return;
698
+ }
699
+ if (submission.kind === 'verdict') {
700
+ const authority = this.store.private('session_authority', submission.sessionId);
701
+ this.options.workspaces.assertRevision(runId, authority.workspaceRevisionId);
702
+ const validated = await this.effect(runId, 'Validate verifier correspondence and evidence', () => this.options.validation.run({
703
+ kind: 'verdict', value: decoded.value, criterionIds: criterionIds(step.exitCriteria.semantic.criteria), evidenceArtifactIds: authority.inputArtifactIds
704
+ }, { runId, signal: this.signal(runId) }));
705
+ this.gate(runId);
706
+ if (!validated.valid) {
707
+ await this.reject(runId, submission, validated.errors);
708
+ return;
709
+ }
710
+ const report = validated.value;
711
+ this.store.coordinator.atomic(() => {
712
+ this.store.put('submissions', { ...submission, state: 'accepted' }, { runId, parentId: submission.sessionId });
713
+ this.store.put('artifacts', { ...artifact, state: 'accepted' }, { runId });
714
+ this.store.event(runId, 'submission_evaluated', 'submission', submission.id, { decision: report.decision });
715
+ });
716
+ await this.closeSession(submission.sessionId);
717
+ plan = this.commands.plan(runId);
718
+ delete plan.pendingSubmissionId;
719
+ delete plan.steps[plan.ordinal].auxiliarySessionId;
720
+ if (report.decision === 'approve')
721
+ plan.stage = 'accept';
722
+ else {
723
+ const candidate = this.store.get('submissions', plan.steps[plan.ordinal].candidateId);
724
+ this.store.put('submissions', { ...candidate, state: 'rejected', validationIssues: [{ code: 'semantic_revision', message: report.guidance }] }, { runId, parentId: candidate.sessionId });
725
+ this.store.put('artifacts', { ...this.store.get('artifacts', candidate.artifactId), state: 'rejected' }, { runId });
726
+ const guidance = { id: randomUUID(), runId, stepExecutionId: candidate.stepExecutionId, kind: 'guidance',
727
+ document: { mediaType: 'text/plain', content: report.guidance }, contentDigest: sha(report.guidance), state: 'accepted', createdAt: new Date(this.commands.now()).toISOString() };
728
+ this.store.put('artifacts', guidance, { runId, immutable: true });
729
+ plan.stage = 'worker';
730
+ this.addInput(plan.steps[plan.ordinal].workerSessionId, guidance.id);
731
+ this.setSession(plan.steps[plan.ordinal].workerSessionId, 'running');
732
+ this.commands.updateRun(runId, { state: 'running' });
733
+ this.stepState(runId, 'running');
734
+ }
735
+ this.store.coordinator.atomic(() => { this.commands.savePlan(runId, plan); this.broker.setHold(runId, 'submission', false); });
736
+ this.wake(runId);
737
+ return;
738
+ }
739
+ const root = plan.graph.roots.find(value => value.stepId === step.id && value.kind === (submission.kind === 'handoff' ? 'handoff' : 'exit'));
740
+ const checked = await this.effect(runId, 'Validate mandatory artifact schema', () => this.options.validation.run({
741
+ kind: 'artifact', rootUri: root.uri, resources: plan.graph.resources, value: decoded.value
742
+ }, { runId, signal: this.signal(runId) }));
743
+ this.gate(runId);
744
+ if (!checked.valid) {
745
+ await this.reject(runId, submission, checked.errors);
746
+ return;
747
+ }
748
+ if (submission.kind === 'handoff') {
749
+ this.store.coordinator.atomic(() => {
750
+ const current = this.commands.plan(runId);
751
+ if (!current.reset)
752
+ throw new Error('handoff_reset_missing');
753
+ current.reset.handoffId = artifact.id;
754
+ current.stage = 'reset';
755
+ delete current.pendingSubmissionId;
756
+ this.commands.savePlan(runId, current);
757
+ this.store.put('submissions', { ...submission, state: 'accepted' }, { runId, parentId: submission.sessionId });
758
+ this.store.put('artifacts', { ...artifact, state: 'accepted' }, { runId });
759
+ this.broker.setHold(runId, 'submission', false);
760
+ });
761
+ this.wake(runId);
762
+ return;
763
+ }
764
+ if (!await this.checks(runId, submission, decoded.value))
765
+ return;
766
+ this.gate(runId);
767
+ this.store.coordinator.atomic(() => {
768
+ const current = this.commands.plan(runId), currentStep = current.steps[current.ordinal];
769
+ currentStep.candidateId = submission.id;
770
+ currentStep.verificationCharges = 0;
771
+ currentStep.verificationConsumedMs = 0;
772
+ delete current.pendingSubmissionId;
773
+ current.stage = step.exitCriteria.semantic?.criteria.length ? 'verify' : 'accept';
774
+ this.commands.savePlan(runId, current);
775
+ this.store.put('submissions', { ...submission, state: 'verifying' }, { runId, parentId: submission.sessionId });
776
+ this.commands.updateRun(runId, { state: 'verifying' });
777
+ this.stepState(runId, 'verifying');
778
+ this.broker.setHold(runId, 'submission', false);
779
+ });
780
+ this.wake(runId);
781
+ }
782
+ async checks(runId, submission, decoded) {
783
+ const plan = this.commands.plan(runId), step = plan.definition.steps[plan.ordinal], artifact = this.store.get('artifacts', submission.artifactId);
784
+ const failures = [];
785
+ for (const name of step.exitCriteria.deterministic?.checks ?? []) {
786
+ this.gate(runId);
787
+ const key = `${submission.id}:${name}`, prior = this.store.private('check_result', key);
788
+ if (prior) {
789
+ if (prior.status === 'fail')
790
+ failures.push({ code: 'named_check_failed', message: prior.explanation, path: name });
791
+ continue;
792
+ }
793
+ const check = this.options.checks.get(name);
794
+ if (!check)
795
+ throw new ApiError(422, 'unknown_named_check', 'A required check is unavailable.');
796
+ const episode = `verification_${submission.id}`, operation = randomUUID();
797
+ this.commands.retries.begin(episode, operation);
798
+ this.store.setPrivate('check_intent', key, { operationId: operation, episodeId: episode, state: 'started' });
799
+ const result = await this.effect(runId, 'Execute registered deterministic check', () => check.execute({ runId,
800
+ stepExecutionId: submission.stepExecutionId, leaseId: this.options.workspaces.lease(runId).id,
801
+ workspaceRevisionId: submission.workspaceRevision.id, artifactId: artifact.id,
802
+ artifact: { mediaType: artifact.document.mediaType, content: artifact.document.content, decoded },
803
+ deadlineAt: Math.min(this.commands.now() + (check.timeoutMs ?? 30_000), plan.clock.deadlineAt ?? Infinity, plan.stepClocks[submission.stepExecutionId]?.deadlineAt ?? Infinity) }, this.signal(runId)));
804
+ if (result.status === 'infrastructure_error') {
805
+ const retry = this.commands.retries.failure(episode, operation, { category: 'infrastructure', verifier: true, alreadyCharged: true,
806
+ infrastructureRetries: this.store.get('runs', runId).policy.infrastructureRetries ?? 3,
807
+ verificationRetries: this.store.get('runs', runId).policy.verificationRetries ?? 3 });
808
+ this.store.setPrivate('check_intent', key, { operationId: operation, episodeId: episode, state: 'failed' });
809
+ if (!retry.retry || !result.retryable)
810
+ this.commands.block(runId, 'verification_failed', 'A mandatory deterministic check could not execute within its retry allowance.', ['increase_budgets', 'rollback']);
811
+ else
812
+ this.wake(runId);
813
+ return false;
814
+ }
815
+ this.store.setPrivate('check_result', key, result);
816
+ this.store.setPrivate('check_intent', key, { operationId: operation, episodeId: episode, state: 'done' });
817
+ if (result.status === 'fail')
818
+ failures.push({ code: 'named_check_failed', message: result.explanation, path: name });
819
+ }
820
+ if (failures.length) {
821
+ await this.reject(runId, submission, failures);
822
+ return false;
823
+ }
824
+ return true;
825
+ }
826
+ async reject(runId, submission, issues) {
827
+ const artifact = this.store.get('artifacts', submission.artifactId);
828
+ let plan = this.commands.plan(runId);
829
+ this.store.coordinator.atomic(() => {
830
+ this.store.put('submissions', { ...submission, state: 'rejected', validationIssues: issues }, { runId, parentId: submission.sessionId });
831
+ this.store.put('artifacts', { ...artifact, state: 'rejected' }, { runId });
832
+ this.store.event(runId, 'submission_evaluated', 'submission', submission.id, { state: 'rejected', issues });
833
+ });
834
+ const session = this.store.get('sessions', submission.sessionId), authority = this.store.private('session_authority', session.id);
835
+ if (submission.kind === 'verdict') {
836
+ const retry = this.commands.retries.failure(authority.retryEpisodeId, authority.logicalOperationId, { category: 'verification_execution',
837
+ verifier: true, alreadyCharged: true, infrastructureRetries: this.store.get('runs', runId).policy.infrastructureRetries ?? 3,
838
+ verificationRetries: this.store.get('runs', runId).policy.verificationRetries ?? 3 });
839
+ await this.closeSession(session.id);
840
+ plan = this.commands.plan(runId);
841
+ delete plan.steps[plan.ordinal].auxiliarySessionId;
842
+ plan.stage = 'verify';
843
+ if (!retry.retry)
844
+ this.commands.block(runId, 'verification_failed', 'Verifier execution retry allowance is exhausted.', ['increase_budgets', 'replace_profile', 'rollback']);
845
+ }
846
+ else if (submission.kind === 'handoff') {
847
+ plan.stage = 'handoff';
848
+ this.setSession(session.id, 'running');
849
+ const current = this.store.private('session_authority', session.id);
850
+ if (expired(current.clock, this.commands.now()) || session.limits.maxSubmissions !== undefined && session.submissionsUsed >= session.limits.maxSubmissions)
851
+ this.commands.block(runId, 'handoff_failed', 'The mandatory handoff could not be produced within the original bounded allowance.', ['increase_budgets', 'replace_profile']);
852
+ }
853
+ else {
854
+ plan.stage = 'worker';
855
+ this.setSession(session.id, 'running');
856
+ }
857
+ delete plan.pendingSubmissionId;
858
+ this.store.coordinator.atomic(() => {
859
+ this.commands.savePlan(runId, plan);
860
+ this.broker.setHold(runId, 'submission', false);
861
+ const content = issues.map(issue => `${issue.code}: ${issue.message}`).join('\n');
862
+ const guidance = { id: randomUUID(), runId, kind: 'guidance', stepExecutionId: submission.stepExecutionId,
863
+ document: { mediaType: 'text/plain', content }, contentDigest: sha(content), state: 'accepted', createdAt: new Date(this.commands.now()).toISOString() };
864
+ this.store.put('artifacts', guidance, { runId, immutable: true });
865
+ this.addInput(session.id, guidance.id);
866
+ });
867
+ this.wake(runId);
868
+ }
869
+ addInput(sessionId, artifactId) {
870
+ const authority = this.store.private('session_authority', sessionId);
871
+ if (!authority.inputArtifactIds.includes(artifactId))
872
+ authority.inputArtifactIds.push(artifactId);
873
+ this.store.setPrivate('session_authority', sessionId, authority);
874
+ const assignment = this.store.private('assignments', sessionId);
875
+ if (assignment)
876
+ this.store.setPrivate('assignments', sessionId, { ...assignment, inputArtifactIds: authority.inputArtifactIds });
877
+ const access = this.store.private('session_access', sessionId);
878
+ this.store.setPrivate('session_access', sessionId, { ...access, inputArtifactIds: authority.inputArtifactIds });
879
+ }
880
+ async closeSession(id) {
881
+ const session = this.store.get('sessions', id), authority = this.store.private('session_authority', id);
882
+ this.store.coordinator.atomic(() => {
883
+ if (this.commands.current(id, session.epoch))
884
+ this.broker.fenceSession(authority.binding);
885
+ this.commands.options.auth.revokeSession(id);
886
+ if (!this.store.private('session_time_accounted', id)) {
887
+ const elapsed = consumed(authority.clock, this.commands.now()), plan = this.commands.plan(session.runId);
888
+ if (session.role === 'verifier')
889
+ plan.steps.find(value => value.id === session.stepExecutionId).verificationConsumedMs += elapsed;
890
+ if (session.role === 'handoff' && plan.reset)
891
+ plan.reset.handoffConsumedMs = (plan.reset.handoffConsumedMs ?? 0) + elapsed;
892
+ this.commands.savePlan(session.runId, plan);
893
+ this.store.setPrivate('session_time_accounted', id, { elapsed });
894
+ }
895
+ this.setSession(id, 'terminated');
896
+ });
897
+ await this.effect(session.runId, 'Wait for managed runtime physical exit', () => this.options.driver.stop(id), id);
898
+ this.#stopped.add(id);
899
+ }
900
+ async stopSessions(runId) {
901
+ for (const row of this.store.list('sessions', { runId, limit: Number.MAX_SAFE_INTEGER })) {
902
+ await this.options.driver.stop(row.value.id);
903
+ this.#stopped.add(row.value.id);
904
+ }
905
+ }
906
+ async accept(runId) {
907
+ this.gate(runId);
908
+ const plan = this.commands.plan(runId), step = plan.steps[plan.ordinal], submission = this.store.get('submissions', step.candidateId);
909
+ for (const id of [step.auxiliarySessionId, step.workerSessionId])
910
+ if (id)
911
+ await this.closeSession(id);
912
+ this.gate(runId);
913
+ if (!this.quiet(runId))
914
+ return;
915
+ const artifact = this.store.get('artifacts', submission.artifactId);
916
+ this.options.workspaces.accept({ runId, stepExecutionId: step.id, artifactId: artifact.id, revisionId: submission.workspaceRevision.id,
917
+ expectedHead: submission.workspaceRevision.headCommit, resultMode: this.commands.plan(runId).resultMode ?? 'commit' }, { onAdmittedSql: job => {
918
+ this.store.setPrivate('workspace_continuation', job.id, { kind: 'accept', submissionId: submission.id, stepId: step.id });
919
+ }, onCompletedSql: job => this.workspaceCompleted(job) });
920
+ this.wake(runId);
921
+ }
922
+ workspaceCompleted(job) {
923
+ if (this.store.private('workspace_completion', job.id))
924
+ return;
925
+ const continuation = this.store.private('workspace_continuation', job.id);
926
+ if (!continuation)
927
+ throw new Error('workspace_continuation_missing');
928
+ const plan = this.commands.plan(job.runId);
929
+ if (continuation.kind === 'accept') {
930
+ const submission = this.store.get('submissions', continuation.submissionId), artifact = this.store.get('artifacts', submission.artifactId);
931
+ const eligible = submission.state !== 'superseded' && plan.steps[plan.ordinal]?.id === continuation.stepId;
932
+ this.store.put('submissions', { ...submission, state: eligible ? 'accepted' : 'superseded' }, { runId: job.runId, parentId: submission.sessionId });
933
+ this.store.put('artifacts', { ...artifact, state: eligible ? 'accepted' : 'superseded', ...(job.resultMode === 'working_tree' ? {} : { commit: job.commit }) }, { runId: job.runId });
934
+ if (eligible) {
935
+ const step = this.store.get('steps', continuation.stepId), stepClock = plan.stepClocks[step.id];
936
+ if (stepClock)
937
+ plan.stepClocks[step.id] = checkpoint(stepClock, false, this.commands.now());
938
+ this.store.put('steps', { ...step, state: 'succeeded', acceptedSubmissionId: submission.id, acceptedRevisionId: job.revisionId, ...(job.resultMode === 'working_tree' ? {} : { acceptedCommit: job.commit }),
939
+ ...(stepClock ? { timing: status(plan.stepClocks[step.id], true, this.commands.now()) } : {}) }, { runId: job.runId });
940
+ plan.ordinal++;
941
+ plan.stage = plan.ordinal >= plan.steps.length ? 'complete' : 'worker';
942
+ }
943
+ this.store.event(job.runId, job.resultMode === 'working_tree' ? 'artifact_accepted' : 'artifact_committed', 'artifact', artifact.id, { ...(job.resultMode === 'working_tree' ? { revisionId: job.revisionId } : { commit: job.commit }), submissionId: submission.id });
944
+ }
945
+ else {
946
+ this.store.setPrivate('restore_completed', job.runId, { operationId: continuation.operationId ?? '', jobId: job.id });
947
+ }
948
+ this.commands.savePlan(job.runId, plan);
949
+ this.syncBrokerDeadlineSql(job.runId, plan);
950
+ this.store.setPrivate('workspace_completion', job.id, { completed: true });
951
+ }
952
+ operationState(id, state, code, blockId) {
953
+ const previous = this.store.get('operations', id);
954
+ const { error: _error, blockId: _block, ...base } = previous;
955
+ this.store.put('operations', { ...base, state, updatedAt: new Date(this.commands.now()).toISOString(),
956
+ ...(code ? { error: problem(new ApiError(409, code, 'The operation could not complete in the current execution state.'), id) } : {}),
957
+ ...(blockId ? { blockId } : {}), ...(state === 'succeeded' ? { result: { resourceType: 'run', resourceId: previous.runId } } : {}) }, { runId: previous.runId });
958
+ }
959
+ pause(runId) {
960
+ const work = this.work(runId), run = this.store.get('runs', runId), operationId = run.executionControl.pauseOperationId;
961
+ if (work.length) {
962
+ const grace = run.executionControl.graceDeadlineAt;
963
+ if (grace && this.commands.now() >= Date.parse(grace)) {
964
+ const block = this.commands.block(runId, 'pause_stalled', 'Active work did not drain before operator pause grace expired.', ['extend_pause_grace'], { hold: 'operator_pause' });
965
+ if (operationId)
966
+ this.operationState(operationId, 'waiting_for_decision', undefined, block.id);
967
+ }
968
+ if (canonical(work) !== canonical(run.executionControl.inFlightWork))
969
+ this.commands.updateRun(runId, { executionControl: { ...this.store.get('runs', runId).executionControl, inFlightWork: work } });
970
+ this.updateClocks(runId);
971
+ return;
972
+ }
973
+ this.store.coordinator.atomic(() => {
974
+ const current = this.store.get('runs', runId);
975
+ for (const { value: session } of this.store.list('sessions', { runId, limit: Number.MAX_SAFE_INTEGER })) {
976
+ if (['starting', 'running', 'paused_for_verification', 'waiting_for_approval'].includes(session.state)) {
977
+ this.setSession(session.id, 'paused');
978
+ this.store.put('sessions', { ...this.store.get('sessions', session.id), suspendedState: session.state }, { runId, parentId: session.stepExecutionId });
979
+ }
980
+ }
981
+ this.commands.updateRun(runId, { state: 'paused', executionControl: { ...current.executionControl, status: 'paused',
982
+ pausedAt: new Date(this.commands.now()).toISOString(), inFlightWork: [] } });
983
+ this.updateClocks(runId);
984
+ if (operationId)
985
+ this.operationState(operationId, 'succeeded');
986
+ this.store.event(runId, 'pause_completed', 'run', runId, {});
987
+ });
988
+ }
989
+ async resume(runId) {
990
+ const operationId = this.store.private('resume_operation', runId).id;
991
+ let run = this.store.get('runs', runId), plan = this.commands.plan(runId);
992
+ const step = plan.steps[plan.ordinal];
993
+ // Recovery already stopped this retiring worker before recording its reset.
994
+ // Re-pausing that authorized transition must not demand its lost conversation
995
+ // again. Every other preserved session still requires the ordinary proof.
996
+ const reset = plan.reset, recovery = reset?.operationId ? this.store.find('operations', reset.operationId) : undefined;
997
+ const retiring = reset?.oldSessionId ? this.store.find('sessions', reset.oldSessionId) : undefined;
998
+ const authority = retiring ? this.store.private('session_authority', retiring.id) : undefined;
999
+ const retiringWorkerId = step && recovery && retiring && authority && reset?.id &&
1000
+ reset.reason === 'recovery' && reset.interrupted === true && reset.role === 'worker' &&
1001
+ !reset.replacementSessionId && reset.oldSessionId === step?.workerSessionId && step?.id === run.currentStepId &&
1002
+ recovery?.id === reset.operationId && recovery.kind === 'recover' && recovery.runId === runId && recovery.state === 'running' &&
1003
+ retiring?.id === reset.oldSessionId && retiring.role === 'worker' && retiring.runId === runId && retiring.stepExecutionId === step.id &&
1004
+ authority?.binding.sessionId === retiring.id && authority.binding.runId === runId && authority.binding.stepExecutionId === step.id &&
1005
+ authority.binding.role === 'worker' && authority.binding.epoch === retiring.epoch && authority.binding.profileVersionId === retiring.profileVersionId
1006
+ ? retiring.id : undefined;
1007
+ const required = [step?.workerSessionId, step?.auxiliarySessionId].filter((id) => !!id)
1008
+ .map(id => this.store.get('sessions', id)).filter(session => session.id !== retiringWorkerId && !['terminated', 'completed'].includes(session.state));
1009
+ if (required.some(session => !this.options.driver.alive(session.id))) {
1010
+ const block = this.commands.block(runId, 'resume_requires_recovery', 'A preserved provider conversation is missing. Explicit recovery is required.', [], { recoveryAllowed: true });
1011
+ this.commands.updateRun(runId, { state: 'blocked', executionControl: { ...run.executionControl, status: 'paused' } });
1012
+ this.operationState(operationId, 'failed', 'resume_requires_recovery', block.id);
1013
+ this.store.event(runId, 'resume_blocked', 'operation', operationId, { blockId: block.id });
1014
+ return;
1015
+ }
1016
+ if (run.pendingBlockIds.length) {
1017
+ this.commands.updateRun(runId, { state: 'blocked', executionControl: { ...run.executionControl, status: 'paused' } });
1018
+ this.operationState(operationId, 'failed', 'state_conflict', run.pendingBlockIds[0]);
1019
+ return;
1020
+ }
1021
+ try {
1022
+ this.options.workspaces.assertKnown(runId);
1023
+ }
1024
+ catch (error) {
1025
+ this.commands.updateRun(runId, { state: 'blocked', executionControl: { ...run.executionControl, status: 'paused' } });
1026
+ this.operationState(operationId, 'failed', 'state_conflict');
1027
+ throw error;
1028
+ }
1029
+ this.store.coordinator.atomic(() => {
1030
+ run = this.store.get('runs', runId);
1031
+ plan = this.commands.plan(runId);
1032
+ this.broker.setHold(runId, 'queued_decisions', plan.queuedDecisions.length > 0);
1033
+ for (const session of required) {
1034
+ if (session.state !== 'paused' || !session.suspendedState)
1035
+ continue;
1036
+ const state = session.suspendedState === 'running' || session.suspendedState === 'waiting_for_approval'
1037
+ ? run.approvalWait.status === 'none' ? 'running' : 'waiting_for_approval'
1038
+ : session.suspendedState;
1039
+ const { suspendedState: _old, ...rest } = session;
1040
+ this.store.put('sessions', rest, { runId, parentId: session.stepExecutionId });
1041
+ this.setSession(session.id, state);
1042
+ }
1043
+ this.commands.updateRun(runId, { state: run.executionControl.continuationState ?? 'running', executionControl: { status: 'running', inFlightWork: [] } });
1044
+ this.broker.resume(runId);
1045
+ this.operationState(operationId, 'succeeded');
1046
+ this.updateClocks(runId);
1047
+ this.store.event(runId, 'resume_completed', 'operation', operationId, {});
1048
+ });
1049
+ if (!plan.queuedDecisions.length && run.approvalWait.status === 'none')
1050
+ for (const session of required)
1051
+ this.options.driver.flush(session.id);
1052
+ this.wake(runId);
1053
+ }
1054
+ async extendGrace(runId) {
1055
+ const plan = this.commands.plan(runId), selected = plan.queuedDecisions.filter(value => value.decision.kind === 'extend_pause_grace');
1056
+ if (!selected.length)
1057
+ return;
1058
+ this.store.coordinator.atomic(() => {
1059
+ for (const queued of selected) {
1060
+ if (queued.decision.kind !== 'extend_pause_grace')
1061
+ continue;
1062
+ const block = queued.blockId && this.store.get('blocks', queued.blockId), run = this.store.get('runs', runId);
1063
+ const deadline = new Date(this.commands.now() + durationMs(queued.decision.duration)).toISOString();
1064
+ if (block && block.hold === 'operator_pause' && run.executionControl.status === 'pausing') {
1065
+ this.commands.updateRun(runId, { executionControl: { ...run.executionControl, graceDeadlineAt: deadline } });
1066
+ if (run.executionControl.pauseOperationId)
1067
+ this.operationState(run.executionControl.pauseOperationId, 'running');
1068
+ }
1069
+ else if (block && block.hold === 'approval_wait' && run.approvalWait.status === 'draining')
1070
+ this.commands.updateRun(runId, { approvalWait: { ...run.approvalWait, graceDeadlineAt: deadline } });
1071
+ this.operationState(queued.operationId, 'succeeded');
1072
+ }
1073
+ const current = this.commands.plan(runId);
1074
+ current.queuedDecisions = current.queuedDecisions.filter(value => !selected.some(chosen => chosen.operationId === value.operationId));
1075
+ this.commands.savePlan(runId, current);
1076
+ });
1077
+ }
1078
+ approvalDrain(runId) {
1079
+ this.store.coordinator.atomic(() => this.approvalDrainSql(runId));
1080
+ }
1081
+ approvalDrainSql(runId) {
1082
+ let run = this.store.get('runs', runId);
1083
+ if (!run.approvalWait.pendingApprovalIds.length) {
1084
+ if (!terminal(run) && !this.commands.plan(runId).cancelOperationId &&
1085
+ run.executionControl.status === 'running' && !run.pendingBlockIds.length) {
1086
+ for (const { value: session } of this.store.list('sessions', { runId, limit: Number.MAX_SAFE_INTEGER }))
1087
+ if (session.state === 'waiting_for_approval' && this.commands.current(session.id, session.epoch))
1088
+ this.setSession(session.id, 'running');
1089
+ }
1090
+ return;
1091
+ }
1092
+ const work = this.work(runId), approvalWait = approvalWaitFor(run, run.approvalWait.pendingApprovalIds, work, this.commands.now());
1093
+ if (canonical(approvalWait) !== canonical(run.approvalWait))
1094
+ this.commands.updateRun(runId, { approvalWait });
1095
+ if (!work.length) {
1096
+ for (const { value: session } of this.store.list('sessions', { runId, limit: Number.MAX_SAFE_INTEGER }))
1097
+ if (session.state === 'running')
1098
+ this.setSession(session.id, 'waiting_for_approval');
1099
+ }
1100
+ else if (this.commands.now() >= Date.parse(approvalWait.graceDeadlineAt))
1101
+ this.commands.block(runId, 'pause_stalled', 'Active work did not drain before approval-wait grace expired.', ['extend_pause_grace'], { hold: 'approval_wait' });
1102
+ this.updateClocks(runId);
1103
+ }
1104
+ updateClocks(runId) {
1105
+ const run = this.store.get('runs', runId), plan = this.commands.plan(runId), now = this.commands.now();
1106
+ const stopped = terminal(run), paused = run.executionControl.status === 'paused';
1107
+ const blocked = run.pendingBlockIds.length > 0 || run.state === 'interrupted';
1108
+ const inputWaiting = this.options.inputWaiting?.(runId) ?? false;
1109
+ const running = !inputWaiting && !stopped && !paused && run.approvalWait.status !== 'waiting' && (!blocked || plan.timingPolicy.blockedTimeAccounting === 'count');
1110
+ plan.clock = checkpoint(plan.clock, running, now);
1111
+ const current = plan.steps[plan.ordinal], stepClock = current && plan.stepClocks[current.id];
1112
+ if (stepClock)
1113
+ plan.stepClocks[current.id] = checkpoint(stepClock, running, now);
1114
+ this.commands.savePlan(runId, plan);
1115
+ const timing = status(plan.clock, stopped, now);
1116
+ if (timing.clockState !== run.timing.clockState || Math.abs(timing.executionConsumedMs - run.timing.executionConsumedMs) >= 1_000)
1117
+ this.commands.updateRun(runId, { timing });
1118
+ if (stepClock) {
1119
+ const step = this.store.get('steps', current.id), next = status(plan.stepClocks[current.id], stopped || step.state === 'succeeded', now);
1120
+ if (step.timing.clockState !== next.clockState || Math.abs(next.executionConsumedMs - step.timing.executionConsumedMs) >= 1_000)
1121
+ this.store.put('steps', { ...step, timing: next }, { runId });
1122
+ }
1123
+ for (const { value: session } of this.store.list('sessions', { runId, limit: Number.MAX_SAFE_INTEGER })) {
1124
+ if (['completed', 'terminated'].includes(session.state))
1125
+ continue;
1126
+ const authority = this.store.private('session_authority', session.id);
1127
+ if (!authority)
1128
+ continue;
1129
+ authority.clock = checkpoint(authority.clock, running && session.state === 'running', now);
1130
+ this.store.setPrivate('session_authority', session.id, authority);
1131
+ }
1132
+ }
1133
+ deadlines(runId) {
1134
+ const plan = this.commands.plan(runId), now = this.commands.now(), step = plan.steps[plan.ordinal], definition = plan.definition.steps[plan.ordinal];
1135
+ const overall = expired(plan.clock, now), stepExpired = step && plan.stepClocks[step.id] && expired(plan.stepClocks[step.id], now);
1136
+ if (overall || stepExpired) {
1137
+ const policy = overall ? plan.definition.config?.timeout?.['on-timeout'] ?? 'fail' : definition?.timeout?.['on-timeout'] ?? 'block';
1138
+ this.broker.setHold(runId, 'deadline', true);
1139
+ this.#controllers.get(runId)?.abort();
1140
+ void this.stopSessions(runId).catch(error => { this.#fatal = error; });
1141
+ if (policy === 'fail') {
1142
+ this.commands.updateRun(runId, { state: 'failed', completedAt: new Date(now).toISOString() });
1143
+ this.wake(runId);
1144
+ }
1145
+ else
1146
+ this.commands.block(runId, 'deadline_exceeded', 'The workflow or step deadline is exhausted.', []);
1147
+ const resume = this.store.private('resume_operation', runId);
1148
+ if (resume && ['pending', 'running'].includes(this.store.get('operations', resume.id).state))
1149
+ this.operationState(resume.id, 'failed', 'deadline_exceeded');
1150
+ this.updateClocks(runId);
1151
+ return true;
1152
+ }
1153
+ if (!step || !definition)
1154
+ return false;
1155
+ for (const id of [step.workerSessionId, step.auxiliarySessionId]) {
1156
+ if (!id)
1157
+ continue;
1158
+ const session = this.store.get('sessions', id), authority = this.store.private('session_authority', id);
1159
+ if (session.state !== 'running')
1160
+ continue;
1161
+ if (expired(authority.clock, now)) {
1162
+ this.setSession(id, 'exhausted');
1163
+ void this.options.driver.stop(id).catch(error => { this.#fatal = error; });
1164
+ if (authority.phase === 'work') {
1165
+ plan.reset = { reason: 'worker_timeout', oldSessionId: id, role: 'worker', interrupted: true };
1166
+ plan.stage = 'reset';
1167
+ this.commands.savePlan(runId, plan);
1168
+ }
1169
+ else {
1170
+ const timeout = authority.phase === 'verification' ? definition.exitCriteria.semantic?.verifier.timeout : definition.handoffArtifact?.timeout;
1171
+ if (timeout?.['on-timeout'] === 'fail')
1172
+ this.commands.updateRun(runId, { state: 'failed', completedAt: new Date(now).toISOString() });
1173
+ else
1174
+ this.commands.block(runId, authority.phase === 'verification' ? 'verification_failed' : 'handoff_failed', 'The bounded role execution-time allowance is exhausted.', ['increase_budgets', 'replace_profile']);
1175
+ }
1176
+ this.wake(runId);
1177
+ return true;
1178
+ }
1179
+ const interval = plan.budgetOverrides?.[step.id]?.submissionInterval ?? definition.execution['submission-interval']?.duration;
1180
+ if (authority.phase === 'work' && interval && consumed(authority.clock, now) - authority.lastSubmissionConsumedMs >= durationMs(interval)) {
1181
+ this.commands.block(runId, 'submission_interval_expired', 'The worker submission interval expired.', ['increase_budgets', 'replace_profile']);
1182
+ this.updateClocks(runId);
1183
+ return true;
1184
+ }
1185
+ }
1186
+ return false;
1187
+ }
1188
+ supersede(runId, role) {
1189
+ const plan = this.commands.plan(runId);
1190
+ const unaccepted = this.store.list('submissions', { runId, limit: Number.MAX_SAFE_INTEGER }).map(row => row.value)
1191
+ .filter(submission => submission.stepExecutionId === plan.steps[plan.ordinal]?.id && !['accepted', 'superseded'].includes(submission.state));
1192
+ const affected = new Set(unaccepted.filter(submission => !role || this.store.get('sessions', submission.sessionId).role === role)
1193
+ .map(submission => submission.id));
1194
+ if (role === 'worker')
1195
+ for (const submission of unaccepted) {
1196
+ if (submission.kind === 'verdict' && submission.subjectSubmissionId && affected.has(submission.subjectSubmissionId))
1197
+ affected.add(submission.id);
1198
+ }
1199
+ for (const submission of unaccepted) {
1200
+ if (!affected.has(submission.id))
1201
+ continue;
1202
+ this.store.put('submissions', { ...submission, state: 'superseded' }, { runId, parentId: submission.sessionId });
1203
+ const artifact = this.store.get('artifacts', submission.artifactId);
1204
+ this.store.put('artifacts', { ...artifact, state: 'superseded' }, { runId });
1205
+ if (plan.pendingSubmissionId === submission.id)
1206
+ delete plan.pendingSubmissionId;
1207
+ }
1208
+ if (!role || role === 'worker')
1209
+ delete plan.steps[plan.ordinal].candidateId;
1210
+ this.commands.savePlan(runId, plan);
1211
+ this.broker.setHold(runId, 'submission', !!plan.pendingSubmissionId);
1212
+ }
1213
+ async decisions(runId) {
1214
+ let plan = this.commands.plan(runId), queued = plan.queuedDecisions[0];
1215
+ const input = queued.decision, step = plan.steps[plan.ordinal], execution = this.store.get('steps', step.id), run = this.store.get('runs', runId);
1216
+ const decisionStepId = queued.stepExecutionId ?? (queued.blockId ? this.store.get('blocks', queued.blockId).stepExecutionId : undefined);
1217
+ if (decisionStepId && decisionStepId !== step.id) {
1218
+ this.operationState(queued.operationId, 'failed', 'state_conflict');
1219
+ plan.queuedDecisions.shift();
1220
+ this.commands.savePlan(runId, plan);
1221
+ this.broker.setHold(runId, 'queued_decisions', plan.queuedDecisions.length > 0);
1222
+ this.wake(runId);
1223
+ return;
1224
+ }
1225
+ this.gate(runId, true, input.kind === 'replace_profile');
1226
+ if (input.kind === 'extend_pause_grace')
1227
+ return;
1228
+ this.operationState(queued.operationId, 'running');
1229
+ if (input.kind === 'increase_budgets') {
1230
+ validateIncrease(run, execution, plan.definition.steps[plan.ordinal], plan.budgetOverrides?.[step.id] ?? {}, input.budgets, step.workerSessionId ? this.store.get('sessions', step.workerSessionId) : undefined);
1231
+ this.store.coordinator.atomic(() => {
1232
+ plan = this.commands.plan(runId);
1233
+ plan.budgetOverrides ??= {};
1234
+ plan.budgetOverrides[step.id] = mergeIncrease(plan.budgetOverrides[step.id] ?? {}, input.budgets);
1235
+ this.commands.savePlan(runId, plan);
1236
+ this.store.put('steps', { ...execution, ...(input.budgets.maxSessionResets === undefined ? {} : { maxSessionResets: input.budgets.maxSessionResets }) }, { runId });
1237
+ const policy = { ...run.policy,
1238
+ ...(input.budgets.infrastructureRetries === undefined ? {} : { infrastructureRetries: input.budgets.infrastructureRetries }),
1239
+ ...(input.budgets.verificationRetries === undefined ? {} : { verificationRetries: input.budgets.verificationRetries }) };
1240
+ this.commands.updateRun(runId, { policy });
1241
+ for (const id of [step.workerSessionId, step.auxiliarySessionId]) {
1242
+ if (!id)
1243
+ continue;
1244
+ const session = this.store.get('sessions', id), authority = this.store.private('session_authority', id);
1245
+ const total = limitsFor(plan.definition.steps[plan.ordinal], session.role, plan.budgetOverrides[step.id]);
1246
+ const retired = session.role === 'verifier' ? step.verificationCharges - session.submissionsUsed :
1247
+ session.role === 'handoff' ? (plan.reset?.handoffCharges ?? 0) - session.submissionsUsed : 0;
1248
+ const retiredTime = session.role === 'verifier' ? step.verificationConsumedMs : session.role === 'handoff' ? plan.reset?.handoffConsumedMs ?? 0 : 0;
1249
+ const limits = { ...total, ...(total.maxSubmissions === undefined ? {} : { maxSubmissions: total.maxSubmissions - Math.max(0, retired) }),
1250
+ ...(total.executionTimeLimit ? { executionTimeLimit: `${Math.max(0, durationMs(total.executionTimeLimit) - retiredTime)}ms` } : {}) };
1251
+ if (limits.executionTimeLimit)
1252
+ authority.clock.limitMs = durationMs(limits.executionTimeLimit);
1253
+ this.store.setPrivate('session_authority', id, authority);
1254
+ this.store.put('sessions', { ...session, limits }, { runId, parentId: session.stepExecutionId });
1255
+ if (session.state === 'exhausted' && this.options.driver.alive(id) && !expired(authority.clock, this.commands.now()) &&
1256
+ (limits.maxSubmissions === undefined || limits.maxSubmissions > session.submissionsUsed))
1257
+ this.setSession(id, 'running');
1258
+ }
1259
+ plan = this.commands.plan(runId);
1260
+ if (plan.reset?.reason === 'worker_exhausted' && !plan.reset.profileVersionId && step.workerSessionId && this.store.get('sessions', step.workerSessionId).state === 'running') {
1261
+ delete plan.reset;
1262
+ plan.stage = 'worker';
1263
+ }
1264
+ this.commands.savePlan(runId, plan);
1265
+ this.completeDecision(runId, queued.operationId);
1266
+ });
1267
+ }
1268
+ else if (input.kind === 'replace_profile') {
1269
+ if (input.role === 'worker' && plan.reset?.profileVersionId)
1270
+ throw new ApiError(409, 'transition_in_progress', 'A worker profile replacement is already pending.');
1271
+ const profile = this.store.get('profile_versions', input.profileVersionId);
1272
+ const validation = await this.effect(runId, 'Validate replacement profile', () => this.commands.options.publication.profileReport({ definition: profile.definition, resources: profile.resources }, this.signal(runId)));
1273
+ this.gate(runId, true, true);
1274
+ if (!validation.valid)
1275
+ throw new ApiError(422, 'invalid_profile', 'Replacement profile is invalid.', false, validation.issues);
1276
+ this.options.workspaces.assertKnown(runId);
1277
+ const snapshot = this.options.pins.assembleRole({ runId, stepExecutionId: step.id, role: input.role, profileVersionId: profile.id,
1278
+ stepInstructions: plan.definition.steps[plan.ordinal].instructions ?? [], stepPackageResources: plan.definition['instruction-resources'] ?? [] });
1279
+ this.options.workspaces.assertKnown(runId);
1280
+ const compiled = await this.effect(runId, 'Compile replacement permissions', () => this.options.validation.run({ kind: 'effective_permissions',
1281
+ profile: profile.definition.permissions, deployment: this.options.deploymentPolicy, role: input.role, configuredTools: profile.definition.tools.map(tool => tool.toolId) }, { runId, signal: this.signal(runId) }));
1282
+ this.gate(runId, true, true);
1283
+ if (!compiled.valid || !compiled.effectivePolicy)
1284
+ throw new ApiError(422, 'invalid_effective_permissions', 'Replacement permissions are invalid.', false, compiled.errors);
1285
+ const configuration = { profileVersionId: profile.id, role: input.role, definition: profile.definition, instructionSnapshotId: snapshot.id,
1286
+ deploymentPolicyDigest: digest(this.options.deploymentPolicy), effectivePermissions: compiled.effectivePolicy };
1287
+ const oldSessionId = input.role === 'worker' ? step.workerSessionId :
1288
+ step.auxiliarySessionId && this.store.get('sessions', step.auxiliarySessionId).role === input.role ? step.auxiliarySessionId : undefined;
1289
+ this.store.coordinator.atomic(() => {
1290
+ this.store.put('snapshots', snapshot, { runId, parentId: step.id, immutable: true });
1291
+ this.store.setPrivate('pending_profile', queued.operationId, { snapshotId: snapshot.id, configuration: { ...configuration, contentDigest: digest(configuration) } });
1292
+ this.supersede(runId, input.role);
1293
+ plan = this.commands.plan(runId);
1294
+ if (oldSessionId && this.commands.current(oldSessionId, this.store.get('sessions', oldSessionId).epoch))
1295
+ this.broker.invalidateSessionActions(this.commands.binding(oldSessionId));
1296
+ if (input.role === 'worker') {
1297
+ const prior = plan.reset;
1298
+ plan.reset = { ...(prior ?? { id: randomUUID(), reason: 'profile_replacement', role: 'worker', ...(oldSessionId ? { oldSessionId } : {}) }),
1299
+ profileVersionId: profile.id, profileOperationId: queued.operationId,
1300
+ operationId: prior?.operationId ?? queued.operationId,
1301
+ operationIds: [...new Set([...(prior?.operationIds ?? []), ...(prior?.operationId ? [prior.operationId] : []), queued.operationId])] };
1302
+ plan.stage = 'reset';
1303
+ }
1304
+ plan.queuedDecisions.shift();
1305
+ this.commands.savePlan(runId, plan);
1306
+ this.broker.setHold(runId, 'queued_decisions', false);
1307
+ this.store.event(runId, 'instruction_snapshot_created', 'instruction_snapshot', snapshot.id, { role: input.role, stepExecutionId: step.id });
1308
+ });
1309
+ if (input.role !== 'worker') {
1310
+ if (oldSessionId)
1311
+ await this.closeSession(oldSessionId);
1312
+ this.store.coordinator.atomic(() => {
1313
+ plan = this.commands.plan(runId);
1314
+ plan.steps[plan.ordinal].profiles[input.role] = { profileVersionId: profile.id, snapshotId: snapshot.id };
1315
+ if (oldSessionId) {
1316
+ delete plan.steps[plan.ordinal].auxiliarySessionId;
1317
+ plan.stage = input.role === 'verifier' ? 'verify' : 'handoff';
1318
+ }
1319
+ this.commands.savePlan(runId, plan);
1320
+ this.store.setPrivate('effective_configuration', `${step.id}:${input.role}`, { ...configuration, contentDigest: digest(configuration) });
1321
+ const publicStep = this.store.get('steps', step.id);
1322
+ this.store.put('steps', { ...publicStep, agentProfiles: { ...publicStep.agentProfiles, [input.role]: profile.id } }, { runId });
1323
+ this.store.event(runId, 'profile_replaced', 'step_execution', step.id, { role: input.role, profileVersionId: profile.id });
1324
+ this.operationState(queued.operationId, 'succeeded');
1325
+ });
1326
+ }
1327
+ }
1328
+ else {
1329
+ this.gate(runId, true);
1330
+ if (input.kind === 'overwrite') {
1331
+ if (!input.approve) {
1332
+ this.completeDecision(runId, queued.operationId);
1333
+ return;
1334
+ }
1335
+ this.options.workspaces.approveOverwrite(runId, input.conflictDigest);
1336
+ }
1337
+ const baselineId = input.kind === 'rollback' ? input.baselineId : plan.reset?.restoreBaselineId ?? step.baselineId;
1338
+ if (!baselineId)
1339
+ throw new ApiError(409, 'baseline_unavailable', 'No recorded baseline is available.');
1340
+ if (input.kind === 'rollback') {
1341
+ this.rewind(runId, this.commands.rollbackOrdinal(runId, baselineId), baselineId, queued.operationId);
1342
+ this.wake(runId);
1343
+ return;
1344
+ }
1345
+ this.store.coordinator.atomic(() => {
1346
+ this.supersede(runId);
1347
+ plan = this.commands.plan(runId);
1348
+ plan.stage = 'reset';
1349
+ if (step.workerSessionId && this.commands.current(step.workerSessionId, this.store.get('sessions', step.workerSessionId).epoch))
1350
+ this.broker.invalidateSessionActions(this.commands.binding(step.workerSessionId));
1351
+ const prior = plan.reset;
1352
+ plan.reset = { ...(prior ?? { id: randomUUID(), reason: 'rollback', role: 'worker', ...(step.workerSessionId ? { oldSessionId: step.workerSessionId } : {}) }),
1353
+ operationId: prior?.operationId ?? queued.operationId,
1354
+ operationIds: [...new Set([...(prior?.operationIds ?? []), ...(prior?.operationId ? [prior.operationId] : []), queued.operationId])],
1355
+ restoreBaselineId: baselineId, ...(input.kind === 'overwrite' ? { overwriteConflictDigest: input.conflictDigest } : {}) };
1356
+ plan.queuedDecisions.shift();
1357
+ this.commands.savePlan(runId, plan);
1358
+ });
1359
+ }
1360
+ this.wake(runId);
1361
+ }
1362
+ rewind(runId, ordinal, baselineId, operationId, restoreProofId) {
1363
+ this.store.coordinator.atomic(() => {
1364
+ const plan = this.commands.plan(runId), source = plan.ordinal, id = randomUUID(), now = this.commands.now();
1365
+ const affected = new Set(plan.steps.slice(ordinal).map(step => step.id));
1366
+ const submissions = this.store.list('submissions', { runId, limit: Number.MAX_SAFE_INTEGER }).map(row => row.value)
1367
+ .filter(value => affected.has(value.stepExecutionId));
1368
+ const artifacts = this.store.list('artifacts', { runId, limit: Number.MAX_SAFE_INTEGER }).map(row => row.value)
1369
+ .filter(value => value.stepExecutionId && affected.has(value.stepExecutionId));
1370
+ this.store.setPrivate('rewind_history', id, { operationId, baselineId, ordinal, source,
1371
+ steps: plan.steps.slice(ordinal).map(step => this.store.get('steps', step.id)), submissions, artifacts });
1372
+ for (const submission of submissions)
1373
+ if (submission.state !== 'superseded')
1374
+ this.store.put('submissions', { ...submission, state: 'superseded' }, { runId, parentId: submission.sessionId });
1375
+ for (const artifact of artifacts)
1376
+ if (artifact.state !== 'superseded')
1377
+ this.store.put('artifacts', { ...artifact, state: 'superseded' }, { runId });
1378
+ for (const queued of plan.queuedDecisions)
1379
+ queued.stepExecutionId ??= plan.steps[source].id;
1380
+ for (let index = ordinal; index < plan.steps.length; index++) {
1381
+ const step = plan.steps[index], clock = plan.stepClocks[step.id];
1382
+ if (!clock)
1383
+ continue;
1384
+ plan.stepClocks[step.id] = checkpoint(clock, false, now);
1385
+ step.reentry ??= { ...(step.workerSessionId ? { oldSessionId: step.workerSessionId } : {}) };
1386
+ if (index === source && plan.reset) {
1387
+ const { handoffId: _handoff, replacementSessionId: _replacement, restoreBaselineId: _restore, overwriteConflictDigest: _overwrite, ...pending } = plan.reset;
1388
+ step.reentry.reset = pending;
1389
+ }
1390
+ delete step.workerSessionId;
1391
+ delete step.auxiliarySessionId;
1392
+ delete step.candidateId;
1393
+ delete step.handoffId;
1394
+ delete step.baselineId;
1395
+ delete step.verifierRetirementId;
1396
+ const { acceptedSubmissionId: _submission, acceptedCommit: _commit, activeSessionId: _session, baselineId: _baseline, ...execution } = this.store.get('steps', step.id);
1397
+ this.store.put('steps', { ...execution, state: 'pending', timing: status(plan.stepClocks[step.id], false, now) }, { runId });
1398
+ }
1399
+ const target = plan.steps[ordinal], pending = target.reentry.reset;
1400
+ const { handoffId: _handoff, replacementSessionId: _replacement, restoreBaselineId: _restore, overwriteConflictDigest: _overwrite, ...retained } = pending ?? {};
1401
+ plan.reset = { ...retained, id: restoreProofId ?? id, reason: 'rollback', role: 'worker',
1402
+ ...(target.reentry.oldSessionId ? { oldSessionId: target.reentry.oldSessionId } : {}),
1403
+ operationId: pending?.operationId ?? operationId,
1404
+ restoreBaselineId: baselineId, operationIds: [...new Set([...(pending?.operationIds ?? []), ...(pending?.operationId ? [pending.operationId] : []), operationId])] };
1405
+ if (target.reentry.oldSessionId)
1406
+ target.workerSessionId = target.reentry.oldSessionId;
1407
+ plan.ordinal = ordinal;
1408
+ plan.stage = 'reset';
1409
+ delete plan.pendingSubmissionId;
1410
+ const retiringSessionIds = this.store.list('sessions', { runId, limit: Number.MAX_SAFE_INTEGER }).map(row => row.value)
1411
+ .filter(session => affected.has(session.stepExecutionId)).map(session => session.id);
1412
+ plan.rewind = { id, targetStepId: target.id, retiringSessionIds };
1413
+ for (const sessionId of retiringSessionIds)
1414
+ if (this.commands.current(sessionId, this.store.get('sessions', sessionId).epoch)) {
1415
+ this.broker.invalidateSessionActions(this.commands.binding(sessionId));
1416
+ if (sessionId !== plan.reset.oldSessionId) {
1417
+ this.broker.fenceSession(this.commands.binding(sessionId));
1418
+ this.commands.options.auth.revokeSession(sessionId);
1419
+ }
1420
+ }
1421
+ plan.queuedDecisions = plan.queuedDecisions.filter(queued => queued.operationId !== operationId);
1422
+ this.commands.savePlan(runId, plan);
1423
+ this.broker.setHold(runId, 'submission', false);
1424
+ this.broker.setHold(runId, 'queued_decisions', plan.queuedDecisions.length > 0);
1425
+ this.commands.updateRun(runId, { state: 'resetting', currentStepId: target.id });
1426
+ this.stepState(runId, 'resetting');
1427
+ this.syncBrokerDeadlineSql(runId, plan);
1428
+ this.store.event(runId, 'step_state_changed', 'step_execution', target.id, { state: 'resetting', rewindId: id, baselineId, sourceOrdinal: source, ordinal });
1429
+ });
1430
+ }
1431
+ completeDecision(runId, operationId) {
1432
+ const plan = this.commands.plan(runId);
1433
+ plan.queuedDecisions = plan.queuedDecisions.filter(value => value.operationId !== operationId);
1434
+ this.commands.savePlan(runId, plan);
1435
+ this.operationState(operationId, 'succeeded');
1436
+ this.broker.setHold(runId, 'queued_decisions', plan.queuedDecisions.length > 0);
1437
+ if (!this.store.get('runs', runId).pendingBlockIds.length)
1438
+ this.commands.updateRun(runId, { state: plan.stage === 'verify' ? 'verifying' : plan.stage === 'startup' ? 'starting' : plan.reset ? 'resetting' : 'running' });
1439
+ }
1440
+ async reset(runId) {
1441
+ this.gate(runId);
1442
+ let plan = this.commands.plan(runId), reset = plan.reset;
1443
+ if (!reset)
1444
+ throw new Error('reset_plan_missing');
1445
+ if (reset.reason === 'rollback' && !plan.rewind && !plan.steps[plan.ordinal].reentry && reset.restoreBaselineId) {
1446
+ const operations = new Set([...(reset.operationIds ?? []), ...(reset.operationId ? [reset.operationId] : [])]);
1447
+ const rollback = this.store.list('decisions', { runId, limit: Number.MAX_SAFE_INTEGER }).reverse()
1448
+ .find(({ value }) => operations.has(value.operationId) && value.decision.kind === 'rollback');
1449
+ if (rollback) {
1450
+ this.rewind(runId, this.commands.rollbackOrdinal(runId, reset.restoreBaselineId), reset.restoreBaselineId, rollback.value.operationId, reset.id);
1451
+ this.wake(runId);
1452
+ return;
1453
+ }
1454
+ }
1455
+ if (!reset.id) {
1456
+ reset.id = randomUUID();
1457
+ this.commands.savePlan(runId, plan);
1458
+ }
1459
+ if (plan.rewind?.retiringSessionIds.length) {
1460
+ for (const id of plan.rewind.retiringSessionIds)
1461
+ if (id !== reset.oldSessionId)
1462
+ await this.closeSession(id);
1463
+ plan = this.commands.plan(runId);
1464
+ plan.rewind.retiringSessionIds = [];
1465
+ this.commands.savePlan(runId, plan);
1466
+ this.gate(runId);
1467
+ reset = plan.reset;
1468
+ }
1469
+ let step = plan.steps[plan.ordinal], definition = plan.definition.steps[plan.ordinal];
1470
+ const execution = this.store.get('steps', step.id);
1471
+ if (reset.role === 'worker' && !reset.replacementSessionId && execution.resetsUsed >= execution.maxSessionResets) {
1472
+ const block = this.commands.block(runId, 'retry_budget_exhausted', 'The current step has no remaining worker reset allowance.', ['increase_budgets', 'replace_profile', 'rollback']);
1473
+ for (const id of new Set([...(reset.operationIds ?? []), ...(reset.operationId ? [reset.operationId] : [])]))
1474
+ this.operationState(id, 'waiting_for_decision', undefined, block.id);
1475
+ return;
1476
+ }
1477
+ if (reset.role === 'worker' && definition.handoffArtifact && !reset.handoffId && !reset.replacementSessionId) {
1478
+ const independent = definition.handoffArtifact['independent-handoff'];
1479
+ let id = independent ? step.auxiliarySessionId : reset.oldSessionId;
1480
+ if (independent && id && this.store.get('sessions', id).role !== 'handoff') {
1481
+ await this.closeSession(id);
1482
+ plan = this.commands.plan(runId);
1483
+ delete plan.steps[plan.ordinal].auxiliarySessionId;
1484
+ this.commands.savePlan(runId, plan);
1485
+ id = undefined;
1486
+ }
1487
+ if (!independent && (!id || reset.interrupted || !this.options.driver.alive(id))) {
1488
+ const block = this.commands.block(runId, 'handoff_failed', 'The mandatory worker-context handoff cannot be generated because its original conversation is unavailable.', ['increase_budgets', 'replace_profile']);
1489
+ for (const operation of new Set([...(reset.operationIds ?? []), ...(reset.operationId ? [reset.operationId] : [])]))
1490
+ this.operationState(operation, 'waiting_for_decision', undefined, block.id);
1491
+ return;
1492
+ }
1493
+ if (id && this.options.driver.active(id)) {
1494
+ this.options.driver.flush(id);
1495
+ return;
1496
+ }
1497
+ if (!this.quiet(runId))
1498
+ return;
1499
+ if (!id)
1500
+ id = await this.launch(runId, 'handoff');
1501
+ const session = this.store.get('sessions', id), authority = this.store.private('session_authority', id);
1502
+ if (expired(authority.clock, this.commands.now()) || session.limits.maxSubmissions !== undefined && session.submissionsUsed >= session.limits.maxSubmissions) {
1503
+ const block = this.commands.block(runId, 'handoff_failed', 'Mandatory handoff has no remaining count or time allowance.', ['increase_budgets', 'replace_profile']);
1504
+ if (reset.operationId)
1505
+ this.operationState(reset.operationId, 'waiting_for_decision', undefined, block.id);
1506
+ return;
1507
+ }
1508
+ this.store.coordinator.atomic(() => {
1509
+ const current = this.commands.plan(runId), root = current.graph.roots.find(value => value.stepId === definition.id && value.kind === 'handoff');
1510
+ authority.phase = 'handoff';
1511
+ authority.outputSchema = current.graph.resources.find(value => value.uri === root.uri).schema;
1512
+ if (this.store.private('execution_completion', authority.logicalOperationId) || this.store.private('execution_failure', authority.logicalOperationId)) {
1513
+ authority.logicalOperationId = randomUUID();
1514
+ this.commands.retries.begin(authority.retryEpisodeId, authority.logicalOperationId);
1515
+ }
1516
+ this.store.setPrivate('session_authority', id, authority);
1517
+ const assignment = this.store.private('assignments', id);
1518
+ this.store.setPrivate('assignments', id, { ...assignment, outputSchema: authority.outputSchema });
1519
+ current.stage = 'handoff';
1520
+ this.commands.savePlan(runId, current);
1521
+ this.commands.updateRun(runId, { state: 'generating_handoff' });
1522
+ this.stepState(runId, 'generating_handoff');
1523
+ this.setSession(id, 'running');
1524
+ });
1525
+ await this.effect(runId, 'Generate bounded mandatory handoff in assigned conversation', () => this.options.driver.turn(id, this.prompt(id)), id);
1526
+ return;
1527
+ }
1528
+ if (!reset.replacementSessionId) {
1529
+ for (const id of [step.auxiliarySessionId, ...(reset.role === 'worker' && reset.oldSessionId ? [reset.oldSessionId] : [])])
1530
+ if (id)
1531
+ await this.closeSession(id);
1532
+ this.gate(runId);
1533
+ if (!this.quiet(runId))
1534
+ return;
1535
+ plan = this.commands.plan(runId);
1536
+ reset = plan.reset;
1537
+ step = plan.steps[plan.ordinal];
1538
+ if (reset.role === 'worker' && (reset.restoreBaselineId || definition.execution['git-reset-on-session-reset'])) {
1539
+ const restored = this.store.private('restore_completed', runId);
1540
+ if (restored?.operationId !== reset.id) {
1541
+ const baselineId = reset.restoreBaselineId ?? step.baselineId;
1542
+ if (!baselineId) {
1543
+ this.commands.block(runId, 'baseline_unavailable', 'The recorded step baseline is unavailable.', ['rollback']);
1544
+ return;
1545
+ }
1546
+ this.options.workspaces.restore({ runId, baselineId, ...(reset.overwriteConflictDigest ? { overwriteConflictDigest: reset.overwriteConflictDigest } : {}) }, {
1547
+ onAdmittedSql: job => this.store.setPrivate('workspace_continuation', job.id, { kind: 'session_reset', operationId: reset.id }),
1548
+ onCompletedSql: job => this.workspaceCompleted(job),
1549
+ });
1550
+ }
1551
+ }
1552
+ if (step.reentry && !step.baselineId)
1553
+ this.options.workspaces.baseline(runId, 'step_start', step.id, { onAdmittedSql: baseline => {
1554
+ const current = this.commands.plan(runId);
1555
+ current.steps[current.ordinal].baselineId = baseline.id;
1556
+ this.commands.savePlan(runId, current);
1557
+ this.store.put('baselines', baseline, { runId, immutable: true });
1558
+ this.store.put('steps', { ...this.store.get('steps', step.id), baselineId: baseline.id }, { runId });
1559
+ } });
1560
+ this.store.coordinator.atomic(() => {
1561
+ plan = this.commands.plan(runId);
1562
+ reset = plan.reset;
1563
+ step = plan.steps[plan.ordinal];
1564
+ if (reset.operationId && reset.profileVersionId) {
1565
+ const replacement = this.store.private('pending_profile', reset.profileOperationId ?? reset.operationId);
1566
+ step.profiles[reset.role] = { profileVersionId: reset.profileVersionId, snapshotId: replacement.snapshotId };
1567
+ this.store.setPrivate('effective_configuration', `${step.id}:${reset.role}`, replacement.configuration);
1568
+ const publicStep = this.store.get('steps', step.id);
1569
+ this.store.put('steps', { ...publicStep, agentProfiles: { ...publicStep.agentProfiles, [reset.role]: reset.profileVersionId } }, { runId });
1570
+ this.store.event(runId, 'profile_replaced', 'step_execution', step.id, { role: reset.role, profileVersionId: reset.profileVersionId });
1571
+ }
1572
+ delete step.auxiliarySessionId;
1573
+ if (reset.role === 'worker') {
1574
+ delete step.workerSessionId;
1575
+ delete step.candidateId;
1576
+ if (reset.handoffId)
1577
+ step.handoffId = reset.handoffId;
1578
+ }
1579
+ this.commands.savePlan(runId, plan);
1580
+ this.commands.updateRun(runId, { state: 'resetting' });
1581
+ this.stepState(runId, 'resetting');
1582
+ });
1583
+ const id = await this.launch(runId, reset.role);
1584
+ plan = this.commands.plan(runId);
1585
+ plan.reset.replacementSessionId = id;
1586
+ this.commands.savePlan(runId, plan);
1587
+ }
1588
+ this.gate(runId);
1589
+ this.store.coordinator.atomic(() => {
1590
+ plan = this.commands.plan(runId);
1591
+ reset = plan.reset;
1592
+ const operationIds = [...new Set([...(reset.operationIds ?? []), ...(reset.operationId ? [reset.operationId] : [])])], role = reset.role;
1593
+ if (plan.rewind?.targetStepId === plan.steps[plan.ordinal].id)
1594
+ delete plan.rewind;
1595
+ delete plan.reset;
1596
+ plan.stage = role === 'verifier' ? 'verify' : role === 'handoff' ? 'handoff' : 'worker';
1597
+ this.commands.savePlan(runId, plan);
1598
+ this.commands.updateRun(runId, { state: role === 'verifier' ? 'verifying' : 'running' });
1599
+ this.stepState(runId, role === 'verifier' ? 'verifying' : 'running');
1600
+ for (const id of operationIds)
1601
+ this.operationState(id, 'succeeded');
1602
+ });
1603
+ this.wake(runId);
1604
+ }
1605
+ /** Called only after the deployment acquired its inherited writer lock and
1606
+ * constructed the broker/workspace recovery owners. Never reconnect threads. */
1607
+ restoreInterrupted() {
1608
+ this.store.coordinator.assertOutsideTransaction();
1609
+ const now = this.commands.now();
1610
+ for (const { value: run } of this.store.list('runs', { limit: Number.MAX_SAFE_INTEGER })) {
1611
+ if (terminal(run))
1612
+ continue;
1613
+ this.store.coordinator.atomic(() => {
1614
+ const plan = this.commands.plan(run.id), count = plan.timingPolicy.downtimeAccounting === 'count';
1615
+ plan.clock = count ? checkpoint(plan.clock, false, now) : { ...plan.clock, changedAt: now, running: false };
1616
+ for (const [id, value] of Object.entries(plan.stepClocks))
1617
+ plan.stepClocks[id] = count ? checkpoint(value, false, now) : { ...value, changedAt: now, running: false };
1618
+ this.commands.savePlan(run.id, plan);
1619
+ this.syncBrokerDeadlineSql(run.id, plan);
1620
+ this.commands.syncBrokerApprovalTimeoutSql(run.id, run.policy);
1621
+ for (const { value: session } of this.store.list('sessions', { runId: run.id, limit: Number.MAX_SAFE_INTEGER })) {
1622
+ if (['completed', 'terminated'].includes(session.state))
1623
+ continue;
1624
+ const authority = this.store.private('session_authority', session.id);
1625
+ if (authority) {
1626
+ authority.clock = count ? checkpoint(authority.clock, false, now) : { ...authority.clock, changedAt: now, running: false };
1627
+ this.store.setPrivate('session_authority', session.id, authority);
1628
+ }
1629
+ this.commands.options.auth.revokeSession(session.id);
1630
+ this.store.put('sessions', { ...session, state: 'interrupted', ...(authority ? { timing: status(authority.clock, false, now) } : {}) }, { runId: run.id, parentId: session.stepExecutionId });
1631
+ }
1632
+ this.broker.pause(run.id);
1633
+ const paused = ['paused', 'pausing', 'resuming'].includes(run.executionControl.status);
1634
+ this.commands.updateRun(run.id, { state: paused ? run.executionControl.status === 'pausing' ? 'pausing' : 'paused' : 'interrupted',
1635
+ timing: status(plan.clock, false, now),
1636
+ executionControl: { ...run.executionControl, status: paused ? run.executionControl.status === 'pausing' ? 'pausing' : 'paused' : 'running',
1637
+ ...(paused ? { continuationState: 'interrupted' } : {}), inFlightWork: this.work(run.id) } });
1638
+ });
1639
+ }
1640
+ }
1641
+ reconcileStoppedModels(runId) {
1642
+ const work = this.store.coordinator.db.prepare("SELECT id FROM broker_work WHERE run_id=? AND state='uncertain'").all(runId);
1643
+ this.store.coordinator.atomic(() => {
1644
+ for (const { id } of work) {
1645
+ const session = this.store.list('sessions', { runId, limit: Number.MAX_SAFE_INTEGER }).find(({ value }) => this.#stopped.has(value.id) && id.startsWith(`external:${value.id}:${value.epoch}:runtime-model:`));
1646
+ if (!session)
1647
+ continue;
1648
+ this.store.setPrivate('model_stop_proof', id, { sessionId: session.value.id, observedAt: this.commands.now() });
1649
+ this.store.coordinator.db.prepare("DELETE FROM broker_work WHERE run_id=? AND id=? AND state='uncertain'").run(runId, id);
1650
+ }
1651
+ });
1652
+ }
1653
+ async recover(runId) {
1654
+ let plan = this.commands.plan(runId);
1655
+ const operationId = plan.recoveryOperationId;
1656
+ if (this.store.get('operations', operationId).state === 'waiting_for_decision')
1657
+ return;
1658
+ this.operationState(operationId, 'running');
1659
+ await this.stopSessions(runId);
1660
+ this.reconcileStoppedModels(runId);
1661
+ try {
1662
+ this.options.reconcileCommands?.(runId);
1663
+ }
1664
+ catch {
1665
+ const block = this.commands.block(runId, 'external_workspace_change', 'Command recovery needs a current source digest and explicit preserve_changes or rollback resolution. Inspect the coding result and retry recover_run with commandResolution.', [], { recoveryAllowed: true });
1666
+ this.store.setPrivate('command_recovery_block', runId, { id: block.id });
1667
+ this.operationState(operationId, 'waiting_for_decision', undefined, block.id);
1668
+ return;
1669
+ }
1670
+ if (this.work(runId).some(value => value.description !== 'Workspace effect requires read-only reconciliation')) {
1671
+ const block = this.commands.block(runId, 'verification_failed', 'Prior tool effects remain uncertain. Recovery cannot redispatch them or treat containment as completion.', []);
1672
+ this.operationState(operationId, 'waiting_for_decision', undefined, block.id);
1673
+ return;
1674
+ }
1675
+ if (this.options.workspaces.activeWork(runId).length) {
1676
+ this.#readProof.add(runId);
1677
+ try {
1678
+ this.options.workspaces.reconcile(runId, { onCompletedSql: job => this.workspaceCompleted(job) });
1679
+ }
1680
+ finally {
1681
+ this.#readProof.delete(runId);
1682
+ }
1683
+ if (this.options.workspaces.activeWork(runId).length) {
1684
+ const block = this.commands.block(runId, 'external_workspace_change', 'An interrupted Git operation cannot be proven complete. Its journal and workspace lease remain held.', []);
1685
+ this.operationState(operationId, 'waiting_for_decision', undefined, block.id);
1686
+ return;
1687
+ }
1688
+ }
1689
+ if (this.options.workspaces.lease(runId).state === 'uncertain')
1690
+ this.options.workspaces.activateLeaseForRecovery(runId);
1691
+ plan = this.commands.plan(runId);
1692
+ const queued = plan.queuedDecisions[0];
1693
+ const workspaceDecision = queued?.blockId && this.store.get('blocks', queued.blockId).reason === 'external_workspace_change' &&
1694
+ (queued.decision.kind === 'rollback' || queued.decision.kind === 'overwrite' && queued.decision.approve);
1695
+ if (workspaceDecision) {
1696
+ // Only after physical/uncertain-tool reconciliation may an explicit
1697
+ // conflict decision select a restore. Ordinary assertKnown must still
1698
+ // reject external bytes until that exact overwrite/rollback is chosen.
1699
+ await this.decisions(runId);
1700
+ plan = this.commands.plan(runId);
1701
+ }
1702
+ if (!plan.reset?.restoreBaselineId)
1703
+ this.options.workspaces.assertKnown(runId);
1704
+ if (plan.workspaceInstructions)
1705
+ this.options.pins.assemble(runId, plan.definition, plan.steps);
1706
+ this.store.coordinator.atomic(() => {
1707
+ plan = this.commands.plan(runId);
1708
+ const step = plan.steps[plan.ordinal], old = step?.workerSessionId ?? plan.reset?.oldSessionId;
1709
+ if ((plan.rewind || step?.reentry || plan.reset?.restoreBaselineId) && plan.reset) {
1710
+ const reset = plan.reset;
1711
+ if (reset.replacementSessionId) {
1712
+ reset.oldSessionId = reset.replacementSessionId;
1713
+ delete reset.replacementSessionId;
1714
+ }
1715
+ reset.interrupted = true;
1716
+ reset.operationIds = [...new Set([...(reset.operationIds ?? []), ...(reset.operationId ? [reset.operationId] : []), operationId])];
1717
+ if (plan.rewind?.attentionBlockId)
1718
+ this.commands.resolveBlock(plan.rewind.attentionBlockId);
1719
+ if (plan.rewind)
1720
+ delete plan.rewind.attentionBlockId;
1721
+ plan.stage = 'reset';
1722
+ }
1723
+ else if (old) {
1724
+ this.supersede(runId);
1725
+ plan = this.commands.plan(runId);
1726
+ plan.reset = { id: randomUUID(), reason: 'recovery', role: 'worker', oldSessionId: old, operationId, interrupted: true };
1727
+ plan.stage = 'reset';
1728
+ }
1729
+ delete plan.recoveryOperationId;
1730
+ this.commands.savePlan(runId, plan);
1731
+ this.broker.setHold(runId, 'recovery', false);
1732
+ this.broker.setHold(runId, 'submission', false);
1733
+ if (!this.store.get('runs', runId).pendingBlockIds.length)
1734
+ this.broker.resume(runId);
1735
+ this.commands.updateRun(runId, { state: 'recovering' });
1736
+ if (!old)
1737
+ this.operationState(operationId, 'succeeded');
1738
+ });
1739
+ this.updateClocks(runId);
1740
+ this.wake(runId);
1741
+ }
1742
+ interrupt(runId) {
1743
+ const run = this.store.get('runs', runId);
1744
+ if (terminal(run) || this.commands.plan(runId).cancelOperationId)
1745
+ return;
1746
+ this.store.coordinator.atomic(() => {
1747
+ this.broker.pause(runId);
1748
+ for (const { value: session } of this.store.list('sessions', { runId, limit: Number.MAX_SAFE_INTEGER })) {
1749
+ if (['completed', 'terminated', 'interrupted'].includes(session.state))
1750
+ continue;
1751
+ if (this.commands.current(session.id, session.epoch))
1752
+ this.broker.fenceSession(this.commands.binding(session.id));
1753
+ this.commands.options.auth.revokeSession(session.id);
1754
+ this.setSession(session.id, 'interrupted');
1755
+ }
1756
+ const paused = run.executionControl.status === 'paused' || run.executionControl.status === 'pausing';
1757
+ this.commands.updateRun(runId, { state: paused ? run.state : 'interrupted',
1758
+ executionControl: { ...run.executionControl, ...(paused ? { continuationState: 'interrupted' } : {}) } });
1759
+ this.updateClocks(runId);
1760
+ });
1761
+ void this.stopSessions(runId).catch(error => { this.#fatal = error; });
1762
+ }
1763
+ async cancel(runId) {
1764
+ const operationId = this.commands.plan(runId).cancelOperationId;
1765
+ await this.stopSessions(runId);
1766
+ this.reconcileStoppedModels(runId);
1767
+ if (!this.quiet(runId))
1768
+ return;
1769
+ this.store.coordinator.atomic(() => {
1770
+ for (const { value: session } of this.store.list('sessions', { runId, limit: Number.MAX_SAFE_INTEGER })) {
1771
+ if (this.commands.current(session.id, session.epoch))
1772
+ this.broker.fenceSession(this.commands.binding(session.id));
1773
+ this.setSession(session.id, 'terminated');
1774
+ }
1775
+ this.supersede(runId);
1776
+ this.commands.updateRun(runId, { state: 'cancelled', completedAt: new Date(this.commands.now()).toISOString(),
1777
+ executionControl: { ...this.store.get('runs', runId).executionControl, status: 'paused', pausedAt: new Date(this.commands.now()).toISOString(), inFlightWork: [] } });
1778
+ this.operationState(operationId, 'succeeded');
1779
+ this.updateClocks(runId);
1780
+ });
1781
+ await this.finish(runId);
1782
+ }
1783
+ async finish(runId) {
1784
+ let run = this.store.get('runs', runId);
1785
+ await this.stopSessions(runId);
1786
+ this.reconcileStoppedModels(runId);
1787
+ if (!this.quiet(runId))
1788
+ return;
1789
+ if (!terminal(run)) {
1790
+ this.gate(runId);
1791
+ this.store.coordinator.atomic(() => {
1792
+ const plan = this.commands.plan(runId);
1793
+ plan.stage = 'complete';
1794
+ this.commands.savePlan(runId, plan);
1795
+ this.broker.setHold(runId, 'complete', true);
1796
+ this.commands.updateRun(runId, { state: 'succeeded', completedAt: new Date(this.commands.now()).toISOString() });
1797
+ this.updateClocks(runId);
1798
+ });
1799
+ }
1800
+ run = this.store.get('runs', runId);
1801
+ if (!this.store.private('lease_released', runId))
1802
+ this.options.workspaces.releaseLease(runId, terminal(run), {
1803
+ onAdmittedSql: () => this.store.setPrivate('lease_released', runId, { releasedAt: this.commands.now() }),
1804
+ });
1805
+ }
1806
+ handleError(runId, error) {
1807
+ if (this.#closed)
1808
+ return;
1809
+ try {
1810
+ if (error instanceof CoordinatorError) {
1811
+ if (error.code === 'run_not_quiescent')
1812
+ return;
1813
+ this.#fatal = error;
1814
+ return;
1815
+ }
1816
+ const run = this.store.get('runs', runId);
1817
+ if (this.#closed || terminal(run) || this.commands.plan(runId).cancelOperationId)
1818
+ return;
1819
+ if (error instanceof ApiError && ['execution_held', 'validation_aborted'].includes(error.code))
1820
+ return;
1821
+ if (error instanceof WorkspaceError) {
1822
+ if (error.code === 'run_not_quiescent' || error.code === 'workspace_writers_or_operations_unresolved')
1823
+ return;
1824
+ const conflict = this.options.workspaces.getConflict(runId);
1825
+ const block = this.commands.block(runId, error.code.includes('baseline') ? 'baseline_unavailable' : 'external_workspace_change', 'Workspace state no longer matches the recorded safe boundary.', conflict ? ['overwrite', 'rollback'] : ['rollback'], conflict ? { workspaceConflict: conflict } : {});
1826
+ const plan = this.commands.plan(runId);
1827
+ if (plan.rewind && this.options.workspaces.activeWork(runId).length) {
1828
+ plan.rewind.attentionBlockId = block.id;
1829
+ this.commands.savePlan(runId, plan);
1830
+ }
1831
+ return;
1832
+ }
1833
+ if (error instanceof ApiError) {
1834
+ if (error.code === 'deadline_exceeded') {
1835
+ this.deadlines(runId);
1836
+ return;
1837
+ }
1838
+ if (error.code === 'session_budget_exhausted') {
1839
+ const plan = this.commands.plan(runId);
1840
+ this.commands.block(runId, plan.stage === 'verify' ? 'verification_failed' : 'handoff_failed', 'The role episode has no remaining bounded allowance.', ['increase_budgets', 'replace_profile']);
1841
+ return;
1842
+ }
1843
+ const queued = this.commands.plan(runId).queuedDecisions[0];
1844
+ if (queued && ['invalid_profile', 'profile_role_mismatch', 'not_found', 'invalid_effective_permissions', 'budget_not_increased', 'transition_in_progress'].includes(error.code)) {
1845
+ this.operationState(queued.operationId, 'failed', error.code);
1846
+ const plan = this.commands.plan(runId);
1847
+ plan.queuedDecisions.shift();
1848
+ this.commands.savePlan(runId, plan);
1849
+ this.broker.setHold(runId, 'queued_decisions', plan.queuedDecisions.length > 0);
1850
+ this.wake(runId);
1851
+ return;
1852
+ }
1853
+ this.commands.block(runId, 'verification_failed', 'A required validation or execution prerequisite failed.', ['replace_profile', 'rollback']);
1854
+ return;
1855
+ }
1856
+ this.interrupt(runId);
1857
+ }
1858
+ catch (failure) {
1859
+ this.#fatal = failure;
1860
+ }
1861
+ }
1862
+ }