@nones/agentflow-core 0.7.0 → 0.8.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/inspection.ts CHANGED
@@ -221,6 +221,10 @@ export interface LogRecord {
221
221
  type: string;
222
222
  waveId?: string;
223
223
  agentId?: string;
224
+ /** Non-agent step selected from the event payload, when recorded. */
225
+ stepId?: string;
226
+ /** Immutable step attempt selected from the event payload, when recorded. */
227
+ attemptId?: string;
224
228
  data?: unknown;
225
229
  /** Explicit data states so a missing body never reads as success. */
226
230
  state: "included" | "redacted" | "truncated" | "omitted";
@@ -231,15 +235,34 @@ export interface LogRecord {
231
235
  summary?: string;
232
236
  }
233
237
 
238
+ export type LogsScope = "run" | "invocation" | "step";
239
+
240
+ /** The durable identity behind `logs <attempt-id>`. */
241
+ export interface StepAttemptScope {
242
+ attemptId: string;
243
+ waveId: string;
244
+ stepId: string;
245
+ kind: StepKind;
246
+ status: string;
247
+ }
248
+
234
249
  export interface LogsPage {
235
250
  snapshotVersion: number;
236
251
  readOnly: true;
252
+ /** How the reference was resolved: a run, a script invocation or a step attempt. */
253
+ scope: LogsScope;
237
254
  runId: string;
255
+ /** All runs covered by an invocation page; one run for a run or attempt page. */
256
+ runIds: string[];
257
+ /** Present when the page was resolved from a script invocation ID. */
258
+ invocationId?: string;
259
+ /** Present when the page was resolved from a non-agent step attempt ID. */
260
+ step?: StepAttemptScope;
238
261
  limit: number;
239
262
  truncated: boolean;
240
263
  nextCursor: string | null;
241
264
  highWaterMark: number;
242
- /** True when the cursor is past everything persisted. */
265
+ /** True when the cursor is past everything persisted in this scope. */
243
266
  atEnd: boolean;
244
267
  records: LogRecord[];
245
268
  /** Non-fatal projection problems (undecodable payloads, dropped bytes). */
@@ -270,6 +293,33 @@ interface CursorShape {
270
293
  seq?: number;
271
294
  }
272
295
 
296
+ /** The resolved reference behind one `logs` page. */
297
+ interface LogScope {
298
+ mode: LogsScope;
299
+ /** The exact reference the caller supplied, echoed when no run id exists. */
300
+ selector: string;
301
+ runIds: string[];
302
+ invocationId?: string;
303
+ step?: StepAttemptScope;
304
+ }
305
+
306
+ /**
307
+ * A non-agent step event belongs to one attempt only when its payload carries
308
+ * that attempt identity. Older events without the field stay untagged instead
309
+ * of being attributed to an attempt that may not have produced them.
310
+ */
311
+ function attemptEventMatches(
312
+ row: { wave_id: string | null; data_json: string | null },
313
+ step: StepAttemptScope,
314
+ ): boolean {
315
+ if (row.wave_id !== null && row.wave_id !== step.waveId) return false;
316
+ const data = parseJson(row.data_json);
317
+ if (!isPlainObject(data)) return false;
318
+ if (typeof data.attemptId !== "string") return false;
319
+ if (data.attemptId !== step.attemptId) return false;
320
+ return typeof data.stepId !== "string" || data.stepId === step.stepId;
321
+ }
322
+
273
323
  /**
274
324
  * Encode a resumable cursor. Human-readable mode prints it too, so machines can
275
325
  * always resume from the last delivered record.
@@ -573,6 +623,13 @@ export class InspectionReader {
573
623
  );
574
624
  }
575
625
 
626
+ /** Additive columns are probed so an older, un-migrated file stays readable. */
627
+ private hasColumn(table: string, column: string): boolean {
628
+ return this.all<{ name: string }>(`PRAGMA table_info("${table}")`).some(
629
+ (row) => row.name === column,
630
+ );
631
+ }
632
+
576
633
  private all<T extends DbRow>(
577
634
  sql: string,
578
635
  ...params: SQLQueryBindings[]
@@ -1348,99 +1405,248 @@ export class InspectionReader {
1348
1405
  // ------------------------------------------------------------------ logs
1349
1406
 
1350
1407
  /**
1351
- * Bounded, redacted diagnostic records for one run. `after` is an opaque
1352
- * cursor wrapping the stable event `seq`, so a truncated page always resumes
1353
- * from the last delivered record without duplicates or gaps.
1408
+ * Bounded, redacted diagnostic records for one run, one script invocation or
1409
+ * one non-agent step attempt. `after` is an opaque cursor wrapping the stable
1410
+ * global event `seq`, so a truncated page always resumes from the last
1411
+ * delivered (or skipped) record without duplicates or gaps.
1412
+ *
1413
+ * Legacy resolution is unchanged: an exact run id wins, then a display name.
1414
+ * Only when neither matches does the reference resolve to a script invocation
1415
+ * (every run it started, ordered by the global event sequence) or to a
1416
+ * `plan_steps.attempt_id` (only events that carry that attempt identity).
1354
1417
  */
1355
1418
  readRunLogs(runRef: string, options: ReadLogsOptions = {}): LogsPage {
1356
1419
  const limit = boundedLimit(options.limit);
1357
1420
  const cursor = decodeCursor(options.after, "logs");
1358
- // The same selector rule as a snapshot: an exact id wins, then a name.
1359
- const run = this.resolveRun(runRef);
1360
- const runId = run.id;
1361
- return this.consistent(() => {
1362
- const highWater =
1363
- this.one<{ seq: number | null }>(
1364
- "SELECT MAX(seq) AS seq FROM events WHERE run_id = ?",
1365
- runId,
1366
- )?.seq ?? 0;
1367
- const params: SQLQueryBindings[] = [runId];
1368
- let where = "run_id = ? AND seq > ?";
1369
- params.push(cursor?.seq ?? 0);
1370
- if (options.agent !== undefined) {
1371
- where +=
1372
- " AND (agent_id = ? OR agent_id IN (SELECT id FROM agents WHERE run_id = ? AND step_key = ?))";
1373
- params.push(options.agent, runId, options.agent);
1421
+ const scope = this.resolveLogScope(runRef);
1422
+ return this.consistent(() =>
1423
+ this.readLogsPage(scope, options, limit, cursor),
1424
+ );
1425
+ }
1426
+
1427
+ private resolveLogScope(selector: string): LogScope {
1428
+ if (typeof selector !== "string" || selector.trim() === "") {
1429
+ throw new AgentFlowError(
1430
+ "validation",
1431
+ "a run id, name, invocation id or step attempt id is required",
1432
+ );
1433
+ }
1434
+ const byId = this.one<{ id: string }>(
1435
+ "SELECT id FROM runs WHERE id = ?",
1436
+ selector,
1437
+ );
1438
+ if (byId !== undefined) {
1439
+ return { mode: "run", selector, runIds: [byId.id] };
1440
+ }
1441
+ if (this.hasColumn("runs", "name")) {
1442
+ const byName = this.one<{ id: string }>(
1443
+ "SELECT id FROM runs WHERE name = ? ORDER BY created_at DESC, id DESC LIMIT 1",
1444
+ selector,
1445
+ );
1446
+ if (byName !== undefined) {
1447
+ return { mode: "run", selector, runIds: [byName.id] };
1374
1448
  }
1375
- if (options.step !== undefined) {
1376
- where +=
1377
- " AND agent_id IN (SELECT id FROM agents WHERE run_id = ? AND (id = ? OR step_key = ?))";
1378
- params.push(runId, options.step, options.step);
1449
+ }
1450
+ if (this.hasColumn("runs", "invocation_id")) {
1451
+ const runs = this.all<{ id: string }>(
1452
+ "SELECT id FROM runs WHERE invocation_id = ? ORDER BY created_at ASC, id ASC",
1453
+ selector,
1454
+ );
1455
+ if (runs.length > 0) {
1456
+ return {
1457
+ mode: "invocation",
1458
+ selector,
1459
+ runIds: runs.map((run) => run.id),
1460
+ invocationId: selector,
1461
+ };
1379
1462
  }
1380
- if (options.errorsOnly === true) where += ` AND ${ERROR_EVENT_FILTER}`;
1381
- const rows = this.all<{
1382
- seq: number;
1383
- type: string;
1384
- wave_id: string | null;
1385
- agent_id: string | null;
1386
- data_json: string | null;
1387
- at: number;
1463
+ }
1464
+ if (this.hasTable("plan_steps")) {
1465
+ const step = this.one<{
1466
+ run_id: string;
1467
+ wave_id: string;
1468
+ step_id: string;
1469
+ kind: StepKind;
1470
+ status: string;
1471
+ attempt_id: string;
1388
1472
  }>(
1389
- `SELECT seq, type, wave_id, agent_id, data_json, at FROM events
1390
- WHERE ${where} ORDER BY seq ASC LIMIT ?`,
1391
- ...params,
1392
- limit + 1,
1473
+ "SELECT run_id, wave_id, step_id, kind, status, attempt_id FROM plan_steps WHERE attempt_id = ? LIMIT 1",
1474
+ selector,
1393
1475
  );
1394
-
1395
- const projectionErrors: string[] = [];
1396
- const records: LogRecord[] = [];
1397
- let bytes = 0;
1398
- // Rows are read in ascending `seq` and a row is either delivered or ends
1399
- // the page, so the delivered sequence is stable, gap-free and strictly
1400
- // increasing. A level-filtered row is skipped and never ends the page.
1401
- let capped: number | undefined;
1402
- for (const row of rows) {
1403
- if (records.length >= limit) break;
1404
- const record = this.logRecord(row, runId, projectionErrors);
1405
- if (
1406
- options.level !== undefined &&
1407
- !levelMatches(record.level, options.level)
1408
- ) {
1409
- continue;
1410
- }
1411
- const size = byteLength(record);
1412
- if (records.length > 0 && bytes + size > INSPECTION_PAGE_MAX_BYTES) {
1413
- capped = row.seq;
1414
- break;
1415
- }
1416
- records.push(record);
1417
- bytes += size;
1476
+ if (step !== undefined) {
1477
+ return {
1478
+ mode: "step",
1479
+ selector,
1480
+ runIds: [step.run_id],
1481
+ step: {
1482
+ attemptId: step.attempt_id,
1483
+ waveId: step.wave_id,
1484
+ stepId: step.step_id,
1485
+ kind: step.kind,
1486
+ status: step.status,
1487
+ },
1488
+ };
1418
1489
  }
1419
- const delivered = records[records.length - 1];
1420
- const nextSeq = delivered?.seq ?? cursor?.seq ?? 0;
1421
- // `truncated` means records exist after this page, either because the
1422
- // limit cut the read or because the byte cap stopped an inspected row.
1423
- const more = rows.length > records.length || capped !== undefined;
1490
+ }
1491
+ throw new AgentFlowError(
1492
+ "not_found",
1493
+ `no run, invocation or step attempt matches ${JSON.stringify(selector)}`,
1494
+ { selector },
1495
+ );
1496
+ }
1497
+
1498
+ /** One SQL predicate for every run covered by the resolved scope. */
1499
+ private scopeFilter(scope: LogScope): {
1500
+ sql: string;
1501
+ params: SQLQueryBindings[];
1502
+ } {
1503
+ if (scope.mode === "invocation") {
1424
1504
  return {
1425
- snapshotVersion: INSPECTION_SNAPSHOT_VERSION,
1426
- readOnly: true,
1427
- runId,
1428
- limit,
1429
- truncated: delivered !== undefined && capped !== undefined,
1430
- nextCursor:
1431
- delivered === undefined
1432
- ? null
1433
- : encodeCursor({ k: "logs", seq: nextSeq }),
1434
- highWaterMark: highWater,
1435
- atEnd: !more && nextSeq >= highWater,
1436
- records,
1437
- projectionErrors,
1505
+ sql: "run_id IN (SELECT id FROM runs WHERE invocation_id = ?)",
1506
+ params: [scope.invocationId as string],
1438
1507
  };
1439
- });
1508
+ }
1509
+ return { sql: "run_id = ?", params: [scope.runIds[0] as string] };
1510
+ }
1511
+
1512
+ private readLogsPage(
1513
+ scope: LogScope,
1514
+ options: ReadLogsOptions,
1515
+ limit: number,
1516
+ cursor: CursorShape | undefined,
1517
+ ): LogsPage {
1518
+ const filter = this.scopeFilter(scope);
1519
+ const highWater =
1520
+ this.one<{ seq: number | null }>(
1521
+ `SELECT MAX(seq) AS seq FROM events WHERE ${filter.sql}`,
1522
+ ...filter.params,
1523
+ )?.seq ?? 0;
1524
+
1525
+ const stepMismatch =
1526
+ scope.mode === "step" &&
1527
+ scope.step !== undefined &&
1528
+ options.step !== undefined &&
1529
+ options.step !== scope.step.stepId;
1530
+
1531
+ const params: SQLQueryBindings[] = [...filter.params, cursor?.seq ?? 0];
1532
+ let where = `${filter.sql} AND seq > ?`;
1533
+ if (scope.mode === "step" && scope.step !== undefined) {
1534
+ // The attempt's own wave bounds the scan; the payload then decides the
1535
+ // exact attempt identity.
1536
+ where += " AND wave_id = ?";
1537
+ params.push(scope.step.waveId);
1538
+ }
1539
+ if (options.agent !== undefined) {
1540
+ where +=
1541
+ " AND (agent_id = ? OR agent_id IN (SELECT id FROM agents WHERE " +
1542
+ `${filter.sql} AND step_key = ?))`;
1543
+ params.push(options.agent, ...filter.params, options.agent);
1544
+ }
1545
+ if (options.step !== undefined && scope.mode !== "step") {
1546
+ where +=
1547
+ " AND agent_id IN (SELECT id FROM agents WHERE " +
1548
+ `${filter.sql} AND (id = ? OR step_key = ?))`;
1549
+ params.push(...filter.params, options.step, options.step);
1550
+ }
1551
+ if (options.errorsOnly === true) where += ` AND ${ERROR_EVENT_FILTER}`;
1552
+
1553
+ const rows = stepMismatch
1554
+ ? []
1555
+ : this.all<{
1556
+ run_id: string;
1557
+ seq: number;
1558
+ type: string;
1559
+ wave_id: string | null;
1560
+ agent_id: string | null;
1561
+ data_json: string | null;
1562
+ at: number;
1563
+ }>(
1564
+ `SELECT run_id, seq, type, wave_id, agent_id, data_json, at FROM events
1565
+ WHERE ${where} ORDER BY seq ASC LIMIT ?`,
1566
+ ...params,
1567
+ limit + 1,
1568
+ );
1569
+
1570
+ const projectionErrors: string[] = [];
1571
+ const records: LogRecord[] = [];
1572
+ let bytes = 0;
1573
+ let capped: number | undefined;
1574
+ let lastSeen: number | undefined;
1575
+ let consumed = 0;
1576
+ let moreRows = false;
1577
+ // Rows are read in ascending `seq`. A row is either delivered, explicitly
1578
+ // skipped (another attempt or a level below the filter) or ends the page.
1579
+ // The cursor always advances past every inspected row, so an attempt page
1580
+ // with sparse matching events cannot rescan the same prefix forever.
1581
+ for (let index = 0; index < rows.length; index += 1) {
1582
+ const row = rows[index] as (typeof rows)[number];
1583
+ lastSeen = row.seq;
1584
+ if (records.length >= limit) {
1585
+ moreRows = true;
1586
+ break;
1587
+ }
1588
+ if (
1589
+ scope.mode === "step" &&
1590
+ scope.step !== undefined &&
1591
+ !attemptEventMatches(row, scope.step)
1592
+ ) {
1593
+ consumed = index + 1;
1594
+ continue;
1595
+ }
1596
+ const record = this.logRecord(row, projectionErrors);
1597
+ if (scope.mode === "step" && scope.step !== undefined) {
1598
+ record.waveId ??= scope.step.waveId;
1599
+ record.stepId ??= scope.step.stepId;
1600
+ record.attemptId ??= scope.step.attemptId;
1601
+ }
1602
+ if (
1603
+ options.level !== undefined &&
1604
+ !levelMatches(record.level, options.level)
1605
+ ) {
1606
+ consumed = index + 1;
1607
+ continue;
1608
+ }
1609
+ const size = byteLength(record);
1610
+ if (records.length > 0 && bytes + size > INSPECTION_PAGE_MAX_BYTES) {
1611
+ capped = row.seq;
1612
+ moreRows = true;
1613
+ break;
1614
+ }
1615
+ records.push(record);
1616
+ bytes += size;
1617
+ consumed = index + 1;
1618
+ }
1619
+ const delivered = records[records.length - 1];
1620
+ const nextSeq = delivered?.seq ?? lastSeen ?? cursor?.seq ?? 0;
1621
+ const more = moreRows || rows.length > limit;
1622
+ return {
1623
+ snapshotVersion: INSPECTION_SNAPSHOT_VERSION,
1624
+ readOnly: true,
1625
+ scope: scope.mode,
1626
+ runId: scope.runIds[0] ?? scope.selector,
1627
+ runIds: [...scope.runIds],
1628
+ ...(scope.invocationId === undefined
1629
+ ? {}
1630
+ : { invocationId: scope.invocationId }),
1631
+ ...(scope.step === undefined ? {} : { step: scope.step }),
1632
+ limit,
1633
+ // `truncated` keeps its meaning: the byte cap ended a page that had a
1634
+ // deliverable record. A page that only skipped rows is not truncated.
1635
+ truncated: delivered !== undefined && capped !== undefined,
1636
+ nextCursor:
1637
+ delivered !== undefined || more
1638
+ ? encodeCursor({ k: "logs", seq: nextSeq })
1639
+ : null,
1640
+ highWaterMark: highWater,
1641
+ atEnd: !more,
1642
+ records,
1643
+ projectionErrors,
1644
+ };
1440
1645
  }
1441
1646
 
1442
1647
  private logRecord(
1443
1648
  row: {
1649
+ run_id: string;
1444
1650
  seq: number;
1445
1651
  type: string;
1446
1652
  wave_id: string | null;
@@ -1448,13 +1654,12 @@ export class InspectionReader {
1448
1654
  data_json: string | null;
1449
1655
  at: number;
1450
1656
  },
1451
- runId: string,
1452
1657
  projectionErrors: string[],
1453
1658
  ): LogRecord {
1454
1659
  const level = levelOf(row.type);
1455
1660
  const record: LogRecord = {
1456
1661
  seq: row.seq,
1457
- runId,
1662
+ runId: row.run_id,
1458
1663
  at: row.at,
1459
1664
  level,
1460
1665
  type: row.type,
@@ -1474,6 +1679,10 @@ export class InspectionReader {
1474
1679
  record.omitted = "undecodable payload";
1475
1680
  return record;
1476
1681
  }
1682
+ if (isPlainObject(data)) {
1683
+ if (typeof data.stepId === "string") record.stepId = data.stepId;
1684
+ if (typeof data.attemptId === "string") record.attemptId = data.attemptId;
1685
+ }
1477
1686
  const redacted = redactValue(data);
1478
1687
  record.data = redacted.value;
1479
1688
  record.state = redacted.state;
package/src/protocol.ts CHANGED
@@ -64,7 +64,12 @@ export interface RpcActionArgs {
64
64
  runs: Record<string, never>;
65
65
  status: { id: string };
66
66
  events: { id: string; after?: number; agentId?: string };
67
- append: { id: string; waves: AppendRequest["waves"] };
67
+ append: {
68
+ id: string;
69
+ waves: AppendRequest["waves"];
70
+ scripts?: AppendRequest["scripts"];
71
+ gates?: AppendRequest["gates"];
72
+ };
68
73
  send: { id: string; agentId: string } & SendOptions;
69
74
  seal: { id: string };
70
75
  cancel: { id: string };
package/src/server.ts CHANGED
@@ -563,6 +563,8 @@ async function dispatch(
563
563
  const typed = args as RpcActionArgs["append"];
564
564
  return engine.append(typed.id, {
565
565
  waves: typed.waves,
566
+ ...(typed.scripts === undefined ? {} : { scripts: typed.scripts }),
567
+ ...(typed.gates === undefined ? {} : { gates: typed.gates }),
566
568
  } as AppendRequest);
567
569
  }
568
570
  case "send": {
@@ -666,7 +668,20 @@ function validateActionArgs(action: string, args: unknown): unknown {
666
668
  if (!Array.isArray(object.waves)) {
667
669
  throw new AgentFlowError("ipc", "append args.waves must be an array");
668
670
  }
669
- return { id: requireString(object, "id"), waves: object.waves };
671
+ for (const key of ["scripts", "gates"] as const) {
672
+ if (object[key] !== undefined && !Array.isArray(object[key])) {
673
+ throw new AgentFlowError(
674
+ "ipc",
675
+ `append args.${key} must be an array`,
676
+ );
677
+ }
678
+ }
679
+ return {
680
+ id: requireString(object, "id"),
681
+ waves: object.waves,
682
+ ...(object.scripts === undefined ? {} : { scripts: object.scripts }),
683
+ ...(object.gates === undefined ? {} : { gates: object.gates }),
684
+ };
670
685
  }
671
686
  case "send": {
672
687
  const delivery = object.delivery;
package/src/store.ts CHANGED
@@ -72,6 +72,8 @@ interface WaveRow {
72
72
  started_at: number | null;
73
73
  finished_at: number | null;
74
74
  phase_id: string | null;
75
+ /** 1 while the wave is a reserved hole (schema v6). */
76
+ hole: number;
75
77
  }
76
78
 
77
79
  interface AgentRow {
@@ -285,6 +287,7 @@ export interface WaveInsert {
285
287
  status: WaveStatus;
286
288
  createdAt: number;
287
289
  phaseId?: string;
290
+ hole?: boolean;
288
291
  }
289
292
 
290
293
  export interface AgentInsert {
@@ -355,7 +358,7 @@ export interface QuotaRateLimitResult {
355
358
  * Highest schema version this build understands. Bump it and append a step to
356
359
  * `MIGRATIONS` for every schema change; never edit a released step in place.
357
360
  */
358
- export const SCHEMA_VERSION = 5;
361
+ export const SCHEMA_VERSION = 6;
359
362
 
360
363
  /**
361
364
  * Frozen version-0 schema: the exact shape released before `user_version`
@@ -507,6 +510,7 @@ const WAVE_PATCH_KEYS = [
507
510
  "started_at",
508
511
  "finished_at",
509
512
  "phase_id",
513
+ "hole",
510
514
  ] as const;
511
515
  const AGENT_PATCH_KEYS = [
512
516
  "status",
@@ -754,6 +758,15 @@ const MIGRATIONS: readonly MigrationStep[] = [
754
758
  }
755
759
  },
756
760
  },
761
+ {
762
+ version: 6,
763
+ // Reserved wave positions. A legacy wave has no hole, so every existing
764
+ // plan keeps its order and behaves exactly as before.
765
+ up(db) {
766
+ if (!tableExists(db, "waves")) return;
767
+ addColumnIfMissing(db, "waves", "hole", "INTEGER NOT NULL DEFAULT 0");
768
+ },
769
+ },
757
770
  ];
758
771
 
759
772
  interface VersionRow {
@@ -967,8 +980,8 @@ export class Store {
967
980
  insertWave(runId: string, wave: WaveInsert): void {
968
981
  this.db
969
982
  .query(
970
- `INSERT INTO waves (run_id, id, idx, status, created_at, phase_id)
971
- VALUES (?, ?, ?, ?, ?, ?)`,
983
+ `INSERT INTO waves (run_id, id, idx, status, created_at, phase_id, hole)
984
+ VALUES (?, ?, ?, ?, ?, ?, ?)`,
972
985
  )
973
986
  .run(
974
987
  runId,
@@ -977,6 +990,7 @@ export class Store {
977
990
  wave.status,
978
991
  wave.createdAt,
979
992
  wave.phaseId ?? null,
993
+ wave.hole === true ? 1 : 0,
980
994
  );
981
995
  }
982
996
 
@@ -1876,12 +1890,18 @@ export class Store {
1876
1890
  const agents = this.getAgentRows(id);
1877
1891
  const artifacts = this.getArtifactRows(id);
1878
1892
  const agentSnapshots = agents.map(agentRowToSnapshot);
1879
- const waveSnapshots: WaveSnapshot[] = waves.map((wave) => ({
1880
- id: wave.id,
1881
- index: wave.idx,
1882
- status: wave.status,
1883
- agents: agentSnapshots.filter((agent) => agent.waveId === wave.id),
1884
- }));
1893
+ const stepResults = this.getPlanStepRows(id).map(planStepRowToResult);
1894
+ const waveSnapshots: WaveSnapshot[] = waves.map((wave) => {
1895
+ const steps = stepResults.filter((step) => step.waveId === wave.id);
1896
+ return {
1897
+ id: wave.id,
1898
+ index: wave.idx,
1899
+ status: wave.status,
1900
+ agents: agentSnapshots.filter((agent) => agent.waveId === wave.id),
1901
+ ...(wave.hole === 1 ? { hole: true } : {}),
1902
+ ...(steps.length === 0 ? {} : { steps }),
1903
+ };
1904
+ });
1885
1905
  return {
1886
1906
  id: run.id,
1887
1907
  status: run.status,
package/src/types.ts CHANGED
@@ -52,6 +52,12 @@ export interface AgentSpec {
52
52
  export interface WaveSpec {
53
53
  id: string;
54
54
  agents: AgentSpec[];
55
+ /**
56
+ * Reserve this wave position without admitting work. A hole is persisted in
57
+ * order, holds every later wave, and is filled by a later `append` with the
58
+ * same wave id. A hole cannot declare agents.
59
+ */
60
+ hole?: boolean;
55
61
  }
56
62
 
57
63
  export type ArtifactType = "json" | "text" | "file";
@@ -464,6 +470,10 @@ export interface WaveSnapshot {
464
470
  index: number;
465
471
  status: WaveStatus;
466
472
  agents: AgentSnapshot[];
473
+ /** True while this wave is a reserved hole that has not been filled. */
474
+ hole?: boolean;
475
+ /** Persisted script and gate results belonging to this wave. */
476
+ steps?: PlanStepResult[];
467
477
  }
468
478
 
469
479
  export interface ArtifactSnapshot {
@@ -551,6 +561,10 @@ export interface EventOptions {
551
561
 
552
562
  export interface AppendRequest {
553
563
  waves: WaveSpec[];
564
+ /** Trusted script steps appended with these waves, keyed by their wave. */
565
+ scripts?: PlanHandlerStep[];
566
+ /** Trusted verification gates appended with these waves, keyed by their wave. */
567
+ gates?: PlanHandlerStep[];
554
568
  }
555
569
 
556
570
  export interface SendOptions {
package/src/validation.ts CHANGED
@@ -106,6 +106,9 @@ export function validateRunPlan(input: unknown): ValidatedPlan {
106
106
 
107
107
  const profile = optionalString(input.profile, "plan.profile");
108
108
  const sealed = optionalBoolean(input.sealed, "plan.sealed") ?? false;
109
+ if (sealed && waves.some((wave) => wave.hole === true)) {
110
+ fail("plan.sealed", "a sealed plan cannot contain a reserved hole");
111
+ }
109
112
 
110
113
  const scripts = validateHandlerSteps(
111
114
  input.scripts,
@@ -253,7 +256,11 @@ function validateWave(
253
256
  const agents = input.agents.map((rawAgent, agentIndex) =>
254
257
  validateAgent(rawAgent, index, agentIndex, agentIds),
255
258
  );
256
- return { id, agents };
259
+ const hole = optionalBoolean(input.hole, `plan.waves[${index}].hole`);
260
+ if (hole === true && agents.length > 0) {
261
+ fail(`plan.waves[${index}].hole`, "a reserved hole cannot contain agents");
262
+ }
263
+ return { id, agents, ...(hole === true ? { hole: true } : {}) };
257
264
  }
258
265
 
259
266
  function validateAgent(