pi-durable-subagents 1.0.41 → 1.0.43

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.
@@ -1,23 +1,43 @@
1
1
  import { open, mkdir } from 'node:fs/promises';
2
- import { closeSync, constants, fstatSync, openSync, readSync } from 'node:fs';
2
+ import { closeSync, constants, fstatSync, fsyncSync, ftruncateSync, openSync, readFileSync, readSync } from 'node:fs';
3
3
  import { dirname } from 'node:path';
4
+ import * as zlib from 'node:zlib';
4
5
  const TABLE = new Uint32Array(256).map((_, n) => { let c = n; for (let k = 0; k < 8; k++)
5
6
  c = (c & 1) ? 0xedb88320 ^ (c >>> 1) : c >>> 1; return c >>> 0; });
7
+ /** The CRC-32 (IEEE) of `bytes` as an unsigned number: node's native one when it has it (22.2+), else a table. */
8
+ const crcValue = typeof zlib.crc32 === 'function'
9
+ ? bytes => zlib.crc32(bytes)
10
+ : bytes => {
11
+ let crc = 0xffffffff;
12
+ for (let i = 0; i < bytes.length; i++)
13
+ crc = TABLE[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8);
14
+ return (crc ^ 0xffffffff) >>> 0;
15
+ };
6
16
  /** C11: the CRC-32 (IEEE) of a record, 8 lowercase hex digits: the frame of every journal line. */
7
17
  export function crc32(bytes) {
8
- let crc = 0xffffffff;
9
- for (let i = 0; i < bytes.length; i++)
10
- crc = TABLE[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8);
11
- return ((crc ^ 0xffffffff) >>> 0).toString(16).padStart(8, '0');
18
+ return crcValue(bytes).toString(16).padStart(8, '0');
19
+ }
20
+ /** The value of the 8 lowercase hex digits at `bytes[0..8)` followed by a space, or -1 when they are not that. */
21
+ function frameHead(bytes) {
22
+ if (bytes.length < 9 || bytes[8] !== 32)
23
+ return -1;
24
+ let value = 0;
25
+ for (let i = 0; i < 8; i++) {
26
+ const c = bytes[i], digit = c >= 48 && c <= 57 ? c - 48 : c >= 97 && c <= 102 ? c - 87 : -1;
27
+ if (digit < 0)
28
+ return -1;
29
+ value = value * 16 + digit;
30
+ }
31
+ return value;
12
32
  }
13
33
  /** C11: One framed line `<crc32 hex 8> <json>\n` (the journal format; the event log uses it too). */
14
34
  export function frameLine(json) { return `${crc32(Buffer.from(json))} ${json}\n`; }
15
35
  /** C11: The JSON text of one framed line (without its newline), or undefined when its frame or checksum is wrong. */
16
36
  export function unframeLine(line) {
17
- if (line.length < 10 || line[8] !== 32)
37
+ if (line.length < 10)
18
38
  return undefined;
19
- const head = Buffer.from(line.subarray(0, 8)).toString(), json = line.subarray(9);
20
- return /^[0-9a-f]{8}$/.test(head) && crc32(json) === head ? Buffer.from(json).toString() : undefined;
39
+ const head = frameHead(line), json = line.subarray(9);
40
+ return head >= 0 && crcValue(json) === head ? Buffer.from(json.buffer, json.byteOffset, json.byteLength).toString() : undefined;
21
41
  }
22
42
  /** Entries are immutable history (A1): freeze them so shared snapshots can be handed out without copying. */
23
43
  function freeze(value) {
@@ -36,10 +56,10 @@ function decode(bytes, prior = []) {
36
56
  if (end < 0)
37
57
  break;
38
58
  try {
39
- const line = bytes.subarray(offset, end), json = line.subarray(9);
40
- if (!/^[0-9a-f]{8} $/.test(line.subarray(0, 9).toString()) || crc32(json) !== line.subarray(0, 8).toString())
59
+ const line = bytes.subarray(offset, end), json = line.subarray(9), head = frameHead(line);
60
+ if (head < 0 || crcValue(json) !== head)
41
61
  throw new Error('CRC');
42
- const entry = JSON.parse(json.toString());
62
+ const entry = JSON.parse(bytes.toString('utf8', offset + 9, end));
43
63
  if (entry.seq !== entries.length + 1 || !Number.isFinite(entry.ts) || typeof entry.type !== 'string')
44
64
  throw new Error('Envelope');
45
65
  entries.push(freeze(entry));
@@ -144,9 +164,37 @@ export function readJournalUncached(path) {
144
164
  closeSync(fd);
145
165
  }
146
166
  }
167
+ /** Find candidate byte positions once per chunk, then advance only as JSON lines pass them. Latin-1 preserves
168
+ * byte offsets for literal multi-needle searches. Pending partial lines are included in the next chunk. */
169
+ function lineCandidates(bytes, needles, pattern) {
170
+ if (pattern) {
171
+ const text = bytes.toString('latin1');
172
+ pattern.lastIndex = 0;
173
+ let hit = pattern.exec(text);
174
+ return (start, end) => {
175
+ if (hit && hit.index < start) {
176
+ pattern.lastIndex = start;
177
+ hit = pattern.exec(text);
178
+ }
179
+ return hit !== null && hit.index < end && hit.index + hit[0].length <= end;
180
+ };
181
+ }
182
+ const needle = needles[0];
183
+ let next = needle ? bytes.indexOf(needle) : -1;
184
+ return (start, end) => {
185
+ if (next >= 0 && next < start)
186
+ next = bytes.indexOf(needle, start);
187
+ return next >= start && next + needle.length <= end;
188
+ };
189
+ }
147
190
  /** Fold a committed prefix a bounded chunk at a time. Only one record (possibly larger than a chunk) is buffered;
148
- * newly appended bytes extend the state, and replacement or shrink rebuilds it. Never repairs the journal. */
149
- export function readJournalFold(path, prior, empty, apply) {
191
+ * newly appended bytes extend the state, and replacement or shrink rebuilds it. Never repairs the journal.
192
+ * With needles, every line is still framed and CRC-checked and counted in seen, but only JSON bytes containing a
193
+ * needle are parsed/applied. The caller guarantees that every entry apply can act on contains a needle in its JSON
194
+ * text (use JSON.stringify of a string field value, or a canonical key/value pair). False positives only cost a
195
+ * parse. Syntax/envelope validation applies to parsed lines; skipped lines still preserve framing/CRC corruption
196
+ * and torn-tail semantics. Keep the same needles and reducer when extending a prior fold. */
197
+ export function readJournalFold(path, prior, empty, apply, options = {}) {
150
198
  let fd;
151
199
  try {
152
200
  fd = openSync(path, 'r');
@@ -162,36 +210,51 @@ export function readJournalFold(path, prior, empty, apply) {
162
210
  return prior;
163
211
  const kept = prior && prior.dev === dev && prior.ino === ino && size >= prior.size;
164
212
  const record = kept ? { ...prior, size } : { dev, ino, size, length: 0, seen: 0, state: empty() };
165
- let offset = record.length, pending = Buffer.alloc(0);
213
+ // A literal newline cannot occur within one framed JSON line. Empty needles match every line.
214
+ let needles = options.needles?.map(needle => Buffer.from(needle)).filter(needle => !needle.includes(10));
215
+ if (needles?.some(needle => !needle.length))
216
+ needles = undefined;
217
+ // One literal alternation scans a chunk once for a set of types/IDs, instead of once for every needle.
218
+ const pattern = needles && needles.length > 1 ? new RegExp(needles.map(needle => needle.toString('latin1').replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|'), 'g') : undefined;
219
+ let offset = record.length, pending = [];
166
220
  const buffer = Buffer.alloc(Math.min(64 * 1024, Math.max(1, size - offset)));
167
221
  while (offset < size) {
168
222
  const n = readSync(fd, buffer, 0, Math.min(buffer.length, size - offset), offset);
169
223
  if (!n)
170
224
  throw new Error(`Journal changed during read: ${path}`);
171
225
  offset += n;
172
- const bytes = pending.length ? Buffer.concat([pending, buffer.subarray(0, n)]) : buffer.subarray(0, n);
226
+ const part = buffer.subarray(0, n);
227
+ if (pending.length && part.indexOf(10) < 0) {
228
+ pending.push(Buffer.from(part));
229
+ continue;
230
+ }
231
+ const bytes = pending.length ? Buffer.concat([...pending, part]) : part;
232
+ let candidate;
173
233
  let start = 0, end;
174
234
  while ((end = bytes.indexOf(10, start)) >= 0) {
175
235
  let entry;
176
236
  try {
177
- const json = unframeLine(bytes.subarray(start, end));
178
- if (json === undefined)
237
+ const line = bytes.subarray(start, end), json = line.subarray(9), head = frameHead(line);
238
+ if (line.length < 10 || head < 0 || crcValue(json) !== head)
179
239
  throw new Error('CRC');
180
- entry = JSON.parse(json);
181
- if (entry.seq !== record.seen + 1 || !Number.isFinite(entry.ts) || typeof entry.type !== 'string')
182
- throw new Error('Envelope');
240
+ if (!needles || (candidate ??= lineCandidates(bytes, needles, pattern))(start + 9, end)) {
241
+ entry = JSON.parse(json.toString('utf8'));
242
+ if (entry.seq !== record.seen + 1 || !Number.isFinite(entry.ts) || typeof entry.type !== 'string')
243
+ throw new Error('Envelope');
244
+ }
183
245
  }
184
246
  catch (cause) {
185
247
  if (offset - bytes.length + end !== size - 1)
186
248
  throw new Error(`Journal corruption at byte ${record.length}`, { cause });
187
249
  return record;
188
250
  }
189
- apply(record.state, entry);
251
+ if (entry)
252
+ apply(record.state, entry, record.length);
190
253
  record.seen++;
191
254
  record.length += end + 1 - start;
192
255
  start = end + 1;
193
256
  }
194
- pending = Buffer.from(bytes.subarray(start));
257
+ pending = start < bytes.length ? [Buffer.from(bytes.subarray(start))] : [];
195
258
  }
196
259
  return record;
197
260
  }
@@ -199,10 +262,35 @@ export function readJournalFold(path, prior, empty, apply) {
199
262
  closeSync(fd);
200
263
  }
201
264
  }
202
- /** Find one record without retaining history (request-time lookups that do not belong in a compact polling state). */
203
- export function findJournalEntry(path, match) {
265
+ /** Find the first matching record without retaining history. Needles have the same caller guarantee as
266
+ * readJournalFold: every entry match can accept must contain a needle in its JSON text. */
267
+ export function findJournalEntry(path, match, options = {}) {
204
268
  return readJournalFold(path, undefined, () => ({}), (state, entry) => { if (!state.found && match(entry))
205
- state.found = entry; })?.state.found;
269
+ state.found = entry; }, options)?.state.found;
270
+ }
271
+ /** Read one framed entry at an offset indexed by this journal's single writer. Never retains a snapshot. */
272
+ export function journalEntryAt(path, offset) {
273
+ const fd = openSync(path, 'r');
274
+ try {
275
+ const chunks = [], buffer = Buffer.alloc(4096);
276
+ for (let pos = offset;;) {
277
+ const n = readSync(fd, buffer, 0, buffer.length, pos);
278
+ if (!n)
279
+ throw new Error(`Missing journal entry at byte ${offset}`);
280
+ const end = buffer.subarray(0, n).indexOf(10);
281
+ chunks.push(Buffer.from(buffer.subarray(0, end < 0 ? n : end)));
282
+ if (end >= 0)
283
+ break;
284
+ pos += n;
285
+ }
286
+ const json = unframeLine(Buffer.concat(chunks));
287
+ if (json === undefined)
288
+ throw new Error(`Journal corruption at byte ${offset}`);
289
+ return JSON.parse(json);
290
+ }
291
+ finally {
292
+ closeSync(fd);
293
+ }
206
294
  }
207
295
  /** How long a resting journal keeps its descriptor after its last append (a burst of appends opens it once). */
208
296
  export const JOURNAL_REST_MS = 1000;
@@ -214,35 +302,179 @@ export function openJournalDescriptors() { return descriptors; }
214
302
  /** A1, C11: Repair only the tail, then serialize durable framed appends. A resting handle (`resting = true`) closes its
215
303
  * descriptor once its appends are done and reopens it for the next append; its entries stay in memory. */
216
304
  export async function openJournal(path) {
217
- await mkdir(dirname(path), { recursive: true });
218
- let created = false;
219
- const first = await open(path, 'ax+').then(f => { created = true; return f; }, async (error) => {
220
- if (error.code !== 'EEXIST')
221
- throw error;
222
- return open(path, 'a+');
223
- });
224
- let entries, size;
305
+ return (await openHandle(path));
306
+ }
307
+ /** A1, C11: The same durable writer with a streaming fold instead of resident history. The reducer must not throw. */
308
+ export async function openFoldedJournal(path, apply) {
309
+ return (await openHandle(path, undefined, apply));
310
+ }
311
+ /** The expectation a journal handle meets now (its committed bytes, read back from the file), for a later lazy open;
312
+ * undefined when the file has no complete entry or does not end at the committed length. */
313
+ export function journalExpectation(journal) {
314
+ const entries = journal.committed?.() ?? journal.entries(), count = entries.length;
315
+ if (!count)
316
+ return undefined;
317
+ let fd;
225
318
  try {
226
- const bytes = await first.readFile(), decoded = decode(bytes);
227
- entries = decoded.entries;
228
- size = decoded.length;
229
- if (decoded.length !== bytes.length) {
230
- await first.truncate(decoded.length);
231
- await first.sync();
319
+ fd = openSync(journal.path, 'r');
320
+ }
321
+ catch {
322
+ return undefined;
323
+ }
324
+ try {
325
+ const { ino, size } = fstatSync(fd), tail = lastLine(fd, size);
326
+ if (!tail)
327
+ return undefined;
328
+ // The last line must be the last committed entry (a torn tail is truncated by every open, never trusted).
329
+ const json = unframeLine(tail.subarray(0, tail.length - 1));
330
+ if (json === undefined || JSON.parse(json).seq !== count)
331
+ return undefined;
332
+ return { ino, size, count, tail: crc32(tail), tailLength: tail.length };
333
+ }
334
+ catch {
335
+ return undefined;
336
+ }
337
+ finally {
338
+ closeSync(fd);
339
+ }
340
+ }
341
+ /** The last line of the file (with its newline), when the file ends with one. Reads from the end in chunks. */
342
+ function lastLine(fd, size) {
343
+ if (!size)
344
+ return undefined;
345
+ let chunk = 4096, buffer = Buffer.alloc(0);
346
+ for (let end = size;;) {
347
+ const start = Math.max(0, end - chunk), part = Buffer.alloc(end - start);
348
+ for (let read = 0; read < part.length;) {
349
+ const n = readSync(fd, part, read, part.length - read, start + read);
350
+ if (!n)
351
+ return undefined;
352
+ read += n;
353
+ }
354
+ buffer = Buffer.concat([part, buffer]);
355
+ if (buffer[buffer.length - 1] !== 10)
356
+ return undefined;
357
+ const previous = buffer.lastIndexOf(10, buffer.length - 2);
358
+ if (previous >= 0)
359
+ return buffer.subarray(previous + 1);
360
+ if (start === 0)
361
+ return buffer;
362
+ end = start;
363
+ chunk *= 2;
364
+ }
365
+ }
366
+ /** A1, C11: A journal handle that decodes nothing yet: when the file still is what `expect` describes (same inode and
367
+ * size, the same last line), the handle reports `loaded: false` and `count()` from it, and decodes the whole file
368
+ * (verifying it as openJournal does) on the first access to its entries or the first append. Undefined when the file
369
+ * is not what was expected: the caller opens it eagerly. Decoding later finds the same bytes or throws (one writer). */
370
+ export async function openLazyJournal(path, expect) {
371
+ let fd;
372
+ try {
373
+ fd = openSync(path, 'r');
374
+ }
375
+ catch {
376
+ return undefined;
377
+ }
378
+ try {
379
+ const { ino, size } = fstatSync(fd);
380
+ if (ino !== expect.ino || size !== expect.size || expect.count < 1 || expect.tailLength < 10 || expect.tailLength > size)
381
+ return undefined;
382
+ const tail = Buffer.alloc(expect.tailLength);
383
+ for (let read = 0; read < tail.length;) {
384
+ const n = readSync(fd, tail, read, tail.length - read, size - tail.length + read);
385
+ if (!n)
386
+ return undefined;
387
+ read += n;
232
388
  }
233
- if (created) {
234
- await first.sync();
235
- await syncDirectory(dirname(path));
389
+ if (tail[tail.length - 1] !== 10 || tail.indexOf(10) !== tail.length - 1 || crc32(tail) !== expect.tail)
390
+ return undefined;
391
+ if (size > tail.length) {
392
+ const before = Buffer.alloc(1);
393
+ if (readSync(fd, before, 0, 1, size - tail.length - 1) !== 1 || before[0] !== 10)
394
+ return undefined;
236
395
  }
237
396
  }
238
- catch (error) {
239
- await first.close();
240
- throw error;
397
+ catch {
398
+ return undefined;
399
+ }
400
+ finally {
401
+ closeSync(fd);
402
+ }
403
+ return openHandle(path, expect);
404
+ }
405
+ /** Decode a journal synchronously as openJournal does (a torn tail is truncated), for a lazy handle's first access. */
406
+ function loadSync(path, expect) {
407
+ const fd = openSync(path, 'r+');
408
+ try {
409
+ const { ino, size } = fstatSync(fd);
410
+ if (ino !== expect.ino || size !== expect.size)
411
+ throw new Error(`Journal changed while not loaded: ${path} has ${size} bytes, ${expect.size} expected`);
412
+ const bytes = readFileSync(fd), decoded = decode(bytes);
413
+ if (decoded.entries.length !== expect.count)
414
+ throw new Error(`Journal changed while not loaded: ${path} has ${decoded.entries.length} entries, ${expect.count} expected`);
415
+ if (decoded.length !== bytes.length) {
416
+ ftruncateSync(fd, decoded.length);
417
+ fsyncSync(fd);
418
+ }
419
+ return { entries: decoded.entries, size: decoded.length };
420
+ }
421
+ finally {
422
+ closeSync(fd);
241
423
  }
242
- let file = first;
243
- descriptors++;
424
+ }
425
+ async function openHandle(path, lazy, apply) {
426
+ let entries, size, file, count = lazy?.count ?? 0;
427
+ if (lazy)
428
+ size = lazy.size;
429
+ else {
430
+ await mkdir(dirname(path), { recursive: true });
431
+ let created = false;
432
+ const first = await open(path, 'ax+').then(f => { created = true; return f; }, async (error) => {
433
+ if (error.code !== 'EEXIST')
434
+ throw error;
435
+ return open(path, 'a+');
436
+ });
437
+ try {
438
+ if (apply) {
439
+ const folded = readJournalFold(path, undefined, () => undefined, (_state, entry, offset) => apply(freeze(entry), offset));
440
+ size = folded.length;
441
+ count = folded.seen;
442
+ }
443
+ else {
444
+ const decoded = decode(await first.readFile());
445
+ entries = decoded.entries;
446
+ size = decoded.length;
447
+ count = entries.length;
448
+ }
449
+ if (size !== (await first.stat()).size) {
450
+ await first.truncate(size);
451
+ await first.sync();
452
+ }
453
+ if (created) {
454
+ await first.sync();
455
+ await syncDirectory(dirname(path));
456
+ }
457
+ }
458
+ catch (error) {
459
+ await first.close();
460
+ throw error;
461
+ }
462
+ file = first;
463
+ descriptors++;
464
+ }
465
+ /** The entries, decoding a lazy handle's file first. */
466
+ const all = () => {
467
+ if (apply)
468
+ throw new Error('Folded journal does not retain entries');
469
+ if (!entries) {
470
+ const loaded = loadSync(path, lazy);
471
+ entries = loaded.entries;
472
+ size = loaded.size;
473
+ }
474
+ return entries;
475
+ };
244
476
  let queue = Promise.resolve(), closed = false, failed, view;
245
- let resting = false, restTimer;
477
+ let resting = lazy !== undefined, restTimer;
246
478
  // Only this process writes the file (A2): a reopened file that is not exactly what was committed was changed by
247
479
  // someone else, and appending to it could interleave records.
248
480
  const reopen = async () => {
@@ -283,10 +515,12 @@ export async function openJournal(path) {
283
515
  const handle = {
284
516
  path,
285
517
  // Shared frozen view, rebuilt only after an append (entries are immutable, see freeze()).
286
- entries: () => view ??= Object.freeze(entries.slice()),
518
+ entries: () => view ??= Object.freeze(all().slice()),
287
519
  // The growing array itself (no copy): it is only ever appended to, so a reader may keep it and read below a length
288
520
  // it saw (the event pump reads new entries per tick without copying the journal).
289
- committed: () => entries,
521
+ committed: () => all(),
522
+ get loaded() { return entries !== undefined; },
523
+ count: () => count,
290
524
  onAppend: undefined,
291
525
  append(type, fields) {
292
526
  if (closed)
@@ -295,7 +529,9 @@ export async function openJournal(path) {
295
529
  const operation = queue.then(async () => {
296
530
  if (failed)
297
531
  throw failed;
298
- const entry = { ...frozen, seq: entries.length + 1, ts: Date.now(), type };
532
+ if (!apply)
533
+ all();
534
+ const entry = { ...frozen, seq: count + 1, ts: Date.now(), type };
299
535
  const json = JSON.stringify(entry), bytes = Buffer.from(json), line = `${crc32(bytes)} ${json}\n`;
300
536
  let target;
301
537
  try {
@@ -307,8 +543,14 @@ export async function openJournal(path) {
307
543
  }
308
544
  await target.writeFile(line);
309
545
  await target.sync();
546
+ const offset = size;
310
547
  size += Buffer.byteLength(line);
311
- entries.push(freeze(JSON.parse(json)));
548
+ const committed = freeze(JSON.parse(json));
549
+ if (apply)
550
+ apply(committed, offset);
551
+ else
552
+ entries.push(committed);
553
+ count++;
312
554
  view = undefined;
313
555
  appends++;
314
556
  rest();
@@ -1,32 +1,75 @@
1
1
  import { contentHash } from "./ids.js";
2
2
  import { dependency } from "./guards.js";
3
- /** A1, A3, P5, P6: Rebuild lifecycle state solely from committed decisions. */
4
- export function reduceLifecycle(records) {
5
- const admitted = new Map(), order = new Map();
6
- const resolved = new Map(), tombstones = new Set(), high = new Map();
7
- for (const record of records) {
3
+ import { OverlayMap, OverlaySet } from "./overlay.js";
4
+ /** Journal records are deeply frozen. Mutable inputs still get a defensive copy. */
5
+ const retained = (record) => Object.isFrozen(record) ? record : structuredClone(record);
6
+ /** A1, A3, P5, P6: The left fold of committed decisions, with an admission-ordered open frontier. */
7
+ export class LifecycleFold {
8
+ admitted = new Map();
9
+ order = new Map();
10
+ resolved = new Map();
11
+ tombstones = new Set();
12
+ high = new Map();
13
+ open = new Map();
14
+ apply(record) {
8
15
  if (record.type === 'admitted') {
9
- if (!admitted.has(record.rid)) {
10
- admitted.set(record.rid, structuredClone(record));
11
- order.set(record.rid, order.size);
16
+ if (!this.admitted.has(record.rid)) {
17
+ const entry = retained(record);
18
+ this.admitted.set(record.rid, entry);
19
+ this.order.set(record.rid, this.order.size);
20
+ if (!this.resolved.has(record.rid))
21
+ this.open.set(record.rid, entry);
12
22
  }
13
- high.set(record.from, Math.max(high.get(record.from) ?? 0, record.sseq));
23
+ this.high.set(record.from, Math.max(this.high.get(record.from) ?? 0, record.sseq));
14
24
  }
15
25
  else if (record.type === 'withdrawn') {
16
26
  for (const rid of record.rids)
17
- tombstones.add(rid);
27
+ this.tombstones.add(rid);
18
28
  }
19
- else if (!(record.type === 'rejected' && record.reason === 'identity-conflict') && !resolved.has(record.rid)) {
20
- resolved.set(record.rid, structuredClone(record));
29
+ else if (isResolution(record) && !this.resolved.has(record.rid)) {
30
+ this.resolved.set(record.rid, retained(record));
31
+ this.open.delete(record.rid);
21
32
  }
22
33
  }
23
- return { admitted, order, resolved, tombstones, high };
34
+ /** O(open requests), with O(1) overlays over history. The source must not change until this copy is discarded. */
35
+ copy() {
36
+ const copy = new LifecycleFold();
37
+ copy.admitted = new OverlayMap(this.admitted);
38
+ copy.order = new OverlayMap(this.order);
39
+ copy.resolved = new OverlayMap(this.resolved);
40
+ copy.tombstones = new OverlaySet(this.tombstones);
41
+ copy.high = new OverlayMap(this.high);
42
+ for (const [rid, record] of this.open)
43
+ copy.open.set(rid, record);
44
+ return copy;
45
+ }
46
+ view() { return { admitted: this.admitted, order: this.order, resolved: this.resolved, tombstones: this.tombstones, high: this.high }; }
47
+ }
48
+ /** Whether a record can be the first terminal decision for a rid; identity conflicts never resolve it. */
49
+ export function isResolution(record) {
50
+ return record.type === 'applied' || record.type === 'rejected' && record.reason !== 'identity-conflict';
51
+ }
52
+ /** Direct equivalent of reduceLifecycle(records).resolved.get(rid), with no cloning. */
53
+ export function lifecycleResolution(records, rid) {
54
+ return records.find((record) => record.rid === rid && isResolution(record));
55
+ }
56
+ /** A1, A3, P5, P6: Rebuild lifecycle state solely from committed decisions. */
57
+ export function reduceLifecycle(records) {
58
+ const fold = new LifecycleFold();
59
+ for (const record of records)
60
+ fold.apply(record);
61
+ return fold.view();
24
62
  }
25
- /** A3, A4/V5, P5, P6: Plan deterministic intake and resolution without I/O or effects. */
63
+ /** A3, A4/V5, P5, P6: Plan deterministic intake and resolution without I/O or effects.
64
+ * The decider receives a defensive request copy and a read-only lifecycle view valid only during that call.
65
+ * A supplied fold stays unchanged; its source must stay unchanged throughout this synchronous call. */
26
66
  export function planDecisions(records, candidates, decide) {
27
67
  const output = [];
28
- let view = reduceLifecycle(records);
29
- const emit = (record) => { output.push(record); view = reduceLifecycle([...records, ...output]); };
68
+ const view = records instanceof LifecycleFold ? records.copy() : new LifecycleFold();
69
+ if (!(records instanceof LifecycleFold))
70
+ for (const record of records)
71
+ view.apply(record);
72
+ const emit = (record) => { output.push(record); view.apply(record); };
30
73
  const cmp = (a, b) => a < b ? -1 : a > b ? 1 : 0;
31
74
  const sorted = candidates.map(req => ({ req: structuredClone(req), hash: contentHash(req) })).sort((a, b) => cmp(a.req.from, b.req.from) || a.req.sseq - b.req.sseq || cmp(a.req.rid, b.req.rid) || cmp(a.hash, b.hash));
32
75
  const envelopes = new Map(), conflicts = new Set();
@@ -48,8 +91,8 @@ export function planDecisions(records, candidates, decide) {
48
91
  envelopes.set(req.rid, req);
49
92
  }
50
93
  // P6 bypasses ordinary consideration, but a withdrawal still obeys its own V5 dependency.
51
- for (const [rid, admitted] of view.admitted) {
52
- if (admitted.kind !== 'withdraw' || view.resolved.has(rid))
94
+ for (const [rid, admitted] of view.open) {
95
+ if (admitted.kind !== 'withdraw')
53
96
  continue;
54
97
  const req = envelopes.get(rid);
55
98
  if (!req)
@@ -58,7 +101,7 @@ export function planDecisions(records, candidates, decide) {
58
101
  emit({ type: 'rejected', rid, reason: 'withdrawn' });
59
102
  continue;
60
103
  }
61
- const state = { order: view.order, resolved: new Set(view.resolved.keys()) };
104
+ const state = { order: view.order, resolved: view.resolved };
62
105
  if (!dependency(state, { rid, after: req.cond?.after, phase: 'admission' })) {
63
106
  emit({ type: 'rejected', rid, reason: 'malformed' });
64
107
  continue;
@@ -77,8 +120,8 @@ export function planDecisions(records, candidates, decide) {
77
120
  emit({ type: 'rejected', rid: target, reason: 'withdrawn' });
78
121
  emit({ type: 'applied', rid });
79
122
  }
80
- for (const [rid, admitted] of view.admitted) {
81
- if (admitted.kind === 'withdraw' || view.resolved.has(rid))
123
+ for (const [rid, admitted] of view.open) {
124
+ if (admitted.kind === 'withdraw')
82
125
  continue;
83
126
  const req = envelopes.get(rid);
84
127
  if (!req)
@@ -87,14 +130,14 @@ export function planDecisions(records, candidates, decide) {
87
130
  emit({ type: 'rejected', rid, reason: 'withdrawn' });
88
131
  continue;
89
132
  }
90
- const state = { order: view.order, resolved: new Set(view.resolved.keys()) };
133
+ const state = { order: view.order, resolved: view.resolved };
91
134
  if (!dependency(state, { rid, after: req.cond?.after, phase: 'admission' })) {
92
135
  emit({ type: 'rejected', rid, reason: 'malformed' });
93
136
  continue;
94
137
  }
95
138
  if (!dependency(state, { rid, after: req.cond?.after, phase: 'application' }))
96
139
  continue;
97
- const decision = decide(structuredClone(req), structuredClone(view));
140
+ const decision = decide(structuredClone(req), view.view());
98
141
  if (decision.action === 'apply')
99
142
  emit({ type: 'applied', rid });
100
143
  else if (decision.action === 'reject')