@noetic-tools/core 5.13.0 → 6.0.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.
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Durable rounds for the model loop.
3
+ *
4
+ * One `callModel` step can run many rounds: the model asks for tools, the harness
5
+ * runs them, the model answers again. The step ledger records the step only when the
6
+ * whole loop ends, so without this a failure on round five throws rounds one to four
7
+ * away — each paid for again on resume, and each tool run again.
8
+ *
9
+ * Each finished round is recorded under `<step path>/round#<n>`, carrying what it
10
+ * added to the loop: the model's output and tool results, the conversation input
11
+ * those became, the items appended to the item log (messages injected between rounds),
12
+ * and the round's usage. A resumed loop replays rounds in order and stops at the first
13
+ * one it does not find; every round after that runs live, because a recorded round
14
+ * belongs to the conversation the earlier recorded rounds built. When the step
15
+ * finishes and records, the ledger prunes its rounds.
16
+ */
17
+ import { frameworkCast } from '@noetic-tools/types';
18
+ import { z } from 'zod';
19
+ import { ContextImpl } from './deps/runtime.js';
20
+ //#region Types
21
+ const ROUND_KIND = 'callModel:round';
22
+ const RoundOutputSchema = z.object({
23
+ items: z.array(z.unknown()),
24
+ input: z.array(z.unknown()),
25
+ usage: z.object({
26
+ inputTokens: z.number(),
27
+ outputTokens: z.number(),
28
+ cachedTokens: z.number().optional(),
29
+ cacheWriteTokens: z.number().optional(),
30
+ }),
31
+ cost: z.number(),
32
+ });
33
+ //#endregion
34
+ //#region Public API
35
+ /**
36
+ * The round ledger for one model loop. `open` gives none when the call is not running
37
+ * as a step on a context with a ledger.
38
+ */
39
+ export class RoundLedger {
40
+ ctx;
41
+ dispatch;
42
+ replaying = true;
43
+ constructor(ctx, dispatch) {
44
+ this.ctx = ctx;
45
+ this.dispatch = dispatch;
46
+ }
47
+ /** Undefined when the loop has nothing to record into. */
48
+ static open(ctx) {
49
+ if (!(ctx instanceof ContextImpl) || !ctx.ledger) {
50
+ return undefined;
51
+ }
52
+ const dispatch = ctx.currentDispatch();
53
+ return dispatch ? new RoundLedger(ctx, dispatch) : undefined;
54
+ }
55
+ /**
56
+ * The recorded round `round`, with its items parsed, or undefined once replay has
57
+ * stopped — at the first round with no usable record, and for good after that.
58
+ */
59
+ take(round, schemas) {
60
+ const ledger = this.ctx.ledger;
61
+ if (!this.replaying || !ledger || ledger.isEmpty) {
62
+ this.replaying = false;
63
+ return undefined;
64
+ }
65
+ const entry = ledger.take(this.key(round), {
66
+ id: this.dispatch.stepId,
67
+ kind: ROUND_KIND,
68
+ inputHash: this.dispatch.inputHash,
69
+ });
70
+ const parsed = entry ? RoundOutputSchema.safeParse(entry.output) : undefined;
71
+ if (!entry || !parsed?.success) {
72
+ this.replaying = false;
73
+ return undefined;
74
+ }
75
+ try {
76
+ return {
77
+ items: schemas.parseMany(parsed.data.items),
78
+ input: parsed.data.input,
79
+ usage: parsed.data.usage,
80
+ cost: parsed.data.cost,
81
+ appended: schemas.parseMany(entry.items ?? []),
82
+ };
83
+ }
84
+ catch {
85
+ this.replaying = false;
86
+ return undefined;
87
+ }
88
+ }
89
+ /** Mark where the log stood when a round began, so its appends can be recorded. */
90
+ mark() {
91
+ return this.ctx.appendedItems().length;
92
+ }
93
+ /** Record a finished round. `logMark` is what `mark()` returned when it began. */
94
+ async record(round, logMark, record) {
95
+ this.replaying = false;
96
+ const appended = this.ctx.appendedItems().slice(logMark);
97
+ await this.ctx.ledger?.record({
98
+ path: this.key(round),
99
+ stepId: this.dispatch.stepId,
100
+ kind: ROUND_KIND,
101
+ inputHash: this.dispatch.inputHash,
102
+ output: frameworkCast(record),
103
+ ...(appended.length > 0
104
+ ? {
105
+ items: appended,
106
+ }
107
+ : {}),
108
+ completedAt: new Date().toISOString(),
109
+ });
110
+ }
111
+ key(round) {
112
+ return `${this.dispatch.path}/round#${round}`;
113
+ }
114
+ }
115
+ //#endregion
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Durable sessions: what lets a new harness pick up a thread that `execute()` drove on
3
+ * an earlier one. See `runtime/durable/session-store` for the stored shape.
4
+ *
5
+ * Storage is the only record. Nothing here is cached between calls: every turn reads
6
+ * the thread's history and in-flight turn from the store, and every change is a
7
+ * read-modify-write of the stored record, so a harness that served the last turn and
8
+ * a harness built a moment ago behave the same.
9
+ */
10
+ import type { Context, Item, SessionUsage } from '@noetic-tools/types';
11
+ import type { RestoreCheckpointOptions, SessionStore, TurnUsage } from './deps/runtime.js';
12
+ /** @internal The harness surface a thread record needs. */
13
+ export interface ThreadRecordHost {
14
+ readonly store: SessionStore;
15
+ restore(executionId: string, opts: RestoreCheckpointOptions): Promise<Context | null>;
16
+ clearCheckpoint(executionId: string): Promise<void>;
17
+ parseItems(raw: unknown[]): Item[];
18
+ }
19
+ /**
20
+ * @internal
21
+ * One thread's stored session. Turns call `history` → `resume` → `begin` → `end`; a
22
+ * turn that throws never reaches `end`, so its record stays for a re-delivery of the
23
+ * same messages to resume. Operations run one at a time, in call order, so a read
24
+ * never overtakes a write issued before it.
25
+ */
26
+ export declare class ThreadRecord {
27
+ private readonly host;
28
+ private readonly threadId;
29
+ private queue;
30
+ constructor(host: ThreadRecordHost, threadId: string);
31
+ /** The history the thread's next turn builds on: what storage holds, or none. */
32
+ history(): Promise<Item[]>;
33
+ /** Replace the stored history (`seedSessionHistory`). */
34
+ seed(items: ReadonlyArray<Item>): Promise<void>;
35
+ /**
36
+ * The context of the cut-off turn, when `messageIds` re-deliver exactly its
37
+ * messages. A cut-off turn that is not re-delivered is abandoned: its record is
38
+ * dropped, its checkpoint cleared, and the new messages start a fresh turn.
39
+ */
40
+ resume(messageIds: ReadonlyArray<string>, opts: RestoreCheckpointOptions): Promise<Context | undefined>;
41
+ /** Record the turn about to run on `ctx`, before any of it runs. */
42
+ begin(ctx: Context, messageIds: ReadonlyArray<string>): Promise<void>;
43
+ /** The turn on `ctx` finished: store the history it left and drop its checkpoint. */
44
+ end(ctx: Context, history: ReadonlyArray<Item>): Promise<void>;
45
+ /** Add one turn's spend to the stored totals, and return the totals now stored. */
46
+ addUsage(spent: TurnUsage): Promise<SessionUsage>;
47
+ /** The stored totals. */
48
+ usage(): Promise<SessionUsage>;
49
+ private update;
50
+ /** Read-modify-write the stored record. Call only from inside `run`. */
51
+ private write;
52
+ private load;
53
+ private run;
54
+ }
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Durable sessions: what lets a new harness pick up a thread that `execute()` drove on
3
+ * an earlier one. See `runtime/durable/session-store` for the stored shape.
4
+ *
5
+ * Storage is the only record. Nothing here is cached between calls: every turn reads
6
+ * the thread's history and in-flight turn from the store, and every change is a
7
+ * read-modify-write of the stored record, so a harness that served the last turn and
8
+ * a harness built a moment ago behave the same.
9
+ */
10
+ const EMPTY_USAGE = {
11
+ inputTokens: 0,
12
+ outputTokens: 0,
13
+ };
14
+ //#endregion
15
+ //#region ThreadRecord
16
+ /**
17
+ * @internal
18
+ * One thread's stored session. Turns call `history` → `resume` → `begin` → `end`; a
19
+ * turn that throws never reaches `end`, so its record stays for a re-delivery of the
20
+ * same messages to resume. Operations run one at a time, in call order, so a read
21
+ * never overtakes a write issued before it.
22
+ */
23
+ export class ThreadRecord {
24
+ host;
25
+ threadId;
26
+ queue = Promise.resolve();
27
+ constructor(host, threadId) {
28
+ this.host = host;
29
+ this.threadId = threadId;
30
+ }
31
+ /** The history the thread's next turn builds on: what storage holds, or none. */
32
+ history() {
33
+ return this.run(async () => this.host.parseItems((await this.load())?.items ?? []));
34
+ }
35
+ /** Replace the stored history (`seedSessionHistory`). */
36
+ seed(items) {
37
+ return this.update((record) => ({
38
+ ...record,
39
+ items: [
40
+ ...items,
41
+ ],
42
+ }));
43
+ }
44
+ /**
45
+ * The context of the cut-off turn, when `messageIds` re-deliver exactly its
46
+ * messages. A cut-off turn that is not re-delivered is abandoned: its record is
47
+ * dropped, its checkpoint cleared, and the new messages start a fresh turn.
48
+ */
49
+ resume(messageIds, opts) {
50
+ return this.run(async () => {
51
+ const turn = (await this.load())?.turn;
52
+ if (!turn) {
53
+ return undefined;
54
+ }
55
+ if (sameIds(turn.messageIds, messageIds)) {
56
+ return (await this.host.restore(turn.executionId, opts)) ?? undefined;
57
+ }
58
+ await this.write(withoutTurn);
59
+ await this.host.clearCheckpoint(turn.executionId);
60
+ return undefined;
61
+ });
62
+ }
63
+ /** Record the turn about to run on `ctx`, before any of it runs. */
64
+ begin(ctx, messageIds) {
65
+ return this.update((record) => ({
66
+ ...record,
67
+ turn: {
68
+ executionId: ctx.id,
69
+ messageIds: [
70
+ ...messageIds,
71
+ ],
72
+ },
73
+ }));
74
+ }
75
+ /** The turn on `ctx` finished: store the history it left and drop its checkpoint. */
76
+ async end(ctx, history) {
77
+ await this.update((record) => ({
78
+ ...withoutTurn(record),
79
+ items: [
80
+ ...history,
81
+ ],
82
+ }));
83
+ await this.host.clearCheckpoint(ctx.id);
84
+ }
85
+ /** Add one turn's spend to the stored totals, and return the totals now stored. */
86
+ addUsage(spent) {
87
+ return this.run(async () => {
88
+ const usage = addUsage((await this.load())?.usage ?? EMPTY_USAGE, spent);
89
+ await this.write((record) => ({
90
+ ...record,
91
+ usage,
92
+ }));
93
+ return usage;
94
+ });
95
+ }
96
+ /** The stored totals. */
97
+ usage() {
98
+ return this.run(async () => (await this.load())?.usage ?? EMPTY_USAGE);
99
+ }
100
+ update(change) {
101
+ return this.run(() => this.write(change));
102
+ }
103
+ /** Read-modify-write the stored record. Call only from inside `run`. */
104
+ async write(change) {
105
+ const record = change((await this.load()) ?? {
106
+ items: [],
107
+ });
108
+ try {
109
+ await this.host.store.save(this.threadId, record);
110
+ }
111
+ catch (error) {
112
+ // Same rule as checkpoints: losing the record costs resumability, not the turn.
113
+ console.warn(`AgentHarness: failed to persist session "${this.threadId}":`, error instanceof Error ? error.message : String(error));
114
+ }
115
+ }
116
+ load() {
117
+ return this.host.store.load(this.threadId);
118
+ }
119
+ run(op) {
120
+ const next = this.queue.then(op);
121
+ this.queue = next.catch(() => { });
122
+ return next;
123
+ }
124
+ }
125
+ function withoutTurn(record) {
126
+ const { turn, ...rest } = record;
127
+ void turn;
128
+ return rest;
129
+ }
130
+ function sameIds(a, b) {
131
+ return a.length === b.length && a.every((id, i) => id === b[i]);
132
+ }
133
+ function addUsage(total, spent) {
134
+ const cost = (total.cost ?? 0) + spent.cost;
135
+ const billedCost = (total.billedCost ?? 0) + spent.billedCost;
136
+ const cachedTokens = spent.cachedTokens === undefined
137
+ ? total.cachedTokens
138
+ : (total.cachedTokens ?? 0) + spent.cachedTokens;
139
+ return {
140
+ inputTokens: total.inputTokens + spent.inputTokens,
141
+ outputTokens: total.outputTokens + spent.outputTokens,
142
+ ...(cachedTokens !== undefined
143
+ ? {
144
+ cachedTokens,
145
+ }
146
+ : {}),
147
+ ...(cost > 0
148
+ ? {
149
+ cost,
150
+ }
151
+ : {}),
152
+ ...(billedCost > 0
153
+ ? {
154
+ billedCost,
155
+ }
156
+ : {}),
157
+ };
158
+ }
159
+ //#endregion
@@ -439,6 +439,7 @@ function recordTurnOutcome(params) {
439
439
  toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
440
440
  usage: response.usage,
441
441
  cost: response.cost,
442
+ billedCost: response.billedCost,
442
443
  serviceTier: response.serviceTier,
443
444
  responseItems: response.items,
444
445
  };
@@ -736,6 +737,8 @@ export async function executeSpawn(step, input, ctx, executeStep, opts) {
736
737
  // with the ones recorded inside the same spawn rather than at the root.
737
738
  pathPrefix: baseCtx instanceof ContextImpl ? baseCtx.currentPath() : '',
738
739
  ledger: baseCtx instanceof ContextImpl ? baseCtx.ledger : undefined,
740
+ // The child's steps checkpoint the root, as an inParallel path's do.
741
+ checkpointFn: () => baseCtx.checkpoint(),
739
742
  });
740
743
  // `childExecutionCtx` predates the spawn span; the child's hooks trace onto that span.
741
744
  const childTracedCtx = {
@@ -42,6 +42,9 @@ function createChildContexts(ctx, paths, stepId) {
42
42
  * restart at the root and collide with its siblings. */
43
43
  pathPrefix: `${parentPath}[${index}]`,
44
44
  ledger: parentLedger,
45
+ // A path's steps checkpoint the root: its usage, state, and layer folds roll
46
+ // into what a resumed root restores.
47
+ checkpointFn: () => ctx.checkpoint(),
45
48
  items: [
46
49
  ...ctx.itemLog.items,
47
50
  ],
@@ -144,13 +144,16 @@ export function resolveLedgerKey(step, input, ctx) {
144
144
  }
145
145
  }
146
146
  /**
147
- * Resume path: when a previous run recorded this exact step at `ledgerKey`,
148
- * replay its output instead of re-running, and emit `step_replayed`. Returns
149
- * `{ hit: false }` when there is nothing to replay so the caller dispatches the
150
- * step normally.
147
+ * Resume path: when a previous run recorded this exact step at `ledgerKey` on the same
148
+ * input, replay its output instead of re-running, put the items it appended back on
149
+ * `stepCtx`'s item log, and emit `step_replayed`. Returns `{ hit: false }` when there
150
+ * is nothing to replay so the caller dispatches the step normally.
151
+ *
152
+ * The items go back through `stepCtx` so the lanes above it note them too: a parent
153
+ * that completes on this resumed run records everything beneath it, replayed or not.
151
154
  */
152
155
  function replayFromLedger(opts) {
153
- const { ledger, ledgerKey, step, broadcaster, agentName } = opts;
156
+ const { ledger, ledgerKey, inputHash, step, stepCtx, broadcaster, agentName } = opts;
154
157
  if (!ledger || ledgerKey === undefined || ledger.isEmpty) {
155
158
  return {
156
159
  hit: false,
@@ -159,12 +162,22 @@ function replayFromLedger(opts) {
159
162
  const replayed = ledger.take(ledgerKey, {
160
163
  id: step.id,
161
164
  kind: step.kind,
165
+ inputHash,
162
166
  });
163
167
  if (!replayed) {
164
168
  return {
165
169
  hit: false,
166
170
  };
167
171
  }
172
+ const items = parseRecordedItems(stepCtx, replayed.items ?? []);
173
+ if (!items) {
174
+ return {
175
+ hit: false,
176
+ };
177
+ }
178
+ for (const item of items) {
179
+ stepCtx.itemLog.append(item);
180
+ }
168
181
  emitFrameworkEvent({
169
182
  broadcaster,
170
183
  agentName,
@@ -180,20 +193,44 @@ function replayFromLedger(opts) {
180
193
  };
181
194
  }
182
195
  /**
183
- * Record a completed step's output so a resumed run replays it rather than
184
- * re-executing. A no-op without a ledger or ledger key. Only successes reach
185
- * here — a step that threw skips this call in `execute` and runs again on resume.
196
+ * Recorded items, parsed through the context's item schemas, or null when one no longer
197
+ * parses — a registry that changed since the run was recorded. The step then runs fresh
198
+ * rather than half-replaying its history.
199
+ */
200
+ function parseRecordedItems(ctx, raw) {
201
+ if (raw.length === 0) {
202
+ return [];
203
+ }
204
+ try {
205
+ return frameworkCast(ctx).itemSchemas?.parseMany(raw) ?? frameworkCast(raw);
206
+ }
207
+ catch {
208
+ return null;
209
+ }
210
+ }
211
+ /**
212
+ * Record a completed step's output, input hash, and the items it appended, so a resumed
213
+ * run replays this step rather than re-executing it. A no-op without a ledger or ledger
214
+ * key. Only successes reach here — a step that threw skips this call in `execute` and
215
+ * runs again on resume.
186
216
  */
187
217
  async function recordToLedger(opts) {
188
- const { ledger, ledgerKey, step, output } = opts;
218
+ const { ledger, ledgerKey, inputHash, lane, step, output } = opts;
189
219
  if (!ledger || ledgerKey === undefined) {
190
220
  return;
191
221
  }
222
+ const items = lane?.appendedItems() ?? [];
192
223
  await ledger.record({
193
224
  path: ledgerKey,
194
225
  stepId: step.id,
195
226
  kind: step.kind,
196
227
  output,
228
+ inputHash,
229
+ ...(items.length > 0
230
+ ? {
231
+ items,
232
+ }
233
+ : {}),
197
234
  completedAt: new Date().toISOString(),
198
235
  });
199
236
  }
@@ -263,11 +300,17 @@ export async function execute(step, input, ctx) {
263
300
  * output instead of re-running it. `ledgerKey`/`ledger` are captured before
264
301
  * dispatch and reused by the record below. */
265
302
  const ledgerKey = resolveLedgerKey(step, input, stepCtx);
303
+ if (ledgerKey === undefined) {
304
+ lane?.skipLedger();
305
+ }
306
+ const inputHash = ledgerKey === undefined ? undefined : lane?.currentDispatch()?.inputHash;
266
307
  const ledger = impl?.ledger;
267
308
  const replay = replayFromLedger({
268
309
  ledger,
269
310
  ledgerKey,
311
+ inputHash,
270
312
  step,
313
+ stepCtx,
271
314
  broadcaster,
272
315
  agentName,
273
316
  });
@@ -337,6 +380,10 @@ export async function execute(step, input, ctx) {
337
380
  }
338
381
  }
339
382
  }
383
+ catch (error) {
384
+ lane?.releaseDispatch();
385
+ throw error;
386
+ }
340
387
  finally {
341
388
  lane?.leaveStep(frame);
342
389
  }
@@ -359,6 +406,8 @@ export async function execute(step, input, ctx) {
359
406
  await recordToLedger({
360
407
  ledger,
361
408
  ledgerKey,
409
+ inputHash,
410
+ lane,
362
411
  step,
363
412
  output: result,
364
413
  });
@@ -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,61 @@ 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[];
190
231
  /**
191
232
  * @internal
192
233
  * Drop `frame` from the in-flight set. Called when its step resolves, success or
193
234
  * failure.
194
235
  */
195
236
  leaveStep(frame: FrontierFrame): void;
237
+ /**
238
+ * @internal
239
+ * Give back this lane's ordinal after its step failed, so a retry runs at the same
240
+ * path. A resumed run never sees the failed attempt — nothing records a failure — so
241
+ * without this a retry would take the next ordinal and every later dispatch would sit
242
+ * one position past where the resume looks for it. Only the latest dispatch of a key
243
+ * can give its ordinal back; once a later one has taken the next, the ordinal stays.
244
+ */
245
+ releaseDispatch(): void;
246
+ /**
247
+ * @internal
248
+ * Mark the start of the outermost run on this context. See `_baseline`.
249
+ */
250
+ beginRun(): void;
251
+ /**
252
+ * @internal
253
+ * Mark a run as finished, so checkpoints record the live log and counts again.
254
+ */
255
+ endRun(): void;
256
+ /**
257
+ * @internal
258
+ * What a checkpoint persists for the item log and dispatch counts — see `_baseline`.
259
+ */
260
+ runBaseline(): RunBaseline;
261
+ /**
262
+ * @internal
263
+ * Whether a run on this context began and never finished — it failed, or is in
264
+ * flight. A run starting now repeats it.
265
+ */
266
+ hasUnfinishedRun(): boolean;
267
+ /**
268
+ * @internal
269
+ * Stand the context back at a stored run baseline: the item log and dispatch counts
270
+ * a checkpoint recorded. For a run retried in place, which must see what a resume on
271
+ * a new harness would — not the items and counts its failed attempt left in memory.
272
+ */
273
+ rebase(baseline: RunBaseline): void;
274
+ /**
275
+ * @internal
276
+ * Seed the dispatch counts a restored run starts from, so a resumed context numbers
277
+ * its dispatches where the recorded run did rather than from zero.
278
+ */
279
+ restoreOccurrences(occurrences: Record<string, number>): void;
196
280
  /**
197
281
  * @internal
198
282
  * Return a defensive copy of the current frontier. Consumed by the
@@ -200,6 +284,11 @@ export declare class ContextImpl implements Context<ContextData> {
200
284
  */
201
285
  serialiseFrontier(): FrontierFrame[];
202
286
  }
287
+ /** @internal Item log and dispatch counts at the start of a run — see `ContextImpl._baseline`. */
288
+ export interface RunBaseline {
289
+ items: Item[];
290
+ occurrences: Record<string, number>;
291
+ }
203
292
  /**
204
293
  * @internal
205
294
  * The context a lane views, or `ctx` itself when it is not a lane. For per-execution