@nones/agentflow-core 0.1.0 → 0.6.1

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.
package/src/engine.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { chmodSync, lstatSync, mkdirSync } from "node:fs";
1
+ import { chmodSync, lstatSync, mkdirSync, realpathSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import {
4
4
  prepareArtifact,
@@ -7,7 +7,9 @@ import {
7
7
  stagedValueJson,
8
8
  } from "./artifacts";
9
9
  import { AgentFlowError, asAgentFlowError } from "./errors";
10
+ import { configureSession } from "./session-configuration";
10
11
  import { newId } from "./ids";
12
+ import { HistoryStore, readProviderHistory } from "./history";
11
13
  import {
12
14
  assertSerializable,
13
15
  fromJson,
@@ -22,25 +24,54 @@ import {
22
24
  type ModuleBroker,
23
25
  } from "./modules";
24
26
  import { QuotaManager, quotaGroupName } from "./quota";
25
- import { Store, type QuotaRateLimitResult } from "./store";
27
+ import {
28
+ Store,
29
+ canonicalProjectId,
30
+ planStepRowToResult,
31
+ type QuotaRateLimitResult,
32
+ } from "./store";
33
+ import type { PlanStepRow } from "./store";
26
34
  import type {
35
+ AgentDefaults,
27
36
  AgentResultSnapshot,
28
37
  AgentSpec,
38
+ AmendPreview,
39
+ AmendRunRequest,
29
40
  AppendRequest,
30
41
  ArtifactDeclaration,
31
42
  ArtifactOutput,
43
+ ContinueRunOptions,
44
+ DrainSummary,
32
45
  Engine,
33
46
  EngineEvent,
34
47
  EngineOptions,
35
48
  EventOptions,
49
+ LimitRunOptions,
36
50
  LimitsSnapshot,
37
51
  MessageSnapshot,
38
52
  MessageState,
53
+ OperationReceipt,
54
+ OperatorActionKind,
55
+ PauseRunOptions,
56
+ PlanDiffEntry,
57
+ PlanHandler,
58
+ PlanHandlerContext,
59
+ PlanHandlerOutput,
60
+ PlanHandlerStep,
61
+ PlanPhaseDescriptor,
62
+ PlanStepDescriptor,
63
+ PlanStepRef,
64
+ PlanStepResult,
65
+ PlanStrategyEnvelope,
39
66
  Profile,
40
67
  ProviderAdapter,
41
68
  RateLimitInfo,
69
+ RecoveryItem,
42
70
  ResumeOptions,
71
+ RetryCandidate,
72
+ RetryRunOptions,
43
73
  RunPlan,
74
+ RunPlanMetadata,
44
75
  RunRequest,
45
76
  RunSnapshot,
46
77
  RunStatus,
@@ -53,10 +84,16 @@ import type {
53
84
  WaveStatus,
54
85
  } from "./types";
55
86
  import {
87
+ applyAgentDefaults,
88
+ handlerKey,
56
89
  validateAdapters,
90
+ validateAgentDefaults,
91
+ validateAgentDefaultsMap,
92
+ validateHandlers,
57
93
  validateProfiles,
58
94
  validateRunPlan,
59
95
  validateStrategies,
96
+ type ValidatedPlan,
60
97
  } from "./validation";
61
98
 
62
99
  const TERMINAL_RUN: ReadonlySet<RunStatus> = new Set([
@@ -65,6 +102,28 @@ const TERMINAL_RUN: ReadonlySet<RunStatus> = new Set([
65
102
  "cancelled",
66
103
  ]);
67
104
 
105
+ /** Default drain grace when `drain()` is called without an argument. */
106
+ const DEFAULT_DRAIN_GRACE_MS = 5_000;
107
+ const DRAIN_OUTCOME_UNKNOWN =
108
+ "drain exceeded its grace period; outcome unknown";
109
+ const DRAIN_PAUSED_RUN = "daemon drain timed out with in-flight work";
110
+
111
+ /** Default actor recorded on operator actions that do not name one. */
112
+ const OPERATOR_ACTOR = "operator";
113
+
114
+ /** Normalized operator options shared by every operator action. */
115
+ interface OperatorOptions {
116
+ actor: string;
117
+ reason?: string;
118
+ actionId?: string;
119
+ }
120
+
121
+ /** Outcome of waiting for one run+quota turn slot before admission. */
122
+ interface WaitOutcome {
123
+ ok: boolean;
124
+ reason?: "stopped" | "cancelled" | "exhausted" | "missing";
125
+ }
126
+
68
127
  const TERMINAL_WAVE: ReadonlySet<WaveStatus> = new Set([
69
128
  "completed",
70
129
  "failed",
@@ -72,6 +131,426 @@ const TERMINAL_WAVE: ReadonlySet<WaveStatus> = new Set([
72
131
  "cancelled",
73
132
  ]);
74
133
 
134
+ /** Highest plan metadata version this build writes. */
135
+ const PLAN_METADATA_VERSION = 1;
136
+
137
+ /**
138
+ * Domain-separated SHA-256 over JSON. Used for plan and step-semantics digests;
139
+ * it is only compared, so the exact algorithm is not a wire contract.
140
+ */
141
+ function digest(kind: string, value: unknown): string {
142
+ return new Bun.CryptoHasher("sha256")
143
+ .update(`${kind}\u0000${toJson(value)}`)
144
+ .digest("hex");
145
+ }
146
+
147
+ function optionalString<T extends object>(
148
+ value: T,
149
+ key: string,
150
+ fallback?: string,
151
+ ): string | undefined {
152
+ const raw = (value as Record<string, unknown>)[key];
153
+ return typeof raw === "string" && raw !== "" ? raw : fallback;
154
+ }
155
+
156
+ /** SHA-256 hex of exact bytes; the only digest a script snapshot may report. */
157
+ const SCRIPT_DIGEST_SHAPE = /^[0-9a-f]{64}$/u;
158
+
159
+ /**
160
+ * Validate optional script provenance. It is caller-supplied data about the
161
+ * script that issued the start, so a malformed value is rejected instead of
162
+ * being stored as if it were authoritative. Absent stays absent: embedded
163
+ * clients and legacy scripts keep working unchanged.
164
+ */
165
+ function resolveScriptProvenance(request: RunRequest): {
166
+ scriptDigest?: string;
167
+ invocationId?: string;
168
+ } {
169
+ const raw = request as unknown as Record<string, unknown>;
170
+ const scriptDigest = raw.scriptDigest;
171
+ if (scriptDigest !== undefined) {
172
+ if (
173
+ typeof scriptDigest !== "string" ||
174
+ !SCRIPT_DIGEST_SHAPE.test(scriptDigest)
175
+ ) {
176
+ throw new AgentFlowError(
177
+ "validation",
178
+ "request.scriptDigest must be a lowercase SHA-256 hex digest",
179
+ );
180
+ }
181
+ }
182
+ const invocationId = raw.invocationId;
183
+ if (invocationId !== undefined) {
184
+ if (
185
+ typeof invocationId !== "string" ||
186
+ invocationId.trim() === "" ||
187
+ invocationId.length > 256 ||
188
+ /[\u0000-\u001f\u007f]/u.test(invocationId)
189
+ ) {
190
+ throw new AgentFlowError(
191
+ "validation",
192
+ "request.invocationId must be a non-empty string of at most 256 characters without control characters",
193
+ );
194
+ }
195
+ }
196
+ return {
197
+ ...(scriptDigest === undefined ? {} : { scriptDigest }),
198
+ ...(invocationId === undefined ? {} : { invocationId }),
199
+ };
200
+ }
201
+
202
+ /**
203
+ * Adapter-neutral plan metadata persisted with every run. A strategy may embed
204
+ * `plan.metadata` (phases, rounds, steps and its own envelope) once types.ts
205
+ * carries it; otherwise the default wave barrier synthesizes one phase per wave
206
+ * and one agent step per agent. Nothing here is interpreted by the scheduler.
207
+ */
208
+ function derivePlanMetadata(
209
+ plan: RunPlan,
210
+ strategy: Strategy,
211
+ ): RunPlanMetadata {
212
+ const raw = plan as unknown as { metadata?: unknown };
213
+ if (isPlainObject(raw.metadata)) {
214
+ const meta = raw.metadata as Partial<RunPlanMetadata>;
215
+ if (
216
+ Array.isArray(meta.phases) &&
217
+ Array.isArray(meta.steps) &&
218
+ meta.phases.every(
219
+ (phase) => isPlainObject(phase) && typeof phase.id === "string",
220
+ ) &&
221
+ meta.steps.every(
222
+ (step) => isPlainObject(step) && typeof step.id === "string",
223
+ )
224
+ ) {
225
+ return {
226
+ version:
227
+ typeof meta.version === "number"
228
+ ? meta.version
229
+ : PLAN_METADATA_VERSION,
230
+ phases: meta.phases.map((phase, index) => ({
231
+ id: phase.id,
232
+ index: typeof phase.index === "number" ? phase.index : index,
233
+ ...(typeof phase.name === "string" ? { name: phase.name } : {}),
234
+ mode:
235
+ phase.mode === "sequence" || phase.mode === "parallel"
236
+ ? phase.mode
237
+ : "wave",
238
+ waveIds: Array.isArray(phase.waveIds)
239
+ ? phase.waveIds.filter((id): id is string => typeof id === "string")
240
+ : [],
241
+ })),
242
+ rounds: Array.isArray(meta.rounds)
243
+ ? meta.rounds.filter(
244
+ (round) =>
245
+ isPlainObject(round) && typeof round.phaseId === "string",
246
+ )
247
+ : [],
248
+ steps: meta.steps.map((step) => ({
249
+ id: step.id,
250
+ phaseId: step.phaseId,
251
+ waveId: step.waveId,
252
+ kind:
253
+ step.kind === "script" || step.kind === "gate"
254
+ ? step.kind
255
+ : "agent",
256
+ ...(step.profile === undefined ? {} : { profile: step.profile }),
257
+ ...(step.model === undefined ? {} : { model: step.model }),
258
+ })),
259
+ ...(isPlainObject(meta.envelope) && typeof meta.envelope.id === "string"
260
+ ? {
261
+ envelope: {
262
+ id: meta.envelope.id,
263
+ version:
264
+ typeof meta.envelope.version === "number"
265
+ ? meta.envelope.version
266
+ : 1,
267
+ ...(meta.envelope.payload === undefined
268
+ ? {}
269
+ : { payload: meta.envelope.payload }),
270
+ } satisfies PlanStrategyEnvelope,
271
+ }
272
+ : {}),
273
+ };
274
+ }
275
+ }
276
+
277
+ const phases: PlanPhaseDescriptor[] = [];
278
+ const steps: PlanStepDescriptor[] = [];
279
+ for (const [index, wave] of plan.waves.entries()) {
280
+ const phaseId = wave.id;
281
+ phases.push({
282
+ id: phaseId,
283
+ index,
284
+ name: wave.id,
285
+ mode: "wave",
286
+ waveIds: [wave.id],
287
+ });
288
+ for (const spec of wave.agents) {
289
+ steps.push({
290
+ id: spec.id,
291
+ phaseId,
292
+ waveId: wave.id,
293
+ kind: "agent",
294
+ ...(spec.profile === undefined ? {} : { profile: spec.profile }),
295
+ ...(spec.model === undefined ? {} : { model: spec.model }),
296
+ });
297
+ }
298
+ }
299
+ return {
300
+ version: PLAN_METADATA_VERSION,
301
+ phases,
302
+ rounds: [],
303
+ steps,
304
+ envelope: {
305
+ id: strategy.id,
306
+ version: 1,
307
+ payload: { barrier: "wave" },
308
+ },
309
+ };
310
+ }
311
+
312
+ /**
313
+ * Semantics of one step that must match before a retained result is reused.
314
+ * It hashes the *effective* spec together with the same profile ID and that
315
+ * profile's configured model, so changing a default or the profile model
316
+ * invalidates a previously completed result.
317
+ */
318
+ function stepSemantics(spec: AgentSpec, profile: Profile): string {
319
+ return digest("step-semantics", {
320
+ prompt: spec.prompt,
321
+ cwd: spec.cwd,
322
+ profile: profile.id,
323
+ profileModel: profile.model ?? profile.settings.model ?? null,
324
+ model: spec.model ?? null,
325
+ settings: spec.settings ?? null,
326
+ strategy: spec.strategy ?? null,
327
+ input: spec.strategyInput ?? null,
328
+ });
329
+ }
330
+
331
+ /** Stable step coordinates used by the plan, results and dependencies. */
332
+ function stepKey(waveId: string, stepId: string): string {
333
+ return `${waveId}/${stepId}`;
334
+ }
335
+
336
+ /** Bounded, JSON-safe handler data. Handlers cannot smuggle unbounded values. */
337
+ const PLAN_STEP_DATA_MAX_BYTES = 64 * 1024;
338
+
339
+ /** One declared non-agent step resolved against the trusted registry. */
340
+ interface BoundStep {
341
+ waveId: string;
342
+ step: PlanHandlerStep;
343
+ handler: PlanHandler;
344
+ dependsOn: PlanStepRef[];
345
+ cwd: string;
346
+ }
347
+
348
+ /**
349
+ * Registry handler name and registered version of one declared step. A plan
350
+ * without an explicit `handlerVersion` resolves the only registered revision of
351
+ * that name; an ambiguous or missing name is rejected, never guessed.
352
+ */
353
+ function bindHandler(
354
+ registry: ReadonlyMap<string, PlanHandler[]>,
355
+ step: PlanHandlerStep,
356
+ ): { handler: PlanHandler; version: string } {
357
+ const candidates = registry.get(step.handler) ?? [];
358
+ const compatible = candidates.filter((entry) => entry.kind === step.kind);
359
+ if (step.handlerVersion !== undefined) {
360
+ const exact = compatible.find(
361
+ (entry) => entry.version === step.handlerVersion,
362
+ );
363
+ if (exact === undefined) {
364
+ throw new AgentFlowError(
365
+ "validation",
366
+ `plan.${step.kind}s ${step.id}: no trusted ${step.kind} handler ${step.handler}@${step.handlerVersion} is registered`,
367
+ );
368
+ }
369
+ return { handler: exact, version: exact.version };
370
+ }
371
+ if (compatible.length === 0) {
372
+ throw new AgentFlowError(
373
+ "validation",
374
+ `plan.${step.kind}s ${step.id}: no trusted ${step.kind} handler named ${step.handler} is registered`,
375
+ );
376
+ }
377
+ if (compatible.length > 1) {
378
+ throw new AgentFlowError(
379
+ "validation",
380
+ `plan.${step.kind}s ${step.id}: handler ${step.handler} has several registered versions; the plan must pin handlerVersion`,
381
+ );
382
+ }
383
+ const only = compatible[0] as PlanHandler;
384
+ return { handler: only, version: only.version };
385
+ }
386
+
387
+ /**
388
+ * Bind every declared non-agent step before admission. Graph errors are fatal;
389
+ * an unregistered handler is reported as a blocker so a persisted plan stays
390
+ * readable while the run waits for the handler instead of dropping the step.
391
+ */
392
+ function bindPlanSteps(
393
+ plan: ValidatedPlan,
394
+ planMeta: RunPlanMetadata,
395
+ registry: ReadonlyMap<string, PlanHandler[]>,
396
+ ): { steps: BoundStep[]; blockers: string[] } {
397
+ const waveOrder = new Map(plan.waves.map((wave, index) => [wave.id, index]));
398
+ const declared = [...plan.scripts, ...plan.gates];
399
+ const declaredByKey = new Map<string, PlanHandlerStep>();
400
+ for (const step of declared) {
401
+ const key = stepKey(step.waveId, step.id);
402
+ if (declaredByKey.has(key)) {
403
+ throw new AgentFlowError("validation", `duplicate plan step ${key}`);
404
+ }
405
+ declaredByKey.set(key, step);
406
+ }
407
+ const graphVisits = new Set<string>();
408
+ const graphResolved = new Set<string>();
409
+ function visit(step: PlanHandlerStep): void {
410
+ const key = stepKey(step.waveId, step.id);
411
+ if (graphResolved.has(key)) return;
412
+ if (graphVisits.has(key))
413
+ throw new AgentFlowError("validation", `cycle at plan step ${key}`);
414
+ graphVisits.add(key);
415
+ for (const ref of step.dependsOn ?? []) {
416
+ const row = declaredByKey.get(stepKey(ref.waveId, ref.id));
417
+ if (row !== undefined) visit(row);
418
+ }
419
+ graphVisits.delete(key);
420
+ graphResolved.add(key);
421
+ }
422
+ for (const step of declared) visit(step);
423
+
424
+ const blockers: string[] = [];
425
+ const bound: BoundStep[] = [];
426
+ for (const step of declared) {
427
+ const waveId = step.waveId;
428
+ let handler: PlanHandler;
429
+ let version: string;
430
+ try {
431
+ const match = bindHandler(registry, step);
432
+ handler = match.handler;
433
+ version = match.version;
434
+ } catch (error) {
435
+ if (error instanceof AgentFlowError && error.code === "validation") {
436
+ blockers.push(error.message);
437
+ continue;
438
+ }
439
+ throw error;
440
+ }
441
+ const meta = planMeta.steps.find(
442
+ (descriptor) =>
443
+ descriptor.kind === step.kind &&
444
+ descriptor.waveId === waveId &&
445
+ descriptor.stepId === step.id,
446
+ );
447
+ const dependsOn = (step.dependsOn ?? []).map((ref) => {
448
+ const key = stepKey(ref.waveId, ref.id);
449
+ if (!waveOrder.has(ref.waveId)) {
450
+ throw new AgentFlowError(
451
+ "validation",
452
+ `plan.${step.kind}s ${step.id}: dependency ${key} names an unknown wave`,
453
+ );
454
+ }
455
+ const parent = declaredByKey.get(key);
456
+ const parentIndex = waveOrder.get(ref.waveId)!;
457
+ const childIndex = waveOrder.get(waveId)!;
458
+ if (
459
+ parentIndex > childIndex ||
460
+ (parent === undefined && parentIndex === childIndex)
461
+ ) {
462
+ throw new AgentFlowError(
463
+ "validation",
464
+ `plan step ${step.id} cannot depend on ${key} before its admission`,
465
+ );
466
+ }
467
+ if (
468
+ parent === undefined &&
469
+ !plan.waves[parentIndex]?.agents.some((agent) => agent.id === ref.id)
470
+ ) {
471
+ throw new AgentFlowError(
472
+ "validation",
473
+ `plan step ${step.id} has unknown dependency ${key}`,
474
+ );
475
+ }
476
+ return { waveId: ref.waveId, id: ref.id };
477
+ });
478
+ const cwd = step.cwd ?? meta?.cwd ?? process.cwd();
479
+ bound.push({
480
+ waveId,
481
+ step: { ...step, handlerVersion: version },
482
+ handler,
483
+ dependsOn,
484
+ cwd,
485
+ });
486
+ }
487
+ return { steps: bound, blockers };
488
+ }
489
+
490
+ /**
491
+ * Accept only the documented handler result shape. A gate that reports
492
+ * `succeeded` without a verdict defaults to passed; anything else is rejected
493
+ * instead of being guessed, so a malformed verdict can never silently pass.
494
+ */
495
+ function normalizeHandlerOutput(
496
+ output: Record<string, unknown>,
497
+ kind: "script" | "gate",
498
+ ): {
499
+ status: "succeeded" | "failed";
500
+ passed?: boolean;
501
+ data?: unknown;
502
+ reason?: string;
503
+ } {
504
+ if (output.status !== "succeeded" && output.status !== "failed") {
505
+ throw new AgentFlowError(
506
+ "validation",
507
+ `a ${kind} handler must return status succeeded or failed`,
508
+ );
509
+ }
510
+ if (output.passed !== undefined && typeof output.passed !== "boolean") {
511
+ throw new AgentFlowError(
512
+ "validation",
513
+ `a ${kind} handler returned a non-boolean passed verdict`,
514
+ );
515
+ }
516
+ if (output.reason !== undefined && typeof output.reason !== "string") {
517
+ throw new AgentFlowError(
518
+ "validation",
519
+ `a ${kind} handler returned a non-string reason`,
520
+ );
521
+ }
522
+ if (output.artifacts !== undefined) {
523
+ throw new AgentFlowError(
524
+ "validation",
525
+ `a ${kind} handler cannot produce artifacts in this engine version`,
526
+ );
527
+ }
528
+ if (output.data !== undefined) {
529
+ try {
530
+ assertSerializable(output.data, "handler.data");
531
+ } catch (error) {
532
+ throw new AgentFlowError(
533
+ "validation",
534
+ `a ${kind} handler returned data that cannot be persisted: ${(error as Error).message}`,
535
+ );
536
+ }
537
+ }
538
+ const passed =
539
+ kind === "gate"
540
+ ? ((output.passed as boolean | undefined) ?? true)
541
+ : undefined;
542
+ const status =
543
+ kind === "gate" && passed === false
544
+ ? "failed"
545
+ : (output.status as "succeeded" | "failed");
546
+ return {
547
+ status,
548
+ passed,
549
+ ...(output.data === undefined ? {} : { data: output.data }),
550
+ ...(output.reason === undefined ? {} : { reason: output.reason as string }),
551
+ };
552
+ }
553
+
75
554
  interface ResolvedAgent {
76
555
  spec: AgentSpec;
77
556
  profile: Profile;
@@ -89,19 +568,72 @@ export function createEngine(options: EngineOptions): Engine {
89
568
  return new EngineImpl(options);
90
569
  }
91
570
 
571
+ /**
572
+ * Validate optional named-run/project metadata and derive the canonical project
573
+ * identity. `projectDir` is normalized; `projectId` defaults to its canonical
574
+ * form and may be supplied explicitly by callers that own their own identity.
575
+ */
576
+ function resolveRunMetadata(request: RunRequest): {
577
+ name?: string;
578
+ projectId?: string;
579
+ projectDir?: string;
580
+ } {
581
+ if (request.name !== undefined) {
582
+ if (typeof request.name !== "string" || request.name.trim() === "") {
583
+ throw new AgentFlowError(
584
+ "validation",
585
+ "request.name must be a non-empty string",
586
+ );
587
+ }
588
+ }
589
+ let projectDir: string | undefined;
590
+ if (request.projectDir !== undefined) {
591
+ if (
592
+ typeof request.projectDir !== "string" ||
593
+ request.projectDir.trim() === ""
594
+ ) {
595
+ throw new AgentFlowError(
596
+ "validation",
597
+ "request.projectDir must be a non-empty string",
598
+ );
599
+ }
600
+ projectDir = canonicalProjectId(request.projectDir);
601
+ }
602
+ let projectId: string | undefined;
603
+ if (request.projectId !== undefined) {
604
+ if (
605
+ typeof request.projectId !== "string" ||
606
+ request.projectId.trim() === ""
607
+ ) {
608
+ throw new AgentFlowError(
609
+ "validation",
610
+ "request.projectId must be a non-empty string",
611
+ );
612
+ }
613
+ projectId = request.projectId;
614
+ }
615
+ projectId ??= projectDir === undefined ? undefined : projectDir;
616
+ return { name: request.name, projectId, projectDir };
617
+ }
618
+
92
619
  export class EngineImpl implements Engine {
93
620
  private readonly store: Store;
94
621
  private readonly quota: QuotaManager;
95
622
  private readonly profiles: Map<string, Profile>;
96
623
  private readonly defaultProfile?: string;
624
+ private readonly agentDefaults?: AgentDefaults;
625
+ private readonly subagents: Record<string, AgentDefaults>;
97
626
  private readonly adapters: Map<string, ProviderAdapter>;
98
627
  private readonly strategies: Map<string, Strategy>;
99
628
  private readonly modules: ModuleBroker;
100
629
  private readonly moduleCallLimit?: number;
630
+ /** Trusted handlers by exact name, then by registered version. */
631
+ private readonly handlers: Map<string, PlanHandler[]>;
101
632
  private readonly verifiers: Record<
102
633
  string,
103
634
  (evidence: unknown) => boolean | Promise<boolean>
104
635
  >;
636
+ private readonly artifactRoot: string;
105
637
  private readonly readyPromise: Promise<void>;
106
638
 
107
639
  private closed = false;
@@ -111,8 +643,14 @@ export class EngineImpl implements Engine {
111
643
  private readonly schedulers = new Map<string, Promise<void>>();
112
644
  private readonly pendingSchedules = new Set<string>();
113
645
  private readonly executingAgents = new Set<string>();
646
+ private readonly executingSteps = new Set<string>();
114
647
  private readonly drainingMessages = new Set<string>();
115
648
 
649
+ /** Instance identity stamped into durable event provenance. */
650
+ private readonly generation: number = Date.now();
651
+ private drainPromise?: Promise<DrainSummary>;
652
+ private drainSummary?: DrainSummary;
653
+
116
654
  constructor(options: EngineOptions) {
117
655
  if (!isPlainObject(options)) {
118
656
  throw new AgentFlowError(
@@ -144,6 +682,14 @@ export class EngineImpl implements Engine {
144
682
  const adapters = validateAdapters(options.adapters);
145
683
  const strategies = validateStrategies(options.strategies);
146
684
  this.modules = createModuleBroker(options.modules);
685
+ const handlers = validateHandlers(options.handlers);
686
+ const registry = new Map<string, PlanHandler[]>();
687
+ for (const handler of handlers) {
688
+ const versions = registry.get(handler.name) ?? [];
689
+ versions.push(handler);
690
+ registry.set(handler.name, versions);
691
+ }
692
+ this.handlers = registry;
147
693
  if (options.moduleCallLimit !== undefined) {
148
694
  if (
149
695
  typeof options.moduleCallLimit !== "number" ||
@@ -174,6 +720,31 @@ export class EngineImpl implements Engine {
174
720
  `default profile ${this.defaultProfile} is not configured`,
175
721
  );
176
722
  }
723
+ this.agentDefaults = validateAgentDefaults(
724
+ options.agentDefaults,
725
+ "agentDefaults",
726
+ );
727
+ this.subagents = validateAgentDefaultsMap(options.subagents, "subagents");
728
+ if (
729
+ this.agentDefaults?.profile !== undefined &&
730
+ !this.profiles.has(this.agentDefaults.profile)
731
+ ) {
732
+ throw new AgentFlowError(
733
+ "validation",
734
+ `agentDefaults selects profile ${this.agentDefaults.profile}, which is not configured`,
735
+ );
736
+ }
737
+ for (const [name, defaults] of Object.entries(this.subagents)) {
738
+ if (
739
+ defaults.profile !== undefined &&
740
+ !this.profiles.has(defaults.profile)
741
+ ) {
742
+ throw new AgentFlowError(
743
+ "validation",
744
+ `subagent preset ${name} selects profile ${defaults.profile}, which is not configured`,
745
+ );
746
+ }
747
+ }
177
748
  this.adapters = new Map(adapters.map((adapter) => [adapter.id, adapter]));
178
749
  this.strategies = new Map(
179
750
  strategies.map((strategy) => [strategy.id, strategy]),
@@ -181,7 +752,9 @@ export class EngineImpl implements Engine {
181
752
  this.verifiers = options.verifiers ?? {};
182
753
 
183
754
  const root = join(options.stateDir, "state.db");
755
+ this.artifactRoot = join(options.stateDir, "artifacts");
184
756
  this.store = new Store(root);
757
+ this.store.generation = this.generation;
185
758
  try {
186
759
  chmodSync(root, 0o600);
187
760
  } catch {
@@ -223,6 +796,8 @@ export class EngineImpl implements Engine {
223
796
  } catch (error) {
224
797
  throw new AgentFlowError("validation", (error as Error).message);
225
798
  }
799
+ const { name, projectId, projectDir } = resolveRunMetadata(request);
800
+ const provenance = resolveScriptProvenance(request);
226
801
  const strategy = this.strategies.get(request.strategy);
227
802
  if (strategy === undefined) {
228
803
  throw new AgentFlowError(
@@ -242,6 +817,17 @@ export class EngineImpl implements Engine {
242
817
  }
243
818
  const plan = validateRunPlan(rawPlan);
244
819
  const runProfile = this.profileFor(request.profile ?? plan.profile);
820
+ const planMeta = derivePlanMetadata(plan, strategy);
821
+ const binding = bindPlanSteps(plan, planMeta, this.handlers);
822
+ if (binding.blockers.length > 0) {
823
+ throw new AgentFlowError("validation", binding.blockers.join(", "));
824
+ }
825
+ const planDigest = digest("plan", plan);
826
+ const phaseByWave = new Map(
827
+ planMeta.steps
828
+ .filter((step) => step.waveId !== undefined)
829
+ .map((step) => [step.waveId as string, step.phaseId]),
830
+ );
245
831
 
246
832
  const runId =
247
833
  request.id === undefined ? newId("run") : validateRunId(request.id);
@@ -268,6 +854,14 @@ export class EngineImpl implements Engine {
268
854
  sealed: plan.sealed,
269
855
  status: "idle",
270
856
  createdAt: now,
857
+ ...(name === undefined ? {} : { name }),
858
+ ...(projectId === undefined ? {} : { projectId }),
859
+ ...(projectDir === undefined ? {} : { projectDir }),
860
+ planDigest,
861
+ ...(optionalString(request, "createdBy") === undefined
862
+ ? {}
863
+ : { createdBy: optionalString(request, "createdBy") as string }),
864
+ ...provenance,
271
865
  });
272
866
  let index = 0;
273
867
  for (const wave of plan.waves) {
@@ -276,6 +870,7 @@ export class EngineImpl implements Engine {
276
870
  index,
277
871
  status: "pending",
278
872
  createdAt: now,
873
+ phaseId: phaseByWave.get(wave.id),
279
874
  });
280
875
  index += 1;
281
876
  for (const spec of wave.agents) {
@@ -289,7 +884,7 @@ export class EngineImpl implements Engine {
289
884
  this.store.insertAgent(runId, {
290
885
  id: spec.id,
291
886
  waveId: wave.id,
292
- specJson: toJson(spec),
887
+ specJson: toJson(match.spec),
293
888
  profileId: match.profileId,
294
889
  profileJson: toJson(match.profile),
295
890
  adapter: match.adapter,
@@ -300,15 +895,38 @@ export class EngineImpl implements Engine {
300
895
  : toJson(spec.strategyInput),
301
896
  status: "pending",
302
897
  createdAt: now,
898
+ stepKey: spec.id,
899
+ stepKind: "agent",
900
+ semanticsDigest: stepSemantics(match.spec, match.profile),
303
901
  });
304
902
  }
305
903
  }
306
904
  for (const artifact of plan.artifacts) {
307
905
  this.store.insertArtifact(runId, artifact, now);
308
906
  }
907
+ for (const entry of binding.steps) {
908
+ this.store.insertPlanStep(runId, {
909
+ waveId: entry.waveId,
910
+ stepId: entry.step.id,
911
+ kind: entry.step.kind,
912
+ handler: entry.step.handler,
913
+ handlerVersion: entry.step.handlerVersion as string,
914
+ cwd: entry.cwd,
915
+ dependsOn: entry.dependsOn,
916
+ attemptId: newId("attempt"),
917
+ startedAt: now,
918
+ });
919
+ }
920
+ this.store.insertPlanMeta(runId, {
921
+ revision: 0,
922
+ digest: planDigest,
923
+ meta: planMeta,
924
+ at: now,
925
+ });
309
926
  this.store.emit({
310
927
  runId,
311
928
  type: "run.created",
929
+ origin: { daemon: this.generation },
312
930
  data: {
313
931
  strategy: strategy.id,
314
932
  profile: runProfile.id,
@@ -316,6 +934,10 @@ export class EngineImpl implements Engine {
316
934
  sealed: plan.sealed,
317
935
  waves: plan.waves.length,
318
936
  agents: resolved.length,
937
+ scripts: plan.scripts.length,
938
+ gates: plan.gates.length,
939
+ // Provenance values only: no script source, path or credentials.
940
+ ...provenance,
319
941
  },
320
942
  });
321
943
  });
@@ -465,7 +1087,7 @@ export class EngineImpl implements Engine {
465
1087
  this.store.insertAgent(id, {
466
1088
  id: spec.id,
467
1089
  waveId: entry.wave.id,
468
- specJson: toJson(spec),
1090
+ specJson: toJson(match.spec),
469
1091
  profileId: match.profileId,
470
1092
  profileJson: toJson(match.profile),
471
1093
  adapter: match.adapter,
@@ -476,6 +1098,9 @@ export class EngineImpl implements Engine {
476
1098
  : toJson(spec.strategyInput),
477
1099
  status: "pending",
478
1100
  createdAt: now,
1101
+ stepKey: spec.id,
1102
+ stepKind: "agent",
1103
+ semanticsDigest: stepSemantics(match.spec, match.profile),
479
1104
  });
480
1105
  }
481
1106
  this.store.emit({
@@ -878,81 +1503,717 @@ export class EngineImpl implements Engine {
878
1503
  return this.quota.limits();
879
1504
  }
880
1505
 
881
- output(id: string, artifactId: string): ArtifactOutput {
882
- this.ensureOpen();
883
- this.requireRun(id);
884
- return readArtifactOutput(this.store, id, artifactId);
885
- }
1506
+ // -------------------------------------------------------- operator actions
886
1507
 
887
- async close(): Promise<void> {
888
- if (this.closed) return;
889
- this.closed = true;
890
- for (const controller of this.runAborts.values()) controller.abort();
891
- for (const handle of this.turnHandles.values()) {
892
- handle.controller.abort();
1508
+ async pauseRun(
1509
+ id: string,
1510
+ options: PauseRunOptions = {},
1511
+ ): Promise<OperationReceipt> {
1512
+ await this.readyPromise;
1513
+ this.ensureOpen();
1514
+ const { actor, reason, actionId } = this.actionOptions(options);
1515
+ const run = this.requireRun(id);
1516
+ if (run.status === "cancelled" || run.status === "completed") {
1517
+ throw new AgentFlowError(
1518
+ "conflict",
1519
+ `run ${id} is ${run.status} and cannot be stopped`,
1520
+ );
893
1521
  }
894
-
895
- const inflight = this.store.listInflightTurnRows();
896
- const groupCounts = new Map<string, number>();
897
- const affectedRuns = new Set<string>();
898
- for (const turn of inflight) {
899
- affectedRuns.add(turn.run_id);
900
- const agent = this.store.getAgentRow(turn.run_id, turn.agent_id);
901
- if (agent === undefined) continue;
902
- const profile = fromJson<Profile>(agent.profile_json, {
903
- id: agent.profile_id,
904
- adapter: agent.adapter,
905
- settings: {},
906
- });
907
- const group = quotaGroupName(profile);
908
- groupCounts.set(group, (groupCounts.get(group) ?? 0) + 1);
1522
+ const existing =
1523
+ actionId === undefined ? undefined : this.store.getOperationRow(actionId);
1524
+ if (existing !== undefined) {
1525
+ return operationReceipt(existing, true, run.id);
909
1526
  }
910
- const now = Date.now();
911
- try {
912
- this.store.tx(() => {
913
- for (const turn of inflight) {
914
- this.store.updateTurn(turn.id, {
915
- state: "interrupted",
916
- error: "daemon stopped while the turn was in flight",
917
- finished_at: now,
918
- });
919
- this.store.emit({
920
- runId: turn.run_id,
921
- waveId: turn.wave_id,
922
- agentId: turn.agent_id,
923
- type: "turn.interrupted",
924
- data: { turnId: turn.id, reason: "daemon_stopped" },
925
- });
926
- }
927
- for (const message of this.store.listDeliveringMessageRows()) {
928
- this.store.updateMessage(message.id, {
929
- state: "interrupted",
930
- error: "daemon stopped while the message was in flight",
931
- updated_at: now,
1527
+ const effectiveId: string = actionId ?? newId("op");
1528
+ const already = run.stopped === 1;
1529
+ if (!already) {
1530
+ this.persistOperatorAction(
1531
+ run.id,
1532
+ effectiveId,
1533
+ "pause",
1534
+ actor,
1535
+ reason,
1536
+ { stopped: false },
1537
+ { stopped: true },
1538
+ () => {
1539
+ this.store.updateRun(run.id, {
1540
+ stopped: 1,
1541
+ updated_at: Date.now(),
932
1542
  });
933
1543
  this.store.emit({
934
- runId: message.run_id,
935
- agentId: message.agent_id,
936
- type: "message.interrupted",
937
- data: { messageId: message.id, reason: "daemon_stopped" },
938
- });
939
- }
940
- for (const runId of affectedRuns) {
941
- this.store.updateRun(runId, {
942
- status: "paused",
943
- error: "daemon stopped with in-flight work",
944
- updated_at: now,
1544
+ runId: run.id,
1545
+ type: "run.stopped",
1546
+ data: { reason: reason ?? "operator_pause" },
945
1547
  });
946
- this.store.emit({
947
- runId,
1548
+ },
1549
+ );
1550
+ }
1551
+ const receipt = this.requireOperation(effectiveId, run.id);
1552
+ return { ...receipt, duplicate: already };
1553
+ }
1554
+
1555
+ async continueRun(
1556
+ id: string,
1557
+ options: ContinueRunOptions = {},
1558
+ ): Promise<OperationReceipt> {
1559
+ await this.readyPromise;
1560
+ this.ensureOpen();
1561
+ const { actor, reason, actionId } = this.actionOptions(options);
1562
+ const run = this.requireRun(id);
1563
+ if (run.status === "cancelled" || run.status === "completed") {
1564
+ throw new AgentFlowError(
1565
+ "conflict",
1566
+ `run ${id} is ${run.status} and cannot continue`,
1567
+ );
1568
+ }
1569
+ const existing =
1570
+ actionId === undefined ? undefined : this.store.getOperationRow(actionId);
1571
+ if (existing !== undefined) {
1572
+ return operationReceipt(existing, true, run.id);
1573
+ }
1574
+ const effectiveId: string = actionId ?? newId("op");
1575
+ const wasStopped = run.stopped === 1;
1576
+ const now = Date.now();
1577
+ this.persistOperatorAction(
1578
+ run.id,
1579
+ effectiveId,
1580
+ "continue",
1581
+ actor,
1582
+ reason,
1583
+ { stopped: wasStopped },
1584
+ { stopped: false },
1585
+ () => {
1586
+ const waves = this.store.getWaveRows(run.id);
1587
+ const interrupted = this.store
1588
+ .getAgentRows(run.id)
1589
+ .filter(
1590
+ (agent) =>
1591
+ agent.status === "interrupted" || agent.status === "paused",
1592
+ );
1593
+ this.store.updateRun(run.id, {
1594
+ stopped: 0,
1595
+ status: "running",
1596
+ error: null,
1597
+ updated_at: now,
1598
+ });
1599
+ this.store.emit({
1600
+ runId: run.id,
1601
+ type: "run.continued",
1602
+ data: {
1603
+ ...(wasStopped ? { resumedAfterStop: true } : {}),
1604
+ readySteps: interrupted.map((agent) => agent.id),
1605
+ },
1606
+ });
1607
+ },
1608
+ );
1609
+ void this.drainQueuedMessages(run.id);
1610
+ this.scheduleRun(run.id);
1611
+ void this.clearQuotaIfExhausted(run.id);
1612
+ const receipt = this.requireOperation(effectiveId, run.id);
1613
+ return receipt;
1614
+ }
1615
+
1616
+ async limitRun(
1617
+ id: string,
1618
+ maxConcurrent: number,
1619
+ options: LimitRunOptions = {},
1620
+ ): Promise<OperationReceipt> {
1621
+ await this.readyPromise;
1622
+ this.ensureOpen();
1623
+ if (
1624
+ typeof maxConcurrent !== "number" ||
1625
+ !Number.isSafeInteger(maxConcurrent) ||
1626
+ maxConcurrent < 1
1627
+ ) {
1628
+ throw new AgentFlowError(
1629
+ "validation",
1630
+ "maxConcurrent must be a positive safe integer",
1631
+ );
1632
+ }
1633
+ const { actor, reason, actionId } = this.actionOptions(options);
1634
+ const run = this.requireRun(id);
1635
+ if (TERMINAL_RUN.has(run.status)) {
1636
+ throw new AgentFlowError(
1637
+ "conflict",
1638
+ `run ${id} is ${run.status} and cannot be limited`,
1639
+ );
1640
+ }
1641
+ const existing =
1642
+ actionId === undefined ? undefined : this.store.getOperationRow(actionId);
1643
+ if (existing !== undefined) {
1644
+ return operationReceipt(existing, true, run.id);
1645
+ }
1646
+ const effectiveId: string = actionId ?? newId("op");
1647
+ const already = run.max_concurrent === maxConcurrent;
1648
+ if (!already) {
1649
+ this.persistOperatorAction(
1650
+ run.id,
1651
+ effectiveId,
1652
+ "limit",
1653
+ actor,
1654
+ reason,
1655
+ { maxConcurrent: run.max_concurrent },
1656
+ { maxConcurrent },
1657
+ () => {
1658
+ this.store.updateRun(run.id, {
1659
+ max_concurrent: maxConcurrent,
1660
+ updated_at: Date.now(),
1661
+ });
1662
+ this.store.emit({
1663
+ runId: run.id,
1664
+ type: "run.limited",
1665
+ data: { maxConcurrent, previous: run.max_concurrent },
1666
+ });
1667
+ },
1668
+ );
1669
+ }
1670
+ const receipt = this.requireOperation(effectiveId, run.id);
1671
+ return { ...receipt, duplicate: already };
1672
+ }
1673
+
1674
+ async retryRun(
1675
+ id: string,
1676
+ options: RetryRunOptions = {},
1677
+ ): Promise<OperationReceipt> {
1678
+ await this.readyPromise;
1679
+ this.ensureOpen();
1680
+ const { actor, reason, actionId } = this.actionOptions(options);
1681
+ const run = this.requireRun(id);
1682
+ if (run.status === "cancelled") {
1683
+ throw new AgentFlowError("conflict", `run ${id} is cancelled`);
1684
+ }
1685
+ const selected =
1686
+ options.steps === undefined
1687
+ ? undefined
1688
+ : new Set(
1689
+ options.steps.filter(
1690
+ (step): step is string => typeof step === "string",
1691
+ ),
1692
+ );
1693
+ const existing =
1694
+ actionId === undefined ? undefined : this.store.getOperationRow(actionId);
1695
+ if (existing !== undefined) {
1696
+ return operationReceipt(existing, true, run.id);
1697
+ }
1698
+ const effectiveId: string = actionId ?? newId("op");
1699
+ const candidates = this.retryCandidates(run.id).filter(
1700
+ (candidate) => selected === undefined || selected.has(candidate.agentId),
1701
+ );
1702
+ const blocked = candidates.filter((candidate) => !candidate.eligible);
1703
+ if (blocked.length > 0) {
1704
+ throw new AgentFlowError(
1705
+ "interrupted",
1706
+ `unknown outcome for ${blocked.map((entry) => entry.agentId).join(", ")}; the affected step must be resolved before retry`,
1707
+ { blockers: blocked },
1708
+ );
1709
+ }
1710
+ const eligible = candidates.filter((candidate) => candidate.eligible);
1711
+ if (eligible.length === 0) {
1712
+ throw new AgentFlowError(
1713
+ "conflict",
1714
+ `run ${id} has no failed step eligible for retry`,
1715
+ { candidates },
1716
+ );
1717
+ }
1718
+ const now = Date.now();
1719
+ this.persistOperatorAction(
1720
+ run.id,
1721
+ effectiveId,
1722
+ "retry",
1723
+ actor,
1724
+ reason,
1725
+ { failed: eligible.map((entry) => entry.agentId) },
1726
+ { failed: eligible.map((entry) => entry.agentId) },
1727
+ () => {
1728
+ for (const candidate of eligible) {
1729
+ this.store.updateAgent(run.id, candidate.agentId, {
1730
+ status: "pending",
1731
+ error: null,
1732
+ blocker: null,
1733
+ started_at: null,
1734
+ finished_at: null,
1735
+ });
1736
+ // The wave holding the failure reopens so the scheduler can run it.
1737
+ this.reopenWave(run.id, candidate.waveId);
1738
+ this.store.emit({
1739
+ runId: run.id,
1740
+ waveId: candidate.waveId,
1741
+ agentId: candidate.agentId,
1742
+ type: "agent.retry_scheduled",
1743
+ data: { base: candidate.kind },
1744
+ });
1745
+ }
1746
+ this.store.updateRun(run.id, {
1747
+ stopped: 0,
1748
+ status: "running",
1749
+ error: null,
1750
+ updated_at: now,
1751
+ });
1752
+ this.store.emit({
1753
+ runId: run.id,
1754
+ type: "run.retried",
1755
+ data: { steps: eligible.map((entry) => entry.agentId) },
1756
+ });
1757
+ },
1758
+ );
1759
+ this.scheduleRun(run.id);
1760
+ return this.requireOperation(effectiveId, run.id);
1761
+ }
1762
+
1763
+ async amendRun(id: string, request: AmendRunRequest): Promise<AmendPreview> {
1764
+ await this.readyPromise;
1765
+ this.ensureOpen();
1766
+ if (!isPlainObject(request) || request.input === undefined) {
1767
+ throw new AgentFlowError(
1768
+ "validation",
1769
+ "amend request.input must be a plan",
1770
+ );
1771
+ }
1772
+ const run = this.requireRun(id);
1773
+ if (run.status === "cancelled") {
1774
+ throw new AgentFlowError("conflict", `run ${id} is cancelled`);
1775
+ }
1776
+ if (run.successor_id !== null) {
1777
+ throw new AgentFlowError(
1778
+ "conflict",
1779
+ `run ${id} already has successor ${run.successor_id}`,
1780
+ );
1781
+ }
1782
+ const strategyId = optionalString(request, "strategy") ?? run.strategy;
1783
+ const strategy = this.strategies.get(strategyId);
1784
+ if (strategy === undefined) {
1785
+ throw new AgentFlowError(
1786
+ "validation",
1787
+ `strategy ${strategyId} is not registered`,
1788
+ );
1789
+ }
1790
+ const plan = validateRunPlan(strategy.compile(request.input));
1791
+ const meta = derivePlanMetadata(plan, strategy);
1792
+ const planDigest = digest("plan", plan);
1793
+ const runProfile =
1794
+ run.profile_json === null
1795
+ ? this.profileFor()
1796
+ : fromJson<Profile>(run.profile_json, this.profileFor());
1797
+ const resolved: ResolvedAgent[] = [];
1798
+ for (const wave of plan.waves) {
1799
+ for (const spec of wave.agents) {
1800
+ resolved.push(this.resolveAgent(spec, runProfile, strategy));
1801
+ }
1802
+ }
1803
+ const resolvedById = new Map(
1804
+ resolved.map((entry) => [entry.spec.id, entry]),
1805
+ );
1806
+ // Reuse and diff are decided from the same effective specs that admission
1807
+ // persists, so changing a default cannot retain a stale result.
1808
+ const diff = this.diffPlan(run.id, plan, meta, resolvedById);
1809
+ const reusable = this.retainedResults(run.id, plan, meta, resolvedById);
1810
+ const reused = reusable.map((entry) => entry.agentId);
1811
+ const invalidated = diff
1812
+ .filter(
1813
+ (entry) =>
1814
+ entry.change !== "added" &&
1815
+ entry.change !== "removed" &&
1816
+ !entry.keep &&
1817
+ entry.scope === "agent",
1818
+ )
1819
+ .map((entry) => entry.id);
1820
+ const revision = this.store.listPlanMetaRows(run.id).length + 1;
1821
+ const apply = request.apply === true;
1822
+ if (!apply) {
1823
+ return {
1824
+ runId: run.id,
1825
+ revision,
1826
+ applied: false,
1827
+ diff,
1828
+ reused,
1829
+ invalidated,
1830
+ };
1831
+ }
1832
+
1833
+ const { actor, reason, actionId } = this.actionOptions(request);
1834
+ const duplicate =
1835
+ actionId !== undefined &&
1836
+ this.store.getOperationRow(actionId) !== undefined;
1837
+ if (duplicate) {
1838
+ const receipt = this.store.getOperationRow(actionId as string) as {
1839
+ new_json: string | null;
1840
+ };
1841
+ const newValue = fromJson<{ successorId?: string } | null>(
1842
+ receipt.new_json,
1843
+ null,
1844
+ );
1845
+ return {
1846
+ runId: run.id,
1847
+ revision,
1848
+ applied: true,
1849
+ ...(newValue?.successorId === undefined
1850
+ ? {}
1851
+ : { successorId: newValue.successorId }),
1852
+ diff,
1853
+ reused,
1854
+ invalidated,
1855
+ };
1856
+ }
1857
+
1858
+ const effectiveId: string = actionId ?? newId("op");
1859
+ const successorId =
1860
+ request.newRunId === undefined
1861
+ ? newId("run")
1862
+ : validateRunId(request.newRunId);
1863
+ if (this.store.hasRun(successorId)) {
1864
+ throw new AgentFlowError("conflict", `run ${successorId} already exists`);
1865
+ }
1866
+ const reusableById = new Map(
1867
+ reusable.map((entry) => [entry.agentId, entry]),
1868
+ );
1869
+ const now = Date.now();
1870
+ this.store.tx(() => {
1871
+ this.store.insertRun({
1872
+ id: successorId,
1873
+ strategy: strategy.id,
1874
+ requestJson: toJson({ ...request, input: plan, apply: true }),
1875
+ profileId: runProfile.id,
1876
+ profileJson: toJson(runProfile),
1877
+ adapter: runProfile.adapter,
1878
+ sealed: plan.sealed === true,
1879
+ status: "idle",
1880
+ createdAt: now,
1881
+ ...(run.name === null ? {} : { name: run.name }),
1882
+ ...(run.project_id === null ? {} : { projectId: run.project_id }),
1883
+ ...(run.project_dir === null ? {} : { projectDir: run.project_dir }),
1884
+ ...(run.max_concurrent === null
1885
+ ? {}
1886
+ : { maxConcurrent: run.max_concurrent }),
1887
+ predecessorId: run.id,
1888
+ planDigest,
1889
+ createdBy: actor,
1890
+ });
1891
+ let index = 0;
1892
+ for (const wave of plan.waves) {
1893
+ this.store.insertWave(successorId, {
1894
+ id: wave.id,
1895
+ index,
1896
+ status: "pending",
1897
+ createdAt: now,
1898
+ phaseId: meta.steps.find((step) => step.waveId === wave.id)?.phaseId,
1899
+ });
1900
+ index += 1;
1901
+ for (const spec of wave.agents) {
1902
+ const match = resolved.find((entry) => entry.spec.id === spec.id);
1903
+ if (match === undefined) continue;
1904
+ const carried = reusableById.get(spec.id);
1905
+ this.store.insertAgent(successorId, {
1906
+ id: spec.id,
1907
+ waveId: wave.id,
1908
+ specJson: toJson(match.spec),
1909
+ profileId: match.profileId,
1910
+ profileJson: toJson(match.profile),
1911
+ adapter: match.adapter,
1912
+ strategy: match.strategy.id,
1913
+ strategyInputJson:
1914
+ spec.strategyInput === undefined
1915
+ ? undefined
1916
+ : toJson(spec.strategyInput),
1917
+ status: carried === undefined ? "pending" : "succeeded",
1918
+ createdAt: now,
1919
+ stepKey: spec.id,
1920
+ stepKind: "agent",
1921
+ semanticsDigest: stepSemantics(match.spec, match.profile),
1922
+ });
1923
+ if (carried !== undefined) {
1924
+ this.store.updateAgent(successorId, spec.id, {
1925
+ session_id: carried.sessionId,
1926
+ turns: carried.turns,
1927
+ result_json: carried.resultJson,
1928
+ finished_at: now,
1929
+ reused_from: carried.sourceRunId,
1930
+ reused_revision: carried.sourceRevision,
1931
+ });
1932
+ this.store.emit({
1933
+ runId: successorId,
1934
+ waveId: wave.id,
1935
+ agentId: spec.id,
1936
+ type: "agent.result_reused",
1937
+ origin: { daemon: this.generation, actionId: effectiveId },
1938
+ data: { fromRun: carried.sourceRunId },
1939
+ });
1940
+ }
1941
+ }
1942
+ }
1943
+ for (const artifact of plan.artifacts ?? []) {
1944
+ this.store.insertArtifact(successorId, artifact, now);
1945
+ }
1946
+ this.store.insertPlanMeta(successorId, {
1947
+ revision,
1948
+ digest: planDigest,
1949
+ sourceRunId: run.id,
1950
+ meta,
1951
+ at: now,
1952
+ });
1953
+ this.store.updateRun(run.id, {
1954
+ successor_id: successorId,
1955
+ stopped: 1,
1956
+ updated_at: now,
1957
+ });
1958
+ this.store.emit({
1959
+ runId: run.id,
1960
+ type: "run.superseded",
1961
+ origin: { daemon: this.generation, actionId: effectiveId },
1962
+ data: { successorId },
1963
+ });
1964
+ this.store.insertOperation({
1965
+ id: effectiveId,
1966
+ runId: run.id,
1967
+ kind: "amend",
1968
+ actor,
1969
+ ...(reason === undefined ? {} : { reason }),
1970
+ oldValue: { digest: run.plan_digest, revision: revision - 1 },
1971
+ newValue: { successorId, digest: planDigest, revision },
1972
+ at: now,
1973
+ });
1974
+ this.store.emit({
1975
+ runId: successorId,
1976
+ type: "run.created",
1977
+ origin: { daemon: this.generation, actionId: effectiveId, revision },
1978
+ data: {
1979
+ strategy: strategy.id,
1980
+ profile: runProfile.id,
1981
+ adapter: runProfile.adapter,
1982
+ sealed: plan.sealed === true,
1983
+ waves: plan.waves.length,
1984
+ agents: resolved.length,
1985
+ predecessorId: run.id,
1986
+ revision,
1987
+ },
1988
+ });
1989
+ });
1990
+ this.scheduleRun(successorId);
1991
+ return {
1992
+ runId: run.id,
1993
+ revision,
1994
+ applied: true,
1995
+ successorId,
1996
+ diff,
1997
+ reused,
1998
+ invalidated,
1999
+ };
2000
+ }
2001
+
2002
+ operations(id: string): OperationReceipt[] {
2003
+ this.ensureOpen();
2004
+ this.requireRun(id);
2005
+ return this.store
2006
+ .listOperationRows(id)
2007
+ .map((row) => operationReceipt(row, false, id));
2008
+ }
2009
+
2010
+ recovery(id: string): RecoveryItem[] {
2011
+ this.ensureOpen();
2012
+ this.requireRun(id);
2013
+ return this.store.listRecoveryItems(id);
2014
+ }
2015
+
2016
+ plan(id: string): RunPlanMetadata | undefined {
2017
+ this.ensureOpen();
2018
+ this.requireRun(id);
2019
+ const rows = this.store.listPlanMetaRows(id);
2020
+ const last = rows[rows.length - 1];
2021
+ if (last === undefined) return undefined;
2022
+ return fromJson<RunPlanMetadata | undefined>(last.meta_json, undefined);
2023
+ }
2024
+
2025
+ steps(id: string): PlanStepResult[] {
2026
+ this.ensureOpen();
2027
+ this.requireRun(id);
2028
+ return this.store.listPlanStepRowsForRun(id);
2029
+ }
2030
+
2031
+ async drain(graceMs?: number): Promise<DrainSummary> {
2032
+ if (this.drainPromise !== undefined) return this.drainPromise;
2033
+ const grace =
2034
+ graceMs === undefined
2035
+ ? DEFAULT_DRAIN_GRACE_MS
2036
+ : Math.max(0, Math.floor(graceMs));
2037
+ this.drainPromise = this.runDrain(grace);
2038
+ return this.drainPromise;
2039
+ }
2040
+
2041
+ /**
2042
+ * Idempotent shutdown. Closing is the same bounded drain, so a process exit,
2043
+ * a signal and an explicit `drain()` share one code path and one summary.
2044
+ */
2045
+ async close(): Promise<void> {
2046
+ if (this.drainPromise !== undefined) {
2047
+ await this.drainPromise;
2048
+ return;
2049
+ }
2050
+ await this.drain();
2051
+ }
2052
+
2053
+ private draining(): boolean {
2054
+ return this.drainPromise !== undefined;
2055
+ }
2056
+
2057
+ private async runDrain(graceMs: number): Promise<DrainSummary> {
2058
+ const startedAt = Date.now();
2059
+ const runIds = new Set<string>();
2060
+ const inflight = this.store.listInflightTurnRows();
2061
+ const inflightSteps = this.store.listRunningPlanStepRows();
2062
+ for (const turn of inflight) runIds.add(turn.run_id);
2063
+ for (const step of inflightSteps) runIds.add(step.run_id);
2064
+ const deadline = startedAt + graceMs;
2065
+ while (!this.closed && Date.now() < deadline) {
2066
+ const active = this.store.listInflightTurnRows();
2067
+ if (
2068
+ active.length === 0 &&
2069
+ this.store.listRunningPlanStepRows().length === 0 &&
2070
+ this.schedulers.size === 0
2071
+ )
2072
+ break;
2073
+ await sleep(10);
2074
+ }
2075
+ const remaining = this.store.listInflightTurnRows();
2076
+ for (const turn of remaining) runIds.add(turn.run_id);
2077
+ const remainingSteps = this.store.listRunningPlanStepRows();
2078
+ const unfinished = remaining.length + remainingSteps.length;
2079
+ const settled = Math.max(
2080
+ 0,
2081
+ inflight.length + inflightSteps.length - unfinished,
2082
+ );
2083
+ const summary: DrainSummary = {
2084
+ id: newId("drain"),
2085
+ outcome: unfinished > 0 ? "timeout" : "complete",
2086
+ graceMs,
2087
+ startedAt,
2088
+ finishedAt: Date.now(),
2089
+ scope: "daemon",
2090
+ runIds: [...runIds],
2091
+ settled,
2092
+ interrupted: unfinished,
2093
+ closed: true,
2094
+ };
2095
+ await this.finalizeShutdown(summary);
2096
+ this.drainSummary = summary;
2097
+ return summary;
2098
+ }
2099
+
2100
+ output(id: string, artifactId: string): ArtifactOutput {
2101
+ this.ensureOpen();
2102
+ this.requireRun(id);
2103
+ return readArtifactOutput(this.store, id, artifactId);
2104
+ }
2105
+
2106
+ /**
2107
+ * Terminal shutdown. Only called by `runDrain` after the grace window; any
2108
+ * turn that is still in flight could not be confirmed, so it is interrupted
2109
+ * with a durable blocker and never resubmitted.
2110
+ */
2111
+ private async finalizeShutdown(summary: DrainSummary): Promise<void> {
2112
+ if (this.closed) return;
2113
+ this.closed = true;
2114
+ const timedOut = summary.interrupted > 0;
2115
+ const error = timedOut
2116
+ ? DRAIN_OUTCOME_UNKNOWN
2117
+ : "daemon stopped while the turn was in flight";
2118
+ for (const controller of this.runAborts.values()) controller.abort();
2119
+ for (const handle of this.turnHandles.values()) {
2120
+ handle.controller.abort();
2121
+ }
2122
+
2123
+ for (const step of this.store.listRunningPlanStepRows()) {
2124
+ this.markPlanStepInterrupted(
2125
+ step.run_id,
2126
+ step.wave_id,
2127
+ step.step_id,
2128
+ error,
2129
+ );
2130
+ }
2131
+ const inflight = this.store.listInflightTurnRows();
2132
+ const groupCounts = new Map<string, number>();
2133
+ const affectedRuns = new Set<string>();
2134
+ for (const turn of inflight) {
2135
+ affectedRuns.add(turn.run_id);
2136
+ const agent = this.store.getAgentRow(turn.run_id, turn.agent_id);
2137
+ if (agent === undefined) continue;
2138
+ const profile = fromJson<Profile>(agent.profile_json, {
2139
+ id: agent.profile_id,
2140
+ adapter: agent.adapter,
2141
+ settings: {},
2142
+ });
2143
+ const group = quotaGroupName(profile);
2144
+ groupCounts.set(group, (groupCounts.get(group) ?? 0) + 1);
2145
+ }
2146
+ const now = Date.now();
2147
+ try {
2148
+ this.store.tx(() => {
2149
+ for (const turn of inflight) {
2150
+ this.store.updateTurn(turn.id, {
2151
+ state: "interrupted",
2152
+ error,
2153
+ finished_at: now,
2154
+ });
2155
+ this.store.emit({
2156
+ runId: turn.run_id,
2157
+ waveId: turn.wave_id,
2158
+ agentId: turn.agent_id,
2159
+ type: "turn.interrupted",
2160
+ data: {
2161
+ turnId: turn.id,
2162
+ attemptId: turn.attempt_id,
2163
+ reason: timedOut ? "drain_timeout" : "daemon_stopped",
2164
+ },
2165
+ });
2166
+ this.store.appendRecovery(turn.run_id, {
2167
+ daemon: this.generation,
2168
+ action: "interrupted",
2169
+ reason: error,
2170
+ waveId: turn.wave_id,
2171
+ agentId: turn.agent_id,
2172
+ ...(turn.attempt_id === null ? {} : { attemptId: turn.attempt_id }),
2173
+ at: now,
2174
+ });
2175
+ // A timed-out attempt may have produced an unknown effect: hold the
2176
+ // step behind an explicit blocker so no automatic retry can replay it.
2177
+ if (timedOut) {
2178
+ this.store.updateAgent(turn.run_id, turn.agent_id, {
2179
+ blocker:
2180
+ "unknown effect: drain timed out before a conclusive result",
2181
+ });
2182
+ }
2183
+ }
2184
+ for (const message of this.store.listDeliveringMessageRows()) {
2185
+ this.store.updateMessage(message.id, {
2186
+ state: "interrupted",
2187
+ error: "daemon stopped while the message was in flight",
2188
+ updated_at: now,
2189
+ });
2190
+ this.store.emit({
2191
+ runId: message.run_id,
2192
+ agentId: message.agent_id,
2193
+ type: "message.interrupted",
2194
+ data: { messageId: message.id, reason: "daemon_stopped" },
2195
+ });
2196
+ }
2197
+ for (const runId of affectedRuns) {
2198
+ this.store.updateRun(runId, {
2199
+ status: "paused",
2200
+ error: timedOut
2201
+ ? DRAIN_PAUSED_RUN
2202
+ : "daemon stopped with in-flight work",
2203
+ updated_at: now,
2204
+ });
2205
+ this.store.emit({
2206
+ runId,
948
2207
  type: "run.paused",
949
- data: { reason: "daemon_stopped" },
2208
+ data: { reason: timedOut ? "drain_timeout" : "daemon_stopped" },
950
2209
  });
951
2210
  for (const agent of this.store.getAgentRows(runId)) {
952
2211
  if (agent.status === "running") {
953
2212
  this.store.updateAgent(runId, agent.id, {
954
2213
  status: "interrupted",
955
- error: "daemon stopped while the turn was in flight",
2214
+ error: timedOut
2215
+ ? DRAIN_OUTCOME_UNKNOWN
2216
+ : "daemon stopped while the turn was in flight",
956
2217
  finished_at: now,
957
2218
  });
958
2219
  this.store.emit({
@@ -960,7 +2221,7 @@ export class EngineImpl implements Engine {
960
2221
  waveId: agent.wave_id,
961
2222
  agentId: agent.id,
962
2223
  type: "agent.interrupted",
963
- data: { reason: "daemon_stopped" },
2224
+ data: { reason: timedOut ? "drain_timeout" : "daemon_stopped" },
964
2225
  });
965
2226
  }
966
2227
  }
@@ -1019,6 +2280,10 @@ export class EngineImpl implements Engine {
1019
2280
  const run = this.store.getRunRow(runId);
1020
2281
  if (run === undefined) return;
1021
2282
  if (TERMINAL_RUN.has(run.status) || run.status === "paused") return;
2283
+ // A persisted operator stop outlives the daemon: never admit new work.
2284
+ if (run.stopped === 1) return;
2285
+ // During a drain no new admission may start; queued work waits.
2286
+ if (this.draining()) return;
1022
2287
 
1023
2288
  const waves = this.store.getWaveRows(runId);
1024
2289
  const actionable = waves.find((wave) => !TERMINAL_WAVE.has(wave.status));
@@ -1078,6 +2343,9 @@ export class EngineImpl implements Engine {
1078
2343
  if (actionable.status === "paused") return;
1079
2344
 
1080
2345
  if (actionable.status === "pending") {
2346
+ const awaited = await this.awaitPlanSteps(runId, actionable.id);
2347
+ if (awaited === "paused") return;
2348
+ if (awaited === "not-ready") return;
1081
2349
  const now = Date.now();
1082
2350
  this.store.tx(() => {
1083
2351
  this.store.updateRun(runId, {
@@ -1108,12 +2376,417 @@ export class EngineImpl implements Engine {
1108
2376
  });
1109
2377
  }
1110
2378
 
1111
- await this.executeWave(runId, actionable.id);
1112
- }
2379
+ await this.executeWave(runId, actionable.id);
2380
+ }
2381
+ }
2382
+
2383
+ /**
2384
+ * Run the declared non-agent steps of a wave that are ready and settle them
2385
+ * durably. Returns `ready` when no step is pending, `paused` when a step needs
2386
+ * operator attention (unknown effect, unknown verdict, cancellation) and
2387
+ * `not-ready` when at least one dependency has not settled yet.
2388
+ */
2389
+ private async awaitPlanSteps(
2390
+ runId: string,
2391
+ waveId: string,
2392
+ ): Promise<"ready" | "paused" | "not-ready"> {
2393
+ if (this.store.getPlanStepRows(runId).length === 0) return "ready";
2394
+ let progressed = true;
2395
+ while (progressed && !this.closed) {
2396
+ progressed = false;
2397
+ const rows = this.store.getPlanStepRows(runId);
2398
+ if (rows.length === 0) return "ready";
2399
+ const byKey = new Map<string, PlanStepRow>();
2400
+ for (const row of rows) byKey.set(stepKey(row.wave_id, row.step_id), row);
2401
+ const settle = (ref: PlanStepRef): "succeeded" | "failed" | "pending" => {
2402
+ const row = byKey.get(stepKey(ref.waveId, ref.id));
2403
+ if (row === undefined) {
2404
+ const agent = this.store.getAgentRow(runId, ref.id);
2405
+ if (agent === undefined) return "pending";
2406
+ return agent.wave_id === ref.waveId && agent.status === "succeeded"
2407
+ ? "succeeded"
2408
+ : agent.status === "failed"
2409
+ ? "failed"
2410
+ : "pending";
2411
+ }
2412
+ if (row.status === "succeeded") return "succeeded";
2413
+ if (row.status === "failed" || row.status === "blocked")
2414
+ return "failed";
2415
+ return "pending";
2416
+ };
2417
+ const dependsOf = (row: PlanStepRow): PlanStepRef[] =>
2418
+ fromJson<PlanStepRef[]>(row.depends_json, []);
2419
+ const paused = rows.find(
2420
+ (row) =>
2421
+ row.wave_id === waveId &&
2422
+ (row.status === "interrupted" || row.status === "cancelled"),
2423
+ );
2424
+ if (paused !== undefined) {
2425
+ this.pauseForPlanStep(runId, waveId, paused);
2426
+ return "paused";
2427
+ }
2428
+ const failedDep = rows.find(
2429
+ (row) =>
2430
+ row.wave_id === waveId &&
2431
+ row.status === "pending" &&
2432
+ dependsOf(row).some((ref) => settle(ref) === "failed"),
2433
+ );
2434
+ if (failedDep !== undefined) {
2435
+ this.blockPlanStep(runId, waveId, failedDep, "an upstream step failed");
2436
+ progressed = true;
2437
+ continue;
2438
+ }
2439
+ const ready = rows.filter(
2440
+ (row) =>
2441
+ row.wave_id === waveId &&
2442
+ row.status === "pending" &&
2443
+ dependsOf(row).every((ref) => settle(ref) === "succeeded"),
2444
+ );
2445
+ if (ready.length > 0) {
2446
+ if (this.isPlanStepAdmissionBlocked(runId)) return "not-ready";
2447
+ await Promise.all(
2448
+ ready.map((row) => this.executePlanStep(runId, waveId, row.step_id)),
2449
+ );
2450
+ progressed = true;
2451
+ continue;
2452
+ }
2453
+ const outstanding = rows.some(
2454
+ (row) => row.wave_id === waveId && row.status === "pending",
2455
+ );
2456
+ if (outstanding) return "not-ready";
2457
+ const failed = rows.find(
2458
+ (row) =>
2459
+ row.wave_id === waveId &&
2460
+ (row.status === "failed" || row.status === "blocked"),
2461
+ );
2462
+ if (failed !== undefined) {
2463
+ this.pauseForPlanStep(runId, waveId, failed);
2464
+ return "paused";
2465
+ }
2466
+ return "ready";
2467
+ }
2468
+ return "not-ready";
2469
+ }
2470
+
2471
+ /** Execute exactly one declared step unless another caller already has it. */
2472
+ private async executePlanStep(
2473
+ runId: string,
2474
+ waveId: string,
2475
+ stepId: string,
2476
+ ): Promise<void> {
2477
+ const key = `${runId}/${stepKey(waveId, stepId)}`;
2478
+ if (this.executingSteps.has(key)) return;
2479
+ this.executingSteps.add(key);
2480
+ try {
2481
+ await this.executePlanStepInner(runId, waveId, stepId);
2482
+ } catch (error) {
2483
+ if (this.closed) return;
2484
+ const failure = asAgentFlowError(error);
2485
+ const row = this.store.getPlanStepRow(runId, waveId, stepId);
2486
+ if (row !== undefined && row.status === "running") {
2487
+ this.store.tx(() => {
2488
+ this.store.updatePlanStep(runId, waveId, stepId, {
2489
+ status: "failed",
2490
+ passed: 0,
2491
+ error: failure.message,
2492
+ finished_at: Date.now(),
2493
+ });
2494
+ this.store.emit({
2495
+ runId,
2496
+ waveId,
2497
+ type: `step.failed`,
2498
+ data: { stepId, kind: row.kind, error: failure.message },
2499
+ });
2500
+ });
2501
+ }
2502
+ } finally {
2503
+ this.executingSteps.delete(key);
2504
+ }
2505
+ }
2506
+
2507
+ private async executePlanStepInner(
2508
+ runId: string,
2509
+ waveId: string,
2510
+ stepId: string,
2511
+ ): Promise<void> {
2512
+ const row = this.store.getPlanStepRow(runId, waveId, stepId);
2513
+ if (row === undefined || row.status !== "pending") return;
2514
+ if (this.isPlanStepAdmissionBlocked(runId)) return;
2515
+ const candidates = this.handlers.get(row.handler) ?? [];
2516
+ const handler = candidates.find(
2517
+ (entry) => entry.version === row.handler_version,
2518
+ );
2519
+ if (handler === undefined) {
2520
+ const blocker = `no trusted handler ${row.handler}@${row.handler_version} is registered`;
2521
+ this.markPlanStepInterrupted(runId, waveId, stepId, blocker);
2522
+ return;
2523
+ }
2524
+ // Rotation retries the same declaration but records a new attempt identity,
2525
+ // so a reused result never inherits `running` from a superseded attempt.
2526
+ const attemptId = this.store.previousPlanStepResult(
2527
+ runId,
2528
+ waveId,
2529
+ stepId,
2530
+ row.attempt_id,
2531
+ )
2532
+ ? newId("attempt")
2533
+ : row.attempt_id;
2534
+ this.store.tx(() => {
2535
+ this.store.updatePlanStep(runId, waveId, stepId, { status: "running" });
2536
+ this.store.emit({
2537
+ runId,
2538
+ waveId,
2539
+ type: "step.started",
2540
+ data: {
2541
+ stepId,
2542
+ kind: row.kind,
2543
+ handler: row.handler,
2544
+ handlerVersion: row.handler_version,
2545
+ attemptId,
2546
+ },
2547
+ });
2548
+ });
2549
+
2550
+ const dependsOn = fromJson<PlanStepRef[]>(row.depends_json, []);
2551
+ const upstream = new Map<string, unknown>();
2552
+ for (const ref of dependsOn) {
2553
+ const upstreamRow = this.store.getPlanStepRow(runId, ref.waveId, ref.id);
2554
+ if (upstreamRow !== undefined) {
2555
+ const result = planStepRowToResult(upstreamRow);
2556
+ upstream.set(stepKey(ref.waveId, ref.id), {
2557
+ status: result.status,
2558
+ passed: result.passed,
2559
+ data: result.data,
2560
+ });
2561
+ continue;
2562
+ }
2563
+ const agent = this.store.getAgentRow(runId, ref.id);
2564
+ upstream.set(stepKey(ref.waveId, ref.id), {
2565
+ status: agent?.status ?? "unknown",
2566
+ result:
2567
+ agent?.result_json === null || agent?.result_json === undefined
2568
+ ? undefined
2569
+ : fromJson<unknown>(agent.result_json, undefined),
2570
+ });
2571
+ }
2572
+
2573
+ const context: PlanHandlerContext = {
2574
+ runId,
2575
+ waveId,
2576
+ stepId,
2577
+ kind: row.kind,
2578
+ handler: row.handler,
2579
+ handlerVersion: row.handler_version,
2580
+ cwd: row.cwd ?? process.cwd(),
2581
+ dependsOn,
2582
+ upstream,
2583
+ signal: this.getRunAbort(runId).signal,
2584
+ };
2585
+
2586
+ let output: PlanHandlerOutput;
2587
+ try {
2588
+ output = await handler.run(context);
2589
+ } catch (error) {
2590
+ if (this.closed) return;
2591
+ const run = this.store.getRunRow(runId);
2592
+ if (
2593
+ run === undefined ||
2594
+ run.status === "cancelled" ||
2595
+ run.stopped === 1
2596
+ ) {
2597
+ this.store.tx(() => {
2598
+ this.store.updatePlanStep(runId, waveId, stepId, {
2599
+ status: "cancelled",
2600
+ error: "the handler was aborted",
2601
+ finished_at: Date.now(),
2602
+ });
2603
+ this.store.emit({
2604
+ runId,
2605
+ waveId,
2606
+ type: "step.cancelled",
2607
+ data: { stepId, kind: row.kind },
2608
+ });
2609
+ });
2610
+ return;
2611
+ }
2612
+ this.store.tx(() => {
2613
+ this.store.updatePlanStep(runId, waveId, stepId, {
2614
+ status: "failed",
2615
+ passed: row.kind === "gate" ? 0 : null,
2616
+ error: (error as Error).message,
2617
+ finished_at: Date.now(),
2618
+ });
2619
+ this.store.emit({
2620
+ runId,
2621
+ waveId,
2622
+ type: "step.failed",
2623
+ data: { stepId, kind: row.kind, error: (error as Error).message },
2624
+ });
2625
+ });
2626
+ return;
2627
+ }
2628
+
2629
+ if (this.closed) return;
2630
+ if (!isPlainObject(output)) {
2631
+ throw new AgentFlowError(
2632
+ "validation",
2633
+ `handler ${row.handler}@${row.handler_version} returned a non-object result`,
2634
+ );
2635
+ }
2636
+ const normalized = normalizeHandlerOutput(output, row.kind);
2637
+ let dataJson: string | null = null;
2638
+ if (normalized.data !== undefined) {
2639
+ dataJson = toJson(normalized.data);
2640
+ if (dataJson.length > PLAN_STEP_DATA_MAX_BYTES) {
2641
+ throw new AgentFlowError(
2642
+ "validation",
2643
+ `handler ${row.handler}@${row.handler_version} returned data larger than ${PLAN_STEP_DATA_MAX_BYTES} bytes`,
2644
+ );
2645
+ }
2646
+ }
2647
+ const now = Date.now();
2648
+ this.store.tx(() => {
2649
+ this.store.updatePlanStep(runId, waveId, stepId, {
2650
+ status: normalized.status,
2651
+ passed:
2652
+ normalized.passed === undefined ? null : normalized.passed ? 1 : 0,
2653
+ data_json: dataJson,
2654
+ reason: normalized.reason ?? null,
2655
+ error: null,
2656
+ finished_at: now,
2657
+ });
2658
+ this.store.emit({
2659
+ runId,
2660
+ waveId,
2661
+ type: `step.${normalized.status}`,
2662
+ data: {
2663
+ stepId,
2664
+ kind: row.kind,
2665
+ handler: row.handler,
2666
+ handlerVersion: row.handler_version,
2667
+ ...(normalized.passed === undefined
2668
+ ? {}
2669
+ : { passed: normalized.passed }),
2670
+ ...(normalized.reason === undefined
2671
+ ? {}
2672
+ : { reason: normalized.reason }),
2673
+ },
2674
+ });
2675
+ });
2676
+ }
2677
+
2678
+ /** Mark a ready step that will never run because a dependency failed. */
2679
+ private blockPlanStep(
2680
+ runId: string,
2681
+ waveId: string,
2682
+ row: PlanStepRow,
2683
+ reason: string,
2684
+ ): void {
2685
+ this.store.tx(() => {
2686
+ this.store.updatePlanStep(runId, waveId, row.step_id, {
2687
+ status: "blocked",
2688
+ reason,
2689
+ finished_at: Date.now(),
2690
+ });
2691
+ this.store.emit({
2692
+ runId,
2693
+ waveId,
2694
+ type: "step.blocked",
2695
+ data: { stepId: row.step_id, kind: row.kind, reason },
2696
+ });
2697
+ });
2698
+ }
2699
+
2700
+ /** A step whose effect is unknown always pauses the run, never replays. */
2701
+ private markPlanStepInterrupted(
2702
+ runId: string,
2703
+ waveId: string,
2704
+ stepId: string,
2705
+ reason: string,
2706
+ ): void {
2707
+ const row = this.store.getPlanStepRow(runId, waveId, stepId);
2708
+ if (row === undefined) return;
2709
+ const now = Date.now();
2710
+ const blocker =
2711
+ "unknown effect: the step outcome could not be confirmed; review the result before rotating or resuming";
2712
+ this.store.tx(() => {
2713
+ this.store.updatePlanStep(runId, waveId, stepId, {
2714
+ status: "interrupted",
2715
+ error: reason,
2716
+ finished_at: now,
2717
+ });
2718
+ this.store.emit({
2719
+ runId,
2720
+ waveId,
2721
+ type: "step.interrupted",
2722
+ data: { stepId, kind: row.kind, reason },
2723
+ });
2724
+ this.store.appendRecovery(runId, {
2725
+ daemon: this.generation,
2726
+ action: "interrupted",
2727
+ reason,
2728
+ waveId,
2729
+ stepId,
2730
+ attemptId: row.attempt_id,
2731
+ blocker,
2732
+ at: now,
2733
+ });
2734
+ this.store.updateWave(runId, waveId, {
2735
+ status: "paused",
2736
+ finished_at: now,
2737
+ });
2738
+ this.store.updateRun(runId, {
2739
+ status: "paused",
2740
+ error: reason,
2741
+ updated_at: now,
2742
+ });
2743
+ this.store.emit({ runId, waveId, type: "wave.paused" });
2744
+ this.store.emit({
2745
+ runId,
2746
+ type: "run.paused",
2747
+ data: { reason: "step_interrupted", waveId, stepId },
2748
+ });
2749
+ });
2750
+ }
2751
+
2752
+ private pauseForPlanStep(
2753
+ runId: string,
2754
+ waveId: string,
2755
+ row: PlanStepRow,
2756
+ ): void {
2757
+ const now = Date.now();
2758
+ const reason = row.error ?? `step ${row.step_id} needs operator attention`;
2759
+ this.store.tx(() => {
2760
+ this.store.updateWave(runId, waveId, {
2761
+ status: "paused",
2762
+ finished_at: now,
2763
+ });
2764
+ this.store.updateRun(runId, {
2765
+ status: "paused",
2766
+ error: reason,
2767
+ updated_at: now,
2768
+ });
2769
+ this.store.emit({ runId, waveId, type: "wave.paused" });
2770
+ this.store.emit({
2771
+ runId,
2772
+ type: "run.paused",
2773
+ data: { reason: "step_paused", waveId, stepId: row.step_id },
2774
+ });
2775
+ });
2776
+ }
2777
+
2778
+ private isPlanStepAdmissionBlocked(runId: string): boolean {
2779
+ if (this.closed || this.draining()) return true;
2780
+ const run = this.store.getRunRow(runId);
2781
+ if (run === undefined) return true;
2782
+ if (run.stopped === 1) return true;
2783
+ if (run.status === "cancelled" || run.status === "failed") return true;
2784
+ if (run.status === "completed" || run.status === "paused") return true;
2785
+ return false;
1113
2786
  }
1114
2787
 
1115
2788
  private async executeWave(runId: string, waveId: string): Promise<void> {
1116
- while (!this.closed) {
2789
+ while (!this.closed && !this.draining()) {
1117
2790
  const run = this.store.getRunRow(runId);
1118
2791
  if (
1119
2792
  run === undefined ||
@@ -1139,6 +2812,13 @@ export class EngineImpl implements Engine {
1139
2812
  const agents = this.store
1140
2813
  .getAgentRows(runId)
1141
2814
  .filter((agent) => agent.wave_id === waveId);
2815
+ if (
2816
+ agents.some(
2817
+ (agent) => agent.status === "pending" || agent.status === "running",
2818
+ )
2819
+ ) {
2820
+ return;
2821
+ }
1142
2822
  const now = Date.now();
1143
2823
 
1144
2824
  if (agents.some((agent) => agent.status === "failed")) {
@@ -1411,11 +3091,24 @@ export class EngineImpl implements Engine {
1411
3091
  });
1412
3092
 
1413
3093
  let sessionId = agent.session_id;
3094
+ let sessionConfig: TurnRequest["sessionConfiguration"];
3095
+ if (sessionId === null || agent.turns === 0) {
3096
+ try {
3097
+ sessionConfig = await configureSession(
3098
+ spec,
3099
+ profile,
3100
+ this.modules.sessionConfiguration(),
3101
+ );
3102
+ } catch (error) {
3103
+ this.markAgent(agent, "interrupted", {
3104
+ reason: `agent configuration failed: ${asAgentFlowError(error).message}`,
3105
+ });
3106
+ return;
3107
+ }
3108
+ }
1414
3109
  if (sessionId === null) {
1415
- const sessionConfig = this.modules.sessionConfiguration();
1416
3110
  try {
1417
- // Only pass the third argument when a module is configured; providers
1418
- // keep their previous request body/behavior otherwise.
3111
+ if (this.closed || this.isAgentSettlingBlocked(runId, agentId)) return;
1419
3112
  sessionId =
1420
3113
  sessionConfig === undefined
1421
3114
  ? await adapter.open(spec, profile)
@@ -1447,7 +3140,7 @@ export class EngineImpl implements Engine {
1447
3140
  let rateLimitAttempts = 0;
1448
3141
 
1449
3142
  while (!this.closed) {
1450
- if (this.isAgentStopped(runId, agentId)) return;
3143
+ if (this.draining() || this.isAdmissionBlocked(runId, agentId)) return;
1451
3144
  const currentAgent = this.store.getAgentRow(runId, agentId);
1452
3145
  if (currentAgent === undefined) return;
1453
3146
  const currentRun = this.store.getRunRow(runId);
@@ -1455,21 +3148,26 @@ export class EngineImpl implements Engine {
1455
3148
 
1456
3149
  const group = this.quota.ensure(profile);
1457
3150
  const runAbort = this.getRunAbort(runId);
1458
- const acquired = await this.quota.acquire(
3151
+ // The run ceiling gates admission before the shared group, so a lowered
3152
+ // cap never interrupts turns that were already admitted.
3153
+ const ceiling = await this.waitForTurnSlot(
3154
+ runId,
1459
3155
  group,
1460
- () => this.isAgentStopped(runId, agentId),
3156
+ () => this.draining() || this.isAdmissionBlocked(runId, agentId),
1461
3157
  runAbort.signal,
1462
3158
  );
1463
- if (!acquired.ok) {
1464
- if (acquired.reason === "exhausted") {
3159
+ if (!ceiling.ok) {
3160
+ if (ceiling.reason === "exhausted") {
1465
3161
  this.markAgent(currentAgent, "paused", {
1466
3162
  reason: "shared quota is exhausted",
1467
3163
  error: "quota exhausted",
1468
3164
  });
1469
- } else if (acquired.reason === "missing") {
3165
+ } else if (ceiling.reason === "missing") {
1470
3166
  this.markAgent(currentAgent, "interrupted", {
1471
3167
  reason: "quota group is missing",
1472
3168
  });
3169
+ } else if (ceiling.reason === "stopped") {
3170
+ return;
1473
3171
  }
1474
3172
  return;
1475
3173
  }
@@ -1538,15 +3236,32 @@ export class EngineImpl implements Engine {
1538
3236
  profile,
1539
3237
  prompt,
1540
3238
  signal: controller.signal,
1541
- onReceipt: (receipt) => {
3239
+ ...(sessionConfig === undefined
3240
+ ? {}
3241
+ : { sessionConfiguration: sessionConfig }),
3242
+ onReceipt: (receipt, nativeSessionId) => {
1542
3243
  if (this.closed) return;
1543
3244
  try {
1544
3245
  const turn = this.store.getTurnRow(turnId);
1545
3246
  if (turn === undefined) return;
1546
3247
  if (turn.state !== "admitted" && turn.state !== "running") return;
1547
- if (turn.receipt === receipt) return;
3248
+ if (
3249
+ turn.receipt === receipt &&
3250
+ (nativeSessionId === undefined ||
3251
+ turn.session_id === nativeSessionId)
3252
+ )
3253
+ return;
1548
3254
  this.store.tx(() => {
1549
- this.store.updateTurn(turnId, { receipt });
3255
+ this.store.updateTurn(turnId, {
3256
+ receipt,
3257
+ ...(nativeSessionId === undefined
3258
+ ? {}
3259
+ : { session_id: nativeSessionId }),
3260
+ });
3261
+ if (nativeSessionId !== undefined)
3262
+ this.store.updateAgent(runId, agentId, {
3263
+ session_id: nativeSessionId,
3264
+ });
1550
3265
  this.store.emit({
1551
3266
  runId,
1552
3267
  waveId: currentAgent.wave_id,
@@ -1682,6 +3397,11 @@ export class EngineImpl implements Engine {
1682
3397
  result,
1683
3398
  );
1684
3399
 
3400
+ if (result.status === "succeeded" && !this.draining()) {
3401
+ await this.captureProviderHistory(adapter, profile, session);
3402
+ if (this.closed || this.isAgentSettlingBlocked(runId, agentId)) return;
3403
+ }
3404
+
1685
3405
  if (result.status === "succeeded") {
1686
3406
  const groupSnapshot = this.quota.recordSuccess(group);
1687
3407
  if (groupSnapshot !== undefined) {
@@ -1709,7 +3429,8 @@ export class EngineImpl implements Engine {
1709
3429
  resultText: result.text,
1710
3430
  signal: runAbort.signal,
1711
3431
  });
1712
- if (this.closed || this.isAgentStopped(runId, agentId)) return;
3432
+ if (this.closed || this.isAgentSettlingBlocked(runId, agentId))
3433
+ return;
1713
3434
  if (moduleOutcome !== undefined) {
1714
3435
  if (moduleOutcome === "paused") return;
1715
3436
  prompt = moduleOutcome;
@@ -1719,7 +3440,7 @@ export class EngineImpl implements Engine {
1719
3440
  }
1720
3441
 
1721
3442
  this.stageArtifacts(runId, currentAgent, result.artifacts);
1722
- if (this.isAgentStopped(runId, agentId)) return;
3443
+ if (this.isAgentSettlingBlocked(runId, agentId)) return;
1723
3444
 
1724
3445
  let decision: TurnDecision | undefined;
1725
3446
  if (strategy.decide !== undefined) {
@@ -1732,7 +3453,7 @@ export class EngineImpl implements Engine {
1732
3453
  verify: (name, evidence) => this.verify(name, evidence),
1733
3454
  });
1734
3455
  } catch (error) {
1735
- if (this.isAgentStopped(runId, agentId)) return;
3456
+ if (this.isAgentSettlingBlocked(runId, agentId)) return;
1736
3457
  const failure = asAgentFlowError(error);
1737
3458
  this.markAgent(currentAgent, "failed", {
1738
3459
  reason: `strategy decision failed: ${failure.message}`,
@@ -1742,7 +3463,7 @@ export class EngineImpl implements Engine {
1742
3463
  return;
1743
3464
  }
1744
3465
  }
1745
- if (this.isAgentStopped(runId, agentId)) return;
3466
+ if (this.isAgentSettlingBlocked(runId, agentId)) return;
1746
3467
 
1747
3468
  if (decision === undefined || decision.status === "complete") {
1748
3469
  const staged = this.stageArtifacts(
@@ -1897,7 +3618,10 @@ export class EngineImpl implements Engine {
1897
3618
  if (reply.kind === "invalid") {
1898
3619
  // A mixed JSON/artifact reply or malformed envelope must be visible, not
1899
3620
  // silently treated as a successful ordinary answer.
1900
- if (this.closed || this.isAgentStopped(input.runId, input.agentId)) {
3621
+ if (
3622
+ this.closed ||
3623
+ this.isAgentSettlingBlocked(input.runId, input.agentId)
3624
+ ) {
1901
3625
  return "paused";
1902
3626
  }
1903
3627
  this.store.emit({
@@ -1943,7 +3667,7 @@ export class EngineImpl implements Engine {
1943
3667
  // Re-check cancellation immediately before handing control to a module.
1944
3668
  if (
1945
3669
  this.closed ||
1946
- this.isAgentStopped(input.runId, input.agentId) ||
3670
+ this.isAgentSettlingBlocked(input.runId, input.agentId) ||
1947
3671
  input.signal.aborted
1948
3672
  ) {
1949
3673
  return "paused";
@@ -2005,7 +3729,7 @@ export class EngineImpl implements Engine {
2005
3729
 
2006
3730
  if (
2007
3731
  this.closed ||
2008
- this.isAgentStopped(input.runId, input.agentId) ||
3732
+ this.isAgentSettlingBlocked(input.runId, input.agentId) ||
2009
3733
  input.signal.aborted
2010
3734
  ) {
2011
3735
  return "paused";
@@ -2058,6 +3782,24 @@ export class EngineImpl implements Engine {
2058
3782
  });
2059
3783
  }
2060
3784
 
3785
+ private async captureProviderHistory(
3786
+ adapter: ProviderAdapter,
3787
+ profile: Profile,
3788
+ sessionId: string,
3789
+ ): Promise<void> {
3790
+ const history = adapter.createHistory?.(profile);
3791
+ if (history === undefined || history === "disabled") return;
3792
+ await readProviderHistory(
3793
+ { id: adapter.id, history },
3794
+ new HistoryStore(this.store),
3795
+ {
3796
+ sessionId,
3797
+ maxPages: 4,
3798
+ signal: AbortSignal.timeout(2000),
3799
+ },
3800
+ );
3801
+ }
3802
+
2061
3803
  private stageArtifacts(
2062
3804
  runId: string,
2063
3805
  agent: { id: string; wave_id: string; spec_json: string },
@@ -2078,6 +3820,18 @@ export class EngineImpl implements Engine {
2078
3820
  }),
2079
3821
  ]),
2080
3822
  );
3823
+ const attemptId = this.store
3824
+ .getTurnRows(runId, agent.id)
3825
+ .at(-1)?.attempt_id;
3826
+ const metadata = this.store.listPlanMetaRows(runId).at(-1);
3827
+ const phases =
3828
+ metadata === undefined
3829
+ ? []
3830
+ : (fromJson<RunPlanMetadata | undefined>(metadata.meta_json, undefined)
3831
+ ?.phases ?? []);
3832
+ const phaseId =
3833
+ phases.find((phase) => phase.waveIds.includes(agent.wave_id))?.id ??
3834
+ agent.wave_id;
2081
3835
  const merged: Record<string, unknown> = {};
2082
3836
  for (const [artifactId, raw] of Object.entries(artifacts)) {
2083
3837
  const declaration = declarations.get(artifactId);
@@ -2093,7 +3847,30 @@ export class EngineImpl implements Engine {
2093
3847
  }
2094
3848
  if (raw === undefined) continue;
2095
3849
  const prepared = prepareArtifact(declaration, raw, spec.cwd);
3850
+ if (declaration.type === "file")
3851
+ mkdirSync(this.artifactRoot, { recursive: true, mode: 0o700 });
2096
3852
  this.store.tx(() => {
3853
+ const version = this.store.recordArtifactVersion({
3854
+ runId,
3855
+ declaration,
3856
+ raw,
3857
+ cwd: spec.cwd,
3858
+ origin: {
3859
+ agentId: agent.id,
3860
+ phaseId,
3861
+ ...(attemptId ? { attemptId } : {}),
3862
+ },
3863
+ options: { root: this.artifactRoot },
3864
+ });
3865
+ if (version.state === "invalid") {
3866
+ prepared.state = "invalid";
3867
+ prepared.error = version.version.error;
3868
+ delete prepared.path;
3869
+ } else if (version.version.storedPath) {
3870
+ prepared.path = realpathSync(
3871
+ join(this.artifactRoot, version.version.storedPath),
3872
+ );
3873
+ }
2097
3874
  this.store.updateArtifact(runId, artifactId, {
2098
3875
  state: prepared.state,
2099
3876
  value_json:
@@ -2116,6 +3893,10 @@ export class EngineImpl implements Engine {
2116
3893
  : "artifact.invalid",
2117
3894
  data: {
2118
3895
  artifactId,
3896
+ version: version.version.version,
3897
+ ...(version.version.digest
3898
+ ? { digest: version.version.digest }
3899
+ : {}),
2119
3900
  ...(prepared.error === undefined ? {} : { error: prepared.error }),
2120
3901
  },
2121
3902
  });
@@ -2329,19 +4110,381 @@ export class EngineImpl implements Engine {
2329
4110
  if (delivered && !this.closed) this.scheduleRun(runId);
2330
4111
  }
2331
4112
 
2332
- // ---------------------------------------------------------------- helpers
4113
+ // ------------------------------------------------------- operator helpers
4114
+
4115
+ private actionOptions(options: {
4116
+ actionId: string;
4117
+ actor?: string;
4118
+ reason?: string;
4119
+ }): OperatorOptions & { actionId: string };
4120
+ private actionOptions(options: {
4121
+ actionId?: string;
4122
+ actor?: string;
4123
+ reason?: string;
4124
+ }): OperatorOptions;
4125
+ private actionOptions(options: {
4126
+ actionId?: string;
4127
+ actor?: string;
4128
+ reason?: string;
4129
+ }): OperatorOptions {
4130
+ if (!isPlainObject(options)) {
4131
+ throw new AgentFlowError(
4132
+ "validation",
4133
+ "operator options must be an object",
4134
+ );
4135
+ }
4136
+ if (options.actionId !== undefined) {
4137
+ if (typeof options.actionId !== "string" || options.actionId === "") {
4138
+ throw new AgentFlowError(
4139
+ "validation",
4140
+ "options.actionId must be a non-empty string",
4141
+ );
4142
+ }
4143
+ }
4144
+ if (options.actor !== undefined && typeof options.actor !== "string") {
4145
+ throw new AgentFlowError("validation", "options.actor must be a string");
4146
+ }
4147
+ if (options.reason !== undefined && typeof options.reason !== "string") {
4148
+ throw new AgentFlowError("validation", "options.reason must be a string");
4149
+ }
4150
+ return {
4151
+ actor: options.actor ?? OPERATOR_ACTOR,
4152
+ ...(options.reason === undefined ? {} : { reason: options.reason }),
4153
+ ...(options.actionId === undefined ? {} : { actionId: options.actionId }),
4154
+ };
4155
+ }
4156
+
4157
+ /**
4158
+ * Apply one operator action atomically with its receipt and event. The event
4159
+ * carries the receipt id so logs can be correlated to the audited change.
4160
+ */
4161
+ private persistOperatorAction(
4162
+ runId: string,
4163
+ actionId: string,
4164
+ kind: OperatorActionKind,
4165
+ actor: string,
4166
+ reason: string | undefined,
4167
+ oldValue: unknown,
4168
+ newValue: unknown,
4169
+ apply: () => void,
4170
+ ): void {
4171
+ const now = Date.now();
4172
+ this.store.withReceipt(actionId, () => {
4173
+ this.store.tx(() => {
4174
+ apply();
4175
+ this.store.insertOperation({
4176
+ id: actionId,
4177
+ runId,
4178
+ kind,
4179
+ actor,
4180
+ ...(reason === undefined ? {} : { reason }),
4181
+ oldValue,
4182
+ newValue,
4183
+ at: now,
4184
+ });
4185
+ this.store.emit({
4186
+ runId,
4187
+ type: `operator.${kind}`,
4188
+ origin: { daemon: this.generation, actionId },
4189
+ data: { actor, ...(reason === undefined ? {} : { reason }) },
4190
+ });
4191
+ });
4192
+ });
4193
+ }
4194
+
4195
+ private requireOperation(id: string, runId: string): OperationReceipt {
4196
+ const row = this.store.getOperationRow(id);
4197
+ if (row === undefined || row.run_id !== runId) {
4198
+ throw new AgentFlowError(
4199
+ "internal",
4200
+ `operation ${id} was not persisted for run ${runId}`,
4201
+ );
4202
+ }
4203
+ return operationReceipt(row, false, runId);
4204
+ }
4205
+
4206
+ /** Failed, and never-admitted blocked, steps eligible for `retryRun`. */
4207
+ private retryCandidates(runId: string): RetryCandidate[] {
4208
+ const candidates: RetryCandidate[] = [];
4209
+ for (const agent of this.store.getAgentRows(runId)) {
4210
+ if (agent.status === "failed") {
4211
+ const uncertain = agent.blocker !== null;
4212
+ candidates.push({
4213
+ agentId: agent.id,
4214
+ waveId: agent.wave_id,
4215
+ status: agent.status,
4216
+ kind: "failed",
4217
+ eligible: true,
4218
+ ...(uncertain ? { blocker: agent.blocker as string } : {}),
4219
+ });
4220
+ continue;
4221
+ }
4222
+ if (agent.status === "interrupted") {
4223
+ candidates.push({
4224
+ agentId: agent.id,
4225
+ waveId: agent.wave_id,
4226
+ status: agent.status,
4227
+ kind: "failed",
4228
+ eligible: false,
4229
+ blocker:
4230
+ agent.blocker ??
4231
+ "unknown effect: a native turn may have been admitted before the cut",
4232
+ });
4233
+ continue;
4234
+ }
4235
+ if (agent.status === "pending" || agent.status === "paused") {
4236
+ const wave = this.store.getWaveRow(runId, agent.wave_id);
4237
+ if (wave !== undefined && wave.status === "blocked") {
4238
+ candidates.push({
4239
+ agentId: agent.id,
4240
+ waveId: agent.wave_id,
4241
+ status: agent.status,
4242
+ kind: "blocked",
4243
+ eligible: true,
4244
+ });
4245
+ }
4246
+ }
4247
+ }
4248
+ return candidates;
4249
+ }
4250
+
4251
+ private reopenWave(runId: string, waveId: string): void {
4252
+ const wave = this.store.getWaveRow(runId, waveId);
4253
+ if (wave === undefined) return;
4254
+ if (
4255
+ wave.status === "blocked" ||
4256
+ wave.status === "failed" ||
4257
+ wave.status === "paused"
4258
+ ) {
4259
+ this.store.updateWave(runId, waveId, {
4260
+ status: "pending",
4261
+ started_at: null,
4262
+ finished_at: null,
4263
+ });
4264
+ }
4265
+ }
4266
+
4267
+ /** Steps completed in the source run whose semantics still match the plan. */
4268
+ private retainedResults(
4269
+ runId: string,
4270
+ plan: RunPlan,
4271
+ meta: RunPlanMetadata,
4272
+ resolvedById: ReadonlyMap<string, ResolvedAgent>,
4273
+ ): Array<{
4274
+ agentId: string;
4275
+ sessionId: string | null;
4276
+ turns: number;
4277
+ resultJson: string | null;
4278
+ sourceRunId: string;
4279
+ sourceRevision: number;
4280
+ }> {
4281
+ const steps = new Map(meta.steps.map((step) => [step.id, step]));
4282
+ const retained: ReturnType<EngineImpl["retainedResults"]> = [];
4283
+ for (const wave of plan.waves) {
4284
+ for (const spec of wave.agents) {
4285
+ const step = steps.get(spec.id);
4286
+ if (step === undefined) continue;
4287
+ const source = this.store.getAgentRow(runId, spec.id);
4288
+ if (source === undefined || source.status !== "succeeded") continue;
4289
+ const resolved = resolvedById.get(spec.id);
4290
+ const effective = resolved?.spec ?? spec;
4291
+ const profile =
4292
+ resolved?.profile ??
4293
+ fromJson<Profile>(source.profile_json, {
4294
+ id: source.profile_id,
4295
+ adapter: source.adapter,
4296
+ settings: {},
4297
+ });
4298
+ if (
4299
+ source.semantics_digest !== null &&
4300
+ source.semantics_digest !== stepSemantics(effective, profile)
4301
+ ) {
4302
+ continue;
4303
+ }
4304
+ retained.push({
4305
+ agentId: spec.id,
4306
+ sessionId: source.session_id,
4307
+ turns: source.turns,
4308
+ resultJson: source.result_json,
4309
+ sourceRunId: runId,
4310
+ sourceRevision: this.store.listPlanMetaRows(runId).length,
4311
+ });
4312
+ }
4313
+ }
4314
+ return retained;
4315
+ }
4316
+
4317
+ /** Structural diff between the source run's persisted work and a new plan. */
4318
+ private diffPlan(
4319
+ runId: string,
4320
+ plan: RunPlan,
4321
+ meta: RunPlanMetadata,
4322
+ resolvedById: ReadonlyMap<string, ResolvedAgent>,
4323
+ ): PlanDiffEntry[] {
4324
+ const diff: PlanDiffEntry[] = [];
4325
+ const existingWaves = new Map(
4326
+ this.store.getWaveRows(runId).map((wave) => [wave.id, wave]),
4327
+ );
4328
+ const existingAgents = new Map(
4329
+ this.store.getAgentRows(runId).map((agent) => [agent.id, agent]),
4330
+ );
4331
+ const steps = new Map(meta.steps.map((step) => [step.id, step]));
4332
+ const seenWaves = new Set<string>();
4333
+ const seenAgents = new Set<string>();
4334
+ for (const wave of plan.waves) {
4335
+ seenWaves.add(wave.id);
4336
+ if (!existingWaves.has(wave.id)) {
4337
+ diff.push({ change: "added", scope: "wave", id: wave.id, keep: false });
4338
+ }
4339
+ for (const spec of wave.agents) {
4340
+ seenAgents.add(spec.id);
4341
+ const step = steps.get(spec.id);
4342
+ const agent = existingAgents.get(spec.id);
4343
+ if (step === undefined) continue;
4344
+ if (agent === undefined) {
4345
+ diff.push({
4346
+ change: "added",
4347
+ scope: "agent",
4348
+ id: spec.id,
4349
+ keep: false,
4350
+ });
4351
+ continue;
4352
+ }
4353
+ const resolved = resolvedById.get(spec.id);
4354
+ const effective = resolved?.spec ?? spec;
4355
+ const profile =
4356
+ resolved?.profile ??
4357
+ fromJson<Profile>(agent.profile_json, {
4358
+ id: agent.profile_id,
4359
+ adapter: agent.adapter,
4360
+ settings: {},
4361
+ });
4362
+ const semantic = stepSemantics(effective, profile);
4363
+ const keep =
4364
+ agent.status === "succeeded" &&
4365
+ (agent.semantics_digest === null ||
4366
+ agent.semantics_digest === semantic);
4367
+ diff.push({
4368
+ change: keep ? "changed" : "changed",
4369
+ scope: "agent",
4370
+ id: spec.id,
4371
+ keep,
4372
+ });
4373
+ }
4374
+ }
4375
+ for (const [waveId] of existingWaves) {
4376
+ if (!seenWaves.has(waveId)) {
4377
+ diff.push({
4378
+ change: "removed",
4379
+ scope: "wave",
4380
+ id: waveId,
4381
+ keep: false,
4382
+ });
4383
+ }
4384
+ }
4385
+ for (const [agentId] of existingAgents) {
4386
+ if (!seenAgents.has(agentId)) {
4387
+ diff.push({
4388
+ change: "removed",
4389
+ scope: "agent",
4390
+ id: agentId,
4391
+ keep: false,
4392
+ });
4393
+ }
4394
+ }
4395
+ return diff;
4396
+ }
4397
+
4398
+ private async clearQuotaIfExhausted(runId: string): Promise<void> {
4399
+ for (const agent of this.store.getAgentRows(runId)) {
4400
+ if (agent.status !== "pending" && agent.status !== "paused") continue;
4401
+ const profile = fromJson<Profile>(agent.profile_json, {
4402
+ id: agent.profile_id,
4403
+ adapter: agent.adapter,
4404
+ settings: {},
4405
+ });
4406
+ try {
4407
+ this.store.clearQuotaExhausted(quotaGroupName(profile));
4408
+ } catch {
4409
+ // Quota clearing is best effort during continuation.
4410
+ }
4411
+ }
4412
+ }
4413
+
4414
+ /**
4415
+ * Wait for one free turn slot in this run and the shared quota group. The run
4416
+ * ceiling is checked first; a lowered cap simply delays queued admission.
4417
+ */
4418
+ private async waitForTurnSlot(
4419
+ runId: string,
4420
+ group: string,
4421
+ isStopped: () => boolean,
4422
+ signal?: AbortSignal,
4423
+ ): Promise<{ ok: boolean; reason?: WaitOutcome["reason"] }> {
4424
+ while (true) {
4425
+ if (isStopped()) return { ok: false, reason: "stopped" };
4426
+ if (signal?.aborted) return { ok: false, reason: "cancelled" };
4427
+ const run = this.store.getRunRow(runId);
4428
+ if (run === undefined) return { ok: false, reason: "stopped" };
4429
+ if (
4430
+ run.max_concurrent !== null &&
4431
+ this.store.countActiveTurns(runId) >= run.max_concurrent
4432
+ ) {
4433
+ try {
4434
+ await sleep(10, signal);
4435
+ } catch {
4436
+ return { ok: false, reason: "stopped" };
4437
+ }
4438
+ continue;
4439
+ }
4440
+ const acquired = await this.quota.acquire(group, isStopped, signal);
4441
+ if (!acquired.ok) {
4442
+ return {
4443
+ ok: false,
4444
+ reason: acquired.reason === "cancelled" ? "stopped" : acquired.reason,
4445
+ };
4446
+ }
4447
+ if (isStopped()) {
4448
+ this.store.releaseQuota(group);
4449
+ return { ok: false, reason: "stopped" };
4450
+ }
4451
+ const latest = this.store.getRunRow(runId);
4452
+ if (
4453
+ latest !== undefined &&
4454
+ latest.max_concurrent !== null &&
4455
+ this.store.countActiveTurns(runId) > latest.max_concurrent
4456
+ ) {
4457
+ // A concurrent admission used this slot; release it and wait again.
4458
+ this.store.releaseQuota(group);
4459
+ continue;
4460
+ }
4461
+ return { ok: true };
4462
+ }
4463
+ }
2333
4464
 
2334
4465
  private resolveAgent(
2335
4466
  spec: AgentSpec,
2336
4467
  runProfile: Profile,
2337
4468
  runStrategy: Strategy,
2338
4469
  ): ResolvedAgent {
4470
+ // Apply configured defaults once, before persistence. The stored spec is
4471
+ // the effective one, so startup recovery never reapplies them.
4472
+ const effective = applyAgentDefaults(spec, {
4473
+ ...(this.agentDefaults === undefined
4474
+ ? {}
4475
+ : { agentDefaults: this.agentDefaults }),
4476
+ subagents: this.subagents,
4477
+ profiles: this.profiles,
4478
+ runProfile,
4479
+ });
2339
4480
  const profile =
2340
- spec.profile === undefined ? runProfile : this.profiles.get(spec.profile);
4481
+ effective.profile === undefined
4482
+ ? runProfile
4483
+ : this.profiles.get(effective.profile);
2341
4484
  if (profile === undefined) {
2342
4485
  throw new AgentFlowError(
2343
4486
  "validation",
2344
- `profile ${spec.profile} is not configured`,
4487
+ `profile ${effective.profile} is not configured`,
2345
4488
  );
2346
4489
  }
2347
4490
  if (profile.adapter !== runProfile.adapter) {
@@ -2356,7 +4499,7 @@ export class EngineImpl implements Engine {
2356
4499
  },
2357
4500
  );
2358
4501
  }
2359
- const strategyId = spec.strategy ?? runStrategy.id;
4502
+ const strategyId = effective.strategy ?? runStrategy.id;
2360
4503
  const strategy = this.strategies.get(strategyId);
2361
4504
  if (strategy === undefined) {
2362
4505
  throw new AgentFlowError(
@@ -2366,7 +4509,7 @@ export class EngineImpl implements Engine {
2366
4509
  }
2367
4510
  this.quota.ensure(profile);
2368
4511
  return {
2369
- spec,
4512
+ spec: effective,
2370
4513
  profile,
2371
4514
  profileId: profile.id,
2372
4515
  adapter: profile.adapter,
@@ -2411,10 +4554,17 @@ export class EngineImpl implements Engine {
2411
4554
  }
2412
4555
  }
2413
4556
 
2414
- private isAgentStopped(runId: string, agentId: string): boolean {
4557
+ /**
4558
+ * Admission gate. An operator stop, a terminal run, cancellation or a closed
4559
+ * engine freezes *future* native work. This is checked only before a new turn
4560
+ * is submitted, never after a turn has already resolved, so a stop cannot
4561
+ * discard a result the provider already produced.
4562
+ */
4563
+ private isAdmissionBlocked(runId: string, agentId: string): boolean {
2415
4564
  if (this.closed) return true;
2416
4565
  const run = this.store.getRunRow(runId);
2417
4566
  if (run === undefined) return true;
4567
+ if (run.stopped === 1) return true;
2418
4568
  if (run.status === "cancelled" || run.status === "failed") return true;
2419
4569
  if (run.status === "completed" || run.status === "paused") return true;
2420
4570
  const agent = this.store.getAgentRow(runId, agentId);
@@ -2422,6 +4572,22 @@ export class EngineImpl implements Engine {
2422
4572
  return agent.status === "cancelled";
2423
4573
  }
2424
4574
 
4575
+ /**
4576
+ * Settlement gate. Once a native turn has a known outcome, only a hard stop —
4577
+ * process close, run cancellation or supersede — may drop persisting that
4578
+ * result. An operator stop is deliberately excluded: it delays admission but
4579
+ * lets the already-admitted turn settle so completed work is never lost.
4580
+ */
4581
+ private isAgentSettlingBlocked(runId: string, agentId: string): boolean {
4582
+ if (this.closed) return true;
4583
+ const run = this.store.getRunRow(runId);
4584
+ if (run === undefined) return true;
4585
+ if (run.status === "cancelled" || run.status === "failed") return true;
4586
+ const agent = this.store.getAgentRow(runId, agentId);
4587
+ if (agent === undefined) return true;
4588
+ return agent.status === "cancelled";
4589
+ }
4590
+
2425
4591
  private getRunAbort(runId: string): AbortController {
2426
4592
  let controller = this.runAborts.get(runId);
2427
4593
  if (controller === undefined) {
@@ -2461,7 +4627,21 @@ export class EngineImpl implements Engine {
2461
4627
  }
2462
4628
  });
2463
4629
 
2464
- const inflight = this.store.listInflightTurnRows();
4630
+ for (const step of this.store.listRunningPlanStepRows()) {
4631
+ this.markPlanStepInterrupted(
4632
+ step.run_id,
4633
+ step.wave_id,
4634
+ step.step_id,
4635
+ "daemon restarted while the registered handler was in flight",
4636
+ );
4637
+ }
4638
+ const drainInterrupted = this.store.listDrainInterruptedTurnRows(
4639
+ DRAIN_OUTCOME_UNKNOWN,
4640
+ );
4641
+ const inflight = [
4642
+ ...this.store.listInflightTurnRows(),
4643
+ ...drainInterrupted,
4644
+ ];
2465
4645
  for (const turn of inflight) {
2466
4646
  const agent = this.store.getAgentRow(turn.run_id, turn.agent_id);
2467
4647
  if (agent === undefined) continue;
@@ -2578,6 +4758,30 @@ export class EngineImpl implements Engine {
2578
4758
  );
2579
4759
  }
2580
4760
 
4761
+ for (const runId of new Set(drainInterrupted.map((turn) => turn.run_id))) {
4762
+ const run = this.store.getRunRow(runId);
4763
+ if (
4764
+ run?.status !== "paused" ||
4765
+ run.stopped === 1 ||
4766
+ run.error !== DRAIN_PAUSED_RUN
4767
+ )
4768
+ continue;
4769
+ const unresolved = this.store
4770
+ .getAgentRows(runId)
4771
+ .some(
4772
+ (agent) =>
4773
+ agent.status === "interrupted" ||
4774
+ agent.status === "paused" ||
4775
+ agent.blocker !== null,
4776
+ );
4777
+ if (!unresolved)
4778
+ this.store.updateRun(runId, {
4779
+ status: "running",
4780
+ error: null,
4781
+ updated_at: Date.now(),
4782
+ });
4783
+ }
4784
+
2581
4785
  const open = this.store.listOpenRunRows();
2582
4786
  for (const run of open) {
2583
4787
  try {
@@ -2610,6 +4814,8 @@ export class EngineImpl implements Engine {
2610
4814
  reason: string,
2611
4815
  ): void {
2612
4816
  const now = Date.now();
4817
+ const blocker =
4818
+ "unknown effect: the provider outcome could not be confirmed after restart; review before retry";
2613
4819
  this.store.tx(() => {
2614
4820
  this.store.updateTurn(turn.id, {
2615
4821
  state: "interrupted",
@@ -2626,8 +4832,15 @@ export class EngineImpl implements Engine {
2626
4832
  this.store.updateAgent(turn.run_id, turn.agent_id, {
2627
4833
  status: "interrupted",
2628
4834
  error: reason,
4835
+ blocker,
2629
4836
  finished_at: now,
2630
4837
  });
4838
+ this.recordRecovery(turn, {
4839
+ action: "interrupted",
4840
+ reason,
4841
+ blocker,
4842
+ at: now,
4843
+ });
2631
4844
  this.store.updateWave(turn.run_id, turn.wave_id, {
2632
4845
  status: "paused",
2633
4846
  finished_at: now,
@@ -2652,6 +4865,31 @@ export class EngineImpl implements Engine {
2652
4865
  });
2653
4866
  }
2654
4867
 
4868
+ /**
4869
+ * Persist one recovery observation and mirror it for `recovery(id)`. Recovery
4870
+ * evidence survives restarts so an operator can see why a step is held.
4871
+ */
4872
+ private recordRecovery(
4873
+ turn: NonNullable<ReturnType<Store["getTurnRow"]>>,
4874
+ entry: {
4875
+ action: RecoveryItem["action"];
4876
+ reason: string;
4877
+ blocker?: string;
4878
+ at: number;
4879
+ },
4880
+ ): void {
4881
+ this.store.appendRecovery(turn.run_id, {
4882
+ daemon: this.generation,
4883
+ action: entry.action,
4884
+ reason: entry.reason,
4885
+ waveId: turn.wave_id,
4886
+ agentId: turn.agent_id,
4887
+ ...(turn.attempt_id === null ? {} : { attemptId: turn.attempt_id }),
4888
+ ...(entry.blocker === undefined ? {} : { blocker: entry.blocker }),
4889
+ at: entry.at,
4890
+ });
4891
+ }
4892
+
2655
4893
  private applyReconciledTurn(
2656
4894
  turn: NonNullable<ReturnType<Store["getTurnRow"]>>,
2657
4895
  result: TurnResult,
@@ -2692,6 +4930,7 @@ export class EngineImpl implements Engine {
2692
4930
  this.store.updateAgent(turn.run_id, turn.agent_id, {
2693
4931
  status: "succeeded",
2694
4932
  error: null,
4933
+ blocker: null,
2695
4934
  result_json: toJson({
2696
4935
  status: "succeeded",
2697
4936
  ...(result.text === undefined ? {} : { text: result.text }),
@@ -2726,8 +4965,22 @@ export class EngineImpl implements Engine {
2726
4965
  this.store.updateAgent(turn.run_id, turn.agent_id, {
2727
4966
  status: "interrupted",
2728
4967
  error: reason,
4968
+ blocker: requiresDecision
4969
+ ? "decision pending: the native turn completed but its decision was never made; do not replay the turn"
4970
+ : null,
2729
4971
  finished_at: now,
2730
4972
  });
4973
+ this.recordRecovery(turn, {
4974
+ action: "interrupted",
4975
+ reason,
4976
+ ...(requiresDecision
4977
+ ? {
4978
+ blocker:
4979
+ "decision pending: the native turn completed but its decision was never made; do not replay the turn",
4980
+ }
4981
+ : {}),
4982
+ at: now,
4983
+ });
2731
4984
  this.store.updateWave(turn.run_id, turn.wave_id, {
2732
4985
  status: "paused",
2733
4986
  finished_at: now,
@@ -2791,6 +5044,38 @@ export class EngineImpl implements Engine {
2791
5044
  }
2792
5045
  }
2793
5046
 
5047
+ /** Public receipt shape for one persisted operator action row. */
5048
+ function operationReceipt(
5049
+ row: {
5050
+ id: string;
5051
+ run_id: string;
5052
+ kind: string;
5053
+ actor: string;
5054
+ reason: string | null;
5055
+ old_json: string | null;
5056
+ new_json: string | null;
5057
+ at: number;
5058
+ },
5059
+ duplicate: boolean,
5060
+ runId: string,
5061
+ ): OperationReceipt {
5062
+ return {
5063
+ id: row.id,
5064
+ runId,
5065
+ kind: row.kind as OperatorActionKind,
5066
+ actor: row.actor,
5067
+ ...(row.reason === null ? {} : { reason: row.reason }),
5068
+ at: row.at,
5069
+ ...(row.old_json === null
5070
+ ? {}
5071
+ : { oldValue: fromJson<unknown>(row.old_json, undefined) }),
5072
+ ...(row.new_json === null
5073
+ ? {}
5074
+ : { newValue: fromJson<unknown>(row.new_json, undefined) }),
5075
+ duplicate,
5076
+ };
5077
+ }
5078
+
2794
5079
  function validateRunId(id: unknown): string {
2795
5080
  if (typeof id !== "string" || id.trim() === "") {
2796
5081
  throw new AgentFlowError(