pi-durable-subagents 1.0.42 → 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.
- package/CHANGELOG.md +21 -0
- package/dist/agent/main/snapshots.js +24 -1
- package/dist/agent/main/tool.js +3 -2
- package/dist/agent/main.js +4 -10
- package/dist/cli/control.js +20 -10
- package/dist/cli/requests.js +51 -32
- package/dist/events/fence.js +2 -0
- package/dist/events/waiting.js +9 -2
- package/dist/kernel/journal.js +114 -25
- package/dist/kernel/lifecycle.js +66 -23
- package/dist/kernel/mailbox.js +49 -32
- package/dist/kernel/overlay.js +47 -0
- package/dist/orchestrator/engine.js +88 -31
- package/dist/orchestrator/executor/sweep.js +40 -24
- package/dist/orchestrator/ledger.js +4 -1
- package/dist/orchestrator/providers.js +2 -0
- package/dist/orchestrator/reader-ledger.js +13 -3
- package/dist/orchestrator/settled.js +10 -2
- package/dist/orchestrator/snapshot.js +2 -0
- package/dist/orchestrator/store.js +133 -33
- package/dist/requests.js +41 -5
- package/package.json +1 -1
package/dist/kernel/journal.js
CHANGED
|
@@ -164,9 +164,37 @@ export function readJournalUncached(path) {
|
|
|
164
164
|
closeSync(fd);
|
|
165
165
|
}
|
|
166
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
|
+
}
|
|
167
190
|
/** Fold a committed prefix a bounded chunk at a time. Only one record (possibly larger than a chunk) is buffered;
|
|
168
|
-
* newly appended bytes extend the state, and replacement or shrink rebuilds it. Never repairs the journal.
|
|
169
|
-
|
|
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 = {}) {
|
|
170
198
|
let fd;
|
|
171
199
|
try {
|
|
172
200
|
fd = openSync(path, 'r');
|
|
@@ -182,36 +210,51 @@ export function readJournalFold(path, prior, empty, apply) {
|
|
|
182
210
|
return prior;
|
|
183
211
|
const kept = prior && prior.dev === dev && prior.ino === ino && size >= prior.size;
|
|
184
212
|
const record = kept ? { ...prior, size } : { dev, ino, size, length: 0, seen: 0, state: empty() };
|
|
185
|
-
|
|
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 = [];
|
|
186
220
|
const buffer = Buffer.alloc(Math.min(64 * 1024, Math.max(1, size - offset)));
|
|
187
221
|
while (offset < size) {
|
|
188
222
|
const n = readSync(fd, buffer, 0, Math.min(buffer.length, size - offset), offset);
|
|
189
223
|
if (!n)
|
|
190
224
|
throw new Error(`Journal changed during read: ${path}`);
|
|
191
225
|
offset += n;
|
|
192
|
-
const
|
|
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;
|
|
193
233
|
let start = 0, end;
|
|
194
234
|
while ((end = bytes.indexOf(10, start)) >= 0) {
|
|
195
235
|
let entry;
|
|
196
236
|
try {
|
|
197
|
-
const
|
|
198
|
-
if (json
|
|
237
|
+
const line = bytes.subarray(start, end), json = line.subarray(9), head = frameHead(line);
|
|
238
|
+
if (line.length < 10 || head < 0 || crcValue(json) !== head)
|
|
199
239
|
throw new Error('CRC');
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
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
|
+
}
|
|
203
245
|
}
|
|
204
246
|
catch (cause) {
|
|
205
247
|
if (offset - bytes.length + end !== size - 1)
|
|
206
248
|
throw new Error(`Journal corruption at byte ${record.length}`, { cause });
|
|
207
249
|
return record;
|
|
208
250
|
}
|
|
209
|
-
|
|
251
|
+
if (entry)
|
|
252
|
+
apply(record.state, entry, record.length);
|
|
210
253
|
record.seen++;
|
|
211
254
|
record.length += end + 1 - start;
|
|
212
255
|
start = end + 1;
|
|
213
256
|
}
|
|
214
|
-
pending = Buffer.from(bytes.subarray(start));
|
|
257
|
+
pending = start < bytes.length ? [Buffer.from(bytes.subarray(start))] : [];
|
|
215
258
|
}
|
|
216
259
|
return record;
|
|
217
260
|
}
|
|
@@ -219,10 +262,35 @@ export function readJournalFold(path, prior, empty, apply) {
|
|
|
219
262
|
closeSync(fd);
|
|
220
263
|
}
|
|
221
264
|
}
|
|
222
|
-
/** Find
|
|
223
|
-
|
|
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 = {}) {
|
|
224
268
|
return readJournalFold(path, undefined, () => ({}), (state, entry) => { if (!state.found && match(entry))
|
|
225
|
-
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
|
+
}
|
|
226
294
|
}
|
|
227
295
|
/** How long a resting journal keeps its descriptor after its last append (a burst of appends opens it once). */
|
|
228
296
|
export const JOURNAL_REST_MS = 1000;
|
|
@@ -236,6 +304,10 @@ export function openJournalDescriptors() { return descriptors; }
|
|
|
236
304
|
export async function openJournal(path) {
|
|
237
305
|
return (await openHandle(path));
|
|
238
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
|
+
}
|
|
239
311
|
/** The expectation a journal handle meets now (its committed bytes, read back from the file), for a later lazy open;
|
|
240
312
|
* undefined when the file has no complete entry or does not end at the committed length. */
|
|
241
313
|
export function journalExpectation(journal) {
|
|
@@ -350,8 +422,8 @@ function loadSync(path, expect) {
|
|
|
350
422
|
closeSync(fd);
|
|
351
423
|
}
|
|
352
424
|
}
|
|
353
|
-
async function openHandle(path, lazy) {
|
|
354
|
-
let entries, size, file;
|
|
425
|
+
async function openHandle(path, lazy, apply) {
|
|
426
|
+
let entries, size, file, count = lazy?.count ?? 0;
|
|
355
427
|
if (lazy)
|
|
356
428
|
size = lazy.size;
|
|
357
429
|
else {
|
|
@@ -363,11 +435,19 @@ async function openHandle(path, lazy) {
|
|
|
363
435
|
return open(path, 'a+');
|
|
364
436
|
});
|
|
365
437
|
try {
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
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);
|
|
371
451
|
await first.sync();
|
|
372
452
|
}
|
|
373
453
|
if (created) {
|
|
@@ -384,6 +464,8 @@ async function openHandle(path, lazy) {
|
|
|
384
464
|
}
|
|
385
465
|
/** The entries, decoding a lazy handle's file first. */
|
|
386
466
|
const all = () => {
|
|
467
|
+
if (apply)
|
|
468
|
+
throw new Error('Folded journal does not retain entries');
|
|
387
469
|
if (!entries) {
|
|
388
470
|
const loaded = loadSync(path, lazy);
|
|
389
471
|
entries = loaded.entries;
|
|
@@ -438,7 +520,7 @@ async function openHandle(path, lazy) {
|
|
|
438
520
|
// it saw (the event pump reads new entries per tick without copying the journal).
|
|
439
521
|
committed: () => all(),
|
|
440
522
|
get loaded() { return entries !== undefined; },
|
|
441
|
-
count: () =>
|
|
523
|
+
count: () => count,
|
|
442
524
|
onAppend: undefined,
|
|
443
525
|
append(type, fields) {
|
|
444
526
|
if (closed)
|
|
@@ -447,8 +529,9 @@ async function openHandle(path, lazy) {
|
|
|
447
529
|
const operation = queue.then(async () => {
|
|
448
530
|
if (failed)
|
|
449
531
|
throw failed;
|
|
450
|
-
|
|
451
|
-
|
|
532
|
+
if (!apply)
|
|
533
|
+
all();
|
|
534
|
+
const entry = { ...frozen, seq: count + 1, ts: Date.now(), type };
|
|
452
535
|
const json = JSON.stringify(entry), bytes = Buffer.from(json), line = `${crc32(bytes)} ${json}\n`;
|
|
453
536
|
let target;
|
|
454
537
|
try {
|
|
@@ -460,8 +543,14 @@ async function openHandle(path, lazy) {
|
|
|
460
543
|
}
|
|
461
544
|
await target.writeFile(line);
|
|
462
545
|
await target.sync();
|
|
546
|
+
const offset = size;
|
|
463
547
|
size += Buffer.byteLength(line);
|
|
464
|
-
|
|
548
|
+
const committed = freeze(JSON.parse(json));
|
|
549
|
+
if (apply)
|
|
550
|
+
apply(committed, offset);
|
|
551
|
+
else
|
|
552
|
+
entries.push(committed);
|
|
553
|
+
count++;
|
|
465
554
|
view = undefined;
|
|
466
555
|
appends++;
|
|
467
556
|
rest();
|
package/dist/kernel/lifecycle.js
CHANGED
|
@@ -1,32 +1,75 @@
|
|
|
1
1
|
import { contentHash } from "./ids.js";
|
|
2
2
|
import { dependency } from "./guards.js";
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
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
|
-
|
|
11
|
-
|
|
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 (
|
|
20
|
-
resolved.set(record.rid,
|
|
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
|
-
|
|
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
|
-
|
|
29
|
-
|
|
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.
|
|
52
|
-
if (admitted.kind !== 'withdraw'
|
|
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:
|
|
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.
|
|
81
|
-
if (admitted.kind === 'withdraw'
|
|
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:
|
|
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),
|
|
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')
|
package/dist/kernel/mailbox.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { link, mkdir, open, readdir, readFile, unlink } from 'node:fs/promises';
|
|
2
2
|
import { join } from 'node:path';
|
|
3
3
|
import { contentHash, ulid } from "./ids.js";
|
|
4
|
-
import {
|
|
4
|
+
import { journalEntryAt, openFoldedJournal, syncDirectory } from "./journal.js";
|
|
5
5
|
function safeName(name) {
|
|
6
6
|
if (!name || name === '.' || name === '..' || /[/\\\0]/.test(name))
|
|
7
7
|
throw new Error('Invalid mailbox identity');
|
|
@@ -17,22 +17,34 @@ export async function publishFile(dir, name, bytes, same = existing => existing.
|
|
|
17
17
|
await file.writeFile(bytes);
|
|
18
18
|
await file.sync();
|
|
19
19
|
await file.close();
|
|
20
|
-
|
|
21
|
-
await link(temp, target);
|
|
22
|
-
}
|
|
23
|
-
catch (error) {
|
|
24
|
-
if (error.code !== 'EEXIST')
|
|
25
|
-
throw error;
|
|
26
|
-
let identical = false;
|
|
20
|
+
for (let attempt = 0;; attempt++) {
|
|
27
21
|
try {
|
|
28
|
-
|
|
22
|
+
await link(temp, target);
|
|
23
|
+
}
|
|
24
|
+
catch (error) {
|
|
25
|
+
if (error.code !== 'EEXIST')
|
|
26
|
+
throw error;
|
|
27
|
+
let existing, identical = false;
|
|
28
|
+
try {
|
|
29
|
+
existing = await readFile(target);
|
|
30
|
+
}
|
|
31
|
+
catch (readError) {
|
|
32
|
+
// The recipient can consume an envelope between EEXIST and this read. Retry the no-replace link, at most
|
|
33
|
+
// five attempts; an already resolved recipient safely consumes a duplicate publication again.
|
|
34
|
+
if (readError.code === 'ENOENT' && attempt < 4)
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
if (existing)
|
|
38
|
+
try {
|
|
39
|
+
identical = same(existing);
|
|
40
|
+
}
|
|
41
|
+
catch { /* Invalid existing content is a conflict. */ }
|
|
42
|
+
await syncDirectory(dir);
|
|
43
|
+
return identical ? 'exists-identical' : 'conflict';
|
|
29
44
|
}
|
|
30
|
-
catch { /* An unreadable existing file is a conflict. */ }
|
|
31
45
|
await syncDirectory(dir);
|
|
32
|
-
return
|
|
46
|
+
return 'published';
|
|
33
47
|
}
|
|
34
|
-
await syncDirectory(dir);
|
|
35
|
-
return 'published';
|
|
36
48
|
}
|
|
37
49
|
finally {
|
|
38
50
|
await file.close();
|
|
@@ -76,31 +88,34 @@ export async function scanInbox(inboxDir, report = (path, error) => console.warn
|
|
|
76
88
|
/** P38: A single-authority durable sender; serialize send, replay and deletion. */
|
|
77
89
|
export class Outbox {
|
|
78
90
|
journal;
|
|
91
|
+
path;
|
|
79
92
|
sender;
|
|
80
93
|
inbox;
|
|
81
94
|
pending = new Map();
|
|
82
|
-
|
|
95
|
+
/** Historical envelopes live only on disk; offsets keep idempotent sends and recovery lookups bounded. */
|
|
96
|
+
offsets = new Map();
|
|
83
97
|
high = new Map();
|
|
84
98
|
queue = Promise.resolve();
|
|
85
99
|
closed = false;
|
|
86
|
-
constructor(
|
|
87
|
-
this.
|
|
100
|
+
constructor(path, sender, inbox) {
|
|
101
|
+
this.path = path;
|
|
88
102
|
this.sender = sender;
|
|
89
103
|
this.inbox = inbox;
|
|
90
|
-
|
|
104
|
+
}
|
|
105
|
+
/** P38: Open outbox/<senderId>.jsonl; caller supplies recipient routing. Only pending envelopes stay resident. */
|
|
106
|
+
static async open(root, senderId, inbox) {
|
|
107
|
+
const box = new Outbox(join(root, 'outbox', `${safeName(senderId)}.jsonl`), senderId, inbox);
|
|
108
|
+
box.journal = await openFoldedJournal(box.path, (entry, offset) => {
|
|
91
109
|
if (entry.type === 'sent') {
|
|
92
110
|
const req = entry.request;
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
111
|
+
box.high.set(req.to, Math.max(box.high.get(req.to) ?? 0, req.sseq));
|
|
112
|
+
box.pending.set(req.rid, req);
|
|
113
|
+
box.offsets.set(req.rid, offset);
|
|
96
114
|
}
|
|
97
115
|
else if (entry.type === 'resolved')
|
|
98
|
-
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
/** P38: Open outbox/<senderId>.jsonl; caller supplies recipient routing. */
|
|
102
|
-
static async open(root, senderId, inbox) {
|
|
103
|
-
return new Outbox(await openJournal(join(root, 'outbox', `${safeName(senderId)}.jsonl`)), senderId, inbox);
|
|
116
|
+
box.pending.delete(entry.rid);
|
|
117
|
+
});
|
|
118
|
+
return box;
|
|
104
119
|
}
|
|
105
120
|
serial(fn) {
|
|
106
121
|
if (this.closed)
|
|
@@ -119,7 +134,7 @@ export class Outbox {
|
|
|
119
134
|
send(to, kind, body, cond, opts = {}) {
|
|
120
135
|
const payload = structuredClone({ body, cond });
|
|
121
136
|
return this.serial(async () => {
|
|
122
|
-
const prior = opts.rid ? this.
|
|
137
|
+
const prior = opts.rid ? this.recorded(opts.rid) : undefined;
|
|
123
138
|
if (prior) {
|
|
124
139
|
if (prior.to !== to || prior.kind !== kind || contentHash({ body: prior.body, cond: prior.cond }) !== contentHash({ body: payload.body, cond: payload.cond }))
|
|
125
140
|
throw new Error(`Outbox identity conflict: ${opts.rid}`);
|
|
@@ -129,15 +144,18 @@ export class Outbox {
|
|
|
129
144
|
}
|
|
130
145
|
const req = { rid: opts.rid ?? ulid(), from: this.sender, to, sseq: (this.high.get(to) ?? 0) + 1, kind, body: payload.body, ...(payload.cond ? { cond: payload.cond } : {}) };
|
|
131
146
|
await this.journal.append('sent', { request: req });
|
|
132
|
-
this.high.set(to, req.sseq);
|
|
133
|
-
this.pending.set(req.rid, req);
|
|
134
|
-
this.sent.set(req.rid, req);
|
|
135
147
|
await this.publish(req);
|
|
136
148
|
return structuredClone(req);
|
|
137
149
|
});
|
|
138
150
|
}
|
|
139
151
|
/** The envelope recorded as sent under `rid`, if any. */
|
|
140
|
-
recorded(rid) {
|
|
152
|
+
recorded(rid) {
|
|
153
|
+
const offset = this.offsets.get(rid);
|
|
154
|
+
const req = this.pending.get(rid) ?? (offset === undefined ? undefined : journalEntryAt(this.path, offset).request);
|
|
155
|
+
return req && structuredClone(req);
|
|
156
|
+
}
|
|
157
|
+
/** The identities still awaiting terminal resolution, without copying their envelopes. */
|
|
158
|
+
pendingRids() { return new Set(this.pending.keys()); }
|
|
141
159
|
/** The recipients of unresolved envelopes. */
|
|
142
160
|
pendingDestinations() { return new Set([...this.pending.values()].map(req => req.to)); }
|
|
143
161
|
/** P38: Re-publish every unresolved envelope under its original identity. */
|
|
@@ -149,7 +167,6 @@ export class Outbox {
|
|
|
149
167
|
if (!this.pending.has(rid))
|
|
150
168
|
return;
|
|
151
169
|
await this.journal.append('resolved', { rid });
|
|
152
|
-
this.pending.delete(rid);
|
|
153
170
|
});
|
|
154
171
|
}
|
|
155
172
|
/** C11: Drain outstanding operations before closing the durable log. */
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/** A map copy that stores only writes; its source must stay unchanged for the copy's lifetime. */
|
|
2
|
+
export class OverlayMap {
|
|
3
|
+
writes = new Map();
|
|
4
|
+
added = 0;
|
|
5
|
+
base;
|
|
6
|
+
constructor(base) { this.base = base; }
|
|
7
|
+
get size() { return this.base.size + this.added; }
|
|
8
|
+
has(key) { return this.writes.has(key) || this.base.has(key); }
|
|
9
|
+
get(key) { return this.writes.has(key) ? this.writes.get(key) : this.base.get(key); }
|
|
10
|
+
set(key, value) { if (!this.has(key))
|
|
11
|
+
this.added++; this.writes.set(key, value); }
|
|
12
|
+
*entries() {
|
|
13
|
+
for (const [key, value] of this.base)
|
|
14
|
+
yield [key, this.writes.has(key) ? this.writes.get(key) : value];
|
|
15
|
+
for (const pair of this.writes)
|
|
16
|
+
if (!this.base.has(pair[0]))
|
|
17
|
+
yield pair;
|
|
18
|
+
}
|
|
19
|
+
*keys() { for (const [key] of this)
|
|
20
|
+
yield key; }
|
|
21
|
+
*values() { for (const [, value] of this)
|
|
22
|
+
yield value; }
|
|
23
|
+
[Symbol.iterator]() { return this.entries(); }
|
|
24
|
+
forEach(callback, thisArg) {
|
|
25
|
+
for (const [key, value] of this)
|
|
26
|
+
callback.call(thisArg, value, key, this);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/** The set equivalent of OverlayMap. */
|
|
30
|
+
export class OverlaySet {
|
|
31
|
+
writes = new Set();
|
|
32
|
+
base;
|
|
33
|
+
constructor(base) { this.base = base; }
|
|
34
|
+
get size() { return this.base.size + this.writes.size; }
|
|
35
|
+
has(value) { return this.writes.has(value) || this.base.has(value); }
|
|
36
|
+
add(value) { if (!this.base.has(value))
|
|
37
|
+
this.writes.add(value); }
|
|
38
|
+
*values() { yield* this.base; yield* this.writes; }
|
|
39
|
+
keys() { return this.values(); }
|
|
40
|
+
*entries() { for (const value of this)
|
|
41
|
+
yield [value, value]; }
|
|
42
|
+
[Symbol.iterator]() { return this.values(); }
|
|
43
|
+
forEach(callback, thisArg) {
|
|
44
|
+
for (const value of this)
|
|
45
|
+
callback.call(thisArg, value, value, this);
|
|
46
|
+
}
|
|
47
|
+
}
|