@noetic-tools/core 5.12.0 → 5.14.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.
Files changed (53) hide show
  1. package/dist/adapters/in-memory-subprocess/step-completion.d.ts +2 -2
  2. package/dist/adapters/in-memory-subprocess/step-completion.js +48 -52
  3. package/dist/adapters/in-memory-subprocess/types.d.ts +3 -6
  4. package/dist/adapters/in-memory-subprocess-adapter.js +30 -48
  5. package/dist/adapters/live-handles.d.ts +26 -0
  6. package/dist/adapters/live-handles.js +50 -0
  7. package/dist/builders/decide-builders.d.ts +2 -2
  8. package/dist/builders/dynamic-workflow.js +2 -0
  9. package/dist/builders/provide-builder.d.ts +2 -2
  10. package/dist/builders/spawn-builder.d.ts +2 -2
  11. package/dist/builders/step-builders.d.ts +5 -5
  12. package/dist/builders/workflow-hydrator.d.ts +1 -1
  13. package/dist/builders/workflow-hydrator.js +54 -6
  14. package/dist/expression/check.js +14 -0
  15. package/dist/expression/jsonata.d.ts +7 -0
  16. package/dist/expression/jsonata.js +11 -1
  17. package/dist/harness/agent-harness.d.ts +59 -5
  18. package/dist/harness/agent-harness.js +176 -25
  19. package/dist/harness/deps/runtime.d.ts +4 -0
  20. package/dist/harness/deps/runtime.js +2 -0
  21. package/dist/harness/model-call.js +69 -0
  22. package/dist/harness/model-rounds.d.ts +52 -0
  23. package/dist/harness/model-rounds.js +115 -0
  24. package/dist/harness/thread-record.d.ts +54 -0
  25. package/dist/harness/thread-record.js +159 -0
  26. package/dist/index.d.ts +7 -3
  27. package/dist/index.js +2 -0
  28. package/dist/interpreter/emit-items.d.ts +19 -0
  29. package/dist/interpreter/emit-items.js +106 -0
  30. package/dist/interpreter/execute-action.js +3 -0
  31. package/dist/interpreter/execute-control.js +3 -0
  32. package/dist/interpreter/execute.js +67 -12
  33. package/dist/interpreter/step-dispatcher.d.ts +2 -2
  34. package/dist/interpreter/step-dispatcher.js +3 -5
  35. package/dist/runtime/context-impl.d.ts +106 -4
  36. package/dist/runtime/context-impl.js +224 -14
  37. package/dist/runtime/durable/harness-checkpoints.d.ts +13 -3
  38. package/dist/runtime/durable/harness-checkpoints.js +66 -7
  39. package/dist/runtime/durable/session-store.d.ts +37 -0
  40. package/dist/runtime/durable/session-store.js +58 -0
  41. package/dist/runtime/durable/step-ledger.d.ts +77 -40
  42. package/dist/runtime/durable/step-ledger.js +193 -73
  43. package/dist/runtime/item-log-impl.d.ts +6 -0
  44. package/dist/runtime/item-log-impl.js +12 -0
  45. package/dist/runtime/session-runner.d.ts +25 -1
  46. package/dist/runtime/session-runner.js +83 -11
  47. package/dist/schemas/workflow.d.ts +1 -1
  48. package/dist/types/checkpoint.d.ts +21 -4
  49. package/dist/types/checkpoint.js +33 -3
  50. package/dist/util/detached-handle.d.ts +9 -20
  51. package/dist/util/detached-handle.js +7 -108
  52. package/package.json +2 -2
  53. package/schema/noetic-workflow.schema.json +391 -0
@@ -3,6 +3,7 @@ import { emitFrameworkEvent, getBroadcaster, shouldEmit } from '../runtime/broad
3
3
  import { ContextImpl } from '../runtime/context-impl.js';
4
4
  import { REPLAY_KEY_PREFIX } from '../runtime/durable/step-ledger.js';
5
5
  import { DetachedHandleImpl } from '../util/detached-handle.js';
6
+ import { appendReplayed, emitStepItems } from './emit-items.js';
6
7
  import { executeAcpAgent } from './execute-acp-agent.js';
7
8
  import { executeCallModel, executeInvokeTool, executeRunCode, executeSpawn, executeWithContext, } from './execute-action.js';
8
9
  import { executeConditional, executeInParallel, executeLoop, executeSchedule, } from './execute-control.js';
@@ -81,12 +82,10 @@ async function dispatchViaAdapter(step, input, ctx, executionId, executor) {
81
82
  },
82
83
  _localExecutor: () => executor(),
83
84
  };
84
- const spawnPromise = adapter.spawn(request);
85
85
  const handle = new DetachedHandleImpl({
86
86
  id: executionId,
87
87
  stepId: step.id,
88
- adapter,
89
- spawnPromise,
88
+ spawned: adapter.spawn(request),
90
89
  });
91
90
  return handle.await();
92
91
  }
@@ -146,13 +145,16 @@ export function resolveLedgerKey(step, input, ctx) {
146
145
  }
147
146
  }
148
147
  /**
149
- * Resume path: when a previous run recorded this exact step at `ledgerKey`,
150
- * replay its output instead of re-running, and emit `step_replayed`. Returns
151
- * `{ hit: false }` when there is nothing to replay so the caller dispatches the
152
- * step normally.
148
+ * Resume path: when a previous run recorded this exact step at `ledgerKey` on the same
149
+ * input, replay its output instead of re-running, put the items it appended back on
150
+ * `stepCtx`'s item log, and emit `step_replayed`. Returns `{ hit: false }` when there
151
+ * is nothing to replay so the caller dispatches the step normally.
152
+ *
153
+ * The items go back through `stepCtx` so the lanes above it note them too: a parent
154
+ * that completes on this resumed run records everything beneath it, replayed or not.
153
155
  */
154
156
  function replayFromLedger(opts) {
155
- const { ledger, ledgerKey, step, broadcaster, agentName } = opts;
157
+ const { ledger, ledgerKey, inputHash, step, stepCtx, broadcaster, agentName } = opts;
156
158
  if (!ledger || ledgerKey === undefined || ledger.isEmpty) {
157
159
  return {
158
160
  hit: false,
@@ -161,12 +163,20 @@ function replayFromLedger(opts) {
161
163
  const replayed = ledger.take(ledgerKey, {
162
164
  id: step.id,
163
165
  kind: step.kind,
166
+ inputHash,
164
167
  });
165
168
  if (!replayed) {
166
169
  return {
167
170
  hit: false,
168
171
  };
169
172
  }
173
+ const items = parseRecordedItems(stepCtx, replayed.items ?? []);
174
+ if (!items) {
175
+ return {
176
+ hit: false,
177
+ };
178
+ }
179
+ appendReplayed(stepCtx, items, replayed.streamed ?? []);
170
180
  emitFrameworkEvent({
171
181
  broadcaster,
172
182
  agentName,
@@ -182,20 +192,50 @@ function replayFromLedger(opts) {
182
192
  };
183
193
  }
184
194
  /**
185
- * Record a completed step's output so a resumed run replays it rather than
186
- * re-executing. A no-op without a ledger or ledger key. Only successes reach
187
- * here — a step that threw skips this call in `execute` and runs again on resume.
195
+ * Recorded items, parsed through the context's item schemas, or null when one no longer
196
+ * parses — a registry that changed since the run was recorded. The step then runs fresh
197
+ * rather than half-replaying its history.
198
+ */
199
+ function parseRecordedItems(ctx, raw) {
200
+ if (raw.length === 0) {
201
+ return [];
202
+ }
203
+ try {
204
+ return frameworkCast(ctx).itemSchemas?.parseMany(raw) ?? frameworkCast(raw);
205
+ }
206
+ catch {
207
+ return null;
208
+ }
209
+ }
210
+ /**
211
+ * Record a completed step's output, input hash, and the items it appended, so a resumed
212
+ * run replays this step rather than re-executing it. A no-op without a ledger or ledger
213
+ * key. Only successes reach here — a step that threw skips this call in `execute` and
214
+ * runs again on resume.
188
215
  */
189
216
  async function recordToLedger(opts) {
190
- const { ledger, ledgerKey, step, output } = opts;
217
+ const { ledger, ledgerKey, inputHash, lane, step, output } = opts;
191
218
  if (!ledger || ledgerKey === undefined) {
192
219
  return;
193
220
  }
221
+ const items = lane?.appendedItems() ?? [];
222
+ const streamed = lane?.emittedIndices() ?? [];
194
223
  await ledger.record({
195
224
  path: ledgerKey,
196
225
  stepId: step.id,
197
226
  kind: step.kind,
198
227
  output,
228
+ inputHash,
229
+ ...(items.length > 0
230
+ ? {
231
+ items,
232
+ }
233
+ : {}),
234
+ ...(streamed.length > 0
235
+ ? {
236
+ streamed,
237
+ }
238
+ : {}),
199
239
  completedAt: new Date().toISOString(),
200
240
  });
201
241
  }
@@ -265,11 +305,17 @@ export async function execute(step, input, ctx) {
265
305
  * output instead of re-running it. `ledgerKey`/`ledger` are captured before
266
306
  * dispatch and reused by the record below. */
267
307
  const ledgerKey = resolveLedgerKey(step, input, stepCtx);
308
+ if (ledgerKey === undefined) {
309
+ lane?.skipLedger();
310
+ }
311
+ const inputHash = ledgerKey === undefined ? undefined : lane?.currentDispatch()?.inputHash;
268
312
  const ledger = impl?.ledger;
269
313
  const replay = replayFromLedger({
270
314
  ledger,
271
315
  ledgerKey,
316
+ inputHash,
272
317
  step,
318
+ stepCtx,
273
319
  broadcaster,
274
320
  agentName,
275
321
  });
@@ -338,6 +384,13 @@ export async function execute(step, input, ctx) {
338
384
  });
339
385
  }
340
386
  }
387
+ // Inside the try, so an item the schemas refuse fails the dispatch like any other
388
+ // error; before the ledger record, so the entry holds the items and replays them.
389
+ await emitStepItems(step, result, stepCtx);
390
+ }
391
+ catch (error) {
392
+ lane?.releaseDispatch();
393
+ throw error;
341
394
  }
342
395
  finally {
343
396
  lane?.leaveStep(frame);
@@ -361,6 +414,8 @@ export async function execute(step, input, ctx) {
361
414
  await recordToLedger({
362
415
  ledger,
363
416
  ledgerKey,
417
+ inputHash,
418
+ lane,
364
419
  step,
365
420
  output: result,
366
421
  });
@@ -43,8 +43,8 @@ export interface DetachedSpawnOverrides {
43
43
  }
44
44
  /**
45
45
  * Route a step through the configured subprocess adapter and return a
46
- * `DetachedHandle` that polls until the adapter reports a terminal
47
- * status. The adapter's `spawn()` may be async (the default in-memory
46
+ * `DetachedHandle` that settles when the adapter reports the child
47
+ * finished. The adapter's `spawn()` may be async (the default in-memory
48
48
  * adapter schedules the step body on the microtask queue, and
49
49
  * out-of-process adapters may await an OS spawn).
50
50
  *
@@ -24,8 +24,8 @@ export function resolveStepAdapter(step, callOverride, fallback) {
24
24
  //#region Dispatcher
25
25
  /**
26
26
  * Route a step through the configured subprocess adapter and return a
27
- * `DetachedHandle` that polls until the adapter reports a terminal
28
- * status. The adapter's `spawn()` may be async (the default in-memory
27
+ * `DetachedHandle` that settles when the adapter reports the child
28
+ * finished. The adapter's `spawn()` may be async (the default in-memory
29
29
  * adapter schedules the step body on the microtask queue, and
30
30
  * out-of-process adapters may await an OS spawn).
31
31
  *
@@ -57,12 +57,10 @@ export function dispatchStepThroughAdapter(h, s, input, parentCtx, overrides) {
57
57
  },
58
58
  _localExecutor: () => executeNoAdapter(s, input, childCtx),
59
59
  };
60
- const spawnPromise = adapter.spawn(request);
61
60
  return new DetachedHandleImpl({
62
61
  id: childCtx.id,
63
62
  stepId: s.id,
64
- adapter,
65
- spawnPromise,
63
+ spawned: adapter.spawn(request),
66
64
  });
67
65
  }
68
66
  //#endregion
@@ -18,6 +18,7 @@ export declare class ContextImpl implements Context<ContextData> {
18
18
  stepCount: number;
19
19
  tokens: TokenUsage;
20
20
  cost: number;
21
+ billedCost: number;
21
22
  state: unknown;
22
23
  readonly parent: Context<ContextData> | null;
23
24
  readonly usageParent: Context<ContextData> | null;
@@ -26,6 +27,8 @@ export declare class ContextImpl implements Context<ContextData> {
26
27
  readonly threadId: string;
27
28
  readonly resourceId?: string;
28
29
  readonly itemLog: ItemLog;
30
+ /** The same log, typed for `rebase`. */
31
+ private readonly log;
29
32
  lastStepMeta: StepMeta | null;
30
33
  lastLayerUsage: LastLayerUsage | undefined;
31
34
  readonly harness: AgentHarnessContract;
@@ -96,6 +99,21 @@ export declare class ContextImpl implements Context<ContextData> {
96
99
  * @internal
97
100
  */
98
101
  readonly ledger?: StepLedger;
102
+ /**
103
+ * The dispatch this view belongs to. Undefined on the context itself; a lane (see
104
+ * `enterStep`) reads its own here.
105
+ * @internal
106
+ */
107
+ private readonly _lane?;
108
+ /**
109
+ * The item log and dispatch counts as they stood when the outermost run on this
110
+ * context began. A checkpoint persists these rather than the live values, because a
111
+ * resumed run starts that run over: its recorded steps replay and re-append their
112
+ * items, so the log must not already hold them. Unset between runs, and kept after a
113
+ * run that failed — that run is what a resume repeats.
114
+ * @internal
115
+ */
116
+ private _baseline?;
99
117
  constructor(opts: {
100
118
  harness: AgentHarnessContract;
101
119
  parent?: Context;
@@ -174,12 +192,29 @@ export declare class ContextImpl implements Context<ContextData> {
174
192
  /**
175
193
  * @internal
176
194
  * Register `frame` as in flight and return the lane its step runs on: a view of
177
- * this context that shares everything except its execution path. `execute()` hands
178
- * the lane to the step, so steps the step dispatches hang under its path no matter
179
- * how other dispatches on this context interleave. The occurrence ordinal is taken
180
- * here, at dispatch, never at settle.
195
+ * this context that shares everything except its execution path and the record of
196
+ * items appended through it. `execute()` hands the lane to the step, so steps the
197
+ * step dispatches hang under its path no matter how other dispatches on this context
198
+ * interleave. The occurrence ordinal is taken here, at dispatch, never at settle.
181
199
  */
182
200
  enterStep(frame: FrontierFrame): ContextImpl;
201
+ /**
202
+ * @internal
203
+ * Mark this lane's step as kept out of the ledger (`durable: false`, `schedule`, a
204
+ * failed `replayKey`), so nothing running inside it records under its identity.
205
+ */
206
+ skipLedger(): void;
207
+ /**
208
+ * @internal
209
+ * The dispatch this lane belongs to, or undefined on the context itself and on a
210
+ * lane kept out of the ledger. Lets code running inside a step (the model loop's
211
+ * rounds) record under the step's identity.
212
+ */
213
+ currentDispatch(): {
214
+ path: string;
215
+ stepId: string;
216
+ inputHash: string | undefined;
217
+ } | undefined;
183
218
  /**
184
219
  * @internal
185
220
  * The execution path of the step this lane belongs to — the ledger key identifying
@@ -187,12 +222,74 @@ export declare class ContextImpl implements Context<ContextData> {
187
222
  * what lets a resumed run line recorded outputs up with the steps that produced them.
188
223
  */
189
224
  currentPath(): string;
225
+ /**
226
+ * @internal
227
+ * Items appended to the item log through this lane, including by steps it
228
+ * dispatched on the same context. Empty on the context itself.
229
+ */
230
+ appendedItems(): Item[];
231
+ /**
232
+ * @internal
233
+ * Indices into `appendedItems()` of the items appended through `appendEmitted`, which
234
+ * a replay streams again under the harness's `emitItemsOnReplay`.
235
+ */
236
+ emittedIndices(): number[];
237
+ /**
238
+ * @internal
239
+ * Append an item a step emitted (`step.emitItems`), marking it in this lane's record
240
+ * and every record above it, so the ledger entry that holds it knows to stream it
241
+ * again on replay.
242
+ */
243
+ appendEmitted(item: Item): void;
190
244
  /**
191
245
  * @internal
192
246
  * Drop `frame` from the in-flight set. Called when its step resolves, success or
193
247
  * failure.
194
248
  */
195
249
  leaveStep(frame: FrontierFrame): void;
250
+ /**
251
+ * @internal
252
+ * Give back this lane's ordinal after its step failed, so a retry runs at the same
253
+ * path. A resumed run never sees the failed attempt — nothing records a failure — so
254
+ * without this a retry would take the next ordinal and every later dispatch would sit
255
+ * one position past where the resume looks for it. Only the latest dispatch of a key
256
+ * can give its ordinal back; once a later one has taken the next, the ordinal stays.
257
+ */
258
+ releaseDispatch(): void;
259
+ /**
260
+ * @internal
261
+ * Mark the start of the outermost run on this context. See `_baseline`.
262
+ */
263
+ beginRun(): void;
264
+ /**
265
+ * @internal
266
+ * Mark a run as finished, so checkpoints record the live log and counts again.
267
+ */
268
+ endRun(): void;
269
+ /**
270
+ * @internal
271
+ * What a checkpoint persists for the item log and dispatch counts — see `_baseline`.
272
+ */
273
+ runBaseline(): RunBaseline;
274
+ /**
275
+ * @internal
276
+ * Whether a run on this context began and never finished — it failed, or is in
277
+ * flight. A run starting now repeats it.
278
+ */
279
+ hasUnfinishedRun(): boolean;
280
+ /**
281
+ * @internal
282
+ * Stand the context back at a stored run baseline: the item log and dispatch counts
283
+ * a checkpoint recorded. For a run retried in place, which must see what a resume on
284
+ * a new harness would — not the items and counts its failed attempt left in memory.
285
+ */
286
+ rebase(baseline: RunBaseline): void;
287
+ /**
288
+ * @internal
289
+ * Seed the dispatch counts a restored run starts from, so a resumed context numbers
290
+ * its dispatches where the recorded run did rather than from zero.
291
+ */
292
+ restoreOccurrences(occurrences: Record<string, number>): void;
196
293
  /**
197
294
  * @internal
198
295
  * Return a defensive copy of the current frontier. Consumed by the
@@ -200,6 +297,11 @@ export declare class ContextImpl implements Context<ContextData> {
200
297
  */
201
298
  serialiseFrontier(): FrontierFrame[];
202
299
  }
300
+ /** @internal Item log and dispatch counts at the start of a run — see `ContextImpl._baseline`. */
301
+ export interface RunBaseline {
302
+ items: Item[];
303
+ occurrences: Record<string, number>;
304
+ }
203
305
  /**
204
306
  * @internal
205
307
  * The context a lane views, or `ctx` itself when it is not a lane. For per-execution
@@ -1,4 +1,5 @@
1
1
  import { buildContextData, defaultItemSchemaRegistry } from './context-deps.js';
2
+ import { hashStepInput } from './durable/step-ledger.js';
2
3
  import { ItemLogImpl } from './item-log-impl.js';
3
4
  const EMPTY_CONTEXT = Object.freeze({});
4
5
  class NoopSpan {
@@ -48,6 +49,7 @@ export class ContextImpl {
48
49
  total: 0,
49
50
  };
50
51
  cost = 0;
52
+ billedCost = 0;
51
53
  state;
52
54
  parent;
53
55
  usageParent;
@@ -56,6 +58,8 @@ export class ContextImpl {
56
58
  threadId;
57
59
  resourceId;
58
60
  itemLog;
61
+ /** The same log, typed for `rebase`. */
62
+ log;
59
63
  lastStepMeta = null;
60
64
  lastLayerUsage = undefined;
61
65
  harness;
@@ -126,6 +130,21 @@ export class ContextImpl {
126
130
  * @internal
127
131
  */
128
132
  ledger;
133
+ /**
134
+ * The dispatch this view belongs to. Undefined on the context itself; a lane (see
135
+ * `enterStep`) reads its own here.
136
+ * @internal
137
+ */
138
+ _lane;
139
+ /**
140
+ * The item log and dispatch counts as they stood when the outermost run on this
141
+ * context began. A checkpoint persists these rather than the live values, because a
142
+ * resumed run starts that run over: its recorded steps replay and re-append their
143
+ * items, so the log must not already hold them. Unset between runs, and kept after a
144
+ * run that failed — that run is what a resume repeats.
145
+ * @internal
146
+ */
147
+ _baseline;
129
148
  constructor(opts) {
130
149
  this.id = opts.id ?? crypto.randomUUID();
131
150
  this._createdAt = Date.now();
@@ -155,6 +174,7 @@ export class ContextImpl {
155
174
  }
156
175
  }
157
176
  this.itemLog = log;
177
+ this.log = log;
158
178
  // Join the parent's abort cascade last, so the child is fully constructed
159
179
  // before an already-aborted parent aborts it.
160
180
  if (this.parent instanceof ContextImpl) {
@@ -295,17 +315,51 @@ export class ContextImpl {
295
315
  /**
296
316
  * @internal
297
317
  * Register `frame` as in flight and return the lane its step runs on: a view of
298
- * this context that shares everything except its execution path. `execute()` hands
299
- * the lane to the step, so steps the step dispatches hang under its path no matter
300
- * how other dispatches on this context interleave. The occurrence ordinal is taken
301
- * here, at dispatch, never at settle.
318
+ * this context that shares everything except its execution path and the record of
319
+ * items appended through it. `execute()` hands the lane to the step, so steps the
320
+ * step dispatches hang under its path no matter how other dispatches on this context
321
+ * interleave. The occurrence ordinal is taken here, at dispatch, never at settle.
302
322
  */
303
323
  enterStep(frame) {
304
324
  const key = `${this._path}/${frame.stepId}`;
305
325
  const occurrence = this._occurrences.get(key) ?? 0;
306
326
  this._occurrences.set(key, occurrence + 1);
307
327
  this._inFlight.add(frame);
308
- return laneOf(this, `${key}#${occurrence}`);
328
+ return laneOf(this, {
329
+ path: `${key}#${occurrence}`,
330
+ key,
331
+ occurrence,
332
+ stepId: frame.stepId,
333
+ inputHash: this.ledger ? hashStepInput(frame.input) : undefined,
334
+ recorded: true,
335
+ appended: new AppendRecord(this._lane?.appended),
336
+ });
337
+ }
338
+ /**
339
+ * @internal
340
+ * Mark this lane's step as kept out of the ledger (`durable: false`, `schedule`, a
341
+ * failed `replayKey`), so nothing running inside it records under its identity.
342
+ */
343
+ skipLedger() {
344
+ if (this._lane) {
345
+ this._lane.recorded = false;
346
+ }
347
+ }
348
+ /**
349
+ * @internal
350
+ * The dispatch this lane belongs to, or undefined on the context itself and on a
351
+ * lane kept out of the ledger. Lets code running inside a step (the model loop's
352
+ * rounds) record under the step's identity.
353
+ */
354
+ currentDispatch() {
355
+ const lane = this._lane;
356
+ return lane?.recorded
357
+ ? {
358
+ path: lane.path,
359
+ stepId: lane.stepId,
360
+ inputHash: lane.inputHash,
361
+ }
362
+ : undefined;
309
363
  }
310
364
  /**
311
365
  * @internal
@@ -316,6 +370,43 @@ export class ContextImpl {
316
370
  currentPath() {
317
371
  return this._path;
318
372
  }
373
+ /**
374
+ * @internal
375
+ * Items appended to the item log through this lane, including by steps it
376
+ * dispatched on the same context. Empty on the context itself.
377
+ */
378
+ appendedItems() {
379
+ return [
380
+ ...(this._lane?.appended.items ?? []),
381
+ ];
382
+ }
383
+ /**
384
+ * @internal
385
+ * Indices into `appendedItems()` of the items appended through `appendEmitted`, which
386
+ * a replay streams again under the harness's `emitItemsOnReplay`.
387
+ */
388
+ emittedIndices() {
389
+ const record = this._lane?.appended;
390
+ if (!record) {
391
+ return [];
392
+ }
393
+ return record.items.flatMap((item, i) => record.emitted.has(item)
394
+ ? [
395
+ i,
396
+ ]
397
+ : []);
398
+ }
399
+ /**
400
+ * @internal
401
+ * Append an item a step emitted (`step.emitItems`), marking it in this lane's record
402
+ * and every record above it, so the ledger entry that holds it knows to stream it
403
+ * again on replay.
404
+ */
405
+ appendEmitted(item) {
406
+ this.itemLog.append(item);
407
+ const items = this.itemLog.items;
408
+ this._lane?.appended.markEmitted(items[items.length - 1]);
409
+ }
319
410
  /**
320
411
  * @internal
321
412
  * Drop `frame` from the in-flight set. Called when its step resolves, success or
@@ -324,6 +415,88 @@ export class ContextImpl {
324
415
  leaveStep(frame) {
325
416
  this._inFlight.delete(frame);
326
417
  }
418
+ /**
419
+ * @internal
420
+ * Give back this lane's ordinal after its step failed, so a retry runs at the same
421
+ * path. A resumed run never sees the failed attempt — nothing records a failure — so
422
+ * without this a retry would take the next ordinal and every later dispatch would sit
423
+ * one position past where the resume looks for it. Only the latest dispatch of a key
424
+ * can give its ordinal back; once a later one has taken the next, the ordinal stays.
425
+ */
426
+ releaseDispatch() {
427
+ const lane = this._lane;
428
+ if (!lane || this._occurrences.get(lane.key) !== lane.occurrence + 1) {
429
+ return;
430
+ }
431
+ this._occurrences.set(lane.key, lane.occurrence);
432
+ for (const key of [
433
+ ...this._occurrences.keys(),
434
+ ]) {
435
+ if (key.startsWith(`${lane.path}/`)) {
436
+ this._occurrences.delete(key);
437
+ }
438
+ }
439
+ }
440
+ /**
441
+ * @internal
442
+ * Mark the start of the outermost run on this context. See `_baseline`.
443
+ */
444
+ beginRun() {
445
+ this._baseline = {
446
+ items: [
447
+ ...this.itemLog.items,
448
+ ],
449
+ occurrences: Object.fromEntries(this._occurrences),
450
+ };
451
+ }
452
+ /**
453
+ * @internal
454
+ * Mark a run as finished, so checkpoints record the live log and counts again.
455
+ */
456
+ endRun() {
457
+ this._baseline = undefined;
458
+ }
459
+ /**
460
+ * @internal
461
+ * What a checkpoint persists for the item log and dispatch counts — see `_baseline`.
462
+ */
463
+ runBaseline() {
464
+ return (this._baseline ?? {
465
+ items: [
466
+ ...this.itemLog.items,
467
+ ],
468
+ occurrences: Object.fromEntries(this._occurrences),
469
+ });
470
+ }
471
+ /**
472
+ * @internal
473
+ * Whether a run on this context began and never finished — it failed, or is in
474
+ * flight. A run starting now repeats it.
475
+ */
476
+ hasUnfinishedRun() {
477
+ return this._baseline !== undefined;
478
+ }
479
+ /**
480
+ * @internal
481
+ * Stand the context back at a stored run baseline: the item log and dispatch counts
482
+ * a checkpoint recorded. For a run retried in place, which must see what a resume on
483
+ * a new harness would — not the items and counts its failed attempt left in memory.
484
+ */
485
+ rebase(baseline) {
486
+ this.log.replace(baseline.items);
487
+ this._occurrences.clear();
488
+ this.restoreOccurrences(baseline.occurrences);
489
+ }
490
+ /**
491
+ * @internal
492
+ * Seed the dispatch counts a restored run starts from, so a resumed context numbers
493
+ * its dispatches where the recorded run did rather than from zero.
494
+ */
495
+ restoreOccurrences(occurrences) {
496
+ for (const [key, count] of Object.entries(occurrences)) {
497
+ this._occurrences.set(key, count);
498
+ }
499
+ }
327
500
  /**
328
501
  * @internal
329
502
  * Return a defensive copy of the current frontier. Consumed by the
@@ -339,21 +512,58 @@ export class ContextImpl {
339
512
  }));
340
513
  }
341
514
  }
342
- //#region Lanes
515
+ /**
516
+ * Items appended through one lane. Each record also feeds its parent lane's, so a
517
+ * composite step's record holds everything appended beneath it on the same context.
518
+ */
519
+ class AppendRecord {
520
+ parent;
521
+ items = [];
522
+ /** The items among `items` a step emitted through `emitItems`. */
523
+ emitted = new Set();
524
+ constructor(parent) {
525
+ this.parent = parent;
526
+ }
527
+ add(item) {
528
+ this.items.push(item);
529
+ this.parent?.add(item);
530
+ }
531
+ markEmitted(item) {
532
+ this.emitted.add(item);
533
+ this.parent?.markEmitted(item);
534
+ }
535
+ }
343
536
  /** The context each lane views, so `laneOf` never stacks a proxy on a proxy. */
344
537
  const laneTargets = new WeakMap();
345
538
  /**
346
- * A view of `ctx` that reads `path` as its execution path and forwards every other
347
- * read and write to the context itself, so state, usage, abort, and the in-flight set
348
- * stay shared. A Proxy rather than a subclass: steps assign `ctx.state` and friends
539
+ * A view of `ctx` that reads `lane` as its dispatch and forwards every other read and
540
+ * write to the context itself, so state, usage, abort, and the in-flight set stay
541
+ * shared. Its item log appends to the shared log and notes each item in the lane's
542
+ * record. A Proxy rather than a subclass: steps assign `ctx.state` and friends
349
543
  * directly, and a copy would keep those writes to itself.
350
544
  */
351
- function laneOf(ctx, path) {
545
+ function laneOf(ctx, lane) {
352
546
  const target = laneTargets.get(ctx) ?? ctx;
353
- const lane = new Proxy(target, {
547
+ const itemLog = {
548
+ get items() {
549
+ return target.itemLog.items;
550
+ },
551
+ append(item) {
552
+ target.itemLog.append(item);
553
+ const items = target.itemLog.items;
554
+ lane.appended.add(items[items.length - 1]);
555
+ },
556
+ };
557
+ const view = new Proxy(target, {
354
558
  get(base, prop, receiver) {
355
559
  if (prop === '_path') {
356
- return path;
560
+ return lane.path;
561
+ }
562
+ if (prop === '_lane') {
563
+ return lane;
564
+ }
565
+ if (prop === 'itemLog') {
566
+ return itemLog;
357
567
  }
358
568
  return Reflect.get(base, prop, receiver);
359
569
  },
@@ -361,8 +571,8 @@ function laneOf(ctx, path) {
361
571
  return Reflect.set(base, prop, value);
362
572
  },
363
573
  });
364
- laneTargets.set(lane, target);
365
- return lane;
574
+ laneTargets.set(view, target);
575
+ return view;
366
576
  }
367
577
  /**
368
578
  * @internal