@nones/agentflow-core 0.1.0 → 0.6.0

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/store.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import { Database, type SQLQueryBindings } from "bun:sqlite";
2
+ import { AgentFlowError } from "./errors";
3
+ import { stageArtifactVersion } from "./artifact-history";
2
4
  import { fromJson, toJson } from "./json";
3
5
  import type {
4
6
  AgentResultSnapshot,
@@ -10,18 +12,32 @@ import type {
10
12
  ArtifactType,
11
13
  EngineEvent,
12
14
  EventOptions,
15
+ EventOrigin,
13
16
  MessageSnapshot,
14
17
  MessageState,
18
+ OperationReceipt,
19
+ OperatorActionKind,
20
+ PlanStepRef,
21
+ PlanStepResult,
22
+ PlanStepStatus,
15
23
  QuotaGroupSnapshot,
16
24
  RateLimitInfo,
25
+ RecoveryItem,
26
+ RunPlanMetadata,
17
27
  RunSnapshot,
18
28
  RunStatus,
19
29
  WaveSnapshot,
20
30
  WaveStatus,
21
31
  } from "./types";
22
32
 
33
+ /** Step kinds persisted with a durable plan. */
34
+ export type AgentStepKind = "agent" | "script" | "gate";
35
+
23
36
  interface RunRow {
24
37
  id: string;
38
+ name: string | null;
39
+ project_id: string | null;
40
+ project_dir: string | null;
25
41
  strategy: string;
26
42
  request_json: string;
27
43
  profile_id: string | null;
@@ -32,6 +48,19 @@ interface RunRow {
32
48
  error: string | null;
33
49
  created_at: number;
34
50
  updated_at: number;
51
+ /** Operator stop persisted across generations (schema v2). */
52
+ stopped: number;
53
+ /** Per-run admission ceiling (schema v2). */
54
+ max_concurrent: number | null;
55
+ predecessor_id: string | null;
56
+ successor_id: string | null;
57
+ /** Digest of the plan the run is executing (schema v2). */
58
+ plan_digest: string | null;
59
+ created_by: string | null;
60
+ /** SHA-256 of the exact script entry that issued the start (schema v4). */
61
+ script_digest: string | null;
62
+ /** Script invocation that created this run (schema v4). */
63
+ invocation_id: string | null;
35
64
  }
36
65
 
37
66
  interface WaveRow {
@@ -42,6 +71,7 @@ interface WaveRow {
42
71
  created_at: number;
43
72
  started_at: number | null;
44
73
  finished_at: number | null;
74
+ phase_id: string | null;
45
75
  }
46
76
 
47
77
  interface AgentRow {
@@ -63,6 +93,17 @@ interface AgentRow {
63
93
  created_at: number;
64
94
  started_at: number | null;
65
95
  finished_at: number | null;
96
+ /** Stable step key inside its phase (schema v2). */
97
+ step_key: string | null;
98
+ step_kind: string | null;
99
+ /** Digest of the step's semantics used to decide result reuse. */
100
+ semantics_digest: string | null;
101
+ attempts: number;
102
+ /** Clarification surfaced for an unknown side effect. */
103
+ blocker: string | null;
104
+ /** Source run of a reused retained result. */
105
+ reused_from: string | null;
106
+ reused_revision: number | null;
66
107
  }
67
108
 
68
109
  interface TurnRow {
@@ -80,6 +121,9 @@ interface TurnRow {
80
121
  created_at: number;
81
122
  started_at: number | null;
82
123
  finished_at: number | null;
124
+ /** Immutable attempt id; one per native submission (schema v2). */
125
+ attempt_id: string | null;
126
+ revision: number | null;
83
127
  }
84
128
 
85
129
  interface ArtifactRow {
@@ -103,6 +147,30 @@ interface EventRow {
103
147
  agent_id: string | null;
104
148
  data_json: string | null;
105
149
  at: number;
150
+ daemon: number | null;
151
+ action_id: string | null;
152
+ revision: number | null;
153
+ }
154
+
155
+ interface OperationRow {
156
+ id: string;
157
+ run_id: string;
158
+ kind: string;
159
+ actor: string;
160
+ reason: string | null;
161
+ old_json: string | null;
162
+ new_json: string | null;
163
+ state: string;
164
+ at: number;
165
+ }
166
+
167
+ interface PlanMetaRow {
168
+ run_id: string;
169
+ revision: number;
170
+ digest: string;
171
+ source_run_id: string | null;
172
+ meta_json: string;
173
+ createdAt: number;
106
174
  }
107
175
 
108
176
  interface MessageRow {
@@ -120,6 +188,26 @@ interface MessageRow {
120
188
  updated_at: number;
121
189
  }
122
190
 
191
+ export interface PlanStepRow {
192
+ run_id: string;
193
+ wave_id: string;
194
+ step_id: string;
195
+ kind: "script" | "gate";
196
+ handler: string;
197
+ handler_version: string;
198
+ cwd: string | null;
199
+ depends_json: string | null;
200
+ status: PlanStepStatus;
201
+ passed: number | null;
202
+ data_json: string | null;
203
+ reason: string | null;
204
+ error: string | null;
205
+ attempt_id: string;
206
+ started_at: number;
207
+ finished_at: number | null;
208
+ reused_from: string | null;
209
+ }
210
+
123
211
  interface QuotaRow {
124
212
  name: string;
125
213
  initial_cap: number;
@@ -143,6 +231,8 @@ export interface EventInput {
143
231
  agentId?: string;
144
232
  data?: unknown;
145
233
  at?: number;
234
+ /** Durable provenance (daemon generation, operator action, revision). */
235
+ origin?: EventOrigin;
146
236
  }
147
237
 
148
238
  export interface RunInsert {
@@ -155,13 +245,46 @@ export interface RunInsert {
155
245
  sealed: boolean;
156
246
  status: RunStatus;
157
247
  createdAt: number;
248
+ /** Optional mutable display name. Names may repeat across runs. */
249
+ name?: string;
250
+ /** Canonical project identity (see `canonicalProjectId`). */
251
+ projectId?: string;
252
+ /** Canonical absolute project directory. */
253
+ projectDir?: string;
254
+ /** Per-run admission ceiling. */
255
+ maxConcurrent?: number;
256
+ predecessorId?: string;
257
+ planDigest?: string;
258
+ createdBy?: string;
259
+ /**
260
+ * SHA-256 of the script entry that issued the start. A client-supplied
261
+ * value, never derived by reading the script file.
262
+ */
263
+ scriptDigest?: string;
264
+ /** Script invocation that started this run; shared across its runs. */
265
+ invocationId?: string;
158
266
  }
159
267
 
268
+ type RunPatch = Patch &
269
+ Partial<
270
+ Record<
271
+ | "name"
272
+ | "project_id"
273
+ | "project_dir"
274
+ | "predecessor_id"
275
+ | "successor_id"
276
+ | "plan_digest"
277
+ | "created_by",
278
+ string | null
279
+ >
280
+ >;
281
+
160
282
  export interface WaveInsert {
161
283
  id: string;
162
284
  index: number;
163
285
  status: WaveStatus;
164
286
  createdAt: number;
287
+ phaseId?: string;
165
288
  }
166
289
 
167
290
  export interface AgentInsert {
@@ -175,6 +298,9 @@ export interface AgentInsert {
175
298
  strategyInputJson?: string;
176
299
  status: AgentStatus;
177
300
  createdAt: number;
301
+ stepKey?: string;
302
+ stepKind?: AgentStepKind;
303
+ semanticsDigest?: string;
178
304
  }
179
305
 
180
306
  export interface MessageInsert {
@@ -198,6 +324,19 @@ export interface TurnInsert {
198
324
  prompt: string;
199
325
  sessionId: string;
200
326
  createdAt: number;
327
+ attemptId?: string;
328
+ revision?: number;
329
+ }
330
+
331
+ export interface OperationInsert {
332
+ id: string;
333
+ runId: string;
334
+ kind: OperatorActionKind;
335
+ actor: string;
336
+ reason?: string;
337
+ oldValue?: unknown;
338
+ newValue?: unknown;
339
+ at: number;
201
340
  }
202
341
 
203
342
  export interface QuotaAcquireResult {
@@ -212,7 +351,19 @@ export interface QuotaRateLimitResult {
212
351
  terminal: boolean;
213
352
  }
214
353
 
215
- const SCHEMA = `
354
+ /**
355
+ * Highest schema version this build understands. Bump it and append a step to
356
+ * `MIGRATIONS` for every schema change; never edit a released step in place.
357
+ */
358
+ export const SCHEMA_VERSION = 5;
359
+
360
+ /**
361
+ * Frozen version-0 schema: the exact shape released before `user_version`
362
+ * existed. Never edit it. Every schema change goes into `MIGRATIONS`, so a
363
+ * brand-new database and a migrated pre-versioned database reach an identical
364
+ * current schema by the same path.
365
+ */
366
+ const SCHEMA_V0 = `
216
367
  CREATE TABLE IF NOT EXISTS runs (
217
368
  id TEXT PRIMARY KEY,
218
369
  strategy TEXT NOT NULL,
@@ -336,8 +487,27 @@ CREATE TABLE IF NOT EXISTS meta (
336
487
  );
337
488
  `;
338
489
 
339
- const RUN_PATCH_KEYS = ["status", "sealed", "error", "updated_at"] as const;
340
- const WAVE_PATCH_KEYS = ["status", "started_at", "finished_at"] as const;
490
+ const RUN_PATCH_KEYS = [
491
+ "status",
492
+ "sealed",
493
+ "error",
494
+ "updated_at",
495
+ "name",
496
+ "project_id",
497
+ "project_dir",
498
+ "stopped",
499
+ "max_concurrent",
500
+ "predecessor_id",
501
+ "successor_id",
502
+ "plan_digest",
503
+ "created_by",
504
+ ] as const;
505
+ const WAVE_PATCH_KEYS = [
506
+ "status",
507
+ "started_at",
508
+ "finished_at",
509
+ "phase_id",
510
+ ] as const;
341
511
  const AGENT_PATCH_KEYS = [
342
512
  "status",
343
513
  "session_id",
@@ -347,6 +517,13 @@ const AGENT_PATCH_KEYS = [
347
517
  "error",
348
518
  "started_at",
349
519
  "finished_at",
520
+ "step_key",
521
+ "step_kind",
522
+ "semantics_digest",
523
+ "attempts",
524
+ "blocker",
525
+ "reused_from",
526
+ "reused_revision",
350
527
  ] as const;
351
528
  const TURN_PATCH_KEYS = [
352
529
  "state",
@@ -356,6 +533,8 @@ const TURN_PATCH_KEYS = [
356
533
  "error",
357
534
  "started_at",
358
535
  "finished_at",
536
+ "attempt_id",
537
+ "revision",
359
538
  ] as const;
360
539
  const ARTIFACT_PATCH_KEYS = [
361
540
  "state",
@@ -376,27 +555,326 @@ const MESSAGE_PATCH_KEYS = [
376
555
 
377
556
  type Patch = Record<string, string | number | null | undefined>;
378
557
 
558
+ interface MigrationStep {
559
+ /** Version the database has after the step commits. Strictly increasing. */
560
+ version: number;
561
+ /** Idempotent DDL. Runs inside the migration transaction. */
562
+ up: (db: Database) => void;
563
+ }
564
+
565
+ /** `true` when the table already exists in this database. */
566
+ function tableExists(db: Database, table: string): boolean {
567
+ return (
568
+ db
569
+ .query<{ name: string }, SQLQueryBindings[]>(
570
+ `PRAGMA table_info("${table}")`,
571
+ )
572
+ .all().length > 0
573
+ );
574
+ }
575
+
576
+ function addColumnIfMissing(
577
+ db: Database,
578
+ table: string,
579
+ column: string,
580
+ definition: string,
581
+ ): void {
582
+ // Idempotent so a partially-applied add (crash before the version bump) never
583
+ // fails a retry.
584
+ const columns = db
585
+ .query<{ name: string }, SQLQueryBindings[]>(
586
+ `PRAGMA table_info("${table}")`,
587
+ )
588
+ .all();
589
+ if (columns.some((entry) => entry.name === column)) return;
590
+ db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`);
591
+ }
592
+
593
+ const MIGRATIONS: readonly MigrationStep[] = [
594
+ {
595
+ version: 1,
596
+ // Named-run metadata. All nullable, so every legacy row stays readable and
597
+ // the pre-versioned baseline keeps its IDs and history unchanged.
598
+ up(db) {
599
+ // A brand-new database has no `runs` yet; the baseline schema that is
600
+ // created before the migration already carries these columns and indexes.
601
+ if (!tableExists(db, "runs")) return;
602
+ addColumnIfMissing(db, "runs", "name", "TEXT");
603
+ addColumnIfMissing(db, "runs", "project_id", "TEXT");
604
+ addColumnIfMissing(db, "runs", "project_dir", "TEXT");
605
+ db.exec(
606
+ "CREATE INDEX IF NOT EXISTS runs_name_idx ON runs (name, created_at)",
607
+ );
608
+ db.exec(
609
+ "CREATE INDEX IF NOT EXISTS runs_project_idx ON runs (project_id, created_at)",
610
+ );
611
+ },
612
+ },
613
+ {
614
+ version: 2,
615
+ // Durable operator state, operation receipts, plan metadata, immutable
616
+ // attempt identity and event provenance. Lifecycle columns are nullable or
617
+ // have a constant default, so every legacy row stays valid and behaves like
618
+ // 0.1.1 (no stop, no ceiling, no lineage, no plan metadata).
619
+ up(db) {
620
+ if (tableExists(db, "runs")) {
621
+ addColumnIfMissing(db, "runs", "stopped", "INTEGER NOT NULL DEFAULT 0");
622
+ addColumnIfMissing(db, "runs", "max_concurrent", "INTEGER");
623
+ addColumnIfMissing(db, "runs", "predecessor_id", "TEXT");
624
+ addColumnIfMissing(db, "runs", "successor_id", "TEXT");
625
+ addColumnIfMissing(db, "runs", "plan_digest", "TEXT");
626
+ addColumnIfMissing(db, "runs", "created_by", "TEXT");
627
+ }
628
+ if (tableExists(db, "waves")) {
629
+ addColumnIfMissing(db, "waves", "phase_id", "TEXT");
630
+ }
631
+ if (tableExists(db, "agents")) {
632
+ addColumnIfMissing(db, "agents", "step_key", "TEXT");
633
+ addColumnIfMissing(db, "agents", "step_kind", "TEXT");
634
+ addColumnIfMissing(db, "agents", "semantics_digest", "TEXT");
635
+ addColumnIfMissing(
636
+ db,
637
+ "agents",
638
+ "attempts",
639
+ "INTEGER NOT NULL DEFAULT 0",
640
+ );
641
+ addColumnIfMissing(db, "agents", "blocker", "TEXT");
642
+ addColumnIfMissing(db, "agents", "reused_from", "TEXT");
643
+ addColumnIfMissing(db, "agents", "reused_revision", "INTEGER");
644
+ db.exec(
645
+ "CREATE INDEX IF NOT EXISTS agents_step_idx ON agents (run_id, step_key)",
646
+ );
647
+ }
648
+ if (tableExists(db, "turns")) {
649
+ addColumnIfMissing(db, "turns", "attempt_id", "TEXT");
650
+ addColumnIfMissing(db, "turns", "revision", "INTEGER");
651
+ db.exec(
652
+ "CREATE INDEX IF NOT EXISTS turns_attempt_idx ON turns (attempt_id)",
653
+ );
654
+ }
655
+ if (tableExists(db, "events")) {
656
+ addColumnIfMissing(db, "events", "daemon", "INTEGER");
657
+ addColumnIfMissing(db, "events", "action_id", "TEXT");
658
+ addColumnIfMissing(db, "events", "revision", "INTEGER");
659
+ }
660
+ db.exec(`
661
+ CREATE TABLE IF NOT EXISTS operations (
662
+ id TEXT PRIMARY KEY,
663
+ run_id TEXT NOT NULL,
664
+ kind TEXT NOT NULL,
665
+ actor TEXT NOT NULL,
666
+ reason TEXT,
667
+ old_json TEXT,
668
+ new_json TEXT,
669
+ state TEXT NOT NULL,
670
+ at INTEGER NOT NULL
671
+ );
672
+ CREATE INDEX IF NOT EXISTS operations_run_idx ON operations (run_id, at, id);
673
+ CREATE TABLE IF NOT EXISTS plan_meta (
674
+ run_id TEXT NOT NULL,
675
+ revision INTEGER NOT NULL,
676
+ digest TEXT NOT NULL,
677
+ source_run_id TEXT,
678
+ meta_json TEXT NOT NULL,
679
+ created_at INTEGER NOT NULL,
680
+ PRIMARY KEY (run_id, revision)
681
+ );
682
+ CREATE TABLE IF NOT EXISTS run_recovery (
683
+ run_id TEXT NOT NULL,
684
+ seq INTEGER NOT NULL,
685
+ wave_id TEXT,
686
+ agent_id TEXT,
687
+ attempt_id TEXT,
688
+ daemon INTEGER NOT NULL,
689
+ action TEXT NOT NULL,
690
+ reason TEXT NOT NULL,
691
+ blocker TEXT,
692
+ at INTEGER NOT NULL,
693
+ PRIMARY KEY (run_id, seq)
694
+ );
695
+ `);
696
+ },
697
+ },
698
+ {
699
+ version: 3,
700
+ // Recovery evidence for a turn whose native effect is unknown must survive
701
+ // as a durable blocker. Additive and nullable so every older recovery row
702
+ // (and every database created at v2) keeps its contents unchanged.
703
+ up(db) {
704
+ if (!tableExists(db, "run_recovery")) return;
705
+ addColumnIfMissing(db, "run_recovery", "blocker", "TEXT");
706
+ },
707
+ },
708
+ {
709
+ version: 4,
710
+ // Script provenance on the run. Both columns are nullable, so every legacy
711
+ // run keeps its rows and simply reports no script digest, and a database
712
+ // that never received a script start stays byte-compatible with v3 data.
713
+ up(db) {
714
+ if (!tableExists(db, "runs")) return;
715
+ addColumnIfMissing(db, "runs", "script_digest", "TEXT");
716
+ addColumnIfMissing(db, "runs", "invocation_id", "TEXT");
717
+ db.exec(
718
+ "CREATE INDEX IF NOT EXISTS runs_invocation_idx ON runs (invocation_id, created_at)",
719
+ );
720
+ },
721
+ },
722
+ {
723
+ version: 5,
724
+ // Durable script and gate rows. A run that declares no non-agent step gets
725
+ // no rows, so its data is unchanged. A `running` row without `finished_at`
726
+ // is an unknown effect on restart and is never replayed automatically.
727
+ up(db) {
728
+ db.exec(`
729
+ CREATE TABLE IF NOT EXISTS plan_steps (
730
+ run_id TEXT NOT NULL,
731
+ wave_id TEXT NOT NULL,
732
+ step_id TEXT NOT NULL,
733
+ kind TEXT NOT NULL,
734
+ handler TEXT NOT NULL,
735
+ handler_version TEXT NOT NULL,
736
+ cwd TEXT,
737
+ depends_json TEXT,
738
+ status TEXT NOT NULL,
739
+ passed INTEGER,
740
+ data_json TEXT,
741
+ reason TEXT,
742
+ error TEXT,
743
+ attempt_id TEXT NOT NULL,
744
+ started_at INTEGER NOT NULL,
745
+ finished_at INTEGER,
746
+ reused_from TEXT,
747
+ PRIMARY KEY (run_id, wave_id, step_id)
748
+ );
749
+ CREATE INDEX IF NOT EXISTS plan_steps_run_idx ON plan_steps (run_id, started_at);
750
+ CREATE INDEX IF NOT EXISTS plan_steps_status_idx ON plan_steps (status);
751
+ `);
752
+ if (tableExists(db, "run_recovery")) {
753
+ addColumnIfMissing(db, "run_recovery", "step_id", "TEXT");
754
+ }
755
+ },
756
+ },
757
+ ];
758
+
759
+ interface VersionRow {
760
+ user_version: number;
761
+ }
762
+
763
+ function readSchemaVersion(db: Database): number {
764
+ const row = db
765
+ .query<VersionRow, SQLQueryBindings[]>("PRAGMA user_version")
766
+ .get();
767
+ return row?.user_version ?? 0;
768
+ }
769
+
770
+ function newerSchemaError(version: number): AgentFlowError {
771
+ return new AgentFlowError(
772
+ "conflict",
773
+ `state database schema version ${version} is newer than the supported version ${SCHEMA_VERSION}; this build cannot open it — use a compatible newer AgentFlow build`,
774
+ { stateSchemaVersion: version, supportedSchemaVersion: SCHEMA_VERSION },
775
+ );
776
+ }
777
+
778
+ /**
779
+ * Bring the database to `SCHEMA_VERSION` in a single write transaction that
780
+ * also carries the bootstrap DDL. Does nothing when the database is already at
781
+ * the current version, so reopening a migrated file mutates nothing.
782
+ *
783
+ * Compatibility is checked outside the transaction so no persistent change
784
+ * happens first, then re-read under the write lock to avoid a race with another
785
+ * process. The version advances with each step inside the same transaction, so
786
+ * a crash leaves the database at the last complete version.
787
+ */
788
+ function migrate(db: Database): void {
789
+ const current = readSchemaVersion(db);
790
+ if (current > SCHEMA_VERSION) throw newerSchemaError(current);
791
+ if (current === SCHEMA_VERSION) return;
792
+ db.transaction(() => {
793
+ const version = readSchemaVersion(db);
794
+ if (version > SCHEMA_VERSION) throw newerSchemaError(version);
795
+ db.exec(SCHEMA_V0);
796
+ for (const step of MIGRATIONS) {
797
+ if (step.version <= version) continue;
798
+ step.up(db);
799
+ // `PRAGMA user_version` does not accept bind parameters.
800
+ db.exec(`PRAGMA user_version = ${step.version}`);
801
+ }
802
+ }).immediate();
803
+ }
804
+
805
+ /**
806
+ * Connection-level PRAGMAs that do not persist data (`journal_mode = WAL`
807
+ * persists, so it is applied separately). Safe to run before the version check.
808
+ */
809
+ function configureConnection(db: Database): void {
810
+ db.exec("PRAGMA synchronous = NORMAL");
811
+ db.exec("PRAGMA foreign_keys = ON");
812
+ db.exec("PRAGMA busy_timeout = 5000");
813
+ }
814
+
815
+ /**
816
+ * Switch to WAL only if the file is not at a newer, unsupported version.
817
+ * `journal_mode = WAL` writes the header, so it must never run before the
818
+ * compatibility guard on a database this build cannot understand.
819
+ */
820
+ function enableWal(db: Database): void {
821
+ const current = readSchemaVersion(db);
822
+ if (current > SCHEMA_VERSION) throw newerSchemaError(current);
823
+ db.exec("PRAGMA journal_mode = WAL");
824
+ }
825
+
379
826
  export class Store {
380
827
  private readonly db: Database;
828
+ /**
829
+ * Daemon generation stamped into durable event provenance. The engine sets
830
+ * this to its own instance identity so log readers can tell generations apart.
831
+ */
832
+ generation = 0;
833
+ /** Receipt id of the operator action currently being applied, if any. */
834
+ private receiptOrigin?: { actionId: string };
381
835
 
382
836
  constructor(path: string) {
383
837
  this.db = new Database(path, { create: true });
384
- this.db.exec("PRAGMA journal_mode = WAL");
385
- this.db.exec("PRAGMA synchronous = NORMAL");
386
- this.db.exec("PRAGMA foreign_keys = ON");
387
- this.db.exec("PRAGMA busy_timeout = 5000");
388
- this.db.exec(SCHEMA);
838
+ try {
839
+ // Non-persistent connection setup first, then the compatibility guard
840
+ // before anything that could rewrite the file.
841
+ configureConnection(this.db);
842
+ enableWal(this.db);
843
+ migrate(this.db);
844
+ } catch (error) {
845
+ try {
846
+ this.db.close();
847
+ } catch {
848
+ // Ignore a failed close; report the original error.
849
+ }
850
+ throw error;
851
+ }
389
852
  }
390
853
 
391
854
  close(): void {
392
855
  this.db.close();
393
856
  }
394
857
 
858
+ schemaVersion(): number {
859
+ return readSchemaVersion(this.db);
860
+ }
861
+
395
862
  tx<T>(fn: () => T): T {
396
863
  const transaction = this.db.transaction(fn);
397
864
  return (transaction as () => T)();
398
865
  }
399
866
 
867
+ /** Bind all events emitted inside `fn` to one operator receipt id. */
868
+ withReceipt<T>(actionId: string, fn: () => T): T {
869
+ const previous = this.receiptOrigin;
870
+ this.receiptOrigin = { actionId };
871
+ try {
872
+ return fn();
873
+ } finally {
874
+ this.receiptOrigin = previous;
875
+ }
876
+ }
877
+
400
878
  private update(
401
879
  table: string,
402
880
  where: string,
@@ -427,11 +905,17 @@ export class Store {
427
905
  this.db
428
906
  .query(
429
907
  `INSERT INTO runs
430
- (id, strategy, request_json, profile_id, profile_json, adapter, sealed, status, created_at, updated_at)
431
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
908
+ (id, name, project_id, project_dir, strategy, request_json, profile_id,
909
+ profile_json, adapter, sealed, status, created_at, updated_at,
910
+ max_concurrent, predecessor_id, plan_digest, created_by,
911
+ script_digest, invocation_id)
912
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
432
913
  )
433
914
  .run(
434
915
  run.id,
916
+ run.name ?? null,
917
+ run.projectId ?? null,
918
+ run.projectDir ?? null,
435
919
  run.strategy,
436
920
  run.requestJson,
437
921
  run.profileId ?? null,
@@ -441,6 +925,12 @@ export class Store {
441
925
  run.status,
442
926
  run.createdAt,
443
927
  run.createdAt,
928
+ run.maxConcurrent ?? null,
929
+ run.predecessorId ?? null,
930
+ run.planDigest ?? null,
931
+ run.createdBy ?? null,
932
+ run.scriptDigest ?? null,
933
+ run.invocationId ?? null,
444
934
  );
445
935
  }
446
936
 
@@ -468,7 +958,7 @@ export class Store {
468
958
  .all();
469
959
  }
470
960
 
471
- updateRun(id: string, patch: Patch): void {
961
+ updateRun(id: string, patch: RunPatch): void {
472
962
  this.update("runs", "id = ?", [id], patch, RUN_PATCH_KEYS);
473
963
  }
474
964
 
@@ -477,10 +967,17 @@ export class Store {
477
967
  insertWave(runId: string, wave: WaveInsert): void {
478
968
  this.db
479
969
  .query(
480
- `INSERT INTO waves (run_id, id, idx, status, created_at)
481
- VALUES (?, ?, ?, ?, ?)`,
970
+ `INSERT INTO waves (run_id, id, idx, status, created_at, phase_id)
971
+ VALUES (?, ?, ?, ?, ?, ?)`,
482
972
  )
483
- .run(runId, wave.id, wave.index, wave.status, wave.createdAt);
973
+ .run(
974
+ runId,
975
+ wave.id,
976
+ wave.index,
977
+ wave.status,
978
+ wave.createdAt,
979
+ wave.phaseId ?? null,
980
+ );
484
981
  }
485
982
 
486
983
  getWaveRows(runId: string): WaveRow[] {
@@ -518,8 +1015,8 @@ export class Store {
518
1015
  .query(
519
1016
  `INSERT INTO agents
520
1017
  (run_id, id, wave_id, spec_json, profile_id, profile_json, adapter, strategy,
521
- strategy_input_json, status, created_at)
522
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
1018
+ strategy_input_json, status, created_at, step_key, step_kind, semantics_digest)
1019
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
523
1020
  )
524
1021
  .run(
525
1022
  runId,
@@ -533,6 +1030,9 @@ export class Store {
533
1030
  agent.strategyInputJson ?? null,
534
1031
  agent.status,
535
1032
  agent.createdAt,
1033
+ agent.stepKey ?? null,
1034
+ agent.stepKind ?? null,
1035
+ agent.semanticsDigest ?? null,
536
1036
  );
537
1037
  }
538
1038
 
@@ -580,8 +1080,9 @@ export class Store {
580
1080
  this.db
581
1081
  .query(
582
1082
  `INSERT INTO turns
583
- (id, run_id, wave_id, agent_id, number, state, prompt, session_id, created_at)
584
- VALUES (?, ?, ?, ?, ?, 'admitted', ?, ?, ?)`,
1083
+ (id, run_id, wave_id, agent_id, number, state, prompt, session_id,
1084
+ created_at, attempt_id, revision)
1085
+ VALUES (?, ?, ?, ?, ?, 'admitted', ?, ?, ?, ?, ?)`,
585
1086
  )
586
1087
  .run(
587
1088
  turn.id,
@@ -592,9 +1093,20 @@ export class Store {
592
1093
  turn.prompt,
593
1094
  turn.sessionId,
594
1095
  turn.createdAt,
1096
+ turn.attemptId ?? turn.id,
1097
+ turn.revision ?? null,
595
1098
  );
596
1099
  }
597
1100
 
1101
+ countActiveTurns(runId: string): number {
1102
+ const row = this.db
1103
+ .query<{ count: number }, SQLQueryBindings[]>(
1104
+ "SELECT COUNT(*) AS count FROM turns WHERE run_id = ? AND state IN ('admitted', 'running')",
1105
+ )
1106
+ .get(runId);
1107
+ return row?.count ?? 0;
1108
+ }
1109
+
598
1110
  getTurnRow(turnId: string): TurnRow | undefined {
599
1111
  return (
600
1112
  (this.db
@@ -633,6 +1145,14 @@ export class Store {
633
1145
  .all(runId);
634
1146
  }
635
1147
 
1148
+ listDrainInterruptedTurnRows(reason: string): TurnRow[] {
1149
+ return this.db
1150
+ .query<TurnRow, [string]>(
1151
+ "SELECT * FROM turns WHERE state = 'interrupted' AND receipt IS NOT NULL AND error = ? ORDER BY created_at ASC",
1152
+ )
1153
+ .all(reason);
1154
+ }
1155
+
636
1156
  updateTurn(turnId: string, patch: Patch): void {
637
1157
  this.update("turns", "id = ?", [turnId], patch, TURN_PATCH_KEYS);
638
1158
  }
@@ -660,6 +1180,12 @@ export class Store {
660
1180
  .all(runId);
661
1181
  }
662
1182
 
1183
+ recordArtifactVersion(
1184
+ input: Omit<Parameters<typeof stageArtifactVersion>[0], "db">,
1185
+ ) {
1186
+ return stageArtifactVersion({ ...input, db: this.db });
1187
+ }
1188
+
663
1189
  getArtifactRow(runId: string, artifactId: string): ArtifactRow | undefined {
664
1190
  return (
665
1191
  (this.db
@@ -693,10 +1219,18 @@ export class Store {
693
1219
 
694
1220
  emit(input: EventInput): EngineEvent {
695
1221
  const at = input.at ?? Date.now();
1222
+ // Any event written by this engine carries its generation; events inside an
1223
+ // operator action also carry that action's receipt id.
1224
+ const origin: EventOrigin = {
1225
+ daemon: this.generation === 0 ? at : this.generation,
1226
+ ...this.receiptOrigin,
1227
+ ...input.origin,
1228
+ };
696
1229
  const result = this.db
697
1230
  .query(
698
- `INSERT INTO events (run_id, type, wave_id, agent_id, data_json, at)
699
- VALUES (?, ?, ?, ?, ?, ?)`,
1231
+ `INSERT INTO events
1232
+ (run_id, type, wave_id, agent_id, data_json, at, daemon, action_id, revision)
1233
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
700
1234
  )
701
1235
  .run(
702
1236
  input.runId,
@@ -705,6 +1239,9 @@ export class Store {
705
1239
  input.agentId ?? null,
706
1240
  input.data === undefined ? null : toJson(input.data),
707
1241
  at,
1242
+ origin.daemon,
1243
+ origin.actionId ?? null,
1244
+ origin.revision ?? null,
708
1245
  );
709
1246
  return {
710
1247
  seq: Number(result.lastInsertRowid),
@@ -714,6 +1251,7 @@ export class Store {
714
1251
  ...(input.waveId === undefined ? {} : { waveId: input.waveId }),
715
1252
  ...(input.agentId === undefined ? {} : { agentId: input.agentId }),
716
1253
  ...(input.data === undefined ? {} : { data: input.data }),
1254
+ origin,
717
1255
  };
718
1256
  }
719
1257
 
@@ -742,6 +1280,15 @@ export class Store {
742
1280
  ...(row.data_json === null
743
1281
  ? {}
744
1282
  : { data: fromJson(row.data_json, null) }),
1283
+ ...(row.daemon === null
1284
+ ? {}
1285
+ : {
1286
+ origin: {
1287
+ daemon: row.daemon,
1288
+ ...(row.action_id === null ? {} : { actionId: row.action_id }),
1289
+ ...(row.revision === null ? {} : { revision: row.revision }),
1290
+ } satisfies EventOrigin,
1291
+ }),
745
1292
  }));
746
1293
  }
747
1294
 
@@ -1015,6 +1562,311 @@ export class Store {
1015
1562
  });
1016
1563
  }
1017
1564
 
1565
+ // ----------------------------------------------------------- operations
1566
+
1567
+ getOperationRow(id: string): OperationRow | undefined {
1568
+ return (
1569
+ (this.db
1570
+ .query<OperationRow, SQLQueryBindings[]>(
1571
+ "SELECT * FROM operations WHERE id = ?",
1572
+ )
1573
+ .get(id) as OperationRow | null) ?? undefined
1574
+ );
1575
+ }
1576
+
1577
+ listOperationRows(runId: string): OperationRow[] {
1578
+ return this.db
1579
+ .query<OperationRow, SQLQueryBindings[]>(
1580
+ "SELECT * FROM operations WHERE run_id = ? ORDER BY at ASC, id ASC",
1581
+ )
1582
+ .all(runId);
1583
+ }
1584
+
1585
+ insertOperation(operation: OperationInsert): void {
1586
+ this.db
1587
+ .query(
1588
+ `INSERT INTO operations (id, run_id, kind, actor, reason, old_json, new_json, state, at)
1589
+ VALUES (?, ?, ?, ?, ?, ?, ?, 'applied', ?)`,
1590
+ )
1591
+ .run(
1592
+ operation.id,
1593
+ operation.runId,
1594
+ operation.kind,
1595
+ operation.actor,
1596
+ operation.reason ?? null,
1597
+ operation.oldValue === undefined ? null : toJson(operation.oldValue),
1598
+ operation.newValue === undefined ? null : toJson(operation.newValue),
1599
+ operation.at,
1600
+ );
1601
+ }
1602
+
1603
+ // ---------------------------------------------------------- plan metadata
1604
+
1605
+ insertPlanMeta(
1606
+ runId: string,
1607
+ entry: {
1608
+ revision: number;
1609
+ digest: string;
1610
+ sourceRunId?: string;
1611
+ meta: RunPlanMetadata;
1612
+ at: number;
1613
+ },
1614
+ ): void {
1615
+ this.db
1616
+ .query(
1617
+ `INSERT INTO plan_meta (run_id, revision, digest, source_run_id, meta_json, created_at)
1618
+ VALUES (?, ?, ?, ?, ?, ?)`,
1619
+ )
1620
+ .run(
1621
+ runId,
1622
+ entry.revision,
1623
+ entry.digest,
1624
+ entry.sourceRunId ?? null,
1625
+ toJson(entry.meta),
1626
+ entry.at,
1627
+ );
1628
+ }
1629
+
1630
+ listPlanMetaRows(runId: string): PlanMetaRow[] {
1631
+ return this.db
1632
+ .query<PlanMetaRow, SQLQueryBindings[]>(
1633
+ "SELECT * FROM plan_meta WHERE run_id = ? ORDER BY revision ASC",
1634
+ )
1635
+ .all(runId);
1636
+ }
1637
+
1638
+ getPlanMetaRow(runId: string, revision: number): PlanMetaRow | undefined {
1639
+ return (
1640
+ (this.db
1641
+ .query<PlanMetaRow, SQLQueryBindings[]>(
1642
+ "SELECT * FROM plan_meta WHERE run_id = ? AND revision = ?",
1643
+ )
1644
+ .get(runId, revision) as PlanMetaRow | null) ?? undefined
1645
+ );
1646
+ }
1647
+
1648
+ // ------------------------------------------------------------- plan steps
1649
+
1650
+ /**
1651
+ * Insert the declared non-agent steps of a run. Every row starts `pending`
1652
+ * with an attempt identity that is never reused, so a crash before the
1653
+ * handler settles is distinguishable from a scheduled step.
1654
+ */
1655
+ insertPlanStep(
1656
+ runId: string,
1657
+ step: {
1658
+ waveId: string;
1659
+ stepId: string;
1660
+ kind: "script" | "gate";
1661
+ handler: string;
1662
+ handlerVersion: string;
1663
+ cwd?: string;
1664
+ dependsOn?: PlanStepRef[];
1665
+ status?: PlanStepStatus;
1666
+ attemptId: string;
1667
+ startedAt: number;
1668
+ reusedFrom?: string;
1669
+ },
1670
+ ): void {
1671
+ this.db
1672
+ .query(
1673
+ `INSERT INTO plan_steps
1674
+ (run_id, wave_id, step_id, kind, handler, handler_version, cwd, depends_json,
1675
+ status, passed, data_json, reason, error, attempt_id, started_at, finished_at, reused_from)
1676
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, NULL, NULL, ?, ?, NULL, ?)`,
1677
+ )
1678
+ .run(
1679
+ runId,
1680
+ step.waveId,
1681
+ step.stepId,
1682
+ step.kind,
1683
+ step.handler,
1684
+ step.handlerVersion,
1685
+ step.cwd ?? null,
1686
+ step.dependsOn === undefined ? null : toJson(step.dependsOn),
1687
+ step.status ?? "pending",
1688
+ step.attemptId,
1689
+ step.startedAt,
1690
+ step.reusedFrom ?? null,
1691
+ );
1692
+ }
1693
+
1694
+ getPlanStepRows(runId: string): PlanStepRow[] {
1695
+ return this.db
1696
+ .query<PlanStepRow, SQLQueryBindings[]>(
1697
+ "SELECT * FROM plan_steps WHERE run_id = ? ORDER BY started_at ASC, wave_id ASC, step_id ASC",
1698
+ )
1699
+ .all(runId);
1700
+ }
1701
+
1702
+ /** Durable results of every declared step, in declaration order. */
1703
+ listPlanStepRowsForRun(runId: string): PlanStepResult[] {
1704
+ return this.getPlanStepRows(runId).map(planStepRowToResult);
1705
+ }
1706
+
1707
+ getPlanStepRow(
1708
+ runId: string,
1709
+ waveId: string,
1710
+ stepId: string,
1711
+ ): PlanStepRow | undefined {
1712
+ return (
1713
+ (this.db
1714
+ .query<PlanStepRow, SQLQueryBindings[]>(
1715
+ "SELECT * FROM plan_steps WHERE run_id = ? AND wave_id = ? AND step_id = ?",
1716
+ )
1717
+ .get(runId, waveId, stepId) as PlanStepRow | null) ?? undefined
1718
+ );
1719
+ }
1720
+
1721
+ /** Rows left `running` by a previous daemon: their effect is unknown. */
1722
+ listRunningPlanStepRows(runId?: string): PlanStepRow[] {
1723
+ if (runId === undefined) {
1724
+ return this.db
1725
+ .query<PlanStepRow, SQLQueryBindings[]>(
1726
+ "SELECT * FROM plan_steps WHERE status = 'running' ORDER BY run_id ASC, started_at ASC",
1727
+ )
1728
+ .all();
1729
+ }
1730
+ return this.db
1731
+ .query<PlanStepRow, SQLQueryBindings[]>(
1732
+ "SELECT * FROM plan_steps WHERE run_id = ? AND status = 'running' ORDER BY started_at ASC",
1733
+ )
1734
+ .all(runId);
1735
+ }
1736
+
1737
+ updatePlanStep(
1738
+ runId: string,
1739
+ waveId: string,
1740
+ stepId: string,
1741
+ patch: Record<string, string | number | null | undefined>,
1742
+ ): void {
1743
+ const allowed = new Set([
1744
+ "status",
1745
+ "passed",
1746
+ "data_json",
1747
+ "reason",
1748
+ "error",
1749
+ "finished_at",
1750
+ ]);
1751
+ const keys = Object.keys(patch);
1752
+ if (keys.length === 0) return;
1753
+ for (const key of keys) {
1754
+ if (!allowed.has(key)) {
1755
+ throw new AgentFlowError(
1756
+ "internal",
1757
+ `plan step column ${key} is not patchable`,
1758
+ );
1759
+ }
1760
+ }
1761
+ const assignments = keys.map((key) => `${key} = ?`).join(", ");
1762
+ const values: SQLQueryBindings[] = keys.map((key) => {
1763
+ const value = patch[key];
1764
+ return value === undefined ? null : value;
1765
+ });
1766
+ this.db
1767
+ .query(
1768
+ `UPDATE plan_steps SET ${assignments} WHERE run_id = ? AND wave_id = ? AND step_id = ?`,
1769
+ )
1770
+ .run(...values, runId, waveId, stepId);
1771
+ }
1772
+
1773
+ previousPlanStepResult(
1774
+ runId: string,
1775
+ waveId: string,
1776
+ stepId: string,
1777
+ attemptId: string,
1778
+ ): PlanStepResult | undefined {
1779
+ const row = this.db
1780
+ .query<PlanStepRow, SQLQueryBindings[]>(
1781
+ `SELECT * FROM plan_steps
1782
+ WHERE run_id = ? AND wave_id = ? AND step_id = ? AND attempt_id <> ?
1783
+ AND status IN ('succeeded', 'failed')
1784
+ ORDER BY finished_at DESC LIMIT 1`,
1785
+ )
1786
+ .get(runId, waveId, stepId, attemptId);
1787
+ return row === null ? undefined : planStepRowToResult(row);
1788
+ }
1789
+
1790
+ // ------------------------------------------------------------- recovery
1791
+
1792
+ /** Append one durable recovery item and return its stable sequence. */
1793
+ appendRecovery(
1794
+ runId: string,
1795
+ item: {
1796
+ daemon: number;
1797
+ action: RecoveryItem["action"];
1798
+ reason: string;
1799
+ waveId?: string;
1800
+ agentId?: string;
1801
+ stepId?: string;
1802
+ attemptId?: string;
1803
+ blocker?: string;
1804
+ at: number;
1805
+ },
1806
+ ): number {
1807
+ const row = this.db
1808
+ .query<{ seq: number }, SQLQueryBindings[]>(
1809
+ "SELECT COALESCE(MAX(seq), 0) + 1 AS seq FROM run_recovery WHERE run_id = ?",
1810
+ )
1811
+ .get(runId);
1812
+ const seq = row?.seq ?? 1;
1813
+ this.db
1814
+ .query(
1815
+ `INSERT INTO run_recovery
1816
+ (run_id, seq, wave_id, agent_id, step_id, attempt_id, daemon, action, reason, blocker, at)
1817
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
1818
+ )
1819
+ .run(
1820
+ runId,
1821
+ seq,
1822
+ item.waveId ?? null,
1823
+ item.agentId ?? null,
1824
+ item.stepId ?? null,
1825
+ item.attemptId ?? null,
1826
+ item.daemon,
1827
+ item.action,
1828
+ item.reason,
1829
+ item.blocker ?? null,
1830
+ item.at,
1831
+ );
1832
+ return seq;
1833
+ }
1834
+
1835
+ listRecoveryItems(runId: string): RecoveryItem[] {
1836
+ const rows = this.db
1837
+ .query<
1838
+ {
1839
+ seq: number;
1840
+ wave_id: string | null;
1841
+ agent_id: string | null;
1842
+ step_id: string | null;
1843
+ attempt_id: string | null;
1844
+ daemon: number;
1845
+ action: RecoveryItem["action"];
1846
+ reason: string;
1847
+ blocker: string | null;
1848
+ at: number;
1849
+ },
1850
+ SQLQueryBindings[]
1851
+ >(
1852
+ "SELECT seq, wave_id, agent_id, step_id, attempt_id, daemon, action, reason, blocker, at FROM run_recovery WHERE run_id = ? ORDER BY seq ASC",
1853
+ )
1854
+ .all(runId);
1855
+ return rows.map((row) => ({
1856
+ runId,
1857
+ seq: row.seq,
1858
+ ...(row.wave_id === null ? {} : { waveId: row.wave_id }),
1859
+ ...(row.agent_id === null ? {} : { agentId: row.agent_id }),
1860
+ ...(row.step_id === null ? {} : { stepId: row.step_id }),
1861
+ ...(row.attempt_id === null ? {} : { attemptId: row.attempt_id }),
1862
+ daemon: row.daemon,
1863
+ action: row.action,
1864
+ reason: row.reason,
1865
+ ...(row.blocker === null ? {} : { blocker: row.blocker }),
1866
+ at: row.at,
1867
+ }));
1868
+ }
1869
+
1018
1870
  // ------------------------------------------------------------- snapshots
1019
1871
 
1020
1872
  getRunSnapshot(id: string): RunSnapshot | undefined {
@@ -1034,7 +1886,29 @@ export class Store {
1034
1886
  id: run.id,
1035
1887
  status: run.status,
1036
1888
  strategy: run.strategy,
1889
+ ...(run.name === null ? {} : { name: run.name }),
1890
+ ...(run.stopped === 1 ? { stopped: true } : {}),
1891
+ ...(run.max_concurrent === null
1892
+ ? {}
1893
+ : { maxConcurrent: run.max_concurrent }),
1894
+ ...(run.predecessor_id === null
1895
+ ? {}
1896
+ : { predecessorId: run.predecessor_id }),
1897
+ ...(run.successor_id === null ? {} : { successorId: run.successor_id }),
1898
+ ...(() => {
1899
+ const revision = this.listPlanMetaRows(id).length;
1900
+ return revision === 0 ? {} : { revision };
1901
+ })(),
1902
+ activeTurns: this.countActiveTurns(id),
1037
1903
  ...(run.profile_id === null ? {} : { profile: run.profile_id }),
1904
+ ...(run.project_id === null ? {} : { projectId: run.project_id }),
1905
+ ...(run.project_dir === null ? {} : { projectDir: run.project_dir }),
1906
+ ...(run.script_digest === null
1907
+ ? {}
1908
+ : { scriptDigest: run.script_digest }),
1909
+ ...(run.invocation_id === null
1910
+ ? {}
1911
+ : { invocationId: run.invocation_id }),
1038
1912
  adapter: run.adapter,
1039
1913
  sealed: run.sealed === 1,
1040
1914
  waves: waveSnapshots,
@@ -1110,6 +1984,68 @@ export function quotaRowToSnapshot(row: QuotaRow): QuotaGroupSnapshot {
1110
1984
  };
1111
1985
  }
1112
1986
 
1987
+ /**
1988
+ * Stable project identity for a working directory.
1989
+ *
1990
+ * The directory is normalized to an absolute POSIX path: redundant separators,
1991
+ * `.` and `..` segments are folded lexically. Trailing separators are dropped so
1992
+ * the same project never produces two IDs. This is deliberately lexical rather
1993
+ * than filesystem-resolving so callers can compute identity for synthetic or
1994
+ * not-yet-created directories; the result is therefore `project_id`, and the
1995
+ * caller persists the normalized path separately as `project_dir`.
1996
+ */
1997
+ export function canonicalProjectId(directory: string): string {
1998
+ if (typeof directory !== "string" || directory.trim() === "") {
1999
+ throw new AgentFlowError(
2000
+ "validation",
2001
+ "project directory must be a non-empty string",
2002
+ );
2003
+ }
2004
+ const unified = directory.replace(/\\/g, "/");
2005
+ const absolute = unified.startsWith("/");
2006
+ const segments: string[] = [];
2007
+ for (const segment of unified.split("/")) {
2008
+ if (segment === "" || segment === ".") continue;
2009
+ if (segment === "..") {
2010
+ if (segments.length > 0 && segments[segments.length - 1] !== "..") {
2011
+ segments.pop();
2012
+ } else if (!absolute) {
2013
+ segments.push("..");
2014
+ }
2015
+ continue;
2016
+ }
2017
+ segments.push(segment);
2018
+ }
2019
+ const body = segments.join("/");
2020
+ if (absolute) return `/${body}`;
2021
+ return body === "" ? "." : body;
2022
+ }
2023
+
2024
+ export function planStepRowToResult(row: PlanStepRow): PlanStepResult {
2025
+ const depends = fromJson<PlanStepRef[] | null>(row.depends_json, null);
2026
+ return {
2027
+ runId: row.run_id,
2028
+ waveId: row.wave_id,
2029
+ stepId: row.step_id,
2030
+ kind: row.kind,
2031
+ handler: row.handler,
2032
+ handlerVersion: row.handler_version,
2033
+ status: row.status,
2034
+ ...(row.passed === null ? {} : { passed: row.passed === 1 }),
2035
+ ...(row.data_json === null
2036
+ ? {}
2037
+ : { data: fromJson<unknown>(row.data_json, undefined) }),
2038
+ ...(row.reason === null ? {} : { reason: row.reason }),
2039
+ ...(row.error === null ? {} : { error: row.error }),
2040
+ ...(row.cwd === null ? {} : { cwd: row.cwd }),
2041
+ ...(depends === null ? {} : { dependsOn: depends }),
2042
+ attemptId: row.attempt_id,
2043
+ startedAt: row.started_at,
2044
+ ...(row.finished_at === null ? {} : { finishedAt: row.finished_at }),
2045
+ ...(row.reused_from === null ? {} : { reusedFrom: row.reused_from }),
2046
+ };
2047
+ }
2048
+
1113
2049
  function messageRowToSnapshot(row: MessageRow): MessageSnapshot {
1114
2050
  return {
1115
2051
  id: row.id,