@noetic-tools/core 5.20.0 → 5.22.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/dist/builders/tool-builder.d.ts +20 -0
  2. package/dist/builders/tool-builder.js +23 -1
  3. package/dist/builders/workflow-hydrator.d.ts +19 -0
  4. package/dist/builders/workflow-hydrator.js +19 -0
  5. package/dist/builders/workflow-step.js +7 -1
  6. package/dist/connections/cron-schedule.js +12 -3
  7. package/dist/connections/durability.d.ts +1 -2
  8. package/dist/connections/durability.js +1 -4
  9. package/dist/connections/gates.js +6 -2
  10. package/dist/connections/harness-wiring.d.ts +5 -0
  11. package/dist/connections/harness-wiring.js +76 -10
  12. package/dist/connections/in-memory-connection.d.ts +4 -0
  13. package/dist/connections/in-memory-connection.js +10 -0
  14. package/dist/connections/model-tools.js +5 -1
  15. package/dist/connections/registry.d.ts +6 -2
  16. package/dist/connections/registry.js +10 -0
  17. package/dist/connections/sources.js +261 -20
  18. package/dist/connections/triggers.d.ts +62 -2
  19. package/dist/connections/triggers.js +375 -35
  20. package/dist/harness/agent-harness.d.ts +263 -4
  21. package/dist/harness/agent-harness.js +1156 -95
  22. package/dist/harness/connection-gate.d.ts +3 -0
  23. package/dist/harness/connection-gate.js +4 -0
  24. package/dist/harness/deps/runtime.d.ts +3 -0
  25. package/dist/harness/deps/runtime.js +2 -0
  26. package/dist/harness/flow-version.d.ts +13 -0
  27. package/dist/harness/flow-version.js +66 -0
  28. package/dist/harness/harness-options.d.ts +82 -0
  29. package/dist/harness/model-call.d.ts +0 -1
  30. package/dist/harness/model-call.js +8 -48
  31. package/dist/harness/model-rounds.d.ts +30 -0
  32. package/dist/harness/model-rounds.js +146 -1
  33. package/dist/harness/model-tool-round.d.ts +3 -0
  34. package/dist/harness/model-tool-round.js +201 -19
  35. package/dist/harness/park-watchers.d.ts +93 -0
  36. package/dist/harness/park-watchers.js +217 -0
  37. package/dist/harness/read-decision.d.ts +23 -0
  38. package/dist/harness/read-decision.js +100 -0
  39. package/dist/harness/spend.js +4 -0
  40. package/dist/harness/steer-inbox.js +3 -1
  41. package/dist/harness/thread-record.d.ts +77 -1
  42. package/dist/harness/thread-record.js +272 -13
  43. package/dist/index.d.ts +17 -7
  44. package/dist/index.js +10 -2
  45. package/dist/interpreter/acp-resume.d.ts +77 -0
  46. package/dist/interpreter/acp-resume.js +164 -0
  47. package/dist/interpreter/acp-tools.d.ts +11 -0
  48. package/dist/interpreter/acp-tools.js +94 -7
  49. package/dist/interpreter/connection-steps.d.ts +24 -1
  50. package/dist/interpreter/connection-steps.js +77 -2
  51. package/dist/interpreter/execute-acp-agent.js +111 -15
  52. package/dist/interpreter/execute-action.js +7 -0
  53. package/dist/interpreter/execute-call.js +30 -4
  54. package/dist/interpreter/execute-control.js +21 -0
  55. package/dist/interpreter/execute-invoke-tool.js +149 -5
  56. package/dist/interpreter/execute-wait.js +67 -9
  57. package/dist/interpreter/execute.js +4 -0
  58. package/dist/interpreter/turn-ending.d.ts +15 -0
  59. package/dist/interpreter/turn-ending.js +46 -0
  60. package/dist/portable/builders.d.ts +1 -1
  61. package/dist/portable/builders.js +1 -1
  62. package/dist/runtime/durable/parking.d.ts +61 -0
  63. package/dist/runtime/durable/parking.js +137 -0
  64. package/dist/runtime/durable/session-store.d.ts +38 -0
  65. package/dist/runtime/durable/session-store.js +79 -1
  66. package/dist/runtime/durable/step-ledger.d.ts +121 -2
  67. package/dist/runtime/durable/step-ledger.js +352 -15
  68. package/dist/runtime/durable/turn-lease.d.ts +128 -0
  69. package/dist/runtime/durable/turn-lease.js +307 -0
  70. package/dist/runtime/held-calls.d.ts +192 -0
  71. package/dist/runtime/held-calls.js +496 -0
  72. package/dist/runtime/in-memory-storage.d.ts +10 -1
  73. package/dist/runtime/in-memory-storage.js +20 -2
  74. package/dist/runtime/message-queue.d.ts +2 -0
  75. package/dist/runtime/message-queue.js +8 -0
  76. package/dist/runtime/session-runner.d.ts +18 -2
  77. package/dist/runtime/session-runner.js +88 -3
  78. package/dist/runtime/tool-approval.d.ts +46 -6
  79. package/dist/runtime/tool-approval.js +160 -38
  80. package/dist/runtime/tool-call.d.ts +34 -2
  81. package/dist/runtime/tool-call.js +182 -13
  82. package/dist/runtime/tool-context.d.ts +15 -1
  83. package/dist/runtime/tool-context.js +38 -2
  84. package/package.json +3 -3
@@ -33,6 +33,8 @@
33
33
  */
34
34
  import type { StorageAdapter } from '@noetic-tools/context';
35
35
  import { z } from 'zod';
36
+ import { Parking } from './parking.js';
37
+ import type { LedgerFence } from './turn-lease.js';
36
38
  /** Marks a ledger key as a step's `replayKey` rather than its execution path. */
37
39
  export declare const REPLAY_KEY_PREFIX = "key:";
38
40
  /** @public One completed step, keyed by its execution path or its `key:` replay key. */
@@ -50,7 +52,28 @@ export declare const StepLedgerEntrySchema: z.ZodObject<{
50
52
  instance: z.ZodString;
51
53
  }, z.core.$strip>>>;
52
54
  completedAt: z.ZodString;
55
+ term: z.ZodOptional<z.ZodNumber>;
56
+ holder: z.ZodOptional<z.ZodString>;
57
+ version: z.ZodOptional<z.ZodString>;
58
+ effect: z.ZodOptional<z.ZodBoolean>;
53
59
  }, z.core.$strip>;
60
+ /** What a ledger entry leaves behind once it is pruned: its trail mark. */
61
+ declare const TrailStubSchema: z.ZodObject<{
62
+ kind: z.ZodString;
63
+ path: z.ZodString;
64
+ stepId: z.ZodString;
65
+ term: z.ZodOptional<z.ZodNumber>;
66
+ holder: z.ZodOptional<z.ZodString>;
67
+ completedAt: z.ZodString;
68
+ version: z.ZodOptional<z.ZodString>;
69
+ receipt: z.ZodOptional<z.ZodUnknown>;
70
+ }, z.core.$strip>;
71
+ /** @public A pruned entry's trail mark, as stored. */
72
+ export type StepTrailStub = z.infer<typeof TrailStubSchema>;
73
+ /** Storage key prefix of one execution's trail: what its pruned ledger entries left. */
74
+ export declare function stepTrailPrefix(executionId: string): string;
75
+ /** The trail mark of an entry. */
76
+ export declare function stubOf(entry: StepLedgerEntry): StepTrailStub;
54
77
  /** @public A completed step recorded for replay. */
55
78
  export type StepLedgerEntry = z.infer<typeof StepLedgerEntrySchema>;
56
79
  /** @public A connection a ledger entry used, with the identity it had then. */
@@ -146,13 +169,38 @@ export interface StepLedgerWindow {
146
169
  export interface StepLedgerStore {
147
170
  /** Record a completed step. Sequence numbers order entries within an execution. */
148
171
  append: (executionId: string, seq: number, entry: StepLedgerEntry) => Promise<void>;
172
+ /**
173
+ * Record a completed step only when nothing holds its sequence number. Resolves
174
+ * undefined when the entry was stored, else what is in the way. Present only on
175
+ * storage that can compare-and-set.
176
+ */
177
+ claim?: (executionId: string, seq: number, entry: StepLedgerEntry) => Promise<StepLedgerClaimConflict | undefined>;
178
+ /** Replace what `claim` found in the way. Resolves false when it changed meanwhile. */
179
+ replace?: (at: StepLedgerSlot, conflict: StepLedgerClaimConflict) => Promise<boolean>;
149
180
  /** Drop one entry by sequence number. No-op when the key is absent. */
150
181
  delete: (executionId: string, seq: number) => Promise<void>;
182
+ /** Keep the trail mark of an entry that is being pruned (spec 23 § The trail). */
183
+ mark: (executionId: string, seq: number, stub: StepTrailStub) => Promise<void>;
184
+ /** An execution's trail marks, oldest first. They outlive `clear`. */
185
+ trail: (executionId: string) => Promise<StepTrailStub[]>;
151
186
  /** Everything recorded for an execution, plus its sequence bounds. */
152
187
  load: (executionId: string) => Promise<StepLedgerWindow>;
153
188
  /** Drop an execution's ledger (paired with `CheckpointStore.clear`). */
154
189
  clear: (executionId: string) => Promise<void>;
155
190
  }
191
+ /** @public An entry and the sequence number it goes at. */
192
+ export interface StepLedgerSlot {
193
+ readonly executionId: string;
194
+ readonly seq: number;
195
+ readonly entry: StepLedgerEntry;
196
+ }
197
+ /** @public What already held a sequence number a ledger tried to claim. */
198
+ export interface StepLedgerClaimConflict {
199
+ /** The stored value, as read. */
200
+ readonly raw: unknown;
201
+ /** Its lease term, or undefined when it carries none or does not parse. */
202
+ readonly term: number | undefined;
203
+ }
156
204
  export declare function createStepLedgerStore(opts: {
157
205
  storage: StorageAdapter;
158
206
  }): StepLedgerStore;
@@ -197,6 +245,18 @@ export declare class StepLedger {
197
245
  private readonly store?;
198
246
  private readonly executionId;
199
247
  private readonly retention;
248
+ /** Which steps are in flight, and whether the turn may park (spec 23 § Parked turns). */
249
+ readonly parking: Parking;
250
+ /** The lease this execution writes under, once the turn has taken one. */
251
+ private held;
252
+ /** The flow version entries are recorded under, when the harness names one. */
253
+ private version;
254
+ /** A host accepted that this resume may discard effects recorded under another version. */
255
+ private accepts;
256
+ /** Paths noted as having a lasting effect, until the entry there records. */
257
+ private readonly effects;
258
+ /** Every live entry, by path: what its trail mark is made from when it is pruned. */
259
+ private readonly entries;
200
260
  private readonly counts;
201
261
  constructor(opts: {
202
262
  executionId: string;
@@ -210,6 +270,37 @@ export declare class StepLedger {
210
270
  * in memory — for a run retried in place, which replays what was stored.
211
271
  */
212
272
  adopt(recovered: StepLedgerWindow): void;
273
+ /**
274
+ * Write under `fence` from here on: entries carry its term, a sequence number is
275
+ * claimed rather than set, and a write that fails stops the turn instead of being
276
+ * logged (spec 23 § One writer per turn, § Fail-stop).
277
+ */
278
+ fence(fence: LedgerFence): void;
279
+ /** Record entries under flow version `version` from here on (spec 23 § Versions). */
280
+ runAs(version: string | undefined): void;
281
+ /**
282
+ * Let this resume discard effects recorded under another version: the host looked
283
+ * at a stuck turn and chose to go on.
284
+ */
285
+ acceptVersionLoss(path?: string): void;
286
+ /** True when an earlier attempt recorded a step at `path` that this run has not replayed yet. */
287
+ has(path: string): boolean;
288
+ /** Note that the step at `path` has a lasting effect; its entry is marked so. */
289
+ noteEffect(path: string | undefined): void;
290
+ /** The entries still in the ledger, as trail marks: those not yet pruned. */
291
+ liveMarks(): StepTrailStub[];
292
+ /**
293
+ * Throws `lease_lost` when this execution writes under a lease it no longer holds.
294
+ * Called before a paid dispatch, so a replaced harness stops before it spends.
295
+ */
296
+ assertHeld(): void;
297
+ /**
298
+ * `assertHeld`, after reading the lease back from storage. Called before a paid
299
+ * dispatch, so a harness that was replaced without knowing it does not pay again.
300
+ */
301
+ verifyHeld(): Promise<void>;
302
+ /** False once this execution writes under a lease it no longer holds. */
303
+ get isHeld(): boolean;
213
304
  /** True when this execution has nothing recovered to replay (the common, fresh case). */
214
305
  get isEmpty(): boolean;
215
306
  /** What retention has done so far. A snapshot — safe to hold. */
@@ -224,15 +315,37 @@ export declare class StepLedger {
224
315
  * An entry recorded without an input hash matches on identity alone.
225
316
  */
226
317
  take(path: string, step: StepLedgerMatch): StepLedgerEntry | undefined;
318
+ /**
319
+ * A step that no longer matches is run again, and what was recorded for it is
320
+ * thrown away. That is safe within one flow version. Under a newer version it is
321
+ * not safe for a step that already had a lasting effect: running it again could
322
+ * repeat the effect, so the turn stops for the host to decide.
323
+ *
324
+ * @throws NoeticError `turn_stuck`.
325
+ */
326
+ private refuseEffectLoss;
227
327
  /**
228
328
  * Record a completed step, then prune what it makes dead: a resumed run replays this
229
329
  * entry without descending, so nothing recorded beneath it will be read again.
230
- * Best-effort: a failed write costs resumability, not the run. Resolves whether
231
- * the entry was stored.
330
+ * Without a lease this is best-effort: a failed write costs resumability, not the
331
+ * run. Resolves whether the entry was stored.
332
+ *
333
+ * @throws NoeticError `lease_lost` when the write shows another harness took the turn.
334
+ * @throws NoeticError `ledger_write_failed` when, under a lease, the write fails.
232
335
  */
233
336
  record(recorded: StepLedgerEntry): Promise<boolean>;
337
+ /** `recorded` with who wrote it, under which version, and whether it had an effect. */
338
+ private stamped;
339
+ /**
340
+ * Store `entry` at `seq`. Under a lease the sequence number is claimed: finding
341
+ * an entry there from a higher term means this harness was replaced, and one from
342
+ * a lower term is a replaced harness's late write, which this one overwrites.
343
+ */
344
+ private write;
234
345
  /** Drop the entry recorded at `path`, when there is one. */
235
346
  drop(path: string): Promise<void>;
347
+ /** Drop the entry recorded at `path` and every entry beneath it. */
348
+ dropWithin(path: string): Promise<void>;
236
349
  /**
237
350
  * Notes that the step at `path` used a connection with the given identity; the
238
351
  * entry recorded at `path` (or at any path above it) carries it.
@@ -255,6 +368,11 @@ export declare class StepLedger {
255
368
  /** `entry` carrying every connection noted at its path or beneath it. */
256
369
  private withConnections;
257
370
  private prune;
371
+ /**
372
+ * Keep the trail mark of the entry at `path` before it is deleted. Best-effort:
373
+ * the trail is a record of what happened, not something a resume reads.
374
+ */
375
+ private leaveMark;
258
376
  private deleteSeq;
259
377
  /**
260
378
  * Whether this entry is small enough, encodable, and within the live cap. An entry
@@ -266,3 +384,4 @@ export declare class StepLedger {
266
384
  /** One warning per reason per execution — a long run would otherwise flood the log. */
267
385
  private warnOnFirstDrop;
268
386
  }
387
+ export {};
@@ -32,8 +32,9 @@
32
32
  * than correctness.
33
33
  */
34
34
  import { storageGetMany } from '@noetic-tools/context';
35
- import { NoeticConfigError } from '@noetic-tools/types';
35
+ import { NoeticConfigError, NoeticErrorImpl } from '@noetic-tools/types';
36
36
  import { z } from 'zod';
37
+ import { isBeneath, Parking } from './parking.js';
37
38
  //#region Entry
38
39
  /** Marks a ledger key as a step's `replayKey` rather than its execution path. */
39
40
  export const REPLAY_KEY_PREFIX = 'key:';
@@ -73,7 +74,77 @@ export const StepLedgerEntrySchema = z.object({
73
74
  }))
74
75
  .optional(),
75
76
  completedAt: z.string(),
77
+ /**
78
+ * The lease term of the harness that wrote the entry (spec 23 § One writer per
79
+ * turn). Absent on storage that cannot compare-and-set. An entry with a lower term
80
+ * than one recorded before it was written by a harness that had been replaced, and
81
+ * is ignored.
82
+ */
83
+ term: z.number().int().nonnegative().optional(),
84
+ /** The lease holder that wrote the entry: the harness's name in its lease. */
85
+ holder: z.string().optional(),
86
+ /** The flow version the step ran under, when the harness names one (spec 23 § Versions). */
87
+ version: z.string().optional(),
88
+ /**
89
+ * The step, or one beneath it, had a lasting effect: a `durable` tool, or a
90
+ * connection operation marked `once` or `effects`. A turn resumed under another
91
+ * version stops rather than discard such an entry.
92
+ */
93
+ effect: z.boolean().optional(),
76
94
  });
95
+ /** What a ledger entry leaves behind once it is pruned: its trail mark. */
96
+ const TrailStubSchema = StepLedgerEntrySchema.pick({
97
+ path: true,
98
+ stepId: true,
99
+ kind: true,
100
+ completedAt: true,
101
+ term: true,
102
+ holder: true,
103
+ version: true,
104
+ }).extend({
105
+ receipt: z.unknown().optional(),
106
+ });
107
+ /** Storage key prefix of one execution's trail: what its pruned ledger entries left. */
108
+ export function stepTrailPrefix(executionId) {
109
+ return `execution:${executionId}:trail:`;
110
+ }
111
+ /** The receipt an effect's output carries, when it has one. */
112
+ function receiptOf(output) {
113
+ if (typeof output !== 'object' || output === null || !('receipt' in output)) {
114
+ return undefined;
115
+ }
116
+ return output.receipt;
117
+ }
118
+ /** The trail mark of an entry. */
119
+ export function stubOf(entry) {
120
+ const receipt = receiptOf(entry.output);
121
+ return {
122
+ path: entry.path,
123
+ stepId: entry.stepId,
124
+ kind: entry.kind,
125
+ completedAt: entry.completedAt,
126
+ ...(entry.term === undefined
127
+ ? {}
128
+ : {
129
+ term: entry.term,
130
+ }),
131
+ ...(entry.holder === undefined
132
+ ? {}
133
+ : {
134
+ holder: entry.holder,
135
+ }),
136
+ ...(entry.version === undefined
137
+ ? {}
138
+ : {
139
+ version: entry.version,
140
+ }),
141
+ ...(receipt === undefined
142
+ ? {}
143
+ : {
144
+ receipt,
145
+ }),
146
+ };
147
+ }
77
148
  /** @public Retention applied when a harness does not configure `stepLedgerRetention`. */
78
149
  export const DEFAULT_STEP_LEDGER_RETENTION = {
79
150
  maxEntryBytes: 128 * 1024,
@@ -178,13 +249,46 @@ function seqFromKey(executionId, key) {
178
249
  }
179
250
  export function createStepLedgerStore(opts) {
180
251
  const { storage } = opts;
252
+ const swap = storage.swap?.bind(storage);
181
253
  return {
182
254
  append: async (executionId, seq, entry) => {
183
255
  await storage.set(seqKey(executionId, seq), entry);
184
256
  },
257
+ ...(swap
258
+ ? {
259
+ claim: async (executionId, seq, entry) => {
260
+ const key = seqKey(executionId, seq);
261
+ if (await swap(key, null, entry)) {
262
+ return undefined;
263
+ }
264
+ const raw = await storage.get(key);
265
+ const parsed = StepLedgerEntrySchema.safeParse(raw);
266
+ return {
267
+ raw,
268
+ term: parsed.success ? parsed.data.term : undefined,
269
+ };
270
+ },
271
+ replace: (at, conflict) => swap(seqKey(at.executionId, at.seq), conflict.raw, at.entry),
272
+ }
273
+ : {}),
185
274
  delete: async (executionId, seq) => {
186
275
  await storage.delete(seqKey(executionId, seq));
187
276
  },
277
+ mark: async (executionId, seq, stub) => {
278
+ await storage.set(`${stepTrailPrefix(executionId)}${String(seq).padStart(8, '0')}`, stub);
279
+ },
280
+ trail: async (executionId) => {
281
+ const keys = (await storage.list(stepTrailPrefix(executionId))).sort();
282
+ const raws = await storageGetMany(storage, keys);
283
+ const marks = [];
284
+ for (const key of keys) {
285
+ const parsed = TrailStubSchema.safeParse(raws.get(key));
286
+ if (parsed.success) {
287
+ marks.push(parsed.data);
288
+ }
289
+ }
290
+ return marks;
291
+ },
188
292
  load: async (executionId) => {
189
293
  const keys = await storage.list(stepLedgerPrefix(executionId));
190
294
  /* One batch read, not one round trip per completed step. Recovery is the
@@ -194,6 +298,9 @@ export function createStepLedgerStore(opts) {
194
298
  /* The next sequence number comes from the KEYS, not the parsed rows: a row that
195
299
  * fails to parse still occupies its key, so it must not be handed back out. */
196
300
  let highestSeq = -1;
301
+ /* The highest lease term seen so far, in sequence order. An entry with a lower
302
+ * term after it came from a harness that had already been replaced. */
303
+ let highestTerm = -1;
197
304
  const seqs = new Map();
198
305
  // Walk the keys sorted: `seqKey`'s zero-padding makes key order dispatch order,
199
306
  // and a later entry at a path must win over an earlier one.
@@ -215,9 +322,23 @@ export function createStepLedgerStore(opts) {
215
322
  console.warn(`StepLedger: discarding unreadable entry "${key}": ${parsed.error.message}`);
216
323
  continue;
217
324
  }
325
+ const term = parsed.data.term;
326
+ if (term !== undefined && term < highestTerm) {
327
+ continue;
328
+ }
329
+ highestTerm = Math.max(highestTerm, term ?? -1);
218
330
  entries.set(parsed.data.path, parsed.data);
219
331
  seqs.set(parsed.data.path, seq);
220
332
  }
333
+ // Trail marks are kept under the sequence number of the entry they came
334
+ // from. A new entry must not take a number a mark already has, or its own
335
+ // mark would one day overwrite that one.
336
+ for (const key of await storage.list(stepTrailPrefix(executionId))) {
337
+ const seq = Number(key.slice(stepTrailPrefix(executionId).length));
338
+ if (Number.isInteger(seq)) {
339
+ highestSeq = Math.max(highestSeq, seq);
340
+ }
341
+ }
221
342
  return {
222
343
  entries,
223
344
  seqs,
@@ -254,6 +375,18 @@ export class StepLedger {
254
375
  store;
255
376
  executionId;
256
377
  retention;
378
+ /** Which steps are in flight, and whether the turn may park (spec 23 § Parked turns). */
379
+ parking = new Parking();
380
+ /** The lease this execution writes under, once the turn has taken one. */
381
+ held;
382
+ /** The flow version entries are recorded under, when the harness names one. */
383
+ version;
384
+ /** A host accepted that this resume may discard effects recorded under another version. */
385
+ accepts = false;
386
+ /** Paths noted as having a lasting effect, until the entry there records. */
387
+ effects = new Set();
388
+ /** Every live entry, by path: what its trail mark is made from when it is pruned. */
389
+ entries = new Map();
257
390
  counts = {
258
391
  recorded: 0,
259
392
  droppedOversize: 0,
@@ -276,8 +409,10 @@ export class StepLedger {
276
409
  */
277
410
  adopt(recovered) {
278
411
  this.replayable.clear();
412
+ this.entries.clear();
279
413
  for (const [path, entry] of recovered.entries) {
280
414
  this.replayable.set(path, entry);
415
+ this.entries.set(path, entry);
281
416
  }
282
417
  this.live.clear();
283
418
  for (const [path, seq] of recovered.seqs) {
@@ -285,6 +420,65 @@ export class StepLedger {
285
420
  }
286
421
  this.seq = Math.max(this.seq, recovered.nextSeq);
287
422
  }
423
+ /**
424
+ * Write under `fence` from here on: entries carry its term, a sequence number is
425
+ * claimed rather than set, and a write that fails stops the turn instead of being
426
+ * logged (spec 23 § One writer per turn, § Fail-stop).
427
+ */
428
+ fence(fence) {
429
+ this.held = fence;
430
+ }
431
+ /** Record entries under flow version `version` from here on (spec 23 § Versions). */
432
+ runAs(version) {
433
+ this.version = version;
434
+ }
435
+ /**
436
+ * Let this resume discard effects recorded under another version: the host looked
437
+ * at a stuck turn and chose to go on.
438
+ */
439
+ acceptVersionLoss(path) {
440
+ this.accepts = path ?? true;
441
+ }
442
+ /** True when an earlier attempt recorded a step at `path` that this run has not replayed yet. */
443
+ has(path) {
444
+ return this.replayable.has(path);
445
+ }
446
+ /** Note that the step at `path` has a lasting effect; its entry is marked so. */
447
+ noteEffect(path) {
448
+ if (path !== undefined) {
449
+ this.effects.add(path);
450
+ }
451
+ }
452
+ /** The entries still in the ledger, as trail marks: those not yet pruned. */
453
+ liveMarks() {
454
+ return [
455
+ ...this.entries.values(),
456
+ ].map(stubOf);
457
+ }
458
+ /**
459
+ * Throws `lease_lost` when this execution writes under a lease it no longer holds.
460
+ * Called before a paid dispatch, so a replaced harness stops before it spends.
461
+ */
462
+ assertHeld() {
463
+ this.held?.assert();
464
+ }
465
+ /**
466
+ * `assertHeld`, after reading the lease back from storage. Called before a paid
467
+ * dispatch, so a harness that was replaced without knowing it does not pay again.
468
+ */
469
+ async verifyHeld() {
470
+ await this.held?.verify();
471
+ }
472
+ /** False once this execution writes under a lease it no longer holds. */
473
+ get isHeld() {
474
+ try {
475
+ this.held?.assert();
476
+ return true;
477
+ }
478
+ catch {
479
+ return false;
480
+ }
481
+ }
288
482
  /** True when this execution has nothing recovered to replay (the common, fresh case). */
289
483
  get isEmpty() {
290
484
  return this.replayable.size === 0;
@@ -313,32 +507,74 @@ export class StepLedger {
313
507
  for (const use of entry.connections ?? []) {
314
508
  this.noteConnection(path, use);
315
509
  }
510
+ // A replayed effect is still an effect: the step above it records one too.
511
+ if (entry.effect === true) {
512
+ this.effects.add(path);
513
+ }
316
514
  return entry;
317
515
  }
318
516
  if (path.startsWith(REPLAY_KEY_PREFIX)) {
517
+ this.refuseEffectLoss([
518
+ entry,
519
+ ]);
319
520
  this.replayable.delete(path);
320
521
  return undefined;
321
522
  }
322
- for (const key of [
323
- ...this.replayable.keys(),
324
- ]) {
325
- if (key === path || isBeneath(key, path)) {
326
- this.replayable.delete(key);
327
- }
523
+ const doomed = [
524
+ ...this.replayable.entries(),
525
+ ].filter(([key]) => key === path || isBeneath(key, path));
526
+ this.refuseEffectLoss(doomed.map(([, lost]) => lost));
527
+ for (const [key] of doomed) {
528
+ this.replayable.delete(key);
328
529
  }
329
530
  return undefined;
330
531
  }
532
+ /**
533
+ * A step that no longer matches is run again, and what was recorded for it is
534
+ * thrown away. That is safe within one flow version. Under a newer version it is
535
+ * not safe for a step that already had a lasting effect: running it again could
536
+ * repeat the effect, so the turn stops for the host to decide.
537
+ *
538
+ * @throws NoeticError `turn_stuck`.
539
+ */
540
+ refuseEffectLoss(lost) {
541
+ const to = this.version;
542
+ const accepted = this.accepts;
543
+ if (accepted === true || to === undefined) {
544
+ return;
545
+ }
546
+ // The host went on past one step. Any other recorded effect still stops the turn.
547
+ const isAccepted = (entry) => typeof accepted === 'string' && (entry.path === accepted || isBeneath(entry.path, accepted));
548
+ const effect = lost.find((entry) => entry.effect === true &&
549
+ entry.version !== undefined &&
550
+ entry.version !== to &&
551
+ !isAccepted(entry));
552
+ if (!effect?.version) {
553
+ return;
554
+ }
555
+ throw new NoeticErrorImpl({
556
+ kind: 'turn_stuck',
557
+ executionId: this.executionId,
558
+ path: effect.path,
559
+ from: effect.version,
560
+ to,
561
+ });
562
+ }
331
563
  /**
332
564
  * Record a completed step, then prune what it makes dead: a resumed run replays this
333
565
  * entry without descending, so nothing recorded beneath it will be read again.
334
- * Best-effort: a failed write costs resumability, not the run. Resolves whether
335
- * the entry was stored.
566
+ * Without a lease this is best-effort: a failed write costs resumability, not the
567
+ * run. Resolves whether the entry was stored.
568
+ *
569
+ * @throws NoeticError `lease_lost` when the write shows another harness took the turn.
570
+ * @throws NoeticError `ledger_write_failed` when, under a lease, the write fails.
336
571
  */
337
572
  async record(recorded) {
338
573
  if (!this.store) {
339
574
  return false;
340
575
  }
341
- const entry = this.withConnections(recorded);
576
+ this.held?.assert();
577
+ const entry = this.withConnections(this.stamped(recorded));
342
578
  if (!this.retainable(entry)) {
343
579
  return false;
344
580
  }
@@ -348,14 +584,28 @@ export class StepLedger {
348
584
  const seq = this.seq;
349
585
  this.seq = seq + 1;
350
586
  try {
351
- await this.store.append(this.executionId, seq, entry);
587
+ await this.write(seq, entry);
352
588
  }
353
589
  catch (error) {
590
+ if (this.held) {
591
+ throw error instanceof NoeticErrorImpl
592
+ ? error
593
+ : new NoeticErrorImpl({
594
+ kind: 'ledger_write_failed',
595
+ executionId: this.executionId,
596
+ path: entry.path,
597
+ cause: error instanceof Error ? error : new Error(String(error)),
598
+ });
599
+ }
354
600
  console.warn(`StepLedger: failed to record "${entry.path}":`, error instanceof Error ? error.message : String(error));
355
601
  return false;
356
602
  }
357
603
  const replaced = this.live.get(entry.path);
358
604
  this.live.set(entry.path, seq);
605
+ this.entries.set(entry.path, entry);
606
+ if (entry.effect) {
607
+ this.effects.add(entry.path);
608
+ }
359
609
  if (replaced === undefined) {
360
610
  this.counts.recorded += 1;
361
611
  }
@@ -367,12 +617,80 @@ export class StepLedger {
367
617
  }
368
618
  return true;
369
619
  }
620
+ /** `recorded` with who wrote it, under which version, and whether it had an effect. */
621
+ stamped(recorded) {
622
+ const hadEffect = recorded.effect === true ||
623
+ [
624
+ ...this.effects,
625
+ ].some((path) => path === recorded.path || isBeneath(path, recorded.path));
626
+ return {
627
+ ...recorded,
628
+ ...(this.held
629
+ ? {
630
+ term: this.held.term,
631
+ }
632
+ : {}),
633
+ ...(this.held?.holder === undefined
634
+ ? {}
635
+ : {
636
+ holder: this.held.holder,
637
+ }),
638
+ ...(this.version === undefined
639
+ ? {}
640
+ : {
641
+ version: this.version,
642
+ }),
643
+ ...(hadEffect
644
+ ? {
645
+ effect: true,
646
+ }
647
+ : {}),
648
+ };
649
+ }
650
+ /**
651
+ * Store `entry` at `seq`. Under a lease the sequence number is claimed: finding
652
+ * an entry there from a higher term means this harness was replaced, and one from
653
+ * a lower term is a replaced harness's late write, which this one overwrites.
654
+ */
655
+ async write(seq, entry) {
656
+ const store = this.store;
657
+ if (!store) {
658
+ return;
659
+ }
660
+ const fence = this.held;
661
+ if (!fence || !store.claim || !store.replace) {
662
+ await store.append(this.executionId, seq, entry);
663
+ return;
664
+ }
665
+ const conflict = await store.claim(this.executionId, seq, entry);
666
+ if (!conflict) {
667
+ return;
668
+ }
669
+ if (conflict.term !== undefined && conflict.term >= fence.term) {
670
+ throw fence.lose(`ledger entry ${seq} was written at term ${conflict.term}`);
671
+ }
672
+ const slot = {
673
+ executionId: this.executionId,
674
+ seq,
675
+ entry,
676
+ };
677
+ if (!(await store.replace(slot, conflict))) {
678
+ throw fence.lose(`ledger entry ${seq} changed while it was being replaced`);
679
+ }
680
+ }
370
681
  /** Drop the entry recorded at `path`, when there is one. */
371
682
  async drop(path) {
372
683
  await this.prune([
373
684
  path,
374
685
  ]);
375
686
  }
687
+ /** Drop the entry recorded at `path` and every entry beneath it. */
688
+ async dropWithin(path) {
689
+ await this.prune([
690
+ path,
691
+ ...this.live.beneath(path),
692
+ ]);
693
+ }
376
694
  /**
377
695
  * Notes that the step at `path` used a connection with the given identity; the
378
696
  * entry recorded at `path` (or at any path above it) carries it.
@@ -462,10 +780,33 @@ export class StepLedger {
462
780
  this.live.delete(path);
463
781
  this.replayable.delete(path);
464
782
  this.counts.pruned += 1;
783
+ await this.leaveMark(path, seq);
465
784
  await this.deleteSeq(seq);
466
785
  }
467
786
  }
787
+ /**
788
+ * Keep the trail mark of the entry at `path` before it is deleted. Best-effort:
789
+ * the trail is a record of what happened, not something a resume reads.
790
+ */
791
+ async leaveMark(path, seq) {
792
+ const entry = this.entries.get(path);
793
+ this.entries.delete(path);
794
+ this.effects.delete(path);
795
+ if (!entry || !this.store || !this.isHeld) {
796
+ return;
797
+ }
798
+ try {
799
+ await this.store.mark(this.executionId, seq, stubOf(entry));
800
+ }
801
+ catch (error) {
802
+ console.warn(`StepLedger: failed to keep the trail mark of "${path}":`, error instanceof Error ? error.message : String(error));
803
+ }
804
+ }
468
805
  async deleteSeq(seq) {
806
+ // A harness that was replaced must not delete what the new holder wrote.
807
+ if (!this.isHeld) {
808
+ return;
809
+ }
469
810
  try {
470
811
  await this.store?.delete(this.executionId, seq);
471
812
  }
@@ -525,10 +866,6 @@ function matches(entry, step) {
525
866
  }
526
867
  return entry.inputHash === undefined || entry.inputHash === step.inputHash;
527
868
  }
528
- /** Whether `path` lies in the subtree under `parent` — a lane below it or a child context's prefix. */
529
- function isBeneath(path, parent) {
530
- return path.startsWith(`${parent}/`) || path.startsWith(`${parent}[`);
531
- }
532
869
  /**
533
870
  * Live entries by path, with the paths also kept sorted. Everything beneath a path
534
871
  * starts with `<path>/` or `<path>[`, so in sorted order each is one contiguous run,