@unieai/rabi-session-persistence-jsonl 0.0.0-stage → 0.2.2-rc.5
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/LICENSE +21 -0
- package/README.md +7 -2
- package/lib/index.js +3650 -0
- package/lib/types/catalog-migration.d.ts +28 -0
- package/lib/types/format.d.ts +200 -0
- package/lib/types/generation.d.ts +179 -0
- package/lib/types/index.d.ts +46 -0
- package/lib/types/lease.d.ts +57 -0
- package/lib/types/migration-verifier.d.ts +15 -0
- package/lib/types/storage.d.ts +250 -0
- package/lib/types/testing/generation.d.ts +8 -0
- package/lib/types/win32.d.ts +48 -0
- package/lib/types/worker.d.ts +3 -0
- package/lib/types/zstd-private-decoder.d.ts +33 -0
- package/lib/types/zstd-public-decoder.d.ts +15 -0
- package/lib/types/zstd.d.ts +68 -0
- package/lib/worker.cjs +14201 -0
- package/locale/de.json +6 -0
- package/locale/en.json +5 -0
- package/locale/es.json +6 -0
- package/locale/fr.json +6 -0
- package/locale/ja.json +6 -0
- package/locale/pt.json +6 -0
- package/locale/ru.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +44 -4
- package/src/catalog-migration.ts +92 -0
- package/src/format.ts +538 -0
- package/src/generation.ts +1059 -0
- package/src/index.ts +1839 -0
- package/src/lease.ts +135 -0
- package/src/migration-verifier.ts +198 -0
- package/src/storage.ts +571 -0
- package/src/testing/generation.ts +16 -0
- package/src/win32.ts +208 -0
- package/src/worker.ts +56 -0
- package/src/zstd-private-decoder.ts +178 -0
- package/src/zstd-public-decoder.ts +40 -0
- package/src/zstd.ts +156 -0
package/lib/index.js
ADDED
|
@@ -0,0 +1,3650 @@
|
|
|
1
|
+
import z from "@unieai/schemastery";
|
|
2
|
+
import { SessionFormatUnsupportedMigrationError, createSessionFormatCatalogWithChildren, historicalSessionFormatCatalog, sessionFormatCatalog } from "@unieai/rabi-session-format-catalog";
|
|
3
|
+
import { readdirSync } from "node:fs";
|
|
4
|
+
import { link, lstat, mkdir, mkdtemp, open, readFile, readdir, realpath, rm, stat, truncate } from "node:fs/promises";
|
|
5
|
+
import { basename, dirname, isAbsolute, join, parse, resolve, toNamespacedPath } from "node:path";
|
|
6
|
+
import { performance } from "node:perf_hooks";
|
|
7
|
+
import { scheduler } from "node:timers/promises";
|
|
8
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
9
|
+
import pLimit from "p-limit";
|
|
10
|
+
import { SessionAlreadyExistsError, SessionAlreadyOwnedError, SessionFormatUnsupportedError, SessionHandleClosedError, SessionPersistence, SessionPersistenceCorruptionError, SessionPersistenceNotFoundError, SessionPersistenceRevision, SessionReadOnlyError, assertContiguous, assertStoredId, materializeAppendBatch, materializeCreateHeader, sessionFormatVersionRefusal, validateStoredEvents } from "@unieai/rabi-session-persistence";
|
|
11
|
+
import { BlockAssembler, errorChain, expandAssistantStream } from "@unieai/rabi-llm";
|
|
12
|
+
import { tryLockExclusive } from "@unieai/node-addon-system/flock";
|
|
13
|
+
import { KNOWN_SESSION_EVENT_TYPES, SESSION_FORMAT_VERSION, Session, SessionId, SessionLogOffset } from "@unieai/rabi-session";
|
|
14
|
+
import { SessionFormatError, SessionFormatUnsupportedMigrationError as SessionFormatUnsupportedMigrationError$1, parseSessionFormatLogFilename, sessionFormatLogFilename } from "@unieai/rabi-session-format";
|
|
15
|
+
import { assertReleasedV4Relationships, assertV4RowAdmission, historicalChildCatalogSource } from "@unieai/rabi-session-format-v3-to-v4";
|
|
16
|
+
import { constants, createZstdCompress, createZstdDecompress, zstdCompress, zstdDecompress, zstdDecompressSync } from "node:zlib";
|
|
17
|
+
import { isDeepStrictEqual, promisify } from "node:util";
|
|
18
|
+
import { constants as constants$1 } from "node:buffer";
|
|
19
|
+
import { Worker } from "node:worker_threads";
|
|
20
|
+
import { currentSessionMessageProjections } from "@unieai/rabi-session-format-catalog/message-projections";
|
|
21
|
+
import { Readable, pipeline } from "node:stream";
|
|
22
|
+
/**
|
|
23
|
+
* The JSONL session handle. Mutations serialize on a per-handle promise
|
|
24
|
+
* chain; reads re-scan the artifact on demand and never observe a shorter log
|
|
25
|
+
* than a prior read on this handle. Routed live events buffer in a bounded
|
|
26
|
+
* window and drain through the same chain as explicit appends.
|
|
27
|
+
*/
|
|
28
|
+
var JsonlSessionHandle = class {
|
|
29
|
+
storage;
|
|
30
|
+
id;
|
|
31
|
+
header;
|
|
32
|
+
access;
|
|
33
|
+
state;
|
|
34
|
+
lease;
|
|
35
|
+
chain = Promise.resolve();
|
|
36
|
+
closing;
|
|
37
|
+
observedLength = 0;
|
|
38
|
+
/** Routed live events awaiting their batching deadline (persistence-owned copies). */
|
|
39
|
+
buffered = [];
|
|
40
|
+
batchTimer;
|
|
41
|
+
/** Set when a drain failed; the automatic timer stays quiet until the next drain. */
|
|
42
|
+
drainPaused = false;
|
|
43
|
+
draining;
|
|
44
|
+
constructor(storage, id, header, access, state, lease) {
|
|
45
|
+
this.storage = storage;
|
|
46
|
+
this.id = id;
|
|
47
|
+
this.header = header;
|
|
48
|
+
this.access = access;
|
|
49
|
+
this.state = state;
|
|
50
|
+
this.lease = lease;
|
|
51
|
+
}
|
|
52
|
+
/** Exact fork-inherited prefix length stored with this session's log. */
|
|
53
|
+
get inheritedEventCount() {
|
|
54
|
+
return this.state.inheritedEventCount;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Read a slice of the valid contiguous logical log; see the seam contract.
|
|
58
|
+
* @param offset - first logical seq to include (default 0).
|
|
59
|
+
* @param length - maximum events returned (default: the rest).
|
|
60
|
+
* @param options - optional cancellation.
|
|
61
|
+
* @returns a slice carrying the aliasing state established by its producer.
|
|
62
|
+
*/
|
|
63
|
+
async read(offset = 0, length = Number.MAX_SAFE_INTEGER, options) {
|
|
64
|
+
this.assertOpen("read");
|
|
65
|
+
if (!Number.isSafeInteger(offset) || offset < 0) throw new TypeError(`read offset must be a non-negative safe integer, got ${String(offset)}`);
|
|
66
|
+
if (!Number.isSafeInteger(length) || length < 0) throw new TypeError(`read length must be a non-negative safe integer, got ${String(length)}`);
|
|
67
|
+
options?.signal?.throwIfAborted();
|
|
68
|
+
let result;
|
|
69
|
+
const primed = this.state.primed;
|
|
70
|
+
if (primed !== void 0) if (this.access === "write") result = this.readPrimed(primed, offset, length);
|
|
71
|
+
else {
|
|
72
|
+
const currentPath = await this.storage.resolveCurrentLog(this.id, options?.signal);
|
|
73
|
+
if (currentPath === void 0) result = this.readPrimed(primed, offset, length);
|
|
74
|
+
else {
|
|
75
|
+
this.state.primed = void 0;
|
|
76
|
+
result = await this.readCurrent(currentPath, offset, length, options?.signal);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
else if (this.access === "write" && !this.state.materialized) result = {
|
|
80
|
+
eventState: "detached",
|
|
81
|
+
events: []
|
|
82
|
+
};
|
|
83
|
+
else {
|
|
84
|
+
const currentPath = await this.storage.resolveCurrentLog(this.id, options?.signal);
|
|
85
|
+
if (currentPath !== void 0) result = await this.readCurrent(currentPath, offset, length, options?.signal);
|
|
86
|
+
else if (this.storage.hasPendingSession(this.id)) result = {
|
|
87
|
+
eventState: "detached",
|
|
88
|
+
events: []
|
|
89
|
+
};
|
|
90
|
+
else throw new SessionPersistenceNotFoundError(this.id);
|
|
91
|
+
}
|
|
92
|
+
return result;
|
|
93
|
+
}
|
|
94
|
+
/** Read one slice from the prepared historical prefix retained by this handle. */
|
|
95
|
+
readPrimed(source, offset, length) {
|
|
96
|
+
this.observedLength = Math.max(this.observedLength, source.events.length);
|
|
97
|
+
return {
|
|
98
|
+
eventState: source.eventState,
|
|
99
|
+
events: source.events.slice(offset, offset + length)
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
/** Read one current physical generation and enforce this handle's monotonic view. */
|
|
103
|
+
async readCurrent(path, offset, length, signal) {
|
|
104
|
+
const source = await this.storage.readStoredLog(path, this.id, signal);
|
|
105
|
+
if (source.events.length < this.observedLength) throw new Error(`session "${this.id}": stored log shrank below a previously observed prefix (${source.events.length} < ${this.observedLength})`);
|
|
106
|
+
this.observedLength = source.events.length;
|
|
107
|
+
return {
|
|
108
|
+
eventState: source.eventState,
|
|
109
|
+
events: source.events.slice(offset, offset + length)
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Durably append a contiguous batch; see the seam contract.
|
|
114
|
+
* @param events - the contiguous batch in seq order.
|
|
115
|
+
* @param options - optional cancellation observed before the write starts.
|
|
116
|
+
*/
|
|
117
|
+
async append(events, options) {
|
|
118
|
+
this.assertOpen("append");
|
|
119
|
+
const batch = materializeAppendBatch(events);
|
|
120
|
+
return this.run("append", async () => {
|
|
121
|
+
options?.signal?.throwIfAborted();
|
|
122
|
+
await this.persistContiguous(batch);
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Durability barrier; materializes the artifact when nothing has been
|
|
127
|
+
* appended yet, so an explicitly flushed empty session survives this process.
|
|
128
|
+
* @param options - optional cancellation observed before the barrier starts.
|
|
129
|
+
*/
|
|
130
|
+
flush(options) {
|
|
131
|
+
return this.run("flush", async () => {
|
|
132
|
+
options?.signal?.throwIfAborted();
|
|
133
|
+
if (this.access !== "write") throw new SessionReadOnlyError(this.id, "flush");
|
|
134
|
+
if (this.state.materialized) return;
|
|
135
|
+
await this.ensureLease();
|
|
136
|
+
await this.storage.persistHeader(this.header, this.state.inheritedEventCount);
|
|
137
|
+
this.state.materialized = true;
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Release the handle; see the seam contract. Idempotent and uncancellable.
|
|
142
|
+
* A write handle first drains its routed live buffer through the still-open
|
|
143
|
+
* storage, so backend teardown loses nothing regardless of which fiber
|
|
144
|
+
* unwinds first; a drain or lock-release failure still frees the in-process
|
|
145
|
+
* claim, then rejects — both failures together reject as one
|
|
146
|
+
* `AggregateError`.
|
|
147
|
+
* @returns settlement of the release.
|
|
148
|
+
*/
|
|
149
|
+
close() {
|
|
150
|
+
return this.closing ??= (async () => {
|
|
151
|
+
let drainFailure;
|
|
152
|
+
for (;;) {
|
|
153
|
+
try {
|
|
154
|
+
await this.drainLive();
|
|
155
|
+
} catch (error) {
|
|
156
|
+
drainFailure = error;
|
|
157
|
+
break;
|
|
158
|
+
}
|
|
159
|
+
await this.chain;
|
|
160
|
+
if (this.buffered.length === 0) break;
|
|
161
|
+
}
|
|
162
|
+
await this.chain;
|
|
163
|
+
const failures = [];
|
|
164
|
+
if (drainFailure !== void 0) failures.push(drainFailure instanceof Error ? drainFailure : new Error(errorChain(drainFailure)));
|
|
165
|
+
try {
|
|
166
|
+
await this.lease?.release();
|
|
167
|
+
} catch (releaseFailure) {
|
|
168
|
+
/* v8 ignore next -- lock releases reject with Error */
|
|
169
|
+
failures.push(releaseFailure instanceof Error ? releaseFailure : new Error(errorChain(releaseFailure)));
|
|
170
|
+
}
|
|
171
|
+
this.storage.releaseHandle(this, this.state.materialized);
|
|
172
|
+
if (failures.length > 1) throw new AggregateError(failures, `session "${this.id}": close failed to drain and to release its write lock`);
|
|
173
|
+
if (failures[0] !== void 0) throw failures[0];
|
|
174
|
+
})();
|
|
175
|
+
}
|
|
176
|
+
/** `await using` support: delegates to {@link close}. */
|
|
177
|
+
[Symbol.asyncDispose]() {
|
|
178
|
+
return this.close();
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Buffer one published live session event and arm the bounded batching
|
|
182
|
+
* window when it is idle. The routing installer is the only caller.
|
|
183
|
+
* @param event - the live event, retained as a persistence-owned copy.
|
|
184
|
+
* @param reportBackgroundFailure - observes a deadline-driven drain failure
|
|
185
|
+
* (the events stay buffered; the next {@link drainLive} retries loudly).
|
|
186
|
+
*/
|
|
187
|
+
enqueueLive(event, reportBackgroundFailure) {
|
|
188
|
+
this.buffered.push(structuredClone(event));
|
|
189
|
+
if (this.batchTimer !== void 0 || this.drainPaused) return;
|
|
190
|
+
this.batchTimer = setTimeout(() => {
|
|
191
|
+
this.batchTimer = void 0;
|
|
192
|
+
this.drainLive().catch(reportBackgroundFailure);
|
|
193
|
+
}, 200);
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Durably drain the routed live buffer through the mutation chain;
|
|
197
|
+
* concurrent callers join one drain, and a failure retains the batch in
|
|
198
|
+
* order so `session/flush` can retry and reject loudly.
|
|
199
|
+
*/
|
|
200
|
+
drainLive() {
|
|
201
|
+
return this.draining ??= this.drainBuffered().finally(() => {
|
|
202
|
+
this.draining = void 0;
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
async drainBuffered() {
|
|
206
|
+
if (this.batchTimer !== void 0) {
|
|
207
|
+
clearTimeout(this.batchTimer);
|
|
208
|
+
this.batchTimer = void 0;
|
|
209
|
+
}
|
|
210
|
+
this.drainPaused = false;
|
|
211
|
+
while (this.buffered.length > 0) await this.enqueueChain(async () => {
|
|
212
|
+
const batch = this.buffered.splice(0);
|
|
213
|
+
try {
|
|
214
|
+
await this.persistContiguous(materializeAppendBatch(batch));
|
|
215
|
+
} catch (error) {
|
|
216
|
+
this.buffered = batch.concat(this.buffered);
|
|
217
|
+
this.drainPaused = true;
|
|
218
|
+
throw error;
|
|
219
|
+
}
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
/** The shared durable-append body: contiguity, ownership, torn-tail repair, storage write, state advance. */
|
|
223
|
+
async persistContiguous(batch) {
|
|
224
|
+
if (this.access !== "write") throw new SessionReadOnlyError(this.id, "append");
|
|
225
|
+
if (batch.length === 0) return;
|
|
226
|
+
await this.ensureLease();
|
|
227
|
+
assertContiguous(this.id, batch, this.state.cursor);
|
|
228
|
+
if (this.state.tornTruncateTo !== void 0) {
|
|
229
|
+
await this.storage.truncateTornTail(this.header, this.state.tornTruncateTo);
|
|
230
|
+
this.state.tornTruncateTo = void 0;
|
|
231
|
+
}
|
|
232
|
+
if (this.state.recoveredTail !== void 0) {
|
|
233
|
+
if (this.state.recoveredTail.length > 0) await this.storage.persistBatch(this.header, this.state.recoveredTail, this.state.materialized, this.state.inheritedEventCount);
|
|
234
|
+
this.state.recoveredTail = void 0;
|
|
235
|
+
}
|
|
236
|
+
await this.storage.persistBatch(this.header, batch, this.state.materialized, this.state.inheritedEventCount);
|
|
237
|
+
this.state.materialized = true;
|
|
238
|
+
this.state.cursor += batch.length;
|
|
239
|
+
this.state.primed = void 0;
|
|
240
|
+
this.observedLength = this.state.cursor;
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Hold the cross-process write lock before this session's first durable
|
|
244
|
+
* write. An open write handle holds it from construction; a create handle
|
|
245
|
+
* acquires it here — immediately before the first log bytes publish — and
|
|
246
|
+
* keeps it through close even when materialization then fails, so a
|
|
247
|
+
* materializing session stays exclusively owned across retries.
|
|
248
|
+
*/
|
|
249
|
+
async ensureLease() {
|
|
250
|
+
this.lease ??= await this.storage.acquireWriteLease(this.header);
|
|
251
|
+
}
|
|
252
|
+
/** Serialize one operation onto the chain without the closed-handle refusal (drain-from-close). */
|
|
253
|
+
enqueueChain(op) {
|
|
254
|
+
const next = this.chain.then(op);
|
|
255
|
+
this.chain = next.catch(() => {});
|
|
256
|
+
return next;
|
|
257
|
+
}
|
|
258
|
+
/** Serialize one public mutating operation onto this handle's chain. */
|
|
259
|
+
async run(operation, op) {
|
|
260
|
+
this.assertOpen(operation);
|
|
261
|
+
return this.enqueueChain(async () => {
|
|
262
|
+
this.assertOpen(operation);
|
|
263
|
+
return op();
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
assertOpen(operation) {
|
|
267
|
+
if (this.closing !== void 0) throw new SessionHandleClosedError(this.id, operation);
|
|
268
|
+
}
|
|
269
|
+
};
|
|
270
|
+
/**
|
|
271
|
+
* The JSONL backend's in-process bookkeeping: the single active writer per
|
|
272
|
+
* session id (doubling as the live event router), the open-handle set the
|
|
273
|
+
* teardown sweep closes, and the created-but-unmaterialized sessions this
|
|
274
|
+
* process can already observe.
|
|
275
|
+
*/
|
|
276
|
+
var JsonlBackendTracker = class {
|
|
277
|
+
name;
|
|
278
|
+
/** Every open handle; teardown closes what remains. */
|
|
279
|
+
openHandles = /* @__PURE__ */ new Set();
|
|
280
|
+
/** `null` marks a claim whose handle is still being constructed. */
|
|
281
|
+
writers = /* @__PURE__ */ new Map();
|
|
282
|
+
pending = /* @__PURE__ */ new Map();
|
|
283
|
+
counter = 0;
|
|
284
|
+
/** @param name - backend label used in in-memory revision tokens and teardown errors. */
|
|
285
|
+
constructor(name) {
|
|
286
|
+
this.name = name;
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Claim write ownership and record the created session as pending, making
|
|
290
|
+
* it observable to this process before it materializes. Before
|
|
291
|
+
* materialization this registration is the only guard — session ids do not
|
|
292
|
+
* collide across processes, and no durable artifact exists for another
|
|
293
|
+
* process to open; the handle takes the cross-process lock at its first
|
|
294
|
+
* materializing write.
|
|
295
|
+
* @param header - the validated detached header.
|
|
296
|
+
* @param inheritedEventCount - the exact fork-inherited prefix length.
|
|
297
|
+
* @throws {SessionAlreadyExistsError} when a concurrent create or an open
|
|
298
|
+
* write handle holds the id — for create, the duplicate is the fact.
|
|
299
|
+
*/
|
|
300
|
+
registerCreated(header, inheritedEventCount) {
|
|
301
|
+
if (this.writers.has(header.id)) throw new SessionAlreadyExistsError(header.id);
|
|
302
|
+
this.writers.set(header.id, null);
|
|
303
|
+
this.pending.set(header.id, {
|
|
304
|
+
header,
|
|
305
|
+
revision: SessionPersistenceRevision(`memory:${this.name}:${++this.counter}`),
|
|
306
|
+
inheritedEventCount
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
/**
|
|
310
|
+
* Claim write ownership for an existing session.
|
|
311
|
+
* @param id - the session to claim.
|
|
312
|
+
* @throws {SessionAlreadyOwnedError} when an active write handle exists.
|
|
313
|
+
*/
|
|
314
|
+
claimWrite(id) {
|
|
315
|
+
if (this.writers.has(id)) throw new SessionAlreadyOwnedError(id);
|
|
316
|
+
this.writers.set(id, null);
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* Roll a failed write open back.
|
|
320
|
+
* @param id - the session whose claim is dropped.
|
|
321
|
+
*/
|
|
322
|
+
releaseClaim(id) {
|
|
323
|
+
this.writers.delete(id);
|
|
324
|
+
}
|
|
325
|
+
/**
|
|
326
|
+
* The pending entry for a created-but-unmaterialized session, if any.
|
|
327
|
+
* @param id - the session to look up.
|
|
328
|
+
* @returns the pending header and in-memory revision.
|
|
329
|
+
*/
|
|
330
|
+
pendingOf(id) {
|
|
331
|
+
return this.pending.get(id);
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
334
|
+
* Whether this process still tracks a created-but-unmaterialized session.
|
|
335
|
+
* @param id - the session to test.
|
|
336
|
+
* @returns true while the pending entry exists.
|
|
337
|
+
*/
|
|
338
|
+
hasPending(id) {
|
|
339
|
+
return this.pending.has(id);
|
|
340
|
+
}
|
|
341
|
+
/**
|
|
342
|
+
* Iterate the pending sessions for listing.
|
|
343
|
+
* @returns the pending entries, keyed by session id.
|
|
344
|
+
*/
|
|
345
|
+
pendingEntries() {
|
|
346
|
+
return this.pending.entries();
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* Drop a pending entry once the session materialized durably.
|
|
350
|
+
* @param id - the session that reached durable storage.
|
|
351
|
+
*/
|
|
352
|
+
materialized(id) {
|
|
353
|
+
this.pending.delete(id);
|
|
354
|
+
}
|
|
355
|
+
/**
|
|
356
|
+
* Track one open handle for teardown and, for a write handle, bind it as
|
|
357
|
+
* the session's live event route.
|
|
358
|
+
* @param handle - the just-constructed handle.
|
|
359
|
+
* @returns the same handle, for construction-site chaining.
|
|
360
|
+
*/
|
|
361
|
+
adopt(handle) {
|
|
362
|
+
this.openHandles.add(handle);
|
|
363
|
+
if (handle.access === "write") this.writers.set(handle.id, handle);
|
|
364
|
+
return handle;
|
|
365
|
+
}
|
|
366
|
+
/**
|
|
367
|
+
* Release one handle's bookkeeping on close. A write handle drops its
|
|
368
|
+
* ownership claim; a creator that never materialized leaves nothing behind —
|
|
369
|
+
* the session never existed.
|
|
370
|
+
* @param handle - the closing handle.
|
|
371
|
+
* @param materialized - whether the session reached durable storage.
|
|
372
|
+
*/
|
|
373
|
+
release(handle, materialized) {
|
|
374
|
+
this.openHandles.delete(handle);
|
|
375
|
+
if (handle.access !== "write") return;
|
|
376
|
+
this.writers.delete(handle.id);
|
|
377
|
+
if (!materialized) this.pending.delete(handle.id);
|
|
378
|
+
}
|
|
379
|
+
/**
|
|
380
|
+
* Drain and flush every active write handle — the service-wide durability
|
|
381
|
+
* barrier behind `SessionPersistence.flush`.
|
|
382
|
+
* @throws {AggregateError} naming each session whose flush failed; the
|
|
383
|
+
* remaining handles still flush.
|
|
384
|
+
*/
|
|
385
|
+
async flushAll() {
|
|
386
|
+
const errors = [];
|
|
387
|
+
for (const writer of [...this.writers.values()]) {
|
|
388
|
+
if (writer === null) continue;
|
|
389
|
+
try {
|
|
390
|
+
await writer.drainLive();
|
|
391
|
+
await writer.flush();
|
|
392
|
+
} catch (error) {
|
|
393
|
+
if (error instanceof SessionHandleClosedError) continue;
|
|
394
|
+
errors.push(error);
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
if (errors.length > 0) throw new AggregateError(errors, `${this.name} flush failed`);
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* Install the backend's live session routing and teardown. Persistence
|
|
401
|
+
* enforces one active write handle per id, so the listeners route published
|
|
402
|
+
* sessions' events by id; the teardown effect closes every open handle —
|
|
403
|
+
* close drains the routed buffer — and aggregates failures. This provider
|
|
404
|
+
* owns no separate storage connection, so closing handles is the complete
|
|
405
|
+
* teardown. The returned effect removes listeners before closing handles.
|
|
406
|
+
* @param ctx - the backend's resource-owning context.
|
|
407
|
+
* @returns the disposer to run after persistence consumers finish unloading.
|
|
408
|
+
*/
|
|
409
|
+
install(ctx) {
|
|
410
|
+
const { writers, openHandles, name } = this;
|
|
411
|
+
return ctx.effect(function* () {
|
|
412
|
+
yield async () => {
|
|
413
|
+
const errors = [];
|
|
414
|
+
for (const handle of [...openHandles]) try {
|
|
415
|
+
await handle.close();
|
|
416
|
+
} catch (error) {
|
|
417
|
+
errors.push(error);
|
|
418
|
+
}
|
|
419
|
+
if (errors.length > 0) throw new AggregateError(errors, `${name} dispose failed`);
|
|
420
|
+
};
|
|
421
|
+
yield ctx.on("session/event", (session, event) => {
|
|
422
|
+
writers.get(session.id)?.enqueueLive(event, (error) => {
|
|
423
|
+
ctx.logger.warn(`session-persistence: background write for session "${session.id}" failed (buffered events retained): ${String(error)}`);
|
|
424
|
+
});
|
|
425
|
+
});
|
|
426
|
+
yield ctx.on("session/flush", (session) => {
|
|
427
|
+
const writer = writers.get(session.id);
|
|
428
|
+
if (writer === null || writer === void 0) return void 0;
|
|
429
|
+
return (async () => {
|
|
430
|
+
await writer.drainLive();
|
|
431
|
+
await writer.flush();
|
|
432
|
+
})();
|
|
433
|
+
});
|
|
434
|
+
yield ctx.on("session/disposed", (session) => {
|
|
435
|
+
const writer = writers.get(session.id);
|
|
436
|
+
if (writer === null || writer === void 0) return;
|
|
437
|
+
writer.close().catch((error) => {
|
|
438
|
+
ctx.logger.warn(`session-persistence: final drain for session "${session.id}" failed: ${String(error)}`);
|
|
439
|
+
});
|
|
440
|
+
});
|
|
441
|
+
}, `${this.name} live routing and open handles`);
|
|
442
|
+
}
|
|
443
|
+
};
|
|
444
|
+
//#endregion
|
|
445
|
+
//#region lib/types/win32.js
|
|
446
|
+
/**
|
|
447
|
+
* Windows durable namespace helpers for the JSONL backend.
|
|
448
|
+
*
|
|
449
|
+
* POSIX publishes a newly-created log by creating a directory entry and then
|
|
450
|
+
* fsyncing the parent directory. Windows does not expose that parent-directory
|
|
451
|
+
* fsync contract through Node, so the Windows path uses the native durable
|
|
452
|
+
* namespace primitive instead: create a staging object in the target directory
|
|
453
|
+
* and publish it with `MoveFileExW(..., MOVEFILE_WRITE_THROUGH)` without
|
|
454
|
+
* replacement or cross-volume copy fallback.
|
|
455
|
+
*
|
|
456
|
+
* @module rabi-session-persistence-jsonl/win32
|
|
457
|
+
*/
|
|
458
|
+
const MOVEFILE_WRITE_THROUGH = 8;
|
|
459
|
+
const WAIT_OBJECT_0 = 0;
|
|
460
|
+
const WAIT_TIMEOUT = 258;
|
|
461
|
+
const ERROR_FILE_NOT_FOUND = 2;
|
|
462
|
+
const ERROR_PATH_NOT_FOUND = 3;
|
|
463
|
+
const ERROR_ACCESS_DENIED = 5;
|
|
464
|
+
const ERROR_NOT_SAME_DEVICE = 17;
|
|
465
|
+
const ERROR_SHARING_VIOLATION = 32;
|
|
466
|
+
const ERROR_FILE_EXISTS = 80;
|
|
467
|
+
const ERROR_INVALID_NAME = 123;
|
|
468
|
+
const ERROR_ALREADY_EXISTS = 183;
|
|
469
|
+
let bindings;
|
|
470
|
+
/** Load the small Win32 API lazily so non-Windows processes never load Koffi. */
|
|
471
|
+
async function win32() {
|
|
472
|
+
if (bindings !== void 0) return bindings;
|
|
473
|
+
const kernel32 = (await import("koffi")).default.load("kernel32.dll");
|
|
474
|
+
bindings = {
|
|
475
|
+
moveFileExW: kernel32.func("__stdcall", "MoveFileExW", "int", [
|
|
476
|
+
"str16",
|
|
477
|
+
"str16",
|
|
478
|
+
"uint"
|
|
479
|
+
]),
|
|
480
|
+
createSemaphoreW: kernel32.func("__stdcall", "CreateSemaphoreW", "intptr", [
|
|
481
|
+
"void*",
|
|
482
|
+
"int",
|
|
483
|
+
"int",
|
|
484
|
+
"str16"
|
|
485
|
+
]),
|
|
486
|
+
waitForSingleObject: kernel32.func("__stdcall", "WaitForSingleObject", "uint", ["intptr", "uint"]),
|
|
487
|
+
releaseSemaphore: kernel32.func("__stdcall", "ReleaseSemaphore", "int", [
|
|
488
|
+
"intptr",
|
|
489
|
+
"int",
|
|
490
|
+
"void*"
|
|
491
|
+
]),
|
|
492
|
+
closeHandle: kernel32.func("__stdcall", "CloseHandle", "int", ["intptr"]),
|
|
493
|
+
getLastError: kernel32.func("__stdcall", "GetLastError", "uint", [])
|
|
494
|
+
};
|
|
495
|
+
return bindings;
|
|
496
|
+
}
|
|
497
|
+
function errnoCode(win32Code) {
|
|
498
|
+
switch (win32Code) {
|
|
499
|
+
case ERROR_FILE_NOT_FOUND:
|
|
500
|
+
case ERROR_PATH_NOT_FOUND: return "ENOENT";
|
|
501
|
+
case ERROR_ACCESS_DENIED: return "EACCES";
|
|
502
|
+
case ERROR_NOT_SAME_DEVICE: return "EXDEV";
|
|
503
|
+
case ERROR_SHARING_VIOLATION: return "EBUSY";
|
|
504
|
+
case ERROR_FILE_EXISTS:
|
|
505
|
+
case ERROR_ALREADY_EXISTS: return "EEXIST";
|
|
506
|
+
case ERROR_INVALID_NAME: return "EINVAL";
|
|
507
|
+
default: return "EIO";
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
function win32Error(syscall, win32Code, path, dest) {
|
|
511
|
+
const code = errnoCode(win32Code);
|
|
512
|
+
const error = /* @__PURE__ */ new Error(`${syscall} ${code} (Win32 ${win32Code}): ${path} -> ${dest}`);
|
|
513
|
+
error.code = code;
|
|
514
|
+
error.errno = win32Code;
|
|
515
|
+
error.syscall = syscall;
|
|
516
|
+
error.path = path;
|
|
517
|
+
error.dest = dest;
|
|
518
|
+
error.win32Code = win32Code;
|
|
519
|
+
return error;
|
|
520
|
+
}
|
|
521
|
+
function isENOENT$1(error) {
|
|
522
|
+
return error?.code === "ENOENT";
|
|
523
|
+
}
|
|
524
|
+
function isEEXIST$1(error) {
|
|
525
|
+
return error?.code === "EEXIST";
|
|
526
|
+
}
|
|
527
|
+
async function assertDirectory(path) {
|
|
528
|
+
try {
|
|
529
|
+
if ((await stat(path === parse(path).root ? path : toNamespacedPath(path))).isDirectory()) return true;
|
|
530
|
+
const error = /* @__PURE__ */ new Error(`path exists but is not a directory: ${path}`);
|
|
531
|
+
error.code = "ENOTDIR";
|
|
532
|
+
error.path = path;
|
|
533
|
+
throw error;
|
|
534
|
+
} catch (error) {
|
|
535
|
+
if (isENOENT$1(error)) return false;
|
|
536
|
+
throw error;
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
/**
|
|
540
|
+
* Publish `existing` at `replacement` with Windows write-through rename
|
|
541
|
+
* semantics. The destination must not already exist; the move must stay within
|
|
542
|
+
* the volume (no copy fallback flag is set).
|
|
543
|
+
* @param existing - the synced staging path to move.
|
|
544
|
+
* @param replacement - the final path, which must not already exist.
|
|
545
|
+
*/
|
|
546
|
+
async function publishNewFileWin32(existing, replacement) {
|
|
547
|
+
const api = await win32();
|
|
548
|
+
if (api.moveFileExW(toNamespacedPath(existing), toNamespacedPath(replacement), MOVEFILE_WRITE_THROUGH) === 0) throw win32Error("MoveFileExW", api.getLastError(), existing, replacement);
|
|
549
|
+
}
|
|
550
|
+
/**
|
|
551
|
+
* Acquire the session write lock as a named kernel semaphore (count 1) whose
|
|
552
|
+
* name is derived from the canonical lock path. A kernel object never touches
|
|
553
|
+
* the filesystem, so readers, searches, and directory removal proceed freely
|
|
554
|
+
* while the lock is held; a second acquirer's zero-timeout wait times out
|
|
555
|
+
* (`EBUSY`); and when the last handle closes — including on any process
|
|
556
|
+
* death — the object is destroyed, so a successor's create starts fresh.
|
|
557
|
+
* @param path - the lock file path the name is derived from (case-folded:
|
|
558
|
+
* Windows paths are case-insensitive).
|
|
559
|
+
* @returns the open semaphore handle, released via {@link releaseLockHandleWin32}.
|
|
560
|
+
*/
|
|
561
|
+
async function acquireLockHandleWin32(path) {
|
|
562
|
+
const api = await win32();
|
|
563
|
+
const name = `Local\\rabi-session-lock-${createHash("sha256").update(resolve(path).toLowerCase()).digest("hex")}`;
|
|
564
|
+
const handle = api.createSemaphoreW(null, 1, 1, name);
|
|
565
|
+
if (handle === 0) throw win32Error("CreateSemaphoreW", api.getLastError(), path, name);
|
|
566
|
+
const wait = api.waitForSingleObject(handle, 0);
|
|
567
|
+
if (wait === WAIT_OBJECT_0) return handle;
|
|
568
|
+
api.closeHandle(handle);
|
|
569
|
+
if (wait === WAIT_TIMEOUT) throw win32Error("WaitForSingleObject", ERROR_SHARING_VIOLATION, path, name);
|
|
570
|
+
throw win32Error("WaitForSingleObject", api.getLastError(), path, name);
|
|
571
|
+
}
|
|
572
|
+
/**
|
|
573
|
+
* Release a lock from {@link acquireLockHandleWin32}: restore the semaphore
|
|
574
|
+
* count and close the handle (the object dies with its last handle).
|
|
575
|
+
* @param handle - the open semaphore handle.
|
|
576
|
+
*/
|
|
577
|
+
async function releaseLockHandleWin32(handle) {
|
|
578
|
+
const api = await win32();
|
|
579
|
+
const released = api.releaseSemaphore(handle, 1, null);
|
|
580
|
+
const closed = api.closeHandle(handle);
|
|
581
|
+
if (released === 0 || closed === 0) throw win32Error("ReleaseSemaphore", api.getLastError(), `handle:${handle}`, `handle:${handle}`);
|
|
582
|
+
}
|
|
583
|
+
/**
|
|
584
|
+
* Create `target` and its missing ancestors with durable Windows namespace
|
|
585
|
+
* publication. Each missing directory is first created as a random staging
|
|
586
|
+
* sibling, then moved to its final name with `MOVEFILE_WRITE_THROUGH`; races
|
|
587
|
+
* with another creator are accepted only after verifying the winner is a
|
|
588
|
+
* directory.
|
|
589
|
+
* @param target - the absolute directory path to create durably when absent.
|
|
590
|
+
*/
|
|
591
|
+
async function ensureDurableDirectoryWin32(target) {
|
|
592
|
+
const absolute = resolve(target);
|
|
593
|
+
const root = parse(absolute).root;
|
|
594
|
+
await assertDirectory(root);
|
|
595
|
+
const segments = absolute.slice(root.length).split(/[\\/]+/).filter((part) => part.length > 0);
|
|
596
|
+
let current = root;
|
|
597
|
+
for (const segment of segments) {
|
|
598
|
+
const next = join(current, segment);
|
|
599
|
+
if (!await assertDirectory(next)) await createLeafDirectoryWin32(current, next);
|
|
600
|
+
current = next;
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
async function createLeafDirectoryWin32(parent, target) {
|
|
604
|
+
const staging = await mkdtemp(toNamespacedPath(join(parent, ".rabi-mkdir-")));
|
|
605
|
+
try {
|
|
606
|
+
await publishNewFileWin32(staging, target);
|
|
607
|
+
} catch (error) {
|
|
608
|
+
await rm(staging, {
|
|
609
|
+
recursive: true,
|
|
610
|
+
force: true
|
|
611
|
+
});
|
|
612
|
+
if (isEEXIST$1(error) && await assertDirectory(target)) return;
|
|
613
|
+
throw error;
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
//#endregion
|
|
617
|
+
//#region lib/types/lease.js
|
|
618
|
+
/**
|
|
619
|
+
* Cross-process write-ownership lock for one session's artifact directory,
|
|
620
|
+
* held for the whole life of a write handle. The arbiter is the kernel:
|
|
621
|
+
* POSIX takes a non-blocking `flock(2)` via native system support on `session.lock`
|
|
622
|
+
* beside the log, and Windows holds a named kernel semaphore derived from
|
|
623
|
+
* that path — never a file lock or handle, so readers, searches, and
|
|
624
|
+
* directory removal proceed freely while the lock is held. Contention maps
|
|
625
|
+
* to `SessionAlreadyOwnedError`; the kernel releases the lock when the
|
|
626
|
+
* holder's descriptor or last object handle closes, including on any process
|
|
627
|
+
* death, so a crashed holder never blocks a successor. A live but wedged
|
|
628
|
+
* holder keeps the lock until its process exits: there is deliberately no
|
|
629
|
+
* expiry that could expropriate a stalled writer whose resumed appends would
|
|
630
|
+
* tear the log.
|
|
631
|
+
* A POSIX lock names an inode, not a path, so after locking the holder
|
|
632
|
+
* verifies the locked inode is still the file at the lock path and retries
|
|
633
|
+
* otherwise: an unlinked-and-recreated lock file carries a fresh inode, and
|
|
634
|
+
* a lock on the orphaned one proves nothing. Removing a live session's lock
|
|
635
|
+
* file therefore forfeits exclusion on POSIX (nothing in the harness does
|
|
636
|
+
* so); Windows has no lock file at all. Readers never touch the lock.
|
|
637
|
+
* The lock is acquired at write-open of an existing artifact and, for a
|
|
638
|
+
* created session, only right before its first materializing write — an
|
|
639
|
+
* unmaterialized session has no filesystem footprint. Release never removes
|
|
640
|
+
* the POSIX lock file: every acquired lock belongs to a materialized or
|
|
641
|
+
* materializing session, and the surviving file keeps the stable inode later
|
|
642
|
+
* lockers verify against. The browser worker stubs the native flock entry to
|
|
643
|
+
* immediate success: it is single-process, so the in-process write claim
|
|
644
|
+
* already excludes every writer.
|
|
645
|
+
* @module @unieai/rabi-session-persistence-jsonl/lease
|
|
646
|
+
*/
|
|
647
|
+
/** Base name of the kernel lock file inside a session's directory. */
|
|
648
|
+
const LEASE_FILENAME = "session.lock";
|
|
649
|
+
/** Whether a flock failure means another descriptor holds the lock. */
|
|
650
|
+
function isLockContention(error) {
|
|
651
|
+
const code = error?.code;
|
|
652
|
+
return code === "EAGAIN" || code === "EWOULDBLOCK";
|
|
653
|
+
}
|
|
654
|
+
/**
|
|
655
|
+
* One held write lock. Constructed only by {@link SessionWriteLease.acquire};
|
|
656
|
+
* `release` closes the descriptor or handle, which is what releases the lock.
|
|
657
|
+
*/
|
|
658
|
+
var SessionWriteLease = class SessionWriteLease {
|
|
659
|
+
held;
|
|
660
|
+
released = false;
|
|
661
|
+
constructor(held) {
|
|
662
|
+
this.held = held;
|
|
663
|
+
}
|
|
664
|
+
/**
|
|
665
|
+
* Acquire the session directory's kernel write lock.
|
|
666
|
+
* @param dir - the session's artifact directory (created if absent).
|
|
667
|
+
* @param id - the session the lock guards, for error identities.
|
|
668
|
+
* @returns the held lock.
|
|
669
|
+
* @throws {SessionAlreadyOwnedError} while another holder keeps the lock.
|
|
670
|
+
*/
|
|
671
|
+
static async acquire(dir, id) {
|
|
672
|
+
const path = join(dir, LEASE_FILENAME);
|
|
673
|
+
await mkdir(dir, {
|
|
674
|
+
recursive: true,
|
|
675
|
+
mode: 448
|
|
676
|
+
});
|
|
677
|
+
/* v8 ignore start -- native Windows coverage exercises this platform branch; Linux covers the POSIX peer */
|
|
678
|
+
if (process.platform === "win32") {
|
|
679
|
+
let handle;
|
|
680
|
+
try {
|
|
681
|
+
handle = await acquireLockHandleWin32(path);
|
|
682
|
+
} catch (error) {
|
|
683
|
+
if (error?.code === "EBUSY") throw new SessionAlreadyOwnedError(id);
|
|
684
|
+
throw error;
|
|
685
|
+
}
|
|
686
|
+
return new SessionWriteLease({
|
|
687
|
+
kind: "win32",
|
|
688
|
+
handle
|
|
689
|
+
});
|
|
690
|
+
}
|
|
691
|
+
/* v8 ignore stop */
|
|
692
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
693
|
+
const handle = await open(path, "w");
|
|
694
|
+
try {
|
|
695
|
+
try {
|
|
696
|
+
await tryLockExclusive(handle.fd);
|
|
697
|
+
} catch (error) {
|
|
698
|
+
if (isLockContention(error)) throw new SessionAlreadyOwnedError(id);
|
|
699
|
+
throw error;
|
|
700
|
+
}
|
|
701
|
+
const held = await handle.stat({ bigint: true });
|
|
702
|
+
const current = await stat(path, { bigint: true }).catch((error) => {
|
|
703
|
+
if (error?.code === "ENOENT") return void 0;
|
|
704
|
+
throw error;
|
|
705
|
+
});
|
|
706
|
+
if (current !== void 0 && current.ino === held.ino && current.dev === held.dev) return new SessionWriteLease({
|
|
707
|
+
kind: "posix",
|
|
708
|
+
handle
|
|
709
|
+
});
|
|
710
|
+
} catch (error) {
|
|
711
|
+
await handle.close();
|
|
712
|
+
throw error;
|
|
713
|
+
}
|
|
714
|
+
await handle.close();
|
|
715
|
+
}
|
|
716
|
+
throw new SessionAlreadyOwnedError(id);
|
|
717
|
+
}
|
|
718
|
+
/**
|
|
719
|
+
* Release the kernel lock by closing its descriptor or handle. The POSIX
|
|
720
|
+
* lock file is never removed: every acquired lock belongs to a
|
|
721
|
+
* materialized or materializing session, and keeping the file preserves
|
|
722
|
+
* the stable inode later lockers verify against. Idempotent.
|
|
723
|
+
*/
|
|
724
|
+
async release() {
|
|
725
|
+
if (this.released) return;
|
|
726
|
+
this.released = true;
|
|
727
|
+
/* v8 ignore start -- native Windows coverage exercises this platform branch; Linux covers the POSIX peer */
|
|
728
|
+
if (this.held.kind === "win32") {
|
|
729
|
+
await releaseLockHandleWin32(this.held.handle);
|
|
730
|
+
return;
|
|
731
|
+
}
|
|
732
|
+
/* v8 ignore stop */
|
|
733
|
+
await this.held.handle.close();
|
|
734
|
+
}
|
|
735
|
+
};
|
|
736
|
+
//#endregion
|
|
737
|
+
//#region lib/types/format.js
|
|
738
|
+
/**
|
|
739
|
+
* On-disk format helpers for the JSONL session-persistence backend: path
|
|
740
|
+
* sanitization (a {@link SessionId} is an unvalidated branded string, so it
|
|
741
|
+
* MUST be encoded before use in a path — no traversal, no collision), the
|
|
742
|
+
* per-project/session directory layout, header-line (de)serialization, and the
|
|
743
|
+
* truncation-repair offset computation.
|
|
744
|
+
*
|
|
745
|
+
* @module rabi-session-persistence-jsonl/format
|
|
746
|
+
*/
|
|
747
|
+
/**
|
|
748
|
+
* Return the artifact suffix for one physical encoding.
|
|
749
|
+
* @param compression - configured JSONL artifact encoding.
|
|
750
|
+
* @returns `.jsonl.zstd` for Zstandard or `.jsonl` for plaintext.
|
|
751
|
+
*/
|
|
752
|
+
function logSuffix(compression) {
|
|
753
|
+
return `.jsonl${compressionSuffix(compression)}`;
|
|
754
|
+
}
|
|
755
|
+
function compressionSuffix(compression) {
|
|
756
|
+
return compression === "zstd" ? ".zstd" : "";
|
|
757
|
+
}
|
|
758
|
+
/**
|
|
759
|
+
* Return the canonical filename for one immutable Session format generation.
|
|
760
|
+
* Version zero retains the original suffix-only name; every later generation
|
|
761
|
+
* carries a lowercase numeric `vN` component.
|
|
762
|
+
* @param version - non-negative safe Session format version.
|
|
763
|
+
* @param compression - configured JSONL artifact encoding.
|
|
764
|
+
* @returns the generation filename inside one Session directory.
|
|
765
|
+
*/
|
|
766
|
+
function generationLogFilename(version, compression) {
|
|
767
|
+
return `${sessionFormatLogFilename(version)}${compressionSuffix(compression)}`;
|
|
768
|
+
}
|
|
769
|
+
/**
|
|
770
|
+
* Parse one canonical generation filename for the selected physical encoding.
|
|
771
|
+
* Noncanonical, temporary, uppercase, leading-zero, and version-zero-tagged names do
|
|
772
|
+
* not identify committed generations.
|
|
773
|
+
* @param filename - one entry from a Session directory.
|
|
774
|
+
* @param compression - configured JSONL artifact encoding.
|
|
775
|
+
* @returns its format version, or `undefined` when the name is not canonical.
|
|
776
|
+
*/
|
|
777
|
+
function parseGenerationLogFilename(filename, compression) {
|
|
778
|
+
const suffix = compressionSuffix(compression);
|
|
779
|
+
if (!filename.endsWith(suffix)) return void 0;
|
|
780
|
+
return parseSessionFormatLogFilename(filename.slice(0, filename.length - suffix.length));
|
|
781
|
+
}
|
|
782
|
+
const HEADER_REQUIRED_KEYS = [
|
|
783
|
+
"type",
|
|
784
|
+
"version",
|
|
785
|
+
"id",
|
|
786
|
+
"createdAt",
|
|
787
|
+
"isSeeded",
|
|
788
|
+
"delegationDepth"
|
|
789
|
+
];
|
|
790
|
+
const HEADER_OPTIONAL_KEYS = [
|
|
791
|
+
"cwd",
|
|
792
|
+
"parentSession",
|
|
793
|
+
"origin",
|
|
794
|
+
"agentPreset"
|
|
795
|
+
];
|
|
796
|
+
const HEADER_KEYS = new Set([...HEADER_REQUIRED_KEYS, ...HEADER_OPTIONAL_KEYS]);
|
|
797
|
+
/**
|
|
798
|
+
* Refuse policy fields that never belong to a released Session header.
|
|
799
|
+
* @param value - parsed physical header candidate.
|
|
800
|
+
* @returns nothing after successful validation.
|
|
801
|
+
*/
|
|
802
|
+
function assertNoRetiredHeaderFields(value) {
|
|
803
|
+
if (typeof value !== "object" || value === null) return;
|
|
804
|
+
if (Object.hasOwn(value, "sandboxMode") || Object.hasOwn(value, "approvalPolicy")) throw new Error("session header uses retired policy baseline fields");
|
|
805
|
+
}
|
|
806
|
+
/**
|
|
807
|
+
* Build the header line object from a {@link SessionHeader}.
|
|
808
|
+
* @param header - the immutable session metadata to serialize.
|
|
809
|
+
* @param inheritedEventCount - exact inherited prefix length; required for a
|
|
810
|
+
* seeded header and omitted only for an unseeded header.
|
|
811
|
+
* @returns the `type: 'session'`-tagged line object, absent optional fields omitted (never null).
|
|
812
|
+
*/
|
|
813
|
+
function toHeaderLine(header, inheritedEventCount) {
|
|
814
|
+
if (header.isSeeded && inheritedEventCount === void 0) throw new Error("seeded session header requires an inherited event count");
|
|
815
|
+
const cut = SessionLogOffset(inheritedEventCount ?? 0);
|
|
816
|
+
if (!header.isSeeded && cut !== 0) throw new Error("unseeded session header inherited event count must be 0");
|
|
817
|
+
return sessionFormatCatalog.encodeCurrentHeader({
|
|
818
|
+
...header,
|
|
819
|
+
delegationDepth: header.delegationDepth ?? 0
|
|
820
|
+
}, cut);
|
|
821
|
+
}
|
|
822
|
+
/**
|
|
823
|
+
* Translate one current physical header into logical metadata and its cut.
|
|
824
|
+
* @param line - the shape-checked first line of a log (see the `isHeaderLine` guard).
|
|
825
|
+
* @returns logical Session metadata paired with the exact inherited prefix length.
|
|
826
|
+
*/
|
|
827
|
+
function fromHeaderLine(line) {
|
|
828
|
+
return {
|
|
829
|
+
meta: {
|
|
830
|
+
version: SESSION_FORMAT_VERSION,
|
|
831
|
+
id: line.id,
|
|
832
|
+
createdAt: line.createdAt,
|
|
833
|
+
...line.cwd !== void 0 ? { cwd: line.cwd } : {},
|
|
834
|
+
...line.parentSession !== void 0 ? { parentSession: line.parentSession } : {},
|
|
835
|
+
isSeeded: line.isSeeded,
|
|
836
|
+
...line.origin !== void 0 ? { origin: line.origin } : {},
|
|
837
|
+
delegationDepth: line.delegationDepth,
|
|
838
|
+
...line.agentPreset !== void 0 ? { agentPreset: line.agentPreset } : {}
|
|
839
|
+
},
|
|
840
|
+
inheritedEventCount: SessionLogOffset(0)
|
|
841
|
+
};
|
|
842
|
+
}
|
|
843
|
+
/** Type guard: a parsed first line is a well-formed session header. */
|
|
844
|
+
function isHeaderLine(value) {
|
|
845
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) && HEADER_REQUIRED_KEYS.every((key) => Object.hasOwn(value, key)) && Object.keys(value).every((key) => HEADER_KEYS.has(key)) && value.type === "session" && typeof value.version === "number" && typeof value.id === "string" && typeof value.createdAt === "number" && Number.isSafeInteger(value.createdAt) && value.createdAt >= 0 && !Object.is(value.createdAt, -0) && typeof value.delegationDepth === "number" && Number.isSafeInteger(value.delegationDepth) && value.delegationDepth >= 0 && !Object.is(value.delegationDepth, -0) && (value.cwd === void 0 || typeof value.cwd === "string" && isAbsolute(value.cwd)) && (value.parentSession === void 0 || typeof value.parentSession === "string") && typeof value.isSeeded === "boolean" && (value.origin === void 0 || value.origin === "subagent") && (value.agentPreset === void 0 || typeof value.agentPreset === "string");
|
|
846
|
+
}
|
|
847
|
+
/**
|
|
848
|
+
* Encode an arbitrary string as a single safe path segment, injectively over ALL JS (UTF-16)
|
|
849
|
+
* strings — including lone surrogates. A {@link SessionId} is an unvalidated branded string,
|
|
850
|
+
* so this neutralizes `../`, absolute paths, NUL, and separators before any filesystem use.
|
|
851
|
+
* Safe code units remain literal; every other unit, including `~`, becomes
|
|
852
|
+
* `~XXXX`. Operating on code units preserves lone surrogates, while special-
|
|
853
|
+
* casing `.` and `..` prevents traversal by an otherwise safe whole segment.
|
|
854
|
+
*
|
|
855
|
+
* @param raw - the string to encode; must be non-empty (throws on `''`).
|
|
856
|
+
* @returns the escaped single path segment, decodable back to `raw`.
|
|
857
|
+
*/
|
|
858
|
+
function encodeSegment(raw) {
|
|
859
|
+
if (raw.length === 0) throw new Error("cannot encode an empty path segment");
|
|
860
|
+
if (raw === ".") return "~002E";
|
|
861
|
+
if (raw === "..") return "~002E~002E";
|
|
862
|
+
let out = "";
|
|
863
|
+
for (let i = 0; i < raw.length; i++) {
|
|
864
|
+
const code = raw.charCodeAt(i);
|
|
865
|
+
const ch = String.fromCharCode(code);
|
|
866
|
+
if (ch !== "~" && /^[A-Za-z0-9._-]$/.test(ch)) out += ch;
|
|
867
|
+
else out += "~" + code.toString(16).toUpperCase().padStart(4, "0");
|
|
868
|
+
}
|
|
869
|
+
return out;
|
|
870
|
+
}
|
|
871
|
+
/**
|
|
872
|
+
* Build the readable directory key for a project path.
|
|
873
|
+
* Filesystem separators and drive separators become `-`; unsafe code units use
|
|
874
|
+
* the same `~XXXX` escape as session ids. The key is bounded for filesystem
|
|
875
|
+
* component limits. Separator replacement and truncation are intentionally
|
|
876
|
+
* lossy, following the common human-navigable project-directory convention.
|
|
877
|
+
* @param cwd - the session's project directory.
|
|
878
|
+
* @returns a single filesystem-safe project directory name.
|
|
879
|
+
*/
|
|
880
|
+
function projectKey(cwd) {
|
|
881
|
+
if (cwd.length === 0) throw new Error("cannot encode an empty project path");
|
|
882
|
+
let readable = "";
|
|
883
|
+
let separatorRun = false;
|
|
884
|
+
for (let i = 0; i < cwd.length; i++) {
|
|
885
|
+
const code = cwd.charCodeAt(i);
|
|
886
|
+
const ch = String.fromCharCode(code);
|
|
887
|
+
if (ch === "/" || ch === "\\" || ch === ":") {
|
|
888
|
+
if (!separatorRun) readable += "-";
|
|
889
|
+
separatorRun = true;
|
|
890
|
+
} else if (ch !== "~" && /^[A-Za-z0-9._-]$/.test(ch)) {
|
|
891
|
+
readable += ch;
|
|
892
|
+
separatorRun = false;
|
|
893
|
+
} else {
|
|
894
|
+
readable += "~" + code.toString(16).toUpperCase().padStart(4, "0");
|
|
895
|
+
separatorRun = false;
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
return `--${(readable.replace(/^-+/, "") || "root").slice(0, 251)}--`;
|
|
899
|
+
}
|
|
900
|
+
/**
|
|
901
|
+
* The configured root's human-navigable project directory. A configured root
|
|
902
|
+
* may be local or shared; this grouping does not prescribe its deployment.
|
|
903
|
+
* @param root - the backend's session root directory.
|
|
904
|
+
* @param cwd - the session's project directory; `undefined` selects `_no-cwd`.
|
|
905
|
+
* @returns the project directory path under `root`.
|
|
906
|
+
*/
|
|
907
|
+
function projectDir(root, cwd) {
|
|
908
|
+
if (cwd === void 0) return join(root, "_no-cwd");
|
|
909
|
+
return join(root, projectKey(cwd));
|
|
910
|
+
}
|
|
911
|
+
/**
|
|
912
|
+
* The directory owned by one session and available for future session-local
|
|
913
|
+
* artifacts.
|
|
914
|
+
* @param root - the backend's session root directory.
|
|
915
|
+
* @param cwd - the session's project directory.
|
|
916
|
+
* @param id - the session id, encoded to one safe path segment.
|
|
917
|
+
* @returns the session directory beneath its project directory.
|
|
918
|
+
*/
|
|
919
|
+
function sessionDir(root, cwd, id) {
|
|
920
|
+
return join(projectDir(root, cwd), encodeSegment(id));
|
|
921
|
+
}
|
|
922
|
+
/**
|
|
923
|
+
* Build one immutable Session format generation path.
|
|
924
|
+
* @param root - the backend's session root directory.
|
|
925
|
+
* @param cwd - the session's project directory (`undefined` → `_no-cwd`).
|
|
926
|
+
* @param id - the session id, path-encoded via {@link encodeSegment} before filesystem use.
|
|
927
|
+
* @param version - physical Session format generation.
|
|
928
|
+
* @param compression - physical artifact encoding and filename suffix.
|
|
929
|
+
* @returns the selected generation's configured JSONL artifact path.
|
|
930
|
+
*/
|
|
931
|
+
function generationLogPath(root, cwd, id, version, compression) {
|
|
932
|
+
return join(sessionDir(root, cwd, id), generationLogFilename(version, compression));
|
|
933
|
+
}
|
|
934
|
+
/**
|
|
935
|
+
* Build the current generation's append target path for a Session.
|
|
936
|
+
* @param root - the backend's session root directory.
|
|
937
|
+
* @param cwd - the session's project directory (`undefined` → `_no-cwd`).
|
|
938
|
+
* @param id - the session id, path-encoded via {@link encodeSegment} before filesystem use.
|
|
939
|
+
* @param compression - physical artifact encoding and filename suffix.
|
|
940
|
+
* @returns the current Session format generation path.
|
|
941
|
+
*/
|
|
942
|
+
function logPath(root, cwd, id, compression) {
|
|
943
|
+
return generationLogPath(root, cwd, id, SESSION_FORMAT_VERSION, compression);
|
|
944
|
+
}
|
|
945
|
+
/**
|
|
946
|
+
* Serialize a current event batch as JSONL lines (no trailing newline). Compact
|
|
947
|
+
* Assistant streams are nested event data; every event occupies one row.
|
|
948
|
+
* @param events - the batch to serialize, in log order.
|
|
949
|
+
* @returns the batch's JSONL text; the writer adds the final newline.
|
|
950
|
+
*/
|
|
951
|
+
function eventLines(events) {
|
|
952
|
+
return events.map(eventLine).join("\n");
|
|
953
|
+
}
|
|
954
|
+
/**
|
|
955
|
+
* Serialize one current event as one JSONL record without its trailing newline.
|
|
956
|
+
* @param event - current event to encode.
|
|
957
|
+
* @returns one physical JSON record.
|
|
958
|
+
*/
|
|
959
|
+
function eventLine(event) {
|
|
960
|
+
return JSON.stringify(sessionFormatCatalog.encodeCurrentEvent(event));
|
|
961
|
+
}
|
|
962
|
+
/**
|
|
963
|
+
* Refuse a header carrying a format version this build does not read BEFORE
|
|
964
|
+
* validating the current header shape or decoding any event row: a future
|
|
965
|
+
* format need not satisfy this build's structural checks at all, and its user
|
|
966
|
+
* must see "upgrade the harness", never "corrupt session log".
|
|
967
|
+
* @param parsed - the JSON-parsed first line of a session artifact.
|
|
968
|
+
*/
|
|
969
|
+
function refuseForeignFormatVersion(parsed) {
|
|
970
|
+
const { version, id } = parsed;
|
|
971
|
+
if (typeof version !== "number" || version === SESSION_FORMAT_VERSION) return;
|
|
972
|
+
throw new SessionFormatUnsupportedError(sessionFormatVersionRefusal(typeof id === "string" ? id : String(id), version));
|
|
973
|
+
}
|
|
974
|
+
/** Parse one complete header record supplied independently from event rows. */
|
|
975
|
+
function parseHeaderRecord(record) {
|
|
976
|
+
if (record.length === 0 || record.at(-1) !== 10 || record.indexOf(10) !== record.length - 1) throw new Error("empty or header-less session log");
|
|
977
|
+
let parsed;
|
|
978
|
+
try {
|
|
979
|
+
parsed = JSON.parse(record.subarray(0, -1).toString("utf8"));
|
|
980
|
+
} catch {
|
|
981
|
+
throw new Error("corrupt session log: header line is not valid JSON");
|
|
982
|
+
}
|
|
983
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error("corrupt session log: first line is not a JSON object");
|
|
984
|
+
refuseForeignFormatVersion(parsed);
|
|
985
|
+
assertNoRetiredHeaderFields(parsed);
|
|
986
|
+
if (!isHeaderLine(parsed)) throw new Error("corrupt session log: first line is not a session header");
|
|
987
|
+
let restore;
|
|
988
|
+
try {
|
|
989
|
+
restore = sessionFormatCatalog.createRestore(parsed, {
|
|
990
|
+
recovery: "strict",
|
|
991
|
+
validation: "transformed"
|
|
992
|
+
});
|
|
993
|
+
} catch {
|
|
994
|
+
/* v8 ignore next -- isHeaderLine matches the current codec; this preserves classification if it tightens. */
|
|
995
|
+
throw new Error("corrupt session log: first line is not a session header");
|
|
996
|
+
}
|
|
997
|
+
return {
|
|
998
|
+
meta: fromHeaderLine(parsed).meta,
|
|
999
|
+
restore
|
|
1000
|
+
};
|
|
1001
|
+
}
|
|
1002
|
+
/**
|
|
1003
|
+
* Incrementally scan complete JSONL event records after an independently
|
|
1004
|
+
* supplied header record. Newline search and byte offsets stay on raw buffers;
|
|
1005
|
+
* only complete records are decoded to UTF-8. A fragment crossing writes is
|
|
1006
|
+
* copied because a decoder may reuse its output buffer after `write()` returns.
|
|
1007
|
+
*/
|
|
1008
|
+
var SessionLogScanner = class {
|
|
1009
|
+
recovery;
|
|
1010
|
+
meta;
|
|
1011
|
+
restore;
|
|
1012
|
+
eventCount = 0;
|
|
1013
|
+
fragments = [];
|
|
1014
|
+
fragmentBytes = 0;
|
|
1015
|
+
inputBytes;
|
|
1016
|
+
committedBytes;
|
|
1017
|
+
eventLine = 0;
|
|
1018
|
+
issue;
|
|
1019
|
+
finished = false;
|
|
1020
|
+
/**
|
|
1021
|
+
* Create an event scanner from exactly one newline-terminated header record.
|
|
1022
|
+
* @param headerRecord - the complete first JSONL record, including its newline.
|
|
1023
|
+
*/
|
|
1024
|
+
constructor(headerRecord, recovery = "recoverable") {
|
|
1025
|
+
this.recovery = recovery;
|
|
1026
|
+
const parsed = parseHeaderRecord(headerRecord);
|
|
1027
|
+
this.meta = parsed.meta;
|
|
1028
|
+
this.restore = parsed.restore;
|
|
1029
|
+
this.inputBytes = headerRecord.length;
|
|
1030
|
+
this.committedBytes = headerRecord.length;
|
|
1031
|
+
}
|
|
1032
|
+
/**
|
|
1033
|
+
* Consume the next raw plaintext chunk, retaining only an incomplete final record.
|
|
1034
|
+
* @param chunk - bytes immediately following all previously supplied bytes.
|
|
1035
|
+
*/
|
|
1036
|
+
write(chunk) {
|
|
1037
|
+
if (this.finished) throw new Error("cannot write to a finished session log scanner");
|
|
1038
|
+
const chunkStart = this.inputBytes;
|
|
1039
|
+
this.inputBytes += chunk.length;
|
|
1040
|
+
let lineStart = 0;
|
|
1041
|
+
for (let newline = chunk.indexOf(10); newline !== -1; newline = chunk.indexOf(10, lineStart)) {
|
|
1042
|
+
const fragment = chunk.subarray(lineStart, newline);
|
|
1043
|
+
let line = fragment;
|
|
1044
|
+
if (this.fragments.length > 0) {
|
|
1045
|
+
if (fragment.length > 0) this.fragments.push(fragment);
|
|
1046
|
+
line = Buffer.concat(this.fragments, this.fragmentBytes + fragment.length);
|
|
1047
|
+
this.fragments = [];
|
|
1048
|
+
this.fragmentBytes = 0;
|
|
1049
|
+
}
|
|
1050
|
+
this.consumeEventLine(line, chunkStart + newline + 1);
|
|
1051
|
+
lineStart = newline + 1;
|
|
1052
|
+
}
|
|
1053
|
+
if (lineStart < chunk.length) {
|
|
1054
|
+
const fragment = Buffer.from(chunk.subarray(lineStart));
|
|
1055
|
+
this.fragments.push(fragment);
|
|
1056
|
+
this.fragmentBytes += fragment.length;
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
/**
|
|
1060
|
+
* Snapshot progress before appending a recoverable torn-frame prefix.
|
|
1061
|
+
* @returns byte, committed-prefix, and expanded-event cursors.
|
|
1062
|
+
*/
|
|
1063
|
+
checkpoint() {
|
|
1064
|
+
return {
|
|
1065
|
+
inputBytes: this.inputBytes,
|
|
1066
|
+
committedBytes: this.committedBytes,
|
|
1067
|
+
eventCount: SessionLogOffset(this.eventCount)
|
|
1068
|
+
};
|
|
1069
|
+
}
|
|
1070
|
+
/**
|
|
1071
|
+
* Finish scanning, ignoring a final record without a newline as a torn tail.
|
|
1072
|
+
* @returns the header, contiguous event prefix, and safe truncation offset.
|
|
1073
|
+
*/
|
|
1074
|
+
finish() {
|
|
1075
|
+
this.finished = true;
|
|
1076
|
+
const artifact = this.restore.finish();
|
|
1077
|
+
assertReleasedV4Relationships(artifact, KNOWN_SESSION_EVENT_TYPES);
|
|
1078
|
+
return {
|
|
1079
|
+
meta: this.meta,
|
|
1080
|
+
inheritedEventCount: SessionLogOffset(artifact.inheritedEventCount),
|
|
1081
|
+
events: artifact.events,
|
|
1082
|
+
committedBytes: this.committedBytes
|
|
1083
|
+
};
|
|
1084
|
+
}
|
|
1085
|
+
/** Decode one complete event row and update the contiguous prefix. */
|
|
1086
|
+
consumeEventLine(line, endByte) {
|
|
1087
|
+
this.eventLine += 1;
|
|
1088
|
+
let decoded;
|
|
1089
|
+
try {
|
|
1090
|
+
decoded = JSON.parse(line.toString("utf8"));
|
|
1091
|
+
} catch {
|
|
1092
|
+
const issue = /* @__PURE__ */ new Error(`corrupt session log: unparsable committed event at line ${this.eventLine}`);
|
|
1093
|
+
if (this.recovery === "strict") throw issue;
|
|
1094
|
+
this.issue ??= issue;
|
|
1095
|
+
return;
|
|
1096
|
+
}
|
|
1097
|
+
try {
|
|
1098
|
+
assertV4RowAdmission(decoded, KNOWN_SESSION_EVENT_TYPES);
|
|
1099
|
+
} catch (error) {
|
|
1100
|
+
if (error instanceof SessionFormatUnsupportedMigrationError$1) throw new SessionFormatUnsupportedError(error.message);
|
|
1101
|
+
throw error;
|
|
1102
|
+
}
|
|
1103
|
+
if (this.issue !== void 0) {
|
|
1104
|
+
if (typeof decoded === "object" && decoded !== null && decoded.type === "turn/end") throw this.issue;
|
|
1105
|
+
return;
|
|
1106
|
+
}
|
|
1107
|
+
try {
|
|
1108
|
+
this.restore.decodeRow(decoded);
|
|
1109
|
+
} catch (error) {
|
|
1110
|
+
/* v8 ignore next -- every production Session format decoder rejects with Error. */
|
|
1111
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
1112
|
+
const issue = new Error(`corrupt session log: invalid committed event at line ${this.eventLine}: ${detail}`, { cause: error });
|
|
1113
|
+
if (this.recovery === "strict") throw issue;
|
|
1114
|
+
this.issue = issue;
|
|
1115
|
+
if (typeof decoded === "object" && decoded !== null && decoded.type === "turn/end") throw issue;
|
|
1116
|
+
return;
|
|
1117
|
+
}
|
|
1118
|
+
this.eventCount += 1;
|
|
1119
|
+
this.committedBytes = endByte;
|
|
1120
|
+
}
|
|
1121
|
+
};
|
|
1122
|
+
/**
|
|
1123
|
+
* Parse a complete or torn JSONL buffer into its preserved event prefix. This
|
|
1124
|
+
* compatibility wrapper supplies the first record separately, then delegates
|
|
1125
|
+
* event rows to {@link SessionLogScanner}.
|
|
1126
|
+
*
|
|
1127
|
+
* @param buffer - the raw bytes of the log file (header line first).
|
|
1128
|
+
* @returns the header, preserved event prefix, and byte offset safe to append at.
|
|
1129
|
+
*/
|
|
1130
|
+
function scanLog(buffer) {
|
|
1131
|
+
const headerEnd = buffer.indexOf(10);
|
|
1132
|
+
if (headerEnd === -1) throw new Error("empty or header-less session log");
|
|
1133
|
+
const scanner = new SessionLogScanner(buffer.subarray(0, headerEnd + 1));
|
|
1134
|
+
scanner.write(buffer.subarray(headerEnd + 1));
|
|
1135
|
+
return scanner.finish();
|
|
1136
|
+
}
|
|
1137
|
+
//#endregion
|
|
1138
|
+
//#region lib/types/zstd-private-decoder.js
|
|
1139
|
+
/**
|
|
1140
|
+
* Node-private synchronous Zstandard frame decoder optimization.
|
|
1141
|
+
* @module rabi-session-persistence-jsonl/zstd-private-decoder
|
|
1142
|
+
*/
|
|
1143
|
+
const DECODE_CHUNK_SIZE = 1024 * 1024;
|
|
1144
|
+
/** Return the stream with its observed private Node contract, or reject that optimization. */
|
|
1145
|
+
function privateZstdStream(stream) {
|
|
1146
|
+
const candidate = stream;
|
|
1147
|
+
const handle = candidate._handle;
|
|
1148
|
+
const errorKey = Reflect.ownKeys(stream).find((key) => typeof key === "symbol" && key.description === "kError");
|
|
1149
|
+
/* v8 ignore next -- one test runtime exposes one Node-private shape; the Node 24/26 matrix checks compatibility. */
|
|
1150
|
+
if (typeof handle !== "object" || handle === null || typeof handle.writeSync !== "function" || !(candidate._writeState instanceof Uint32Array) || candidate._writeState.length < 2 || typeof candidate._defaultFlushFlag !== "number" || errorKey === void 0 || candidate[errorKey] !== null) return void 0;
|
|
1151
|
+
return {
|
|
1152
|
+
stream,
|
|
1153
|
+
errorKey
|
|
1154
|
+
};
|
|
1155
|
+
}
|
|
1156
|
+
/**
|
|
1157
|
+
* Synchronous multi-frame decoder backed by one Node Zstd stream handle. Node
|
|
1158
|
+
* exposes synchronous decoding only as a one-shot API, so this adapter uses
|
|
1159
|
+
* the stream's private handle contract to reuse its native context and output
|
|
1160
|
+
* chunks across frames.
|
|
1161
|
+
*/
|
|
1162
|
+
var NodePrivateZstdFrameDecoder = class NodePrivateZstdFrameDecoder {
|
|
1163
|
+
stream;
|
|
1164
|
+
errorKey;
|
|
1165
|
+
output = Buffer.allocUnsafe(DECODE_CHUNK_SIZE);
|
|
1166
|
+
decoderError;
|
|
1167
|
+
started = false;
|
|
1168
|
+
closed = false;
|
|
1169
|
+
constructor(stream, errorKey) {
|
|
1170
|
+
this.stream = stream;
|
|
1171
|
+
this.errorKey = errorKey;
|
|
1172
|
+
this.stream.on("error", (error) => {
|
|
1173
|
+
this.decoderError ??= error;
|
|
1174
|
+
});
|
|
1175
|
+
}
|
|
1176
|
+
/**
|
|
1177
|
+
* Create the optimized decoder when this Node release exposes the expected
|
|
1178
|
+
* private stream shape.
|
|
1179
|
+
* @returns a shared decoder, or `undefined` when callers must use the public fallback.
|
|
1180
|
+
*/
|
|
1181
|
+
static create() {
|
|
1182
|
+
const stream = createZstdDecompress({ chunkSize: DECODE_CHUNK_SIZE });
|
|
1183
|
+
const privateAccess = privateZstdStream(stream);
|
|
1184
|
+
/* v8 ignore next -- reached only when a supported Node release changes its private stream shape. */
|
|
1185
|
+
if (privateAccess !== void 0) return new NodePrivateZstdFrameDecoder(privateAccess.stream, privateAccess.errorKey);
|
|
1186
|
+
/* v8 ignore next -- the active Node runtime passed the private-shape probe above. */
|
|
1187
|
+
stream.close();
|
|
1188
|
+
}
|
|
1189
|
+
/** @inheritdoc */
|
|
1190
|
+
*decode(source, frames) {
|
|
1191
|
+
if (this.started) throw new Error("Zstandard frame decoder was already started");
|
|
1192
|
+
if (this.closed) throw new Error("cannot start a closed Zstandard frame decoder");
|
|
1193
|
+
this.started = true;
|
|
1194
|
+
try {
|
|
1195
|
+
for (const frame of frames) try {
|
|
1196
|
+
yield this.decodeFrame(source.subarray(frame.start, frame.end));
|
|
1197
|
+
} catch (error) {
|
|
1198
|
+
throw new Error(`corrupt Zstandard session log: frame at byte ${frame.start} failed validation`, { cause: error });
|
|
1199
|
+
}
|
|
1200
|
+
} finally {
|
|
1201
|
+
this.close();
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
1204
|
+
/** Decode one frame; its returned scratch view remains valid until the next call. */
|
|
1205
|
+
decodeFrame(input) {
|
|
1206
|
+
const handle = this.stream._handle;
|
|
1207
|
+
/* v8 ignore next -- decode() rejects closed instances before entering this private frame operation. */
|
|
1208
|
+
if (this.closed || handle === null) throw new Error("cannot decode with a closed Zstandard frame decoder");
|
|
1209
|
+
let inputOffset = 0;
|
|
1210
|
+
let inputRemaining = input.length;
|
|
1211
|
+
let outputBytes = 0;
|
|
1212
|
+
const fullChunks = [];
|
|
1213
|
+
for (;;) {
|
|
1214
|
+
handle.writeSync(this.stream._defaultFlushFlag, input, inputOffset, inputRemaining, this.output, 0, this.output.length);
|
|
1215
|
+
if (this.decoderError !== void 0) throw this.decoderError;
|
|
1216
|
+
const internalError = this.stream[this.errorKey];
|
|
1217
|
+
if (internalError !== null) {
|
|
1218
|
+
if (internalError instanceof Error) throw internalError;
|
|
1219
|
+
throw new Error("Zstandard decoder exposed a non-Error internal failure");
|
|
1220
|
+
}
|
|
1221
|
+
const outputAfter = this.stream._writeState[0];
|
|
1222
|
+
const inputAfter = this.stream._writeState[1];
|
|
1223
|
+
const consumed = inputRemaining - inputAfter;
|
|
1224
|
+
const produced = this.output.length - outputAfter;
|
|
1225
|
+
if (produced > 0) {
|
|
1226
|
+
outputBytes += produced;
|
|
1227
|
+
/* v8 ignore next -- Buffer cannot materialize a frame beyond its own process-wide maximum length. */
|
|
1228
|
+
if (outputBytes > constants$1.MAX_LENGTH) throw new Error(`Zstandard frame output exceeds ${constants$1.MAX_LENGTH} bytes`);
|
|
1229
|
+
}
|
|
1230
|
+
if (outputAfter !== 0) {
|
|
1231
|
+
/* v8 ignore next -- structurally scanned ranges contain exactly one complete frame and no trailing bytes. */
|
|
1232
|
+
if (inputAfter !== 0) throw new Error("Zstandard frame decoder left trailing input");
|
|
1233
|
+
const finalChunk = this.output.subarray(0, produced);
|
|
1234
|
+
if (fullChunks.length === 0) return finalChunk;
|
|
1235
|
+
if (produced > 0) fullChunks.push(Buffer.from(finalChunk));
|
|
1236
|
+
const onlyChunk = fullChunks[0];
|
|
1237
|
+
return fullChunks.length === 1 ? onlyChunk : Buffer.concat(fullChunks, outputBytes);
|
|
1238
|
+
}
|
|
1239
|
+
fullChunks.push(Buffer.from(this.output));
|
|
1240
|
+
inputOffset += consumed;
|
|
1241
|
+
inputRemaining = inputAfter;
|
|
1242
|
+
}
|
|
1243
|
+
}
|
|
1244
|
+
/** @inheritdoc */
|
|
1245
|
+
close() {
|
|
1246
|
+
if (this.closed) return;
|
|
1247
|
+
this.closed = true;
|
|
1248
|
+
this.stream.close();
|
|
1249
|
+
}
|
|
1250
|
+
};
|
|
1251
|
+
//#endregion
|
|
1252
|
+
//#region lib/types/zstd-public-decoder.js
|
|
1253
|
+
/**
|
|
1254
|
+
* Public-API synchronous Zstandard frame decoder fallback.
|
|
1255
|
+
* @module rabi-session-persistence-jsonl/zstd-public-decoder
|
|
1256
|
+
*/
|
|
1257
|
+
/** Multi-frame adapter built exclusively from Node's supported one-shot API. */
|
|
1258
|
+
var PublicZstdFrameDecoder = class {
|
|
1259
|
+
started = false;
|
|
1260
|
+
closed = false;
|
|
1261
|
+
/** @inheritdoc */
|
|
1262
|
+
*decode(source, frames) {
|
|
1263
|
+
if (this.started) throw new Error("Zstandard frame decoder was already started");
|
|
1264
|
+
if (this.closed) throw new Error("cannot start a closed Zstandard frame decoder");
|
|
1265
|
+
this.started = true;
|
|
1266
|
+
try {
|
|
1267
|
+
for (const { start, end } of frames) {
|
|
1268
|
+
let decoded;
|
|
1269
|
+
try {
|
|
1270
|
+
decoded = zstdDecompressSync(source.subarray(start, end));
|
|
1271
|
+
} catch (error) {
|
|
1272
|
+
throw new Error(`corrupt Zstandard session log: frame at byte ${start} failed validation`, { cause: error });
|
|
1273
|
+
}
|
|
1274
|
+
yield decoded;
|
|
1275
|
+
}
|
|
1276
|
+
} finally {
|
|
1277
|
+
this.close();
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
/** @inheritdoc */
|
|
1281
|
+
close() {
|
|
1282
|
+
this.closed = true;
|
|
1283
|
+
}
|
|
1284
|
+
};
|
|
1285
|
+
//#endregion
|
|
1286
|
+
//#region lib/types/zstd.js
|
|
1287
|
+
/**
|
|
1288
|
+
* Zstandard frame primitives for the JSONL persistence backend. The backend
|
|
1289
|
+
* owns a concatenated-frame container so it can append and recover batches
|
|
1290
|
+
* without exposing compression mechanics through the persistence seam.
|
|
1291
|
+
* @module rabi-session-persistence-jsonl/zstd
|
|
1292
|
+
*/
|
|
1293
|
+
const ZSTD_MAGIC = 4247762216;
|
|
1294
|
+
const zstdCompressAsync = promisify(zstdCompress);
|
|
1295
|
+
const zstdDecompressAsync = promisify(zstdDecompress);
|
|
1296
|
+
const CHECKSUM_OPTIONS = { params: { [constants.ZSTD_c_checksumFlag]: 1 } };
|
|
1297
|
+
const INCOMPLETE_FRAME_OPTIONS = { finishFlush: constants.ZSTD_e_flush };
|
|
1298
|
+
/**
|
|
1299
|
+
* Locate complete frames without decompressing their blocks. Invalid complete
|
|
1300
|
+
* structure rejects; EOF inside the final frame returns its start for repair.
|
|
1301
|
+
* @param buffer - complete bytes currently present in the session artifact.
|
|
1302
|
+
* @param maxFrames - optional complete-frame limit for metadata-only readers.
|
|
1303
|
+
* @returns complete frame ranges and an optional incomplete-final-frame start.
|
|
1304
|
+
*/
|
|
1305
|
+
function scanZstdFrames(buffer, maxFrames = Number.POSITIVE_INFINITY) {
|
|
1306
|
+
const frames = [];
|
|
1307
|
+
let offset = 0;
|
|
1308
|
+
while (offset < buffer.length) {
|
|
1309
|
+
const start = offset;
|
|
1310
|
+
if (buffer.length - offset < 4) return {
|
|
1311
|
+
frames,
|
|
1312
|
+
tornStart: start
|
|
1313
|
+
};
|
|
1314
|
+
if (buffer.readUInt32LE(offset) !== ZSTD_MAGIC) throw new Error(`corrupt Zstandard session log: invalid frame magic at byte ${offset}`);
|
|
1315
|
+
offset += 4;
|
|
1316
|
+
if (offset === buffer.length) return {
|
|
1317
|
+
frames,
|
|
1318
|
+
tornStart: start
|
|
1319
|
+
};
|
|
1320
|
+
const descriptor = buffer.readUInt8(offset);
|
|
1321
|
+
offset += 1;
|
|
1322
|
+
if ((descriptor & 24) !== 0) throw new Error(`corrupt Zstandard session log: reserved frame-header bit at byte ${offset - 1}`);
|
|
1323
|
+
const contentSizeFlag = descriptor >>> 6;
|
|
1324
|
+
const singleSegment = (descriptor & 32) !== 0;
|
|
1325
|
+
const checksum = (descriptor & 4) !== 0;
|
|
1326
|
+
const dictionaryFlag = descriptor & 3;
|
|
1327
|
+
const dictionaryBytes = dictionaryFlag === 3 ? 4 : dictionaryFlag;
|
|
1328
|
+
const contentSizeBytes = contentSizeFlag === 0 ? singleSegment ? 1 : 0 : 1 << contentSizeFlag;
|
|
1329
|
+
const remainingHeaderBytes = (singleSegment ? 0 : 1) + dictionaryBytes + contentSizeBytes;
|
|
1330
|
+
if (buffer.length - offset < remainingHeaderBytes) return {
|
|
1331
|
+
frames,
|
|
1332
|
+
tornStart: start
|
|
1333
|
+
};
|
|
1334
|
+
offset += remainingHeaderBytes;
|
|
1335
|
+
for (;;) {
|
|
1336
|
+
if (buffer.length - offset < 3) return {
|
|
1337
|
+
frames,
|
|
1338
|
+
tornStart: start
|
|
1339
|
+
};
|
|
1340
|
+
const blockHeader = buffer.readUIntLE(offset, 3);
|
|
1341
|
+
offset += 3;
|
|
1342
|
+
const lastBlock = (blockHeader & 1) !== 0;
|
|
1343
|
+
const blockType = blockHeader >>> 1 & 3;
|
|
1344
|
+
const blockSize = blockHeader >>> 3;
|
|
1345
|
+
if (blockType === 3) throw new Error(`corrupt Zstandard session log: reserved block type at byte ${offset - 3}`);
|
|
1346
|
+
const payloadBytes = blockType === 1 ? 1 : blockSize;
|
|
1347
|
+
if (buffer.length - offset < payloadBytes) return {
|
|
1348
|
+
frames,
|
|
1349
|
+
tornStart: start
|
|
1350
|
+
};
|
|
1351
|
+
offset += payloadBytes;
|
|
1352
|
+
if (lastBlock) break;
|
|
1353
|
+
}
|
|
1354
|
+
if (checksum) {
|
|
1355
|
+
if (buffer.length - offset < 4) return {
|
|
1356
|
+
frames,
|
|
1357
|
+
tornStart: start
|
|
1358
|
+
};
|
|
1359
|
+
offset += 4;
|
|
1360
|
+
}
|
|
1361
|
+
frames.push({
|
|
1362
|
+
start,
|
|
1363
|
+
end: offset
|
|
1364
|
+
});
|
|
1365
|
+
if (frames.length === maxFrames) return { frames };
|
|
1366
|
+
}
|
|
1367
|
+
return { frames };
|
|
1368
|
+
}
|
|
1369
|
+
/**
|
|
1370
|
+
* Compress one independently decodable, checksummed Zstandard frame.
|
|
1371
|
+
* @param input - JSONL bytes for a header or durable event batch.
|
|
1372
|
+
* @returns the complete encoded frame.
|
|
1373
|
+
*/
|
|
1374
|
+
async function compressZstdFrame(input) {
|
|
1375
|
+
return zstdCompressAsync(input, CHECKSUM_OPTIONS);
|
|
1376
|
+
}
|
|
1377
|
+
/**
|
|
1378
|
+
* Decompress one complete frame and validate its checksum.
|
|
1379
|
+
* @param input - one structurally complete Zstandard frame.
|
|
1380
|
+
* @returns the frame plaintext.
|
|
1381
|
+
*/
|
|
1382
|
+
async function decompressZstdFrame(input) {
|
|
1383
|
+
return zstdDecompressAsync(input);
|
|
1384
|
+
}
|
|
1385
|
+
/**
|
|
1386
|
+
* Select the shared private decoder when the running Node 24/26 shape is
|
|
1387
|
+
* compatible, otherwise preserve correctness with the public one-shot API.
|
|
1388
|
+
* @returns a synchronous decoder with an implementation-independent lifecycle.
|
|
1389
|
+
*/
|
|
1390
|
+
function createZstdFrameDecoder() {
|
|
1391
|
+
return NodePrivateZstdFrameDecoder.create() ?? new PublicZstdFrameDecoder();
|
|
1392
|
+
}
|
|
1393
|
+
/**
|
|
1394
|
+
* Recover available plaintext from a structurally incomplete final frame.
|
|
1395
|
+
* `ZSTD_e_flush` deliberately suppresses final-frame and checksum completion;
|
|
1396
|
+
* callers must establish the torn frame boundary before using this helper.
|
|
1397
|
+
* @param input - available bytes from a known incomplete Zstandard frame.
|
|
1398
|
+
* @returns plaintext produced from the available input.
|
|
1399
|
+
*/
|
|
1400
|
+
async function decompressZstdPrefix(input) {
|
|
1401
|
+
return zstdDecompressAsync(input, INCOMPLETE_FRAME_OPTIONS);
|
|
1402
|
+
}
|
|
1403
|
+
//#endregion
|
|
1404
|
+
//#region lib/types/migration-verifier.js
|
|
1405
|
+
/** Isolated verification for a staged or competing current JSONL generation. */
|
|
1406
|
+
/** Process-wide memory bound for full-generation verification isolates. */
|
|
1407
|
+
const MAX_CONCURRENT_VERIFIERS = 2;
|
|
1408
|
+
var VerificationScheduler = class {
|
|
1409
|
+
active = 0;
|
|
1410
|
+
waiting = [];
|
|
1411
|
+
async run(operation, signal) {
|
|
1412
|
+
const permit = this.acquire(signal);
|
|
1413
|
+
if (permit !== void 0) await permit;
|
|
1414
|
+
try {
|
|
1415
|
+
signal?.throwIfAborted();
|
|
1416
|
+
return await operation();
|
|
1417
|
+
} finally {
|
|
1418
|
+
this.release();
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
acquire(signal) {
|
|
1422
|
+
signal?.throwIfAborted();
|
|
1423
|
+
if (this.active < MAX_CONCURRENT_VERIFIERS) {
|
|
1424
|
+
this.active += 1;
|
|
1425
|
+
return;
|
|
1426
|
+
}
|
|
1427
|
+
return new Promise((resolve, reject) => {
|
|
1428
|
+
const waiter = { grant: () => {
|
|
1429
|
+
signal?.removeEventListener("abort", abort);
|
|
1430
|
+
resolve();
|
|
1431
|
+
} };
|
|
1432
|
+
const abort = () => {
|
|
1433
|
+
const index = this.waiting.indexOf(waiter);
|
|
1434
|
+
this.waiting.splice(index, 1);
|
|
1435
|
+
reject(verifierAbortError(signal));
|
|
1436
|
+
};
|
|
1437
|
+
this.waiting.push(waiter);
|
|
1438
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
1439
|
+
});
|
|
1440
|
+
}
|
|
1441
|
+
release() {
|
|
1442
|
+
const next = this.waiting.shift();
|
|
1443
|
+
if (next === void 0) {
|
|
1444
|
+
this.active -= 1;
|
|
1445
|
+
return;
|
|
1446
|
+
}
|
|
1447
|
+
next.grant();
|
|
1448
|
+
}
|
|
1449
|
+
};
|
|
1450
|
+
const verificationScheduler = new VerificationScheduler();
|
|
1451
|
+
function workerSpawn(request) {
|
|
1452
|
+
/* v8 ignore next 3 -- built-worker coverage owns the bundled path. */
|
|
1453
|
+
if (!import.meta.url.endsWith(".ts")) return {
|
|
1454
|
+
entry: new URL("./worker.cjs", import.meta.url),
|
|
1455
|
+
options: {
|
|
1456
|
+
workerData: request,
|
|
1457
|
+
execArgv: []
|
|
1458
|
+
}
|
|
1459
|
+
};
|
|
1460
|
+
const workerEntry = new URL("./worker.ts", import.meta.url);
|
|
1461
|
+
const bootstrap = [
|
|
1462
|
+
`import { register as registerEsm } from ${JSON.stringify(import.meta.resolve("tsx/esm/api"))}`,
|
|
1463
|
+
`import { register as registerCjs } from ${JSON.stringify(import.meta.resolve("tsx/cjs/api"))}`,
|
|
1464
|
+
"registerCjs()",
|
|
1465
|
+
"registerEsm()",
|
|
1466
|
+
`await import(${JSON.stringify(workerEntry.href)})`
|
|
1467
|
+
].join("\n");
|
|
1468
|
+
return {
|
|
1469
|
+
entry: new URL(`data:text/javascript,${encodeURIComponent(bootstrap)}`),
|
|
1470
|
+
options: {
|
|
1471
|
+
workerData: request,
|
|
1472
|
+
execArgv: []
|
|
1473
|
+
}
|
|
1474
|
+
};
|
|
1475
|
+
}
|
|
1476
|
+
/**
|
|
1477
|
+
* Verify one current generation in a fresh Worker Thread.
|
|
1478
|
+
* @param path - staged or competing current-generation path.
|
|
1479
|
+
* @param compression - configured physical encoding.
|
|
1480
|
+
* @param expectedId - Session id expected in the decoded header.
|
|
1481
|
+
* @param expectedEventCount - exact logical event count expected after decoding.
|
|
1482
|
+
* @param expectedPrefix - verified physical prefix; an append tail may be present and is not validated.
|
|
1483
|
+
* @param signal - optional cancellation for scheduler wait and Worker execution.
|
|
1484
|
+
* @returns the worker's physical identity and digest after its natural zero exit.
|
|
1485
|
+
*/
|
|
1486
|
+
function verifyCurrentGenerationInWorker(path, compression, expectedId, expectedEventCount, expectedPrefix, signal) {
|
|
1487
|
+
return verificationScheduler.run(() => runVerificationWorker(path, compression, expectedId, expectedEventCount, expectedPrefix, signal), signal);
|
|
1488
|
+
}
|
|
1489
|
+
function runVerificationWorker(path, compression, expectedId, expectedEventCount, expectedPrefix, signal) {
|
|
1490
|
+
signal?.throwIfAborted();
|
|
1491
|
+
const { entry, options } = workerSpawn({
|
|
1492
|
+
path,
|
|
1493
|
+
compression,
|
|
1494
|
+
expectedId,
|
|
1495
|
+
expectedEventCount,
|
|
1496
|
+
...expectedPrefix === void 0 ? {} : { expectedPrefix }
|
|
1497
|
+
});
|
|
1498
|
+
const worker = new Worker(entry, options);
|
|
1499
|
+
return new Promise((resolve, reject) => {
|
|
1500
|
+
let settled = false;
|
|
1501
|
+
let success;
|
|
1502
|
+
const cleanup = () => {
|
|
1503
|
+
signal?.removeEventListener("abort", abort);
|
|
1504
|
+
};
|
|
1505
|
+
const fail = (error) => {
|
|
1506
|
+
/* v8 ignore next -- a late error/exit races only after another terminal callback settled. */
|
|
1507
|
+
if (settled) return;
|
|
1508
|
+
settled = true;
|
|
1509
|
+
cleanup();
|
|
1510
|
+
worker.terminate().then(() => {
|
|
1511
|
+
reject(error);
|
|
1512
|
+
}, (cleanup) => {
|
|
1513
|
+
reject(new AggregateError([error, cleanup], "migration verifier termination failed"));
|
|
1514
|
+
});
|
|
1515
|
+
};
|
|
1516
|
+
worker.once("message", (value) => {
|
|
1517
|
+
/* v8 ignore next -- a duplicate message races only after another terminal callback settled. */
|
|
1518
|
+
if (settled) return;
|
|
1519
|
+
if (typeof value !== "object" || value === null || typeof value.ok !== "boolean") {
|
|
1520
|
+
fail(/* @__PURE__ */ new Error("migration verifier returned an invalid response"));
|
|
1521
|
+
return;
|
|
1522
|
+
}
|
|
1523
|
+
const response = value;
|
|
1524
|
+
if (!response.ok) {
|
|
1525
|
+
const error = new Error(response.message);
|
|
1526
|
+
if (response.stack !== void 0) error.stack = response.stack;
|
|
1527
|
+
fail(error);
|
|
1528
|
+
return;
|
|
1529
|
+
}
|
|
1530
|
+
success = response;
|
|
1531
|
+
});
|
|
1532
|
+
worker.once("error", fail);
|
|
1533
|
+
worker.once("exit", (code) => {
|
|
1534
|
+
if (settled) return;
|
|
1535
|
+
settled = true;
|
|
1536
|
+
cleanup();
|
|
1537
|
+
if (success === void 0) reject(/* @__PURE__ */ new Error(`migration verifier exited before reporting a result (code ${code})`));
|
|
1538
|
+
else if (code !== 0) reject(/* @__PURE__ */ new Error(`migration verifier exited after reporting a result (code ${code})`));
|
|
1539
|
+
else resolve(success.result);
|
|
1540
|
+
});
|
|
1541
|
+
const abort = () => {
|
|
1542
|
+
fail(verifierAbortError(signal));
|
|
1543
|
+
};
|
|
1544
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
1545
|
+
});
|
|
1546
|
+
}
|
|
1547
|
+
function verifierAbortError(signal) {
|
|
1548
|
+
const reason = signal?.reason;
|
|
1549
|
+
return reason instanceof Error ? reason : new Error("migration verifier aborted", { cause: reason });
|
|
1550
|
+
}
|
|
1551
|
+
//#endregion
|
|
1552
|
+
//#region lib/types/generation.js
|
|
1553
|
+
/**
|
|
1554
|
+
* Durable whole-generation publication for JSONL Session artifacts.
|
|
1555
|
+
*
|
|
1556
|
+
* Format packages transform parsed JSON values. This module owns the physical
|
|
1557
|
+
* encoding, exact source identity, immutable generation files, and exclusive
|
|
1558
|
+
* current-generation publication for both configured JSONL suffixes.
|
|
1559
|
+
* @module @unieai/rabi-session-persistence-jsonl/generation
|
|
1560
|
+
*/
|
|
1561
|
+
/** Internal scheduling bounds: preserve old decode cadence and cap each synchronous encode slice. */
|
|
1562
|
+
const MIGRATION_DECODE_YIELD_INTERVAL_MS = 500;
|
|
1563
|
+
const MIGRATION_WORK_CHUNK_BYTES = 1024 * 1024;
|
|
1564
|
+
const MIGRATION_WRITE_CHUNK_BYTES = 4 * 1024 * 1024;
|
|
1565
|
+
const ZSTD_CHECKSUM_OPTIONS = {
|
|
1566
|
+
chunkSize: MIGRATION_WORK_CHUNK_BYTES,
|
|
1567
|
+
params: { [constants.ZSTD_c_checksumFlag]: 1 }
|
|
1568
|
+
};
|
|
1569
|
+
/** A historical source changed after its single decode and migration pass. */
|
|
1570
|
+
var JsonlGenerationSourceChangedError = class extends Error {
|
|
1571
|
+
path;
|
|
1572
|
+
name = "JsonlGenerationSourceChangedError";
|
|
1573
|
+
/** @param path - historical generation whose revision changed. */
|
|
1574
|
+
constructor(path) {
|
|
1575
|
+
super(`historical session generation changed during migration: "${path}"`);
|
|
1576
|
+
this.path = path;
|
|
1577
|
+
}
|
|
1578
|
+
};
|
|
1579
|
+
/** A historical artifact is intact, but the format edge refuses its contents. */
|
|
1580
|
+
var JsonlGenerationUnsupportedMigrationError = class extends Error {
|
|
1581
|
+
fromVersion;
|
|
1582
|
+
reason;
|
|
1583
|
+
name = "JsonlGenerationUnsupportedMigrationError";
|
|
1584
|
+
/**
|
|
1585
|
+
* @param fromVersion - unchanged source generation version.
|
|
1586
|
+
* @param reason - format-edge refusal.
|
|
1587
|
+
*/
|
|
1588
|
+
constructor(fromVersion, reason) {
|
|
1589
|
+
super(reason.message, { cause: reason });
|
|
1590
|
+
this.fromVersion = fromVersion;
|
|
1591
|
+
this.reason = reason;
|
|
1592
|
+
}
|
|
1593
|
+
};
|
|
1594
|
+
/** A current-generation filename already names different or invalid bytes. */
|
|
1595
|
+
var JsonlGenerationTargetConflictError = class extends Error {
|
|
1596
|
+
path;
|
|
1597
|
+
reason;
|
|
1598
|
+
name = "JsonlGenerationTargetConflictError";
|
|
1599
|
+
/**
|
|
1600
|
+
* @param path - immutable target that prevented exclusive publication.
|
|
1601
|
+
* @param reason - why the existing target cannot be accepted.
|
|
1602
|
+
*/
|
|
1603
|
+
constructor(path, reason) {
|
|
1604
|
+
super(`current session generation already exists at "${path}": ${reason.message}`, { cause: reason });
|
|
1605
|
+
this.path = path;
|
|
1606
|
+
this.reason = reason;
|
|
1607
|
+
}
|
|
1608
|
+
};
|
|
1609
|
+
const defaultFileSystem = {
|
|
1610
|
+
open: (path, flags, mode) => open(path, flags, mode),
|
|
1611
|
+
readFile: (path, signal) => readFile(path, signal === void 0 ? void 0 : { signal }),
|
|
1612
|
+
readdir: (path) => readdir(path),
|
|
1613
|
+
stat: (path) => stat(path, { bigint: true }),
|
|
1614
|
+
lstat: (path) => lstat(path),
|
|
1615
|
+
link,
|
|
1616
|
+
rm: (path) => rm(path, { force: true })
|
|
1617
|
+
};
|
|
1618
|
+
const defaultInternals = {
|
|
1619
|
+
fs: defaultFileSystem,
|
|
1620
|
+
randomToken: () => randomBytes(8).toString("hex"),
|
|
1621
|
+
platform: process.platform,
|
|
1622
|
+
publishNewWin32: publishNewFileWin32,
|
|
1623
|
+
barrier: () => {}
|
|
1624
|
+
};
|
|
1625
|
+
function isEEXIST(error) {
|
|
1626
|
+
return error?.code === "EEXIST";
|
|
1627
|
+
}
|
|
1628
|
+
/** Whether a filesystem-owned failure should retain its original errno and path. */
|
|
1629
|
+
function isErrnoException$1(error) {
|
|
1630
|
+
return typeof error?.code === "string";
|
|
1631
|
+
}
|
|
1632
|
+
function identity(value) {
|
|
1633
|
+
return [
|
|
1634
|
+
value.dev,
|
|
1635
|
+
value.ino,
|
|
1636
|
+
value.size,
|
|
1637
|
+
value.mtimeNs,
|
|
1638
|
+
value.ctimeNs
|
|
1639
|
+
].join(":");
|
|
1640
|
+
}
|
|
1641
|
+
/**
|
|
1642
|
+
* Read one stable revision of a JSONL file with a single retry. If an append
|
|
1643
|
+
* overlaps both reads, return the second read's committed pre-read prefix
|
|
1644
|
+
* instead of starving behind a continuous writer.
|
|
1645
|
+
* @param path - the generation file to read.
|
|
1646
|
+
* @param signal - optional cancellation for the stat/read work.
|
|
1647
|
+
* @returns the stable bytes (or the committed prefix) and their stat identity.
|
|
1648
|
+
*/
|
|
1649
|
+
async function readStableJsonlFile(path, signal) {
|
|
1650
|
+
return defaultGenerationRuntime.readStable(path, signal);
|
|
1651
|
+
}
|
|
1652
|
+
async function readStableSnapshot(path, signal, fs) {
|
|
1653
|
+
signal?.throwIfAborted();
|
|
1654
|
+
let before = await fs.stat(path);
|
|
1655
|
+
for (let attempt = 0;; attempt += 1) {
|
|
1656
|
+
const bytes = await fs.readFile(path, signal);
|
|
1657
|
+
signal?.throwIfAborted();
|
|
1658
|
+
const after = await fs.stat(path);
|
|
1659
|
+
if (identity(before) === identity(after)) {
|
|
1660
|
+
signal?.throwIfAborted();
|
|
1661
|
+
return {
|
|
1662
|
+
bytes,
|
|
1663
|
+
identity: after
|
|
1664
|
+
};
|
|
1665
|
+
}
|
|
1666
|
+
if (attempt === 1) return {
|
|
1667
|
+
bytes: bytes.subarray(0, Number(before.size)),
|
|
1668
|
+
identity: before
|
|
1669
|
+
};
|
|
1670
|
+
before = after;
|
|
1671
|
+
}
|
|
1672
|
+
}
|
|
1673
|
+
/** Parse the version discriminator without validating any version-specific field. */
|
|
1674
|
+
function storedVersion(header) {
|
|
1675
|
+
if (typeof header !== "object" || header === null || Array.isArray(header)) throw new Error("corrupt session log: first line is not a JSON object");
|
|
1676
|
+
const version = header.version;
|
|
1677
|
+
if (!Number.isSafeInteger(version) || version < 0 || Object.is(version, -0)) throw new Error("corrupt session log: header version is not a non-negative safe integer");
|
|
1678
|
+
return version;
|
|
1679
|
+
}
|
|
1680
|
+
function parseJson(text, subject) {
|
|
1681
|
+
try {
|
|
1682
|
+
return JSON.parse(text);
|
|
1683
|
+
} catch (error) {
|
|
1684
|
+
throw new Error(`corrupt session log: ${subject} is not valid JSON`, { cause: error });
|
|
1685
|
+
}
|
|
1686
|
+
}
|
|
1687
|
+
/** Incremental JSONL parser that retains only one cross-frame record fragment. */
|
|
1688
|
+
var MigratingJsonlRows = class {
|
|
1689
|
+
restore;
|
|
1690
|
+
fragments = [];
|
|
1691
|
+
fragmentBytes = 0;
|
|
1692
|
+
rowIndex = 0;
|
|
1693
|
+
issue;
|
|
1694
|
+
constructor(restore) {
|
|
1695
|
+
this.restore = restore;
|
|
1696
|
+
}
|
|
1697
|
+
/** Consume plaintext bytes following the independently decoded header. */
|
|
1698
|
+
write(chunk) {
|
|
1699
|
+
let lineStart = 0;
|
|
1700
|
+
for (let newline = chunk.indexOf(10); newline !== -1; newline = chunk.indexOf(10, lineStart)) {
|
|
1701
|
+
const fragment = chunk.subarray(lineStart, newline);
|
|
1702
|
+
let line = fragment;
|
|
1703
|
+
if (this.fragments.length > 0) {
|
|
1704
|
+
if (fragment.length > 0) this.fragments.push(fragment);
|
|
1705
|
+
line = Buffer.concat(this.fragments, this.fragmentBytes + fragment.length);
|
|
1706
|
+
this.fragments = [];
|
|
1707
|
+
this.fragmentBytes = 0;
|
|
1708
|
+
}
|
|
1709
|
+
this.consume(line);
|
|
1710
|
+
lineStart = newline + 1;
|
|
1711
|
+
}
|
|
1712
|
+
if (lineStart < chunk.length) {
|
|
1713
|
+
const fragment = Buffer.from(chunk.subarray(lineStart));
|
|
1714
|
+
this.fragments.push(fragment);
|
|
1715
|
+
this.fragmentBytes += fragment.length;
|
|
1716
|
+
}
|
|
1717
|
+
}
|
|
1718
|
+
/** Refuse a record fragment left by structurally complete Zstandard frames. */
|
|
1719
|
+
assertCompleteFramesEndOnRecord() {
|
|
1720
|
+
if (this.fragments.length > 0) throw new Error("corrupt Zstandard session log: complete frame contains a torn JSONL record");
|
|
1721
|
+
}
|
|
1722
|
+
finish() {
|
|
1723
|
+
return this.restore.finish();
|
|
1724
|
+
}
|
|
1725
|
+
consume(line) {
|
|
1726
|
+
const index = this.rowIndex;
|
|
1727
|
+
this.rowIndex += 1;
|
|
1728
|
+
let row;
|
|
1729
|
+
try {
|
|
1730
|
+
row = parseJson(line.toString("utf8"), `row ${index + 1}`);
|
|
1731
|
+
} catch (error) {
|
|
1732
|
+
this.issue ??= asError(error);
|
|
1733
|
+
return;
|
|
1734
|
+
}
|
|
1735
|
+
if (this.issue !== void 0) {
|
|
1736
|
+
if (typeof row === "object" && row !== null && row.type === "turn/end") throw this.issue;
|
|
1737
|
+
return;
|
|
1738
|
+
}
|
|
1739
|
+
this.restore.decodeRow(row);
|
|
1740
|
+
}
|
|
1741
|
+
};
|
|
1742
|
+
async function startMigrationStream(headerRecord, sourceVersion, format, validateHistoricalHeader) {
|
|
1743
|
+
const value = parseJson(headerRecord.subarray(0, -1).toString("utf8"), "header line");
|
|
1744
|
+
const version = storedVersion(value);
|
|
1745
|
+
if (version !== sourceVersion) throw new Error(`resolved JSONL source filename identifies v${sourceVersion}, but its header identifies v${version}`);
|
|
1746
|
+
const header = value;
|
|
1747
|
+
const validation = validateHistoricalHeader?.(header);
|
|
1748
|
+
if (validation !== void 0) await validation;
|
|
1749
|
+
return { parser: new MigratingJsonlRows(format.createRestore(header)) };
|
|
1750
|
+
}
|
|
1751
|
+
async function consumeMigrationBytes(rows, chunks, signal) {
|
|
1752
|
+
signal?.throwIfAborted();
|
|
1753
|
+
let yieldDeadline = performance.now() + MIGRATION_DECODE_YIELD_INTERVAL_MS;
|
|
1754
|
+
for (const bytes of chunks) for (let offset = 0; offset < bytes.length; offset += MIGRATION_WORK_CHUNK_BYTES) {
|
|
1755
|
+
rows.write(bytes.subarray(offset, offset + MIGRATION_WORK_CHUNK_BYTES));
|
|
1756
|
+
if (performance.now() < yieldDeadline) continue;
|
|
1757
|
+
await scheduler.yield();
|
|
1758
|
+
signal?.throwIfAborted();
|
|
1759
|
+
yieldDeadline = performance.now() + MIGRATION_DECODE_YIELD_INTERVAL_MS;
|
|
1760
|
+
}
|
|
1761
|
+
}
|
|
1762
|
+
async function decodeStreamingMigration(bytes, compression, sourceVersion, format, validateHistoricalHeader, signal) {
|
|
1763
|
+
signal?.throwIfAborted();
|
|
1764
|
+
if (compression === "none") {
|
|
1765
|
+
const headerEnd = bytes.indexOf(10);
|
|
1766
|
+
if (headerEnd === -1) throw new Error("empty or header-less session log");
|
|
1767
|
+
const stream = await startMigrationStream(bytes.subarray(0, headerEnd + 1), sourceVersion, format, validateHistoricalHeader);
|
|
1768
|
+
signal?.throwIfAborted();
|
|
1769
|
+
const bodyEnd = bytes.lastIndexOf(10);
|
|
1770
|
+
if (bodyEnd > headerEnd) await consumeMigrationBytes(stream.parser, [bytes.subarray(headerEnd + 1, bodyEnd + 1)], signal);
|
|
1771
|
+
return stream.parser.finish();
|
|
1772
|
+
}
|
|
1773
|
+
const { frames, tornStart } = scanZstdFrames(bytes);
|
|
1774
|
+
if (frames.length === 0) throw new Error("empty or header-less Zstandard session log");
|
|
1775
|
+
const decoder = createZstdFrameDecoder();
|
|
1776
|
+
try {
|
|
1777
|
+
const decoded = decoder.decode(bytes, frames);
|
|
1778
|
+
const first = decoded.next();
|
|
1779
|
+
/* v8 ignore next -- a non-empty structural frame list yields once or throws. */
|
|
1780
|
+
if (first.done) throw new Error("empty or header-less Zstandard session log");
|
|
1781
|
+
assertIndependentHeaderFrame(first.value);
|
|
1782
|
+
const stream = await startMigrationStream(first.value, sourceVersion, format, validateHistoricalHeader);
|
|
1783
|
+
signal?.throwIfAborted();
|
|
1784
|
+
await consumeMigrationBytes(stream.parser, decoded, signal);
|
|
1785
|
+
stream.parser.assertCompleteFramesEndOnRecord();
|
|
1786
|
+
if (tornStart !== void 0) {
|
|
1787
|
+
let recovered = Buffer.alloc(0);
|
|
1788
|
+
try {
|
|
1789
|
+
recovered = await decompressZstdPrefix(bytes.subarray(tornStart));
|
|
1790
|
+
} catch {
|
|
1791
|
+
/* v8 ignore next -- decoder failure plus concurrent abort is timing-dependent. */
|
|
1792
|
+
if (signal?.aborted) signal.throwIfAborted();
|
|
1793
|
+
}
|
|
1794
|
+
signal?.throwIfAborted();
|
|
1795
|
+
const newline = recovered.lastIndexOf(10);
|
|
1796
|
+
if (newline !== -1) await consumeMigrationBytes(stream.parser, [recovered.subarray(0, newline + 1)], signal);
|
|
1797
|
+
}
|
|
1798
|
+
return stream.parser.finish();
|
|
1799
|
+
} finally {
|
|
1800
|
+
decoder.close();
|
|
1801
|
+
}
|
|
1802
|
+
}
|
|
1803
|
+
async function verifyCurrentGeneration(path, compression, expectedId, expectedEventCount, fs, expectedPrefix) {
|
|
1804
|
+
const before = await fs.stat(path);
|
|
1805
|
+
const bytes = await fs.readFile(path);
|
|
1806
|
+
const after = await fs.stat(path);
|
|
1807
|
+
if (expectedPrefix !== void 0) {
|
|
1808
|
+
if (bytes.length < expectedPrefix.bytes) throw new Error("target bytes are shorter than the migrated generation");
|
|
1809
|
+
const digest = createHash("sha256").update(bytes.subarray(0, expectedPrefix.bytes)).digest("hex");
|
|
1810
|
+
if (digest !== expectedPrefix.digest) throw new Error("target bytes do not begin with the migrated generation");
|
|
1811
|
+
return {
|
|
1812
|
+
identity: after,
|
|
1813
|
+
bytes: expectedPrefix.bytes,
|
|
1814
|
+
digest
|
|
1815
|
+
};
|
|
1816
|
+
}
|
|
1817
|
+
if (identity(before) !== identity(after)) throw new Error("current session generation changed during verification");
|
|
1818
|
+
const snapshot = {
|
|
1819
|
+
bytes,
|
|
1820
|
+
identity: after
|
|
1821
|
+
};
|
|
1822
|
+
const generation = decodeCurrentGeneration(snapshot.bytes, compression);
|
|
1823
|
+
validateStoredEvents(generation.meta, generation.events, {
|
|
1824
|
+
kind: "jsonl",
|
|
1825
|
+
path
|
|
1826
|
+
});
|
|
1827
|
+
if (generation.meta.id !== expectedId) throw new Error(`current session generation contains id "${generation.meta.id}", expected "${expectedId}"`);
|
|
1828
|
+
if (generation.events.length !== expectedEventCount) throw new Error(`current session generation contains ${generation.events.length} events, expected ${expectedEventCount}`);
|
|
1829
|
+
Session.fromRestore(generation.meta.id, generation.events, generation.meta, generation.inheritedEventCount, "detached", currentSessionMessageProjections);
|
|
1830
|
+
assertCurrentAssistantStreams(generation.events);
|
|
1831
|
+
return {
|
|
1832
|
+
identity: snapshot.identity,
|
|
1833
|
+
bytes: snapshot.bytes.length,
|
|
1834
|
+
digest: createHash("sha256").update(snapshot.bytes).digest("hex")
|
|
1835
|
+
};
|
|
1836
|
+
}
|
|
1837
|
+
/** Fully replay embedded streams only inside isolated current-generation verification. */
|
|
1838
|
+
function assertCurrentAssistantStreams(events) {
|
|
1839
|
+
for (const [index, event] of events.entries()) {
|
|
1840
|
+
if (event.type !== "assistant/message" && event.type !== "assistant/attempt") continue;
|
|
1841
|
+
const assembler = new BlockAssembler();
|
|
1842
|
+
let timed;
|
|
1843
|
+
try {
|
|
1844
|
+
timed = expandAssistantStream(event.data.stream);
|
|
1845
|
+
for (const member of timed) assembler.push(member.chunk);
|
|
1846
|
+
} catch (error) {
|
|
1847
|
+
throw new Error(`seed ${event.type} at index ${index} has an invalid embedded stream`, { cause: error });
|
|
1848
|
+
}
|
|
1849
|
+
if (event.type === "assistant/attempt" || timed.length === 0) continue;
|
|
1850
|
+
const content = event.data.interrupted === true ? assembler.interruptedBlocks() : assembler.blocks();
|
|
1851
|
+
if (!isDeepStrictEqual(event.data.message.content, content)) throw new Error(`seed assistant/message at index ${index} content disagrees with its embedded stream`);
|
|
1852
|
+
if (!isDeepStrictEqual(event.data.usage, assembler.usage)) throw new Error(`seed assistant/message at index ${index} usage disagrees with its embedded stream`);
|
|
1853
|
+
if (!isDeepStrictEqual(event.data.message.source.replayState, assembler.replayState)) throw new Error(`seed assistant/message at index ${index} replay state disagrees with its embedded stream`);
|
|
1854
|
+
}
|
|
1855
|
+
}
|
|
1856
|
+
function decodeCurrentGeneration(bytes, compression) {
|
|
1857
|
+
if (compression === "none") {
|
|
1858
|
+
const headerEnd = bytes.indexOf(10);
|
|
1859
|
+
if (headerEnd === -1) throw new Error("empty or header-less session log");
|
|
1860
|
+
const scanner = new SessionLogScanner(bytes.subarray(0, headerEnd + 1), "strict");
|
|
1861
|
+
scanner.write(bytes.subarray(headerEnd + 1));
|
|
1862
|
+
return finishCurrentGenerationScan(scanner);
|
|
1863
|
+
}
|
|
1864
|
+
const { frames, tornStart } = scanZstdFrames(bytes);
|
|
1865
|
+
if (frames.length === 0) throw new Error("empty or header-less Zstandard session log");
|
|
1866
|
+
if (tornStart !== void 0) throw new Error("current session generation has a torn physical tail");
|
|
1867
|
+
const decoder = createZstdFrameDecoder();
|
|
1868
|
+
try {
|
|
1869
|
+
const plaintext = decoder.decode(bytes, frames);
|
|
1870
|
+
const header = plaintext.next();
|
|
1871
|
+
/* v8 ignore next -- a non-empty structural frame list yields once or throws. */
|
|
1872
|
+
if (header.done) throw new Error("empty or header-less Zstandard session log");
|
|
1873
|
+
assertIndependentHeaderFrame(header.value);
|
|
1874
|
+
const scanner = new SessionLogScanner(header.value, "strict");
|
|
1875
|
+
for (const chunk of plaintext) scanner.write(chunk);
|
|
1876
|
+
return finishCurrentGenerationScan(scanner);
|
|
1877
|
+
} finally {
|
|
1878
|
+
decoder.close();
|
|
1879
|
+
}
|
|
1880
|
+
}
|
|
1881
|
+
function finishCurrentGenerationScan(scanner) {
|
|
1882
|
+
const inputBytes = scanner.checkpoint().inputBytes;
|
|
1883
|
+
const decoded = scanner.finish();
|
|
1884
|
+
if (decoded.committedBytes !== inputBytes) throw new Error("current session generation has a torn physical tail");
|
|
1885
|
+
return decoded;
|
|
1886
|
+
}
|
|
1887
|
+
function stringifyJson(value, subject) {
|
|
1888
|
+
let text;
|
|
1889
|
+
try {
|
|
1890
|
+
text = JSON.stringify(value);
|
|
1891
|
+
} catch (error) {
|
|
1892
|
+
throw new Error(`${subject} is not lossless JSON`, { cause: error });
|
|
1893
|
+
}
|
|
1894
|
+
if (typeof text !== "string") throw new Error(`${subject} is not lossless JSON`);
|
|
1895
|
+
return text;
|
|
1896
|
+
}
|
|
1897
|
+
function assertIndependentHeaderFrame(plaintext) {
|
|
1898
|
+
if (plaintext.length === 0 || plaintext.indexOf(10) !== plaintext.length - 1) throw new Error("corrupt Zstandard session log: first frame is not exactly one header line");
|
|
1899
|
+
}
|
|
1900
|
+
function assertGenerationPaths(sourcePath, sourceVersion, currentPath, currentVersion, compression) {
|
|
1901
|
+
const expectedSource = generationLogFilename(sourceVersion, compression);
|
|
1902
|
+
const expectedCurrent = generationLogFilename(currentVersion, compression);
|
|
1903
|
+
if (basename(sourcePath) !== expectedSource) throw new Error(`resolved JSONL source path must end with "${expectedSource}": ${sourcePath}`);
|
|
1904
|
+
if (basename(currentPath) !== expectedCurrent) throw new Error(`current JSONL generation path must end with "${expectedCurrent}": ${currentPath}`);
|
|
1905
|
+
if (dirname(sourcePath) !== dirname(currentPath)) throw new Error("source and current JSONL generations must share one Session directory");
|
|
1906
|
+
return logSuffix(compression);
|
|
1907
|
+
}
|
|
1908
|
+
async function syncDirectory(path, internals) {
|
|
1909
|
+
/* v8 ignore next -- Windows namespace operations request write-through directly. */
|
|
1910
|
+
if (internals.platform === "win32") return;
|
|
1911
|
+
const handle = await internals.fs.open(path, "r");
|
|
1912
|
+
try {
|
|
1913
|
+
await handle.sync();
|
|
1914
|
+
} finally {
|
|
1915
|
+
await handle.close();
|
|
1916
|
+
}
|
|
1917
|
+
}
|
|
1918
|
+
/** Produce bounded JSONL chunks while yielding between main-thread encoding slices. */
|
|
1919
|
+
async function* encodeMigrationRows(artifact, format, signal) {
|
|
1920
|
+
signal?.throwIfAborted();
|
|
1921
|
+
let lines = [];
|
|
1922
|
+
let bytes = 0;
|
|
1923
|
+
for (const value of artifact.events) {
|
|
1924
|
+
const line = `${stringifyJson(format.encodeEvent(value), `migrated Session event ${value.seq}`)}\n`;
|
|
1925
|
+
const lineBytes = Buffer.byteLength(line);
|
|
1926
|
+
if (bytes > 0 && bytes + lineBytes > MIGRATION_WORK_CHUNK_BYTES) {
|
|
1927
|
+
yield Buffer.from(lines.join(""));
|
|
1928
|
+
await scheduler.yield();
|
|
1929
|
+
signal?.throwIfAborted();
|
|
1930
|
+
lines = [];
|
|
1931
|
+
bytes = 0;
|
|
1932
|
+
}
|
|
1933
|
+
lines.push(line);
|
|
1934
|
+
bytes += lineBytes;
|
|
1935
|
+
}
|
|
1936
|
+
yield Buffer.from(lines.join(""));
|
|
1937
|
+
}
|
|
1938
|
+
async function writeMigrationChunks(chunks, write) {
|
|
1939
|
+
let pending = [];
|
|
1940
|
+
let bytes = 0;
|
|
1941
|
+
for await (const chunk of chunks) {
|
|
1942
|
+
pending.push(chunk);
|
|
1943
|
+
bytes += chunk.length;
|
|
1944
|
+
if (bytes < MIGRATION_WRITE_CHUNK_BYTES) continue;
|
|
1945
|
+
await write(pending.length === 1 ? pending[0] : Buffer.concat(pending, bytes));
|
|
1946
|
+
pending = [];
|
|
1947
|
+
bytes = 0;
|
|
1948
|
+
}
|
|
1949
|
+
if (bytes > 0) await write(pending.length === 1 ? pending[0] : Buffer.concat(pending, bytes));
|
|
1950
|
+
}
|
|
1951
|
+
/** Encode directly into one synced stage without a whole-artifact row or byte buffer. */
|
|
1952
|
+
async function writeSyncedTemp(currentPath, suffix, compression, artifact, format, signal, internals) {
|
|
1953
|
+
signal?.throwIfAborted();
|
|
1954
|
+
let path;
|
|
1955
|
+
let handle;
|
|
1956
|
+
for (;;) {
|
|
1957
|
+
path = join(dirname(currentPath), `session.migration.${internals.randomToken()}${suffix}.tmp`);
|
|
1958
|
+
try {
|
|
1959
|
+
handle = await internals.fs.open(path, "wx", 384);
|
|
1960
|
+
break;
|
|
1961
|
+
} catch (error) {
|
|
1962
|
+
if (isEEXIST(error)) continue;
|
|
1963
|
+
throw error;
|
|
1964
|
+
}
|
|
1965
|
+
}
|
|
1966
|
+
const hash = createHash("sha256");
|
|
1967
|
+
let bytes = 0;
|
|
1968
|
+
const write = async (chunk) => {
|
|
1969
|
+
await handle.writeFile(chunk);
|
|
1970
|
+
hash.update(chunk);
|
|
1971
|
+
bytes += chunk.length;
|
|
1972
|
+
};
|
|
1973
|
+
let failure;
|
|
1974
|
+
try {
|
|
1975
|
+
const headerValue = format.encodeHeader(artifact.header, artifact.inheritedEventCount);
|
|
1976
|
+
const header = Buffer.from(`${stringifyJson(headerValue, "migrated session header")}\n`);
|
|
1977
|
+
await write(compression === "zstd" ? await compressZstdFrame(header) : header);
|
|
1978
|
+
if (artifact.events.length > 0) {
|
|
1979
|
+
const rows = encodeMigrationRows(artifact, format, signal);
|
|
1980
|
+
if (compression === "none") await writeMigrationChunks(rows, write);
|
|
1981
|
+
else await new Promise((resolve, reject) => {
|
|
1982
|
+
pipeline(Readable.from(rows, {
|
|
1983
|
+
objectMode: false,
|
|
1984
|
+
highWaterMark: MIGRATION_WORK_CHUNK_BYTES
|
|
1985
|
+
}), createZstdCompress(ZSTD_CHECKSUM_OPTIONS), async (source) => {
|
|
1986
|
+
await writeMigrationChunks(source, write);
|
|
1987
|
+
}, (error) => {
|
|
1988
|
+
if (error instanceof Error) reject(error);
|
|
1989
|
+
else resolve();
|
|
1990
|
+
});
|
|
1991
|
+
});
|
|
1992
|
+
}
|
|
1993
|
+
signal?.throwIfAborted();
|
|
1994
|
+
await handle.sync();
|
|
1995
|
+
} catch (error) {
|
|
1996
|
+
failure = error;
|
|
1997
|
+
}
|
|
1998
|
+
try {
|
|
1999
|
+
await handle.close();
|
|
2000
|
+
} catch (error) {
|
|
2001
|
+
failure = failure === void 0 ? error : new AggregateError([failure, error], `failed to write and close migration stage "${path}"`);
|
|
2002
|
+
}
|
|
2003
|
+
if (failure !== void 0) {
|
|
2004
|
+
const writeError = failure instanceof Error ? failure : new Error("migration stage write failed with a non-Error rejection", { cause: failure });
|
|
2005
|
+
await removeTemporary(path, writeError, internals);
|
|
2006
|
+
throw writeError;
|
|
2007
|
+
}
|
|
2008
|
+
return {
|
|
2009
|
+
path,
|
|
2010
|
+
bytes,
|
|
2011
|
+
digest: hash.digest("hex")
|
|
2012
|
+
};
|
|
2013
|
+
}
|
|
2014
|
+
/** Remove one temporary file without hiding the operation failure that made it disposable. */
|
|
2015
|
+
async function removeTemporary(path, primaryFailure, internals) {
|
|
2016
|
+
try {
|
|
2017
|
+
await internals.fs.rm(path);
|
|
2018
|
+
} catch (cleanupFailure) {
|
|
2019
|
+
throw new AggregateError([primaryFailure, cleanupFailure], `failed to clean migration temporary "${path}" after an earlier failure`);
|
|
2020
|
+
}
|
|
2021
|
+
}
|
|
2022
|
+
/** Remove a redundant stage after the target has been validated as committed. */
|
|
2023
|
+
async function removeCommittedTemporary(path, internals) {
|
|
2024
|
+
try {
|
|
2025
|
+
await internals.fs.rm(path);
|
|
2026
|
+
} catch {}
|
|
2027
|
+
}
|
|
2028
|
+
async function publishCurrentExclusive(staged, currentPath, internals) {
|
|
2029
|
+
if (internals.platform === "win32") try {
|
|
2030
|
+
await internals.publishNewWin32(staged, currentPath);
|
|
2031
|
+
return true;
|
|
2032
|
+
} catch (error) {
|
|
2033
|
+
/* v8 ignore else -- native helper tests own non-collision Win32 failures. */
|
|
2034
|
+
if (isEEXIST(error)) return false;
|
|
2035
|
+
/* v8 ignore next -- the filesystem error is already complete. */
|
|
2036
|
+
throw error;
|
|
2037
|
+
}
|
|
2038
|
+
try {
|
|
2039
|
+
await internals.fs.link(staged, currentPath);
|
|
2040
|
+
} catch (error) {
|
|
2041
|
+
/* v8 ignore else -- a non-collision filesystem error propagates unchanged. */
|
|
2042
|
+
if (isEEXIST(error)) return false;
|
|
2043
|
+
/* v8 ignore next -- the filesystem error is already complete. */
|
|
2044
|
+
throw error;
|
|
2045
|
+
}
|
|
2046
|
+
await syncDirectory(dirname(currentPath), internals);
|
|
2047
|
+
return true;
|
|
2048
|
+
}
|
|
2049
|
+
function asError(error) {
|
|
2050
|
+
return error instanceof Error ? error : new Error("current-generation validation failed with a non-Error rejection", { cause: error });
|
|
2051
|
+
}
|
|
2052
|
+
async function inspectExpectedCurrent(currentPath, internals, inspect) {
|
|
2053
|
+
try {
|
|
2054
|
+
const expectedName = basename(currentPath);
|
|
2055
|
+
const names = await internals.fs.readdir(dirname(currentPath));
|
|
2056
|
+
if (!names.includes(expectedName)) {
|
|
2057
|
+
const noncanonical = names.find((name) => name.toLowerCase() === expectedName.toLowerCase());
|
|
2058
|
+
if (noncanonical !== void 0) throw new Error(`target resolves to noncanonical directory entry "${noncanonical}"`);
|
|
2059
|
+
}
|
|
2060
|
+
const info = await internals.fs.lstat(currentPath);
|
|
2061
|
+
if (info.isSymbolicLink() || !info.isFile()) throw new Error(`target is a ${info.isSymbolicLink() ? "symbolic link" : "non-regular file"}`);
|
|
2062
|
+
return await inspect();
|
|
2063
|
+
} catch (error) {
|
|
2064
|
+
if (isErrnoException$1(error)) throw error;
|
|
2065
|
+
throw new JsonlGenerationTargetConflictError(currentPath, asError(error));
|
|
2066
|
+
}
|
|
2067
|
+
}
|
|
2068
|
+
function withOverrides(overrides) {
|
|
2069
|
+
return {
|
|
2070
|
+
...defaultInternals,
|
|
2071
|
+
...overrides,
|
|
2072
|
+
fs: {
|
|
2073
|
+
...defaultFileSystem,
|
|
2074
|
+
...overrides.fs
|
|
2075
|
+
}
|
|
2076
|
+
};
|
|
2077
|
+
}
|
|
2078
|
+
async function publishPreparedMigration(options, suffix, artifact, sourceIdentity, internals) {
|
|
2079
|
+
await scheduler.yield();
|
|
2080
|
+
const { sourcePath, currentPath, compression, verifyCurrentFile } = options;
|
|
2081
|
+
const eventCount = artifact.events.length;
|
|
2082
|
+
let staged = await writeSyncedTemp(currentPath, suffix, compression, artifact, options.format, void 0, internals);
|
|
2083
|
+
try {
|
|
2084
|
+
const verifiedStage = await verifyCurrentFile(staged.path, compression, artifact.header.id, eventCount);
|
|
2085
|
+
if (verifiedStage.bytes !== staged.bytes || verifiedStage.digest !== staged.digest) throw new Error("staged session generation changed during verification");
|
|
2086
|
+
await internals.barrier("before-source-check", 1);
|
|
2087
|
+
await options.validateRelatedSources?.();
|
|
2088
|
+
if (identity(await internals.fs.stat(sourcePath)) !== identity(sourceIdentity)) throw new JsonlGenerationSourceChangedError(sourcePath);
|
|
2089
|
+
const published = await publishCurrentExclusive(staged.path, currentPath, internals);
|
|
2090
|
+
if (published && internals.platform === "win32") staged = {
|
|
2091
|
+
...staged,
|
|
2092
|
+
path: ""
|
|
2093
|
+
};
|
|
2094
|
+
await internals.barrier("after-publication", 1);
|
|
2095
|
+
let currentIdentity;
|
|
2096
|
+
if (published) {
|
|
2097
|
+
if (staged.path !== "") {
|
|
2098
|
+
await removeCommittedTemporary(staged.path, internals);
|
|
2099
|
+
staged = {
|
|
2100
|
+
...staged,
|
|
2101
|
+
path: ""
|
|
2102
|
+
};
|
|
2103
|
+
}
|
|
2104
|
+
currentIdentity = await internals.fs.stat(currentPath);
|
|
2105
|
+
} else {
|
|
2106
|
+
currentIdentity = (await inspectExpectedCurrent(currentPath, internals, async () => {
|
|
2107
|
+
const candidate = await verifyCurrentFile(currentPath, compression, artifact.header.id, eventCount, staged);
|
|
2108
|
+
if (candidate.bytes !== staged.bytes || candidate.digest !== staged.digest) throw new Error("target bytes differ from the migrated generation");
|
|
2109
|
+
return candidate;
|
|
2110
|
+
})).identity;
|
|
2111
|
+
await removeCommittedTemporary(staged.path, internals);
|
|
2112
|
+
staged = {
|
|
2113
|
+
...staged,
|
|
2114
|
+
path: ""
|
|
2115
|
+
};
|
|
2116
|
+
}
|
|
2117
|
+
return currentIdentity;
|
|
2118
|
+
} catch (error) {
|
|
2119
|
+
if (staged.path !== "") await removeTemporary(staged.path, error, internals);
|
|
2120
|
+
throw error;
|
|
2121
|
+
}
|
|
2122
|
+
}
|
|
2123
|
+
async function prepareMigration(options, internals) {
|
|
2124
|
+
const { sourcePath, sourceVersion, currentPath, compression, format, signal } = options;
|
|
2125
|
+
const suffix = assertGenerationPaths(sourcePath, sourceVersion, currentPath, format.currentVersion, compression);
|
|
2126
|
+
if (sourceVersion >= format.currentVersion) throw new Error(`migration preparation requires a historical source, got v${sourceVersion}`);
|
|
2127
|
+
const source = await readStableSnapshot(sourcePath, signal, internals.fs);
|
|
2128
|
+
let artifact;
|
|
2129
|
+
try {
|
|
2130
|
+
artifact = await decodeStreamingMigration(source.bytes, compression, sourceVersion, format, options.validateHistoricalHeader, signal);
|
|
2131
|
+
} catch (error) {
|
|
2132
|
+
if (format.isUnsupportedMigrationError?.(error) === true) throw new JsonlGenerationUnsupportedMigrationError(sourceVersion, error);
|
|
2133
|
+
throw error;
|
|
2134
|
+
}
|
|
2135
|
+
if (artifact.header.version !== format.currentVersion) throw new Error(`format migration returned v${artifact.header.version}, expected v${format.currentVersion}`);
|
|
2136
|
+
await options.validateRelatedSources?.();
|
|
2137
|
+
const sourceIdentity = source.identity;
|
|
2138
|
+
let publication;
|
|
2139
|
+
return {
|
|
2140
|
+
sourceIdentity,
|
|
2141
|
+
artifact,
|
|
2142
|
+
publish() {
|
|
2143
|
+
if (publication === void 0) publication = publishPreparedMigration(options, suffix, artifact, sourceIdentity, internals);
|
|
2144
|
+
return publication;
|
|
2145
|
+
}
|
|
2146
|
+
};
|
|
2147
|
+
}
|
|
2148
|
+
/**
|
|
2149
|
+
* Decode and migrate one historical generation without writing its successor.
|
|
2150
|
+
* @param options - resolved source, current target, format adapter, and load cancellation.
|
|
2151
|
+
* @returns the current artifact and an idempotent explicit publication operation.
|
|
2152
|
+
*/
|
|
2153
|
+
function prepareJsonlMigration(options) {
|
|
2154
|
+
return defaultGenerationRuntime.prepare(options);
|
|
2155
|
+
}
|
|
2156
|
+
/**
|
|
2157
|
+
* Create one generation runtime with fixed filesystem and publication dependencies.
|
|
2158
|
+
* @param overrides - deterministic filesystem, platform, and race dependencies.
|
|
2159
|
+
* @returns bound generation operations.
|
|
2160
|
+
*/
|
|
2161
|
+
function createJsonlGenerationRuntime(overrides = {}) {
|
|
2162
|
+
const internals = withOverrides(overrides);
|
|
2163
|
+
return {
|
|
2164
|
+
readStable: (path, signal) => readStableSnapshot(path, signal, internals.fs),
|
|
2165
|
+
prepare: (options) => prepareMigration(options, internals),
|
|
2166
|
+
verify: (path, compression, expectedId, expectedEventCount, expectedPrefix) => verifyCurrentGeneration(path, compression, expectedId, expectedEventCount, internals.fs, expectedPrefix)
|
|
2167
|
+
};
|
|
2168
|
+
}
|
|
2169
|
+
const defaultGenerationRuntime = createJsonlGenerationRuntime();
|
|
2170
|
+
/**
|
|
2171
|
+
* Read one stable source through the shared streaming parser without publishing a generation.
|
|
2172
|
+
* @param path - selected source generation path.
|
|
2173
|
+
* @param version - physical source version identified by its filename.
|
|
2174
|
+
* @param compression - source encoding.
|
|
2175
|
+
* @param format - codec/restore factory, independent of current-generation publication.
|
|
2176
|
+
* @param signal - cancellation observed during source reads and decode yields.
|
|
2177
|
+
* @returns decoded artifact and physical source identity for later revalidation.
|
|
2178
|
+
* @throws SessionFormatError for physical decoding failures; storage, cancellation, and unsupported migration errors retain their category.
|
|
2179
|
+
*/
|
|
2180
|
+
async function readDecodedJsonlSource(path, version, compression, format, signal) {
|
|
2181
|
+
const source = await readStableJsonlFile(path, signal);
|
|
2182
|
+
let artifact;
|
|
2183
|
+
try {
|
|
2184
|
+
artifact = await decodeStreamingMigration(source.bytes, compression, version, format, void 0, signal);
|
|
2185
|
+
} catch (error) {
|
|
2186
|
+
if (signal?.aborted || error instanceof SessionFormatError) throw error;
|
|
2187
|
+
throw new SessionFormatError(String(error), { cause: error });
|
|
2188
|
+
}
|
|
2189
|
+
return {
|
|
2190
|
+
artifact,
|
|
2191
|
+
identity: source.identity
|
|
2192
|
+
};
|
|
2193
|
+
}
|
|
2194
|
+
//#endregion
|
|
2195
|
+
//#region lib/types/catalog-migration.js
|
|
2196
|
+
/** Collect historical discovery facts without recursively preparing related current generations. */
|
|
2197
|
+
/**
|
|
2198
|
+
* Collect each related child's own descriptor through existing historical codecs.
|
|
2199
|
+
* @param parentId - parent whose incoming migration consumes these facts.
|
|
2200
|
+
* @param sources - header-indexed direct children in the selected source corpus.
|
|
2201
|
+
* @param compression - configured source encoding.
|
|
2202
|
+
* @param signal - cancellation forwarded through each source read.
|
|
2203
|
+
* @returns compact facts and child-local failures; complete child event arrays are released after extraction.
|
|
2204
|
+
*/
|
|
2205
|
+
async function prepareCatalogFacts(parentId, sources, compression, signal) {
|
|
2206
|
+
const facts = [];
|
|
2207
|
+
const failures = [];
|
|
2208
|
+
const witnesses = [];
|
|
2209
|
+
for (const source of sources) {
|
|
2210
|
+
signal.throwIfAborted();
|
|
2211
|
+
const version = parseGenerationLogFilename(basename(source.path), compression);
|
|
2212
|
+
if (version === void 0) throw new SessionFormatUnsupportedMigrationError$1(`unrecognized historical child generation ${source.path}`);
|
|
2213
|
+
const witness = {
|
|
2214
|
+
path: source.path,
|
|
2215
|
+
identity: await stat(source.path, { bigint: true })
|
|
2216
|
+
};
|
|
2217
|
+
witnesses.push(witness);
|
|
2218
|
+
const unavailable = {
|
|
2219
|
+
childId: source.header.id,
|
|
2220
|
+
childCreatedAt: source.header.createdAt,
|
|
2221
|
+
descriptorCount: 0,
|
|
2222
|
+
descriptor: null,
|
|
2223
|
+
sourcePath: source.path
|
|
2224
|
+
};
|
|
2225
|
+
let restored;
|
|
2226
|
+
try {
|
|
2227
|
+
restored = await readDecodedJsonlSource(source.path, version, compression, { createRestore: (header) => (version <= 3 ? historicalSessionFormatCatalog : sessionFormatCatalog).createRestore(header, {
|
|
2228
|
+
recovery: "recoverable",
|
|
2229
|
+
validation: "current"
|
|
2230
|
+
}) }, signal);
|
|
2231
|
+
} catch (error) {
|
|
2232
|
+
signal.throwIfAborted();
|
|
2233
|
+
failures.push({
|
|
2234
|
+
path: source.path,
|
|
2235
|
+
error
|
|
2236
|
+
});
|
|
2237
|
+
facts.push(unavailable);
|
|
2238
|
+
continue;
|
|
2239
|
+
}
|
|
2240
|
+
witness.identity = restored.identity;
|
|
2241
|
+
const header = restored.artifact.header;
|
|
2242
|
+
if (header.id !== source.header.id || header.createdAt !== source.header.createdAt || header.parentSession !== parentId || header.origin !== "subagent" || [
|
|
2243
|
+
"cwd",
|
|
2244
|
+
"isSeeded",
|
|
2245
|
+
"delegationDepth",
|
|
2246
|
+
"agentPreset"
|
|
2247
|
+
].some((key) => header[key] !== source.header[key])) throw new JsonlGenerationSourceChangedError(source.path);
|
|
2248
|
+
let fact;
|
|
2249
|
+
try {
|
|
2250
|
+
fact = historicalChildCatalogSource(restored.artifact);
|
|
2251
|
+
} catch (error) {
|
|
2252
|
+
failures.push({
|
|
2253
|
+
path: source.path,
|
|
2254
|
+
error
|
|
2255
|
+
});
|
|
2256
|
+
facts.push(unavailable);
|
|
2257
|
+
continue;
|
|
2258
|
+
}
|
|
2259
|
+
facts.push({
|
|
2260
|
+
...fact,
|
|
2261
|
+
sourcePath: source.path
|
|
2262
|
+
});
|
|
2263
|
+
}
|
|
2264
|
+
return {
|
|
2265
|
+
facts,
|
|
2266
|
+
failures,
|
|
2267
|
+
async validate() {
|
|
2268
|
+
for (const witness of witnesses) {
|
|
2269
|
+
const current = await stat(witness.path, { bigint: true });
|
|
2270
|
+
if (current.dev !== witness.identity.dev || current.ino !== witness.identity.ino || current.size !== witness.identity.size || current.mtimeNs !== witness.identity.mtimeNs || current.ctimeNs !== witness.identity.ctimeNs) throw new JsonlGenerationSourceChangedError(witness.path);
|
|
2271
|
+
}
|
|
2272
|
+
}
|
|
2273
|
+
};
|
|
2274
|
+
}
|
|
2275
|
+
//#endregion
|
|
2276
|
+
//#region lib/types/index.js
|
|
2277
|
+
/**
|
|
2278
|
+
* JSONL durable session-persistence backend. It stores a header and contiguous
|
|
2279
|
+
* events in immutable generation files under one directory per session and serves the handle-based
|
|
2280
|
+
* `SessionPersistence` API: `create`/`open` return per-session handles, and
|
|
2281
|
+
* every read validates the same fail-closed storage contract.
|
|
2282
|
+
* @module @unieai/rabi-session-persistence-jsonl
|
|
2283
|
+
*/
|
|
2284
|
+
/**
|
|
2285
|
+
* Internal handoff-reuse policy, not deployment configuration: a cold
|
|
2286
|
+
* observation and the resume that immediately follows it reuse one parsed
|
|
2287
|
+
* log, so the memo only needs the sessions in flight between those steps.
|
|
2288
|
+
*/
|
|
2289
|
+
const COLD_LOG_MEMO_MAX_ENTRIES = 2;
|
|
2290
|
+
const DEFAULT_COMPRESSION = "zstd";
|
|
2291
|
+
/**
|
|
2292
|
+
* Internal scheduling constant, not deployment configuration: balance
|
|
2293
|
+
* frame-boundary event-loop yields against `setImmediate` overhead. One frame
|
|
2294
|
+
* remains an indivisible synchronous decode.
|
|
2295
|
+
*/
|
|
2296
|
+
const ZSTD_DECODE_YIELD_INTERVAL_MS = 500;
|
|
2297
|
+
/** Assert that the independently decodable first frame contains only the header record. */
|
|
2298
|
+
function assertZstdHeaderFrame(plaintext) {
|
|
2299
|
+
if (plaintext.length === 0 || plaintext.indexOf(10) !== plaintext.length - 1) throw new Error("corrupt Zstandard session log: first frame is not exactly one header line");
|
|
2300
|
+
}
|
|
2301
|
+
/** Loader schema for the JSONL artifact's physical encoding. */
|
|
2302
|
+
const JsonlCompressionSchema = z.union([z.const("zstd"), z.const("none")]).default(DEFAULT_COMPRESSION);
|
|
2303
|
+
/** Default maximum listing filesystem operations in flight per backend. */
|
|
2304
|
+
const DEFAULT_LIST_CONCURRENCY = 3;
|
|
2305
|
+
/** Deep-freeze acyclic stored JSON; its arrays contain only indexed JSON values. */
|
|
2306
|
+
function freezeStoredEvent(event) {
|
|
2307
|
+
const pending = [event];
|
|
2308
|
+
while (pending.length > 0) {
|
|
2309
|
+
const current = pending.pop();
|
|
2310
|
+
Object.freeze(current);
|
|
2311
|
+
if (Array.isArray(current)) for (let index = 0; index < current.length; index += 1) {
|
|
2312
|
+
const child = current[index];
|
|
2313
|
+
if (child !== null && typeof child === "object") pending.push(child);
|
|
2314
|
+
}
|
|
2315
|
+
else for (const key in current) {
|
|
2316
|
+
const child = current[key];
|
|
2317
|
+
if (child !== null && typeof child === "object") pending.push(child);
|
|
2318
|
+
}
|
|
2319
|
+
}
|
|
2320
|
+
}
|
|
2321
|
+
/** Establish immutable sharing for one decoded event graph and report that state. */
|
|
2322
|
+
function freezeStoredEvents(events) {
|
|
2323
|
+
for (const event of events) freezeStoredEvent(event);
|
|
2324
|
+
Object.freeze(events);
|
|
2325
|
+
return {
|
|
2326
|
+
eventState: "shared-frozen",
|
|
2327
|
+
events
|
|
2328
|
+
};
|
|
2329
|
+
}
|
|
2330
|
+
/** Build the stat-derived best-effort change token shared by full and lightweight reads. */
|
|
2331
|
+
function fileRevision(identity) {
|
|
2332
|
+
return SessionPersistenceRevision([
|
|
2333
|
+
identity.dev,
|
|
2334
|
+
identity.ino,
|
|
2335
|
+
identity.size,
|
|
2336
|
+
identity.mtimeNs,
|
|
2337
|
+
identity.ctimeNs
|
|
2338
|
+
].join(":"));
|
|
2339
|
+
}
|
|
2340
|
+
/** Whether a filesystem error means absence; every non-ENOENT failure must surface. */
|
|
2341
|
+
function isENOENT(error) {
|
|
2342
|
+
return error?.code === "ENOENT";
|
|
2343
|
+
}
|
|
2344
|
+
/**
|
|
2345
|
+
* Run `task` over `items` through the backend's shared listing limiter and
|
|
2346
|
+
* settle every call. Callers consume the outcomes in input order, so the first
|
|
2347
|
+
* failure they report matches a sequential loop whatever the completion order.
|
|
2348
|
+
* A limited task must never wait on the same limiter.
|
|
2349
|
+
* @param limit - the backend's shared listing limiter.
|
|
2350
|
+
* @param items - inputs in their sequential order.
|
|
2351
|
+
* @param task - per-item operation.
|
|
2352
|
+
* @returns one outcome per item, in input order.
|
|
2353
|
+
*/
|
|
2354
|
+
function settleLimited(limit, items, task) {
|
|
2355
|
+
return Promise.allSettled(items.map((item) => limit(() => task(item))));
|
|
2356
|
+
}
|
|
2357
|
+
/**
|
|
2358
|
+
* Unwrap outcomes from {@link settleLimited}, rethrowing the first rejection in input order.
|
|
2359
|
+
* @param outcomes - outcomes in input order.
|
|
2360
|
+
* @returns the fulfilled values in input order.
|
|
2361
|
+
*/
|
|
2362
|
+
function settledValues(outcomes) {
|
|
2363
|
+
return outcomes.map((outcome) => {
|
|
2364
|
+
if (outcome.status === "rejected") throw outcome.reason;
|
|
2365
|
+
return outcome.value;
|
|
2366
|
+
});
|
|
2367
|
+
}
|
|
2368
|
+
/** Whether a filesystem-owned failure should retain its original errno and path. */
|
|
2369
|
+
function isErrnoException(error) {
|
|
2370
|
+
return typeof error?.code === "string";
|
|
2371
|
+
}
|
|
2372
|
+
/** Preserve an Error abort reason and normalize hostile non-Error reasons. */
|
|
2373
|
+
function abortError(signal) {
|
|
2374
|
+
return signal.reason instanceof Error ? signal.reason : new Error("session migration preparation aborted", { cause: signal.reason });
|
|
2375
|
+
}
|
|
2376
|
+
/** Let one caller stop waiting without transferring cancellation ownership to shared work. */
|
|
2377
|
+
function waitWithAbort(operation, signal) {
|
|
2378
|
+
if (signal === void 0) return operation;
|
|
2379
|
+
/* v8 ignore next -- requireStoredLog synchronously rechecks the signal immediately before waiting. */
|
|
2380
|
+
if (signal.aborted) return Promise.reject(abortError(signal));
|
|
2381
|
+
return new Promise((resolve, reject) => {
|
|
2382
|
+
const stopWaiting = () => {
|
|
2383
|
+
reject(abortError(signal));
|
|
2384
|
+
};
|
|
2385
|
+
signal.addEventListener("abort", stopWaiting, { once: true });
|
|
2386
|
+
operation.then((value) => {
|
|
2387
|
+
signal.removeEventListener("abort", stopWaiting);
|
|
2388
|
+
resolve(value);
|
|
2389
|
+
}, (error) => {
|
|
2390
|
+
signal.removeEventListener("abort", stopWaiting);
|
|
2391
|
+
/* v8 ignore else -- the preparation owner normalizes every rejection before this waiter sees it. */
|
|
2392
|
+
if (error instanceof Error) reject(error);
|
|
2393
|
+
else reject(new Error("session migration preparation failed", { cause: error }));
|
|
2394
|
+
});
|
|
2395
|
+
});
|
|
2396
|
+
}
|
|
2397
|
+
/**
|
|
2398
|
+
* The JSONL backend registered as `ctx.sessionPersistence` by the plugin.
|
|
2399
|
+
* Sessions materialize lazily: a created session is
|
|
2400
|
+
* visible to this process immediately, reaches disk on its first append or
|
|
2401
|
+
* flush, and never existed if the process crashes before that.
|
|
2402
|
+
*/
|
|
2403
|
+
var JsonlSessionPersistence = class extends SessionPersistence {
|
|
2404
|
+
config;
|
|
2405
|
+
tracker;
|
|
2406
|
+
/** Backend label for diagnostics and effects; shadows `Service.name` without changing the service key. */
|
|
2407
|
+
name = "session-persistence-jsonl";
|
|
2408
|
+
root;
|
|
2409
|
+
compression;
|
|
2410
|
+
/**
|
|
2411
|
+
* Bounds directory, header, and stat I/O across every concurrent listing of
|
|
2412
|
+
* this backend (`list()`, the root encoding check, historical fingerprints).
|
|
2413
|
+
* Queued tasks of a cancelled listing run and reject at their signal check.
|
|
2414
|
+
*/
|
|
2415
|
+
listLimit;
|
|
2416
|
+
rootEncodingCheck;
|
|
2417
|
+
generationFormat;
|
|
2418
|
+
/**
|
|
2419
|
+
* Bounded LRU of parsed, validated stored logs keyed by session id and
|
|
2420
|
+
* guarded by the stat-derived revision, so an immediate cold-read handoff
|
|
2421
|
+
* (observation then resume) parses the artifact once. Every local mutation
|
|
2422
|
+
* for an id invalidates its entry; a foreign write misses through the
|
|
2423
|
+
* revision guard.
|
|
2424
|
+
*/
|
|
2425
|
+
coldLogMemo = /* @__PURE__ */ new Map();
|
|
2426
|
+
/** One joinable decode/migration operation per selected historical Session file revision. */
|
|
2427
|
+
migrationPreparations = /* @__PURE__ */ new Map();
|
|
2428
|
+
constructor(ctx, config, tracker) {
|
|
2429
|
+
super(ctx);
|
|
2430
|
+
this.config = config;
|
|
2431
|
+
this.tracker = tracker;
|
|
2432
|
+
/* v8 ignore next 5 -- generated catalog and Session source share one build-time version owner. */
|
|
2433
|
+
if (sessionFormatCatalog.currentVersion !== SESSION_FORMAT_VERSION) throw new Error(`session-persistence-jsonl: format catalog v${sessionFormatCatalog.currentVersion} does not match Session v${SESSION_FORMAT_VERSION}`);
|
|
2434
|
+
this.root = resolve(config.root);
|
|
2435
|
+
this.compression = config.compression ?? DEFAULT_COMPRESSION;
|
|
2436
|
+
this.listLimit = pLimit(config.listConcurrency ?? DEFAULT_LIST_CONCURRENCY);
|
|
2437
|
+
this.generationFormat = {
|
|
2438
|
+
currentVersion: sessionFormatCatalog.currentVersion,
|
|
2439
|
+
encodeHeader: (header, inheritedEventCount) => sessionFormatCatalog.encodeCurrentHeader(header, inheritedEventCount),
|
|
2440
|
+
encodeEvent: (event) => sessionFormatCatalog.encodeCurrentEvent(event),
|
|
2441
|
+
isUnsupportedMigrationError: (error) => error instanceof SessionFormatUnsupportedMigrationError
|
|
2442
|
+
};
|
|
2443
|
+
this.assertUsableRoot();
|
|
2444
|
+
}
|
|
2445
|
+
/**
|
|
2446
|
+
* Refusal-diagnostics hook: the absolute target path, without touching the filesystem.
|
|
2447
|
+
* @param meta - the stored header naming the session and its cwd.
|
|
2448
|
+
* @returns the artifact kind and absolute path.
|
|
2449
|
+
*/
|
|
2450
|
+
locate(meta) {
|
|
2451
|
+
return {
|
|
2452
|
+
kind: "jsonl",
|
|
2453
|
+
path: logPath(this.root, meta.cwd, meta.id, this.compression)
|
|
2454
|
+
};
|
|
2455
|
+
}
|
|
2456
|
+
/**
|
|
2457
|
+
* Create a new stored session and take its write ownership. The session is
|
|
2458
|
+
* visible to this process immediately; the physical artifact appears on the
|
|
2459
|
+
* first append or flush.
|
|
2460
|
+
* @param header - the immutable header to store; must be losslessly
|
|
2461
|
+
* JSON-serializable with a non-negative safe-integer `createdAt`.
|
|
2462
|
+
* @param options - optional cancellation.
|
|
2463
|
+
* @returns the owned write handle.
|
|
2464
|
+
*/
|
|
2465
|
+
async create(header, options) {
|
|
2466
|
+
options?.signal?.throwIfAborted();
|
|
2467
|
+
const snapshot = materializeCreateHeader(header);
|
|
2468
|
+
toHeaderLine(snapshot, options?.inheritedEventCount);
|
|
2469
|
+
const inheritedEventCount = SessionLogOffset(options?.inheritedEventCount ?? 0);
|
|
2470
|
+
await this.ensureRootEncoding();
|
|
2471
|
+
options?.signal?.throwIfAborted();
|
|
2472
|
+
if (this.tracker.hasPending(snapshot.id) || await this.findLog(snapshot.id, options?.signal) !== void 0) throw new SessionAlreadyExistsError(snapshot.id);
|
|
2473
|
+
options?.signal?.throwIfAborted();
|
|
2474
|
+
this.tracker.registerCreated(snapshot, inheritedEventCount);
|
|
2475
|
+
return this.tracker.adopt(new JsonlSessionHandle(this, snapshot.id, snapshot, "write", {
|
|
2476
|
+
cursor: 0,
|
|
2477
|
+
materialized: false,
|
|
2478
|
+
inheritedEventCount
|
|
2479
|
+
}));
|
|
2480
|
+
}
|
|
2481
|
+
/**
|
|
2482
|
+
* Open an existing stored session for `read` or single-writer `write`.
|
|
2483
|
+
* @param id - the stored session to open.
|
|
2484
|
+
* @param access - `read` (no ownership) or `write` (atomic in-process claim).
|
|
2485
|
+
* @param options - optional cancellation.
|
|
2486
|
+
* @returns the open handle.
|
|
2487
|
+
*/
|
|
2488
|
+
async open(id, access, options) {
|
|
2489
|
+
options?.signal?.throwIfAborted();
|
|
2490
|
+
await this.ensureRootEncoding();
|
|
2491
|
+
options?.signal?.throwIfAborted();
|
|
2492
|
+
const pending = this.tracker.pendingOf(id);
|
|
2493
|
+
if (access === "read") {
|
|
2494
|
+
if (pending !== void 0) return this.tracker.adopt(new JsonlSessionHandle(this, id, pending.header, "read", {
|
|
2495
|
+
cursor: 0,
|
|
2496
|
+
materialized: false,
|
|
2497
|
+
inheritedEventCount: pending.inheritedEventCount
|
|
2498
|
+
}));
|
|
2499
|
+
let stored;
|
|
2500
|
+
try {
|
|
2501
|
+
stored = await this.requireStoredLog(id, options?.signal);
|
|
2502
|
+
} catch (error) {
|
|
2503
|
+
if (!(error instanceof JsonlGenerationSourceChangedError)) throw error;
|
|
2504
|
+
stored = await this.requireStoredLog(id, options?.signal);
|
|
2505
|
+
}
|
|
2506
|
+
let state;
|
|
2507
|
+
if (stored.status === "prepared") state = {
|
|
2508
|
+
cursor: 0,
|
|
2509
|
+
materialized: true,
|
|
2510
|
+
inheritedEventCount: stored.inheritedEventCount,
|
|
2511
|
+
primed: stored
|
|
2512
|
+
};
|
|
2513
|
+
else state = {
|
|
2514
|
+
cursor: 0,
|
|
2515
|
+
materialized: true,
|
|
2516
|
+
inheritedEventCount: stored.inheritedEventCount
|
|
2517
|
+
};
|
|
2518
|
+
return this.tracker.adopt(new JsonlSessionHandle(this, id, stored.meta, "read", state));
|
|
2519
|
+
}
|
|
2520
|
+
this.tracker.claimWrite(id);
|
|
2521
|
+
let lease;
|
|
2522
|
+
try {
|
|
2523
|
+
const resolved = await this.findLog(id, options?.signal);
|
|
2524
|
+
if (resolved === void 0) throw new SessionPersistenceNotFoundError(id);
|
|
2525
|
+
lease = await this.acquireLease(id, void 0, dirname(resolved.currentPath));
|
|
2526
|
+
const prepared = await this.requireStoredLog(id, options?.signal);
|
|
2527
|
+
options?.signal?.throwIfAborted();
|
|
2528
|
+
let stored;
|
|
2529
|
+
if (prepared.status === "prepared") stored = await this.publishStoredMigration(id, prepared);
|
|
2530
|
+
else stored = prepared;
|
|
2531
|
+
options?.signal?.throwIfAborted();
|
|
2532
|
+
return this.tracker.adopt(new JsonlSessionHandle(this, id, stored.meta, "write", {
|
|
2533
|
+
cursor: stored.events.length,
|
|
2534
|
+
materialized: true,
|
|
2535
|
+
tornTruncateTo: stored.tornTruncateTo,
|
|
2536
|
+
recoveredTail: stored.recoveredTail,
|
|
2537
|
+
inheritedEventCount: stored.inheritedEventCount,
|
|
2538
|
+
primed: stored
|
|
2539
|
+
}, lease));
|
|
2540
|
+
} catch (error) {
|
|
2541
|
+
/* v8 ignore next -- typed backends and fs reject with Error */
|
|
2542
|
+
const failure = error instanceof Error ? error : new Error(String(error));
|
|
2543
|
+
let releaseFailure;
|
|
2544
|
+
try {
|
|
2545
|
+
await lease?.release();
|
|
2546
|
+
} catch (raw) {
|
|
2547
|
+
/* v8 ignore next -- lock releases reject with Error */
|
|
2548
|
+
releaseFailure = raw instanceof Error ? raw : new Error(String(raw));
|
|
2549
|
+
}
|
|
2550
|
+
this.tracker.releaseClaim(id);
|
|
2551
|
+
if (releaseFailure !== void 0) throw new AggregateError([failure, releaseFailure], `session "${id}": write open failed and its lock release failed`);
|
|
2552
|
+
throw failure;
|
|
2553
|
+
}
|
|
2554
|
+
}
|
|
2555
|
+
/**
|
|
2556
|
+
* Flush every active write handle in one durability barrier; see the seam
|
|
2557
|
+
* contract.
|
|
2558
|
+
* @returns resolution once every write handle active at the call has flushed.
|
|
2559
|
+
*/
|
|
2560
|
+
flush() {
|
|
2561
|
+
return this.tracker.flushAll();
|
|
2562
|
+
}
|
|
2563
|
+
/**
|
|
2564
|
+
* Observe one stored session without reading its event log.
|
|
2565
|
+
* @param id - the stored session to observe.
|
|
2566
|
+
* @param options - optional cancellation.
|
|
2567
|
+
* @returns the snapshot (`sizeBytes` carries the physical artifact size), or
|
|
2568
|
+
* `undefined` when the session does not exist.
|
|
2569
|
+
*/
|
|
2570
|
+
async stat(id, options) {
|
|
2571
|
+
options?.signal?.throwIfAborted();
|
|
2572
|
+
await this.ensureRootEncoding();
|
|
2573
|
+
options?.signal?.throwIfAborted();
|
|
2574
|
+
const pending = this.tracker.pendingOf(id);
|
|
2575
|
+
if (pending !== void 0) return {
|
|
2576
|
+
header: pending.header,
|
|
2577
|
+
revision: pending.revision
|
|
2578
|
+
};
|
|
2579
|
+
const selected = await this.findLog(id, options?.signal);
|
|
2580
|
+
if (selected === void 0) return void 0;
|
|
2581
|
+
const metadata = await this.readGenerationHeader(selected, id, options?.signal);
|
|
2582
|
+
if (metadata === void 0) return void 0;
|
|
2583
|
+
try {
|
|
2584
|
+
const identity = await stat(selected.sourcePath, { bigint: true });
|
|
2585
|
+
options?.signal?.throwIfAborted();
|
|
2586
|
+
return {
|
|
2587
|
+
...metadata,
|
|
2588
|
+
revision: selected.sourceVersion < SESSION_FORMAT_VERSION ? SessionPersistenceRevision(`${fileRevision(identity)}:${await this.historicalCorpusRevision(options?.signal)}`) : fileRevision(identity),
|
|
2589
|
+
sizeBytes: Number(identity.size),
|
|
2590
|
+
location: {
|
|
2591
|
+
kind: "jsonl",
|
|
2592
|
+
path: selected.sourcePath
|
|
2593
|
+
}
|
|
2594
|
+
};
|
|
2595
|
+
} catch (error) {
|
|
2596
|
+
options?.signal?.throwIfAborted();
|
|
2597
|
+
if (isENOENT(error)) return void 0;
|
|
2598
|
+
throw error;
|
|
2599
|
+
}
|
|
2600
|
+
}
|
|
2601
|
+
/**
|
|
2602
|
+
* List every stored session visible to this process: materialized artifacts
|
|
2603
|
+
* plus this process's created-but-unmaterialized sessions.
|
|
2604
|
+
* @param options - optional cancellation.
|
|
2605
|
+
* @returns one snapshot per session, in no promised order.
|
|
2606
|
+
*/
|
|
2607
|
+
async list(options) {
|
|
2608
|
+
const signal = options?.signal;
|
|
2609
|
+
const snapshots = [];
|
|
2610
|
+
const listed = /* @__PURE__ */ new Set();
|
|
2611
|
+
const pending = [...this.tracker.pendingEntries()];
|
|
2612
|
+
const artifacts = await this.listArtifacts(signal);
|
|
2613
|
+
const corpusRevision = artifacts.some((artifact) => artifact.sourceVersion < SESSION_FORMAT_VERSION) ? await this.historicalCorpusRevision(signal) : void 0;
|
|
2614
|
+
const statted = settledValues(await settleLimited(this.listLimit, artifacts, async (artifact) => {
|
|
2615
|
+
signal?.throwIfAborted();
|
|
2616
|
+
try {
|
|
2617
|
+
const identity = await stat(artifact.path, { bigint: true });
|
|
2618
|
+
signal?.throwIfAborted();
|
|
2619
|
+
return {
|
|
2620
|
+
artifact,
|
|
2621
|
+
identity
|
|
2622
|
+
};
|
|
2623
|
+
} catch (error) {
|
|
2624
|
+
signal?.throwIfAborted();
|
|
2625
|
+
if (!isENOENT(error)) throw error;
|
|
2626
|
+
return;
|
|
2627
|
+
}
|
|
2628
|
+
}));
|
|
2629
|
+
for (const entry of statted) {
|
|
2630
|
+
if (entry === void 0) continue;
|
|
2631
|
+
const { artifact, identity } = entry;
|
|
2632
|
+
listed.add(artifact.header.id);
|
|
2633
|
+
snapshots.push({
|
|
2634
|
+
header: artifact.header,
|
|
2635
|
+
formatStatus: artifact.formatStatus,
|
|
2636
|
+
revision: artifact.sourceVersion < SESSION_FORMAT_VERSION ? SessionPersistenceRevision(`${fileRevision(identity)}:${corpusRevision}`) : fileRevision(identity),
|
|
2637
|
+
sizeBytes: Number(identity.size),
|
|
2638
|
+
location: {
|
|
2639
|
+
kind: "jsonl",
|
|
2640
|
+
path: artifact.path
|
|
2641
|
+
}
|
|
2642
|
+
});
|
|
2643
|
+
}
|
|
2644
|
+
for (const [id, entry] of pending) if (!listed.has(id)) snapshots.push({
|
|
2645
|
+
header: entry.header,
|
|
2646
|
+
revision: entry.revision
|
|
2647
|
+
});
|
|
2648
|
+
signal?.throwIfAborted();
|
|
2649
|
+
return snapshots;
|
|
2650
|
+
}
|
|
2651
|
+
/** Resolve and read one stored log, refusing loudly when the artifact is absent. */
|
|
2652
|
+
async requireStoredLog(id, signal) {
|
|
2653
|
+
const selected = await this.findLog(id, signal);
|
|
2654
|
+
if (selected === void 0) throw new SessionPersistenceNotFoundError(id);
|
|
2655
|
+
if (selected.sourceVersion < SESSION_FORMAT_VERSION) {
|
|
2656
|
+
const sourceRevision = fileRevision(await stat(selected.sourcePath, { bigint: true }));
|
|
2657
|
+
signal?.throwIfAborted();
|
|
2658
|
+
let preparation = this.migrationPreparations.get(id);
|
|
2659
|
+
if (preparation === void 0 || preparation.sourcePath !== selected.sourcePath || preparation.sourceRevision !== sourceRevision) {
|
|
2660
|
+
const controller = new AbortController();
|
|
2661
|
+
const promise = this.loadStoredMigration(id, selected, sourceRevision, controller.signal);
|
|
2662
|
+
preparation = {
|
|
2663
|
+
sourcePath: selected.sourcePath,
|
|
2664
|
+
sourceRevision,
|
|
2665
|
+
controller,
|
|
2666
|
+
promise,
|
|
2667
|
+
settled: false,
|
|
2668
|
+
waiters: 0
|
|
2669
|
+
};
|
|
2670
|
+
this.migrationPreparations.set(id, preparation);
|
|
2671
|
+
const created = preparation;
|
|
2672
|
+
const release = () => {
|
|
2673
|
+
created.settled = true;
|
|
2674
|
+
if (this.migrationPreparations.get(id) === created) this.migrationPreparations.delete(id);
|
|
2675
|
+
};
|
|
2676
|
+
promise.then(release, release);
|
|
2677
|
+
}
|
|
2678
|
+
signal?.throwIfAborted();
|
|
2679
|
+
return this.waitForPreparation(id, preparation, signal);
|
|
2680
|
+
}
|
|
2681
|
+
if (selected.sourceVersion > SESSION_FORMAT_VERSION) {
|
|
2682
|
+
/* v8 ignore else -- a readable future header is rejected inside readGenerationHeader. */
|
|
2683
|
+
if (await this.readGenerationHeader(selected, id, signal) === void 0) throw new SessionPersistenceCorruptionError(`session "${id}": stored log has a malformed header (raw log: ${selected.sourcePath})`, { cause: /* @__PURE__ */ new Error("malformed Session header") });
|
|
2684
|
+
/* v8 ignore next -- readGenerationHeader rejects every future version. */
|
|
2685
|
+
throw new SessionFormatUnsupportedError(`${sessionFormatVersionRefusal(id, selected.sourceVersion)} (raw log: ${selected.sourcePath})`, {
|
|
2686
|
+
kind: "jsonl",
|
|
2687
|
+
path: selected.sourcePath
|
|
2688
|
+
});
|
|
2689
|
+
}
|
|
2690
|
+
const probe = fileRevision(await stat(selected.sourcePath, { bigint: true }));
|
|
2691
|
+
const memoized = this.coldLogMemo.get(id);
|
|
2692
|
+
if (memoized?.status === "current" && memoized.revision === probe) {
|
|
2693
|
+
this.coldLogMemo.delete(id);
|
|
2694
|
+
this.coldLogMemo.set(id, memoized);
|
|
2695
|
+
return memoized;
|
|
2696
|
+
}
|
|
2697
|
+
const current = await readStableJsonlFile(selected.sourcePath, signal);
|
|
2698
|
+
return this.decodeStoredLog(selected.sourcePath, id, current.bytes, fileRevision(current.identity), signal);
|
|
2699
|
+
}
|
|
2700
|
+
/** Probe the memo and otherwise decode one historical generation under backend cancellation. */
|
|
2701
|
+
async loadStoredMigration(id, selected, sourceRevision, signal) {
|
|
2702
|
+
signal.throwIfAborted();
|
|
2703
|
+
const memoized = this.coldLogMemo.get(id);
|
|
2704
|
+
if (memoized?.status === "prepared" && memoized.revision === sourceRevision) {
|
|
2705
|
+
try {
|
|
2706
|
+
await memoized.validateRelatedSources();
|
|
2707
|
+
} catch (error) {
|
|
2708
|
+
this.coldLogMemo.delete(id);
|
|
2709
|
+
throw this.generationFailure(id, selected, error);
|
|
2710
|
+
}
|
|
2711
|
+
this.coldLogMemo.delete(id);
|
|
2712
|
+
this.coldLogMemo.set(id, memoized);
|
|
2713
|
+
return memoized;
|
|
2714
|
+
}
|
|
2715
|
+
return this.prepareStoredMigration(id, selected, signal);
|
|
2716
|
+
}
|
|
2717
|
+
/** Await shared preparation for one caller and abort it only after its last waiter leaves. */
|
|
2718
|
+
async waitForPreparation(id, preparation, signal) {
|
|
2719
|
+
preparation.waiters += 1;
|
|
2720
|
+
try {
|
|
2721
|
+
return await waitWithAbort(preparation.promise, signal);
|
|
2722
|
+
} finally {
|
|
2723
|
+
preparation.waiters -= 1;
|
|
2724
|
+
if (preparation.waiters === 0 && !preparation.settled) {
|
|
2725
|
+
/* v8 ignore else -- a newer selected source may already own this id's preparation slot. */
|
|
2726
|
+
if (this.migrationPreparations.get(id) === preparation) this.migrationPreparations.delete(id);
|
|
2727
|
+
preparation.controller.abort();
|
|
2728
|
+
}
|
|
2729
|
+
}
|
|
2730
|
+
}
|
|
2731
|
+
/** Decode one historical generation without publishing a successor. */
|
|
2732
|
+
async prepareStoredMigration(id, selected, signal) {
|
|
2733
|
+
let prepared;
|
|
2734
|
+
let validateRelatedSources;
|
|
2735
|
+
try {
|
|
2736
|
+
const children = async () => (await this.listArtifacts(signal)).filter((source) => source.header.origin === "subagent" && source.header.parentSession === id);
|
|
2737
|
+
const sources = await children();
|
|
2738
|
+
const related = await prepareCatalogFacts(id, sources, this.compression, signal);
|
|
2739
|
+
for (const failure of related.failures) this.ctx.logger.warn(`${this.name}: session "${id}" catalog retained a child with unknown descriptor (raw log: ${failure.path}): ${String(failure.error)}`);
|
|
2740
|
+
const membership = sources.map((source) => source.path).sort();
|
|
2741
|
+
validateRelatedSources = async () => {
|
|
2742
|
+
const current = (await children()).map((source) => source.path).sort();
|
|
2743
|
+
const before = new Set(membership);
|
|
2744
|
+
const after = new Set(current);
|
|
2745
|
+
const changed = current.find((path) => !before.has(path)) ?? membership.find((path) => !after.has(path));
|
|
2746
|
+
if (changed !== void 0) throw new JsonlGenerationSourceChangedError(changed);
|
|
2747
|
+
await related.validate();
|
|
2748
|
+
};
|
|
2749
|
+
prepared = await prepareJsonlMigration({
|
|
2750
|
+
sourcePath: selected.sourcePath,
|
|
2751
|
+
sourceVersion: selected.sourceVersion,
|
|
2752
|
+
currentPath: selected.currentPath,
|
|
2753
|
+
compression: this.compression,
|
|
2754
|
+
format: {
|
|
2755
|
+
...this.generationFormat,
|
|
2756
|
+
createRestore: (header) => createSessionFormatCatalogWithChildren(related.facts).createRestore(header, {
|
|
2757
|
+
recovery: "recoverable",
|
|
2758
|
+
validation: "transformed"
|
|
2759
|
+
})
|
|
2760
|
+
},
|
|
2761
|
+
validateRelatedSources,
|
|
2762
|
+
verifyCurrentFile: verifyCurrentGenerationInWorker,
|
|
2763
|
+
validateHistoricalHeader: (headerValue) => this.validateSourceIdentity(selected, headerValue, id, signal),
|
|
2764
|
+
signal
|
|
2765
|
+
});
|
|
2766
|
+
} catch (error) {
|
|
2767
|
+
throw this.generationFailure(id, selected, error);
|
|
2768
|
+
}
|
|
2769
|
+
const meta = this.currentHeader(prepared.artifact.header);
|
|
2770
|
+
assertStoredId(id, meta);
|
|
2771
|
+
const events = prepared.artifact.events;
|
|
2772
|
+
validateStoredEvents(meta, events, {
|
|
2773
|
+
kind: "jsonl",
|
|
2774
|
+
path: selected.sourcePath
|
|
2775
|
+
});
|
|
2776
|
+
const stored = {
|
|
2777
|
+
status: "prepared",
|
|
2778
|
+
validateRelatedSources,
|
|
2779
|
+
meta,
|
|
2780
|
+
...freezeStoredEvents(events),
|
|
2781
|
+
tornTruncateTo: void 0,
|
|
2782
|
+
recoveredTail: [],
|
|
2783
|
+
inheritedEventCount: SessionLogOffset(prepared.artifact.inheritedEventCount),
|
|
2784
|
+
revision: fileRevision(prepared.sourceIdentity),
|
|
2785
|
+
publication: {
|
|
2786
|
+
source: selected,
|
|
2787
|
+
value: prepared
|
|
2788
|
+
}
|
|
2789
|
+
};
|
|
2790
|
+
this.memoizeStoredLog(id, stored);
|
|
2791
|
+
return stored;
|
|
2792
|
+
}
|
|
2793
|
+
/** Publish a prepared historical log before granting write access. */
|
|
2794
|
+
async publishStoredMigration(id, stored) {
|
|
2795
|
+
const migration = stored.publication;
|
|
2796
|
+
let identity;
|
|
2797
|
+
try {
|
|
2798
|
+
identity = await migration.value.publish();
|
|
2799
|
+
} catch (error) {
|
|
2800
|
+
/* v8 ignore else -- a newer preparation may have replaced this stale cache entry. */
|
|
2801
|
+
if (this.coldLogMemo.get(id) === stored) this.coldLogMemo.delete(id);
|
|
2802
|
+
throw this.generationFailure(id, migration.source, error);
|
|
2803
|
+
}
|
|
2804
|
+
const published = {
|
|
2805
|
+
status: "current",
|
|
2806
|
+
meta: stored.meta,
|
|
2807
|
+
eventState: stored.eventState,
|
|
2808
|
+
events: stored.events,
|
|
2809
|
+
tornTruncateTo: stored.tornTruncateTo,
|
|
2810
|
+
recoveredTail: stored.recoveredTail,
|
|
2811
|
+
inheritedEventCount: stored.inheritedEventCount,
|
|
2812
|
+
revision: fileRevision(identity)
|
|
2813
|
+
};
|
|
2814
|
+
this.memoizeStoredLog(id, published);
|
|
2815
|
+
return published;
|
|
2816
|
+
}
|
|
2817
|
+
/** Translate generation-layer failures into the persistence seam's error vocabulary. */
|
|
2818
|
+
generationFailure(id, selected, error) {
|
|
2819
|
+
if (error instanceof JsonlGenerationUnsupportedMigrationError) return new SessionFormatUnsupportedError(`${error.message}; source v${error.fromVersion} artifact remains unchanged (raw log: ${selected.sourcePath})`, {
|
|
2820
|
+
kind: "jsonl",
|
|
2821
|
+
path: selected.sourcePath
|
|
2822
|
+
});
|
|
2823
|
+
if (error instanceof JsonlGenerationSourceChangedError) return error;
|
|
2824
|
+
if (error instanceof SessionFormatUnsupportedError || error instanceof SessionPersistenceCorruptionError || isErrnoException(error) || error instanceof DOMException && error.name === "AbortError") return error;
|
|
2825
|
+
return new SessionPersistenceCorruptionError(`session "${id}": stored log is corrupt: ${String(error)} (raw log: ${selected.sourcePath})`, { cause: error });
|
|
2826
|
+
}
|
|
2827
|
+
/**
|
|
2828
|
+
* Read, parse, and validate one stored log as the current logical prefix.
|
|
2829
|
+
* @param path - the artifact file to read.
|
|
2830
|
+
* @param expectedId - the session identity the artifact must carry.
|
|
2831
|
+
* @param signal - optional cancellation for the stat/read/decode work.
|
|
2832
|
+
* @returns the validated stored log with any torn-tail truncation point.
|
|
2833
|
+
*/
|
|
2834
|
+
async readStoredLog(path, expectedId, signal) {
|
|
2835
|
+
signal?.throwIfAborted();
|
|
2836
|
+
const probe = fileRevision(await stat(path, { bigint: true }));
|
|
2837
|
+
const memoized = this.coldLogMemo.get(expectedId);
|
|
2838
|
+
if (memoized?.status === "current" && memoized.revision === probe) {
|
|
2839
|
+
this.coldLogMemo.delete(expectedId);
|
|
2840
|
+
this.coldLogMemo.set(expectedId, memoized);
|
|
2841
|
+
return memoized;
|
|
2842
|
+
}
|
|
2843
|
+
const { bytes, identity } = await readStableJsonlFile(path, signal);
|
|
2844
|
+
return this.decodeStoredLog(path, expectedId, bytes, fileRevision(identity), signal);
|
|
2845
|
+
}
|
|
2846
|
+
/** Decode and memoize one already-stable current physical snapshot. */
|
|
2847
|
+
async decodeStoredLog(path, expectedId, buffer, revision, signal) {
|
|
2848
|
+
let parsed;
|
|
2849
|
+
try {
|
|
2850
|
+
if (this.compression === "zstd") parsed = await this.readZstdPrefix(buffer, signal);
|
|
2851
|
+
else {
|
|
2852
|
+
signal?.throwIfAborted();
|
|
2853
|
+
const { meta, inheritedEventCount, events, committedBytes } = scanLog(buffer);
|
|
2854
|
+
signal?.throwIfAborted();
|
|
2855
|
+
parsed = {
|
|
2856
|
+
meta,
|
|
2857
|
+
inheritedEventCount,
|
|
2858
|
+
events,
|
|
2859
|
+
tornTruncateTo: committedBytes < buffer.byteLength ? committedBytes : void 0,
|
|
2860
|
+
recoveredTail: []
|
|
2861
|
+
};
|
|
2862
|
+
}
|
|
2863
|
+
} catch (error) {
|
|
2864
|
+
signal?.throwIfAborted();
|
|
2865
|
+
if (error instanceof SessionFormatUnsupportedError) throw new SessionFormatUnsupportedError(`${error.message} (raw log: ${path})`, {
|
|
2866
|
+
kind: "jsonl",
|
|
2867
|
+
path
|
|
2868
|
+
});
|
|
2869
|
+
throw new SessionPersistenceCorruptionError(`session "${expectedId}": stored log is corrupt: ${String(error)} (raw log: ${path})`, { cause: error });
|
|
2870
|
+
}
|
|
2871
|
+
signal?.throwIfAborted();
|
|
2872
|
+
await this.assertStoredIdentity(path, SESSION_FORMAT_VERSION, parsed.meta, expectedId, signal);
|
|
2873
|
+
signal?.throwIfAborted();
|
|
2874
|
+
assertStoredId(expectedId, parsed.meta);
|
|
2875
|
+
const location = this.locate(parsed.meta);
|
|
2876
|
+
validateStoredEvents(parsed.meta, parsed.events, location);
|
|
2877
|
+
const { events, ...rest } = parsed;
|
|
2878
|
+
const stored = {
|
|
2879
|
+
status: "current",
|
|
2880
|
+
...rest,
|
|
2881
|
+
...freezeStoredEvents(events),
|
|
2882
|
+
revision
|
|
2883
|
+
};
|
|
2884
|
+
this.memoizeStoredLog(expectedId, stored);
|
|
2885
|
+
return stored;
|
|
2886
|
+
}
|
|
2887
|
+
/** Insert one parsed log into the bounded handoff cache. */
|
|
2888
|
+
memoizeStoredLog(id, stored) {
|
|
2889
|
+
this.coldLogMemo.delete(id);
|
|
2890
|
+
this.coldLogMemo.set(id, stored);
|
|
2891
|
+
for (const oldest of this.coldLogMemo.keys()) {
|
|
2892
|
+
if (this.coldLogMemo.size <= COLD_LOG_MEMO_MAX_ENTRIES) break;
|
|
2893
|
+
this.coldLogMemo.delete(oldest);
|
|
2894
|
+
}
|
|
2895
|
+
}
|
|
2896
|
+
/**
|
|
2897
|
+
* Resolve a session's current-generation log path.
|
|
2898
|
+
* @param id - the stored session to locate.
|
|
2899
|
+
* @param signal - optional cancellation for the directory scans.
|
|
2900
|
+
* @returns the current artifact path, or `undefined` while only a historical generation exists.
|
|
2901
|
+
*/
|
|
2902
|
+
async resolveCurrentLog(id, signal) {
|
|
2903
|
+
await this.ensureRootEncoding();
|
|
2904
|
+
signal?.throwIfAborted();
|
|
2905
|
+
const selected = await this.findLog(id, signal);
|
|
2906
|
+
if (selected === void 0) return void 0;
|
|
2907
|
+
if (selected.sourceVersion === SESSION_FORMAT_VERSION) return selected.sourcePath;
|
|
2908
|
+
if (selected.sourceVersion < SESSION_FORMAT_VERSION) return void 0;
|
|
2909
|
+
throw new SessionFormatUnsupportedError(`${sessionFormatVersionRefusal(id, selected.sourceVersion)} (raw log: ${selected.sourcePath})`, {
|
|
2910
|
+
kind: "jsonl",
|
|
2911
|
+
path: selected.sourcePath
|
|
2912
|
+
});
|
|
2913
|
+
}
|
|
2914
|
+
/**
|
|
2915
|
+
* Durably append one validated batch; lazily materializes on the first write.
|
|
2916
|
+
* @param header - the session's stored header.
|
|
2917
|
+
* @param events - the validated contiguous batch, in seq order.
|
|
2918
|
+
* @param isMaterialized - whether the session already has a durable artifact.
|
|
2919
|
+
* @param inheritedEventCount - the exact fork-inherited prefix length written into a materializing header line.
|
|
2920
|
+
*/
|
|
2921
|
+
async persistBatch(header, events, isMaterialized, inheritedEventCount) {
|
|
2922
|
+
this.coldLogMemo.delete(header.id);
|
|
2923
|
+
await this.ensureRootEncoding();
|
|
2924
|
+
if (isMaterialized) await this.appendLines(header, events);
|
|
2925
|
+
else {
|
|
2926
|
+
await this.materialize(header, inheritedEventCount, events);
|
|
2927
|
+
this.tracker.materialized(header.id);
|
|
2928
|
+
}
|
|
2929
|
+
}
|
|
2930
|
+
/**
|
|
2931
|
+
* Materialize a header-only artifact for an explicitly durable empty session.
|
|
2932
|
+
* @param header - the session's stored header.
|
|
2933
|
+
* @param inheritedEventCount - the exact fork-inherited prefix length written into the header line.
|
|
2934
|
+
*/
|
|
2935
|
+
async persistHeader(header, inheritedEventCount) {
|
|
2936
|
+
this.coldLogMemo.delete(header.id);
|
|
2937
|
+
await this.ensureRootEncoding();
|
|
2938
|
+
await this.materialize(header, inheritedEventCount, []);
|
|
2939
|
+
this.tracker.materialized(header.id);
|
|
2940
|
+
}
|
|
2941
|
+
/**
|
|
2942
|
+
* Truncate a torn physical tail durably before this session's first new append.
|
|
2943
|
+
* @param header - the session's stored header.
|
|
2944
|
+
* @param truncateTo - the byte offset the artifact is truncated to.
|
|
2945
|
+
*/
|
|
2946
|
+
async truncateTornTail(header, truncateTo) {
|
|
2947
|
+
this.coldLogMemo.delete(header.id);
|
|
2948
|
+
await this.repair(header, truncateTo);
|
|
2949
|
+
this.ctx.logger.warn(`${this.name}: session "${header.id}" recovered from a torn tail; incomplete tail bytes were discarded`);
|
|
2950
|
+
}
|
|
2951
|
+
/**
|
|
2952
|
+
* Whether this process still tracks a created-but-unmaterialized session.
|
|
2953
|
+
* @param id - the session to test.
|
|
2954
|
+
* @returns true while the pending entry exists.
|
|
2955
|
+
*/
|
|
2956
|
+
hasPendingSession(id) {
|
|
2957
|
+
return this.tracker.hasPending(id);
|
|
2958
|
+
}
|
|
2959
|
+
/**
|
|
2960
|
+
* Release one handle's backend bookkeeping on close.
|
|
2961
|
+
* @param handle - the closing handle.
|
|
2962
|
+
* @param materialized - whether the session reached durable storage.
|
|
2963
|
+
*/
|
|
2964
|
+
releaseHandle(handle, materialized) {
|
|
2965
|
+
this.tracker.release(handle, materialized);
|
|
2966
|
+
}
|
|
2967
|
+
/**
|
|
2968
|
+
* Acquire the session directory's kernel write lock; the kernel holds it
|
|
2969
|
+
* until the handle's close releases the descriptor, including on process death.
|
|
2970
|
+
* @param id - the session the lock guards.
|
|
2971
|
+
* @param cwd - header cwd used to derive the directory for a fresh session.
|
|
2972
|
+
* @param dir - the resolved directory of an existing artifact, when known.
|
|
2973
|
+
* @returns the held lock.
|
|
2974
|
+
*/
|
|
2975
|
+
acquireLease(id, cwd, dir = sessionDir(this.root, cwd, id)) {
|
|
2976
|
+
return SessionWriteLease.acquire(dir, id);
|
|
2977
|
+
}
|
|
2978
|
+
/**
|
|
2979
|
+
* Acquire the cross-process write lock for a materializing created session,
|
|
2980
|
+
* called by its handle immediately before the first log bytes publish.
|
|
2981
|
+
* @param header - the session's stored header (its cwd derives the directory).
|
|
2982
|
+
* @returns the held lock.
|
|
2983
|
+
*/
|
|
2984
|
+
async acquireWriteLease(header) {
|
|
2985
|
+
await this.rejectOppositeArtifact(header.cwd, header.id);
|
|
2986
|
+
return this.acquireLease(header.id, header.cwd);
|
|
2987
|
+
}
|
|
2988
|
+
/** Decode complete frames and retain complete JSONL records from a torn final frame. */
|
|
2989
|
+
async readZstdPrefix(buffer, signal) {
|
|
2990
|
+
signal?.throwIfAborted();
|
|
2991
|
+
const { frames, tornStart } = scanZstdFrames(buffer);
|
|
2992
|
+
signal?.throwIfAborted();
|
|
2993
|
+
if (frames.length === 0) throw new Error("empty or header-less Zstandard session log");
|
|
2994
|
+
const decoder = createZstdFrameDecoder();
|
|
2995
|
+
let yieldDeadline = performance.now() + ZSTD_DECODE_YIELD_INTERVAL_MS;
|
|
2996
|
+
try {
|
|
2997
|
+
const decodedFrames = decoder.decode(buffer, frames);
|
|
2998
|
+
signal?.throwIfAborted();
|
|
2999
|
+
const headerFrame = decodedFrames.next();
|
|
3000
|
+
signal?.throwIfAborted();
|
|
3001
|
+
/* v8 ignore next -- a non-empty structural frame list makes the decoder yield its first frame or throw. */
|
|
3002
|
+
if (headerFrame.done) throw new Error("empty or header-less Zstandard session log");
|
|
3003
|
+
assertZstdHeaderFrame(headerFrame.value);
|
|
3004
|
+
const scanner = new SessionLogScanner(headerFrame.value);
|
|
3005
|
+
let remainingFrames = frames.length - 1;
|
|
3006
|
+
for (const plaintext of decodedFrames) {
|
|
3007
|
+
signal?.throwIfAborted();
|
|
3008
|
+
scanner.write(plaintext);
|
|
3009
|
+
remainingFrames -= 1;
|
|
3010
|
+
if (remainingFrames > 0 && performance.now() >= yieldDeadline) {
|
|
3011
|
+
await scheduler.yield();
|
|
3012
|
+
signal?.throwIfAborted();
|
|
3013
|
+
yieldDeadline = performance.now() + ZSTD_DECODE_YIELD_INTERVAL_MS;
|
|
3014
|
+
}
|
|
3015
|
+
}
|
|
3016
|
+
signal?.throwIfAborted();
|
|
3017
|
+
const complete = scanner.checkpoint();
|
|
3018
|
+
if (complete.committedBytes !== complete.inputBytes) throw new Error("corrupt Zstandard session log: complete frame contains a torn JSONL record");
|
|
3019
|
+
if (tornStart === void 0) {
|
|
3020
|
+
const prefix = scanner.finish();
|
|
3021
|
+
return {
|
|
3022
|
+
meta: prefix.meta,
|
|
3023
|
+
inheritedEventCount: prefix.inheritedEventCount,
|
|
3024
|
+
events: prefix.events,
|
|
3025
|
+
tornTruncateTo: void 0,
|
|
3026
|
+
recoveredTail: []
|
|
3027
|
+
};
|
|
3028
|
+
}
|
|
3029
|
+
let recoveredPlaintext = Buffer.alloc(0);
|
|
3030
|
+
try {
|
|
3031
|
+
signal?.throwIfAborted();
|
|
3032
|
+
recoveredPlaintext = await decompressZstdPrefix(buffer.subarray(tornStart));
|
|
3033
|
+
} catch {
|
|
3034
|
+
/* v8 ignore next -- decoder failure plus concurrent abort is timing-dependent */
|
|
3035
|
+
if (signal?.aborted) signal.throwIfAborted();
|
|
3036
|
+
}
|
|
3037
|
+
signal?.throwIfAborted();
|
|
3038
|
+
scanner.write(recoveredPlaintext);
|
|
3039
|
+
const prefix = scanner.finish();
|
|
3040
|
+
return {
|
|
3041
|
+
meta: prefix.meta,
|
|
3042
|
+
inheritedEventCount: prefix.inheritedEventCount,
|
|
3043
|
+
events: prefix.events,
|
|
3044
|
+
tornTruncateTo: tornStart,
|
|
3045
|
+
recoveredTail: prefix.events.slice(complete.eventCount)
|
|
3046
|
+
};
|
|
3047
|
+
} catch (error) {
|
|
3048
|
+
/* v8 ignore next -- decoder failure plus concurrent abort is timing-dependent */
|
|
3049
|
+
if (signal?.aborted) signal.throwIfAborted();
|
|
3050
|
+
throw error;
|
|
3051
|
+
} finally {
|
|
3052
|
+
decoder.close();
|
|
3053
|
+
}
|
|
3054
|
+
}
|
|
3055
|
+
/** Enumerate selected physical generations without interpreting their headers or bodies. */
|
|
3056
|
+
async listGenerations(signal) {
|
|
3057
|
+
return (await this.mapSessionDirectories((dir) => {
|
|
3058
|
+
signal?.throwIfAborted();
|
|
3059
|
+
return this.resolveGenerationInDirectory(dir, signal);
|
|
3060
|
+
}, signal)).filter((source) => source !== void 0);
|
|
3061
|
+
}
|
|
3062
|
+
/**
|
|
3063
|
+
* Apply `task` to every Session directory through the shared listing
|
|
3064
|
+
* limiter. Results and the first failure follow the sequential
|
|
3065
|
+
* project-then-directory order; a project whose listing fails ends the
|
|
3066
|
+
* traversal after the directories of the projects before it.
|
|
3067
|
+
* @param task - per-directory operation; must not wait on the listing limiter.
|
|
3068
|
+
* @param signal - optional cancellation for directory listings.
|
|
3069
|
+
* @returns per-directory results in traversal order.
|
|
3070
|
+
*/
|
|
3071
|
+
async mapSessionDirectories(task, signal) {
|
|
3072
|
+
const limit = this.listLimit;
|
|
3073
|
+
const projects = await settleLimited(limit, await limit(() => this.listProjectDirs(signal)), (project) => this.listSessionDirs(project, signal));
|
|
3074
|
+
const dirs = [];
|
|
3075
|
+
let projectFailure;
|
|
3076
|
+
for (const outcome of projects) {
|
|
3077
|
+
if (outcome.status === "rejected") {
|
|
3078
|
+
projectFailure = outcome;
|
|
3079
|
+
break;
|
|
3080
|
+
}
|
|
3081
|
+
for (const dir of outcome.value) dirs.push(dir);
|
|
3082
|
+
}
|
|
3083
|
+
const results = settledValues(await settleLimited(limit, dirs, task));
|
|
3084
|
+
if (projectFailure !== void 0) throw projectFailure.reason;
|
|
3085
|
+
return results;
|
|
3086
|
+
}
|
|
3087
|
+
/** Historical logical events depend on the corpus, including members with unreadable headers. */
|
|
3088
|
+
async historicalCorpusRevision(signal) {
|
|
3089
|
+
const paths = (await this.listGenerations(signal)).map((source) => source.sourcePath).sort();
|
|
3090
|
+
const entries = settledValues(await settleLimited(this.listLimit, paths, async (path) => {
|
|
3091
|
+
signal?.throwIfAborted();
|
|
3092
|
+
try {
|
|
3093
|
+
return {
|
|
3094
|
+
path,
|
|
3095
|
+
revision: fileRevision(await stat(path, { bigint: true }))
|
|
3096
|
+
};
|
|
3097
|
+
} catch (error) {
|
|
3098
|
+
if (!isENOENT(error)) throw error;
|
|
3099
|
+
return {
|
|
3100
|
+
path,
|
|
3101
|
+
revision: "missing"
|
|
3102
|
+
};
|
|
3103
|
+
}
|
|
3104
|
+
}));
|
|
3105
|
+
const hash = createHash("sha256");
|
|
3106
|
+
for (const { path, revision } of entries) hash.update(JSON.stringify([path, revision]));
|
|
3107
|
+
signal?.throwIfAborted();
|
|
3108
|
+
return hash.digest("hex");
|
|
3109
|
+
}
|
|
3110
|
+
async listArtifacts(signal) {
|
|
3111
|
+
signal?.throwIfAborted();
|
|
3112
|
+
await this.ensureRootEncoding();
|
|
3113
|
+
signal?.throwIfAborted();
|
|
3114
|
+
const generations = await this.listGenerations(signal);
|
|
3115
|
+
const headers = await settleLimited(this.listLimit, generations, async (selected) => {
|
|
3116
|
+
signal?.throwIfAborted();
|
|
3117
|
+
try {
|
|
3118
|
+
return {
|
|
3119
|
+
selected,
|
|
3120
|
+
metadata: await this.readGenerationHeader(selected, void 0, signal)
|
|
3121
|
+
};
|
|
3122
|
+
} catch (error) {
|
|
3123
|
+
if (error instanceof SessionFormatUnsupportedError || error instanceof SessionPersistenceCorruptionError) return {
|
|
3124
|
+
selected,
|
|
3125
|
+
metadata: void 0
|
|
3126
|
+
};
|
|
3127
|
+
throw error;
|
|
3128
|
+
}
|
|
3129
|
+
});
|
|
3130
|
+
const artifacts = [];
|
|
3131
|
+
const ids = /* @__PURE__ */ new Set();
|
|
3132
|
+
for (const outcome of headers) {
|
|
3133
|
+
if (outcome.status === "rejected") throw outcome.reason;
|
|
3134
|
+
const { selected, metadata } = outcome.value;
|
|
3135
|
+
if (metadata === void 0) continue;
|
|
3136
|
+
if (ids.has(metadata.header.id)) throw new Error(`duplicate JSONL session id "${metadata.header.id}" appears in multiple project directories`);
|
|
3137
|
+
ids.add(metadata.header.id);
|
|
3138
|
+
artifacts.push({
|
|
3139
|
+
...metadata,
|
|
3140
|
+
path: selected.sourcePath,
|
|
3141
|
+
sourceVersion: selected.sourceVersion
|
|
3142
|
+
});
|
|
3143
|
+
}
|
|
3144
|
+
signal?.throwIfAborted();
|
|
3145
|
+
return artifacts;
|
|
3146
|
+
}
|
|
3147
|
+
/** Read and translate one selected generation header without inspecting its body. */
|
|
3148
|
+
async readGenerationHeader(selected, expectedId, signal) {
|
|
3149
|
+
let first;
|
|
3150
|
+
try {
|
|
3151
|
+
first = this.compression === "zstd" ? await this.readFirstZstdLine(selected.sourcePath, signal) : await this.readFirstLine(selected.sourcePath, signal);
|
|
3152
|
+
} catch (error) {
|
|
3153
|
+
signal?.throwIfAborted();
|
|
3154
|
+
if (isENOENT(error)) return void 0;
|
|
3155
|
+
throw error;
|
|
3156
|
+
}
|
|
3157
|
+
signal?.throwIfAborted();
|
|
3158
|
+
if (first === void 0) return void 0;
|
|
3159
|
+
let value;
|
|
3160
|
+
try {
|
|
3161
|
+
value = JSON.parse(first);
|
|
3162
|
+
} catch {
|
|
3163
|
+
return;
|
|
3164
|
+
}
|
|
3165
|
+
assertNoRetiredHeaderFields(value);
|
|
3166
|
+
const result = sessionFormatCatalog.readHeader(value);
|
|
3167
|
+
if ("storedVersion" in result && result.storedVersion !== selected.sourceVersion) throw new Error(`session generation filename identifies v${selected.sourceVersion}, but its header identifies v${result.storedVersion}`);
|
|
3168
|
+
if (result.status === "unsupported") {
|
|
3169
|
+
const physicalId = String(value.id);
|
|
3170
|
+
let reason = result.reason;
|
|
3171
|
+
/* v8 ignore else -- released historical header migrations cannot refuse after physical decoding. */
|
|
3172
|
+
if (result.storedVersion > SESSION_FORMAT_VERSION) reason = sessionFormatVersionRefusal(physicalId, result.storedVersion);
|
|
3173
|
+
throw new SessionFormatUnsupportedError(`${reason} (raw log: ${selected.sourcePath})`, {
|
|
3174
|
+
kind: "jsonl",
|
|
3175
|
+
path: selected.sourcePath
|
|
3176
|
+
});
|
|
3177
|
+
}
|
|
3178
|
+
if (result.status === "malformed") return void 0;
|
|
3179
|
+
const header = this.currentHeader(result.header);
|
|
3180
|
+
await this.assertStoredIdentity(selected.sourcePath, selected.sourceVersion, header, expectedId, signal);
|
|
3181
|
+
return {
|
|
3182
|
+
header,
|
|
3183
|
+
formatStatus: result.status
|
|
3184
|
+
};
|
|
3185
|
+
}
|
|
3186
|
+
/** Convert format-catalog string identities to current branded Session metadata. */
|
|
3187
|
+
currentHeader(header) {
|
|
3188
|
+
/* v8 ignore next 3 -- readable catalog results are restored to its configured current version. */
|
|
3189
|
+
if (header.version !== SESSION_FORMAT_VERSION) throw new Error(`format catalog returned non-current logical header v${header.version}`);
|
|
3190
|
+
return {
|
|
3191
|
+
version: SESSION_FORMAT_VERSION,
|
|
3192
|
+
id: SessionId(header.id),
|
|
3193
|
+
createdAt: header.createdAt,
|
|
3194
|
+
...header.cwd === void 0 ? {} : { cwd: header.cwd },
|
|
3195
|
+
...header.parentSession === void 0 ? {} : { parentSession: SessionId(header.parentSession) },
|
|
3196
|
+
isSeeded: header.isSeeded,
|
|
3197
|
+
...header.origin === void 0 ? {} : { origin: header.origin },
|
|
3198
|
+
delegationDepth: header.delegationDepth,
|
|
3199
|
+
...header.agentPreset === void 0 ? {} : { agentPreset: header.agentPreset }
|
|
3200
|
+
};
|
|
3201
|
+
}
|
|
3202
|
+
/** Atomically write the header line + first batch (temp-write, fsync, publish). */
|
|
3203
|
+
async materialize(meta, inheritedEventCount, events) {
|
|
3204
|
+
const project = projectDir(this.root, meta.cwd);
|
|
3205
|
+
const dir = sessionDir(this.root, meta.cwd, meta.id);
|
|
3206
|
+
const finalPath = logPath(this.root, meta.cwd, meta.id, this.compression);
|
|
3207
|
+
await this.rejectOppositeArtifact(meta.cwd, meta.id);
|
|
3208
|
+
const content = await this.encodeMaterialization(meta, inheritedEventCount, events);
|
|
3209
|
+
/* v8 ignore next -- native Windows coverage exercises this platform dispatch; Linux covers the POSIX peer */
|
|
3210
|
+
if (process.platform === "win32") await this.materializeWin32(project, dir, finalPath, meta.id, content);
|
|
3211
|
+
else await this.materializePosix(project, dir, finalPath, meta.id, content);
|
|
3212
|
+
}
|
|
3213
|
+
/* v8 ignore start -- Windows uses the Win32 durable-publish path; POSIX coverage exercises this peer. */
|
|
3214
|
+
async materializePosix(project, dir, finalPath, id, content) {
|
|
3215
|
+
await mkdir(this.root, {
|
|
3216
|
+
recursive: true,
|
|
3217
|
+
mode: 448
|
|
3218
|
+
});
|
|
3219
|
+
await this.syncDirPosix(dirname(this.root));
|
|
3220
|
+
await mkdir(project, {
|
|
3221
|
+
recursive: true,
|
|
3222
|
+
mode: 448
|
|
3223
|
+
});
|
|
3224
|
+
await this.syncDirPosix(this.root);
|
|
3225
|
+
await mkdir(dir, {
|
|
3226
|
+
recursive: true,
|
|
3227
|
+
mode: 448
|
|
3228
|
+
});
|
|
3229
|
+
await this.syncDirPosix(project);
|
|
3230
|
+
await this.rejectExistingLog(finalPath, id);
|
|
3231
|
+
const tmp = await this.writeSyncedTempFile(finalPath, content);
|
|
3232
|
+
let linked = false;
|
|
3233
|
+
try {
|
|
3234
|
+
await link(tmp, finalPath);
|
|
3235
|
+
linked = true;
|
|
3236
|
+
} finally {
|
|
3237
|
+
/* v8 ignore next -- link failure is the TOCTOU/IO race guarded above; not reachable in test */
|
|
3238
|
+
if (!linked) await rm(tmp, { force: true });
|
|
3239
|
+
}
|
|
3240
|
+
await this.syncDirPosix(dir);
|
|
3241
|
+
try {
|
|
3242
|
+
await rm(tmp, { force: true });
|
|
3243
|
+
} catch {}
|
|
3244
|
+
}
|
|
3245
|
+
/* v8 ignore stop */
|
|
3246
|
+
/* v8 ignore start -- native Windows coverage exercises this integration path */
|
|
3247
|
+
async materializeWin32(project, dir, finalPath, id, content) {
|
|
3248
|
+
await ensureDurableDirectoryWin32(this.root);
|
|
3249
|
+
await ensureDurableDirectoryWin32(project);
|
|
3250
|
+
await ensureDurableDirectoryWin32(dir);
|
|
3251
|
+
await this.rejectExistingLog(finalPath, id);
|
|
3252
|
+
const tmp = await this.writeSyncedTempFile(finalPath, content);
|
|
3253
|
+
try {
|
|
3254
|
+
await publishNewFileWin32(tmp, finalPath);
|
|
3255
|
+
} catch (error) {
|
|
3256
|
+
await rm(tmp, { force: true });
|
|
3257
|
+
throw error;
|
|
3258
|
+
}
|
|
3259
|
+
}
|
|
3260
|
+
/* v8 ignore stop */
|
|
3261
|
+
async rejectExistingLog(finalPath, id) {
|
|
3262
|
+
/* v8 ignore next 3 -- create guards collisions before materialize; this is a TOCTOU backstop */
|
|
3263
|
+
if (await this.resolveGenerationInDirectory(dirname(finalPath)) !== void 0) throw new Error(`refusing to materialize "${id}": a log already exists on disk (open it instead)`);
|
|
3264
|
+
}
|
|
3265
|
+
async writeSyncedTempFile(finalPath, content) {
|
|
3266
|
+
const tmp = `${finalPath}.${randomBytes(6).toString("hex")}.tmp`;
|
|
3267
|
+
const handle = await open(tmp, "wx", 384);
|
|
3268
|
+
try {
|
|
3269
|
+
await handle.writeFile(content);
|
|
3270
|
+
await handle.sync();
|
|
3271
|
+
} finally {
|
|
3272
|
+
await handle.close();
|
|
3273
|
+
}
|
|
3274
|
+
return tmp;
|
|
3275
|
+
}
|
|
3276
|
+
/** Encode the header and first batch without combining their frame boundaries. */
|
|
3277
|
+
async encodeMaterialization(meta, inheritedEventCount, events) {
|
|
3278
|
+
const header = JSON.stringify(toHeaderLine(meta, meta.isSeeded ? inheritedEventCount : void 0)) + "\n";
|
|
3279
|
+
if (events.length === 0) return this.compression === "none" ? header : compressZstdFrame(header);
|
|
3280
|
+
const body = eventLines(events) + "\n";
|
|
3281
|
+
if (this.compression === "none") return header + body;
|
|
3282
|
+
const headerFrame = await compressZstdFrame(header);
|
|
3283
|
+
const eventFrame = await compressZstdFrame(body);
|
|
3284
|
+
return Buffer.concat([headerFrame, eventFrame]);
|
|
3285
|
+
}
|
|
3286
|
+
/** Encode one durable append batch in the configured physical representation. */
|
|
3287
|
+
async encodeEventBatch(events) {
|
|
3288
|
+
const body = eventLines(events) + "\n";
|
|
3289
|
+
return this.compression === "zstd" ? compressZstdFrame(body) : body;
|
|
3290
|
+
}
|
|
3291
|
+
/** fsync a POSIX directory so a just-created/renamed entry is crash-durable. */
|
|
3292
|
+
/* v8 ignore start -- Windows uses write-through namespace operations; POSIX coverage exercises directory fsync. */
|
|
3293
|
+
async syncDirPosix(dir) {
|
|
3294
|
+
const handle = await open(dir, "r");
|
|
3295
|
+
try {
|
|
3296
|
+
await handle.sync();
|
|
3297
|
+
} finally {
|
|
3298
|
+
await handle.close();
|
|
3299
|
+
}
|
|
3300
|
+
}
|
|
3301
|
+
/* v8 ignore stop */
|
|
3302
|
+
/**
|
|
3303
|
+
* Append and fsync event lines. On a partial write or sync failure, restore the
|
|
3304
|
+
* previous size before rethrowing because the unchanged cursor will retry the
|
|
3305
|
+
* batch; leaving partial bytes would create duplicate sequence numbers.
|
|
3306
|
+
*/
|
|
3307
|
+
async appendLines(meta, events) {
|
|
3308
|
+
const content = await this.encodeEventBatch(events);
|
|
3309
|
+
const path = logPath(this.root, meta.cwd, meta.id, this.compression);
|
|
3310
|
+
const handle = await open(path, "a");
|
|
3311
|
+
let closed = false;
|
|
3312
|
+
const closeAppendHandle = async () => {
|
|
3313
|
+
if (closed) return;
|
|
3314
|
+
closed = true;
|
|
3315
|
+
await handle.close();
|
|
3316
|
+
};
|
|
3317
|
+
try {
|
|
3318
|
+
const { size: before } = await handle.stat();
|
|
3319
|
+
try {
|
|
3320
|
+
await handle.writeFile(content);
|
|
3321
|
+
await handle.sync();
|
|
3322
|
+
} catch (error) {
|
|
3323
|
+
try {
|
|
3324
|
+
await closeAppendHandle();
|
|
3325
|
+
await this.rollbackAppend(path, before);
|
|
3326
|
+
} catch (rollbackError) {
|
|
3327
|
+
throw new AggregateError([error, rollbackError], `failed to roll back append to "${path}"`);
|
|
3328
|
+
}
|
|
3329
|
+
throw error;
|
|
3330
|
+
}
|
|
3331
|
+
} finally {
|
|
3332
|
+
await closeAppendHandle();
|
|
3333
|
+
}
|
|
3334
|
+
}
|
|
3335
|
+
async rollbackAppend(path, size) {
|
|
3336
|
+
const handle = await open(path, "r+");
|
|
3337
|
+
try {
|
|
3338
|
+
await handle.truncate(size);
|
|
3339
|
+
await handle.sync();
|
|
3340
|
+
} finally {
|
|
3341
|
+
await handle.close();
|
|
3342
|
+
}
|
|
3343
|
+
}
|
|
3344
|
+
/** Truncate the log file to `offset` bytes and fsync (discard the crash tail). */
|
|
3345
|
+
async repair(meta, offset) {
|
|
3346
|
+
const path = logPath(this.root, meta.cwd, meta.id, this.compression);
|
|
3347
|
+
await truncate(path, offset);
|
|
3348
|
+
const handle = await open(path, "r+");
|
|
3349
|
+
try {
|
|
3350
|
+
await handle.sync();
|
|
3351
|
+
} finally {
|
|
3352
|
+
await handle.close();
|
|
3353
|
+
}
|
|
3354
|
+
}
|
|
3355
|
+
/**
|
|
3356
|
+
* Read the first newline-terminated line of a file without loading the whole
|
|
3357
|
+
* file. Returns undefined if the file is empty or has no complete first line.
|
|
3358
|
+
* Reads in bounded chunks so a huge log costs only the header read.
|
|
3359
|
+
*/
|
|
3360
|
+
async readFirstLine(path, signal) {
|
|
3361
|
+
signal?.throwIfAborted();
|
|
3362
|
+
const handle = await open(path, "r");
|
|
3363
|
+
try {
|
|
3364
|
+
signal?.throwIfAborted();
|
|
3365
|
+
const chunks = [];
|
|
3366
|
+
const buf = Buffer.alloc(8192);
|
|
3367
|
+
for (;;) {
|
|
3368
|
+
signal?.throwIfAborted();
|
|
3369
|
+
const { bytesRead } = await handle.read(buf, 0, buf.length, null);
|
|
3370
|
+
signal?.throwIfAborted();
|
|
3371
|
+
if (bytesRead === 0) return void 0;
|
|
3372
|
+
const slice = buf.subarray(0, bytesRead);
|
|
3373
|
+
const nl = slice.indexOf(10);
|
|
3374
|
+
if (nl !== -1) {
|
|
3375
|
+
chunks.push(slice.subarray(0, nl));
|
|
3376
|
+
signal?.throwIfAborted();
|
|
3377
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
3378
|
+
}
|
|
3379
|
+
chunks.push(Buffer.from(slice));
|
|
3380
|
+
}
|
|
3381
|
+
} finally {
|
|
3382
|
+
await handle.close();
|
|
3383
|
+
}
|
|
3384
|
+
}
|
|
3385
|
+
/** Read only the header frame; compression failures reject as corruption, while I/O and cancellation propagate. */
|
|
3386
|
+
async readFirstZstdLine(path, signal) {
|
|
3387
|
+
signal?.throwIfAborted();
|
|
3388
|
+
const handle = await open(path, "r");
|
|
3389
|
+
try {
|
|
3390
|
+
signal?.throwIfAborted();
|
|
3391
|
+
let content = Buffer.alloc(0);
|
|
3392
|
+
const chunk = Buffer.alloc(8192);
|
|
3393
|
+
for (;;) {
|
|
3394
|
+
signal?.throwIfAborted();
|
|
3395
|
+
const { bytesRead } = await handle.read(chunk, 0, chunk.length, null);
|
|
3396
|
+
signal?.throwIfAborted();
|
|
3397
|
+
if (bytesRead === 0) return void 0;
|
|
3398
|
+
signal?.throwIfAborted();
|
|
3399
|
+
content = Buffer.concat([content, chunk.subarray(0, bytesRead)]);
|
|
3400
|
+
signal?.throwIfAborted();
|
|
3401
|
+
try {
|
|
3402
|
+
const first = scanZstdFrames(content, 1).frames[0];
|
|
3403
|
+
if (first === void 0) continue;
|
|
3404
|
+
const plaintext = await decompressZstdFrame(content.subarray(first.start, first.end));
|
|
3405
|
+
signal?.throwIfAborted();
|
|
3406
|
+
assertZstdHeaderFrame(plaintext);
|
|
3407
|
+
return plaintext.subarray(0, -1).toString("utf8");
|
|
3408
|
+
} catch (error) {
|
|
3409
|
+
/* v8 ignore next -- decoder failure plus concurrent abort is timing-dependent */
|
|
3410
|
+
if (signal?.aborted) signal.throwIfAborted();
|
|
3411
|
+
throw new SessionPersistenceCorruptionError(`corrupt Zstandard session log: header frame failed validation: ${String(error)} (raw log: ${path})`, { cause: error });
|
|
3412
|
+
}
|
|
3413
|
+
}
|
|
3414
|
+
} finally {
|
|
3415
|
+
await handle.close();
|
|
3416
|
+
}
|
|
3417
|
+
}
|
|
3418
|
+
/** Select the numerically highest canonical generation in one Session directory. */
|
|
3419
|
+
async resolveGenerationInDirectory(dir, signal) {
|
|
3420
|
+
signal?.throwIfAborted();
|
|
3421
|
+
let entries;
|
|
3422
|
+
try {
|
|
3423
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
3424
|
+
} catch (error) {
|
|
3425
|
+
if (isENOENT(error)) return void 0;
|
|
3426
|
+
throw error;
|
|
3427
|
+
}
|
|
3428
|
+
signal?.throwIfAborted();
|
|
3429
|
+
const generations = [];
|
|
3430
|
+
const opposite = [];
|
|
3431
|
+
for (const entry of entries) {
|
|
3432
|
+
const version = parseGenerationLogFilename(entry.name, this.compression);
|
|
3433
|
+
if (version !== void 0) {
|
|
3434
|
+
generations.push({
|
|
3435
|
+
path: join(dir, entry.name),
|
|
3436
|
+
version
|
|
3437
|
+
});
|
|
3438
|
+
continue;
|
|
3439
|
+
}
|
|
3440
|
+
if (parseGenerationLogFilename(entry.name, this.oppositeCompression()) !== void 0) opposite.push(join(dir, entry.name));
|
|
3441
|
+
}
|
|
3442
|
+
if (opposite.length > 0) throw this.encodingMismatch(opposite[0]);
|
|
3443
|
+
const latest = generations.sort((left, right) => right.version - left.version)[0];
|
|
3444
|
+
if (latest === void 0) return void 0;
|
|
3445
|
+
return {
|
|
3446
|
+
sourcePath: latest.path,
|
|
3447
|
+
sourceVersion: latest.version,
|
|
3448
|
+
currentPath: join(dir, generationLogFilename(sessionFormatCatalog.currentVersion, this.compression))
|
|
3449
|
+
};
|
|
3450
|
+
}
|
|
3451
|
+
/** Find the unique authoritative generation for an id across project directories. */
|
|
3452
|
+
async findLog(id, signal) {
|
|
3453
|
+
const matches = [];
|
|
3454
|
+
for (const project of await this.listProjectDirs(signal)) {
|
|
3455
|
+
signal?.throwIfAborted();
|
|
3456
|
+
await this.rejectLegacyFlatArtifact(project, id, signal);
|
|
3457
|
+
signal?.throwIfAborted();
|
|
3458
|
+
const dir = join(project, encodeSegment(id));
|
|
3459
|
+
const selected = await this.resolveGenerationInDirectory(dir, signal);
|
|
3460
|
+
if (selected !== void 0) matches.push(selected);
|
|
3461
|
+
}
|
|
3462
|
+
if (matches.length > 1) throw new Error(`duplicate JSONL session id "${id}" appears in multiple project directories`);
|
|
3463
|
+
signal?.throwIfAborted();
|
|
3464
|
+
return matches[0];
|
|
3465
|
+
}
|
|
3466
|
+
/** Require an existing configured root to be a readable directory. */
|
|
3467
|
+
assertUsableRoot() {
|
|
3468
|
+
try {
|
|
3469
|
+
readdirSync(this.root);
|
|
3470
|
+
} catch (error) {
|
|
3471
|
+
if (isENOENT(error)) return;
|
|
3472
|
+
throw error;
|
|
3473
|
+
}
|
|
3474
|
+
}
|
|
3475
|
+
/** Reject metadata that does not identify the selected physical log. */
|
|
3476
|
+
async assertStoredIdentity(path, storedVersion, meta, expectedId, signal) {
|
|
3477
|
+
signal?.throwIfAborted();
|
|
3478
|
+
if (expectedId !== void 0 && meta.id !== expectedId) throw new Error(`corrupt session log "${path}": requested id "${expectedId}" does not match header id "${meta.id}"`);
|
|
3479
|
+
let expectedPath;
|
|
3480
|
+
try {
|
|
3481
|
+
expectedPath = generationLogPath(this.root, meta.cwd, meta.id, storedVersion, this.compression);
|
|
3482
|
+
} catch (error) {
|
|
3483
|
+
throw new Error(`corrupt session log "${path}": header id cannot name a storage path`, { cause: error });
|
|
3484
|
+
}
|
|
3485
|
+
if (path !== expectedPath && !await this.sameFile(path, expectedPath, signal)) throw new Error(`corrupt session log "${path}": header id "${meta.id}" and cwd identify "${expectedPath}"`);
|
|
3486
|
+
signal?.throwIfAborted();
|
|
3487
|
+
}
|
|
3488
|
+
/** Validate a supported historical header against the selected source path. */
|
|
3489
|
+
validateSourceIdentity(selected, headerValue, expectedId, signal) {
|
|
3490
|
+
const result = sessionFormatCatalog.readHeader(headerValue);
|
|
3491
|
+
if (result.status !== "current" && result.status !== "migration-required") return;
|
|
3492
|
+
return this.assertStoredIdentity(selected.sourcePath, selected.sourceVersion, this.currentHeader(result.header), expectedId, signal);
|
|
3493
|
+
}
|
|
3494
|
+
/**
|
|
3495
|
+
* Whether two path spellings resolve to the same physical file. This admits
|
|
3496
|
+
* case aliases on case-insensitive filesystems without weakening identity
|
|
3497
|
+
* checks on case-sensitive stores.
|
|
3498
|
+
*/
|
|
3499
|
+
async sameFile(path, expectedPath, signal) {
|
|
3500
|
+
signal?.throwIfAborted();
|
|
3501
|
+
try {
|
|
3502
|
+
const [actual, expected] = await Promise.all([realpath(path), realpath(expectedPath)]);
|
|
3503
|
+
signal?.throwIfAborted();
|
|
3504
|
+
return actual === expected;
|
|
3505
|
+
} catch (error) {
|
|
3506
|
+
signal?.throwIfAborted();
|
|
3507
|
+
/* v8 ignore else -- non-ENOENT realpath failures require an external permission or I/O fault */
|
|
3508
|
+
if (isENOENT(error)) return false;
|
|
3509
|
+
/* v8 ignore next -- non-ENOENT realpath failures are external I/O faults, propagated unchanged */
|
|
3510
|
+
throw error;
|
|
3511
|
+
}
|
|
3512
|
+
}
|
|
3513
|
+
/** The human-readable project directories under the configured root. */
|
|
3514
|
+
async listProjectDirs(signal) {
|
|
3515
|
+
try {
|
|
3516
|
+
signal?.throwIfAborted();
|
|
3517
|
+
const entries = await readdir(this.root, { withFileTypes: true });
|
|
3518
|
+
signal?.throwIfAborted();
|
|
3519
|
+
return entries.filter((e) => e.isDirectory()).map((e) => join(this.root, e.name));
|
|
3520
|
+
} catch (error) {
|
|
3521
|
+
if (isENOENT(error)) return [];
|
|
3522
|
+
throw error;
|
|
3523
|
+
}
|
|
3524
|
+
}
|
|
3525
|
+
/** List session-owned directories and reject the obsolete flat-file layout. */
|
|
3526
|
+
async listSessionDirs(project, signal) {
|
|
3527
|
+
signal?.throwIfAborted();
|
|
3528
|
+
const entries = await readdir(project, { withFileTypes: true });
|
|
3529
|
+
signal?.throwIfAborted();
|
|
3530
|
+
const legacy = entries.find((entry) => entry.isFile() && (entry.name.endsWith(".jsonl") || entry.name.endsWith(".jsonl.zstd")));
|
|
3531
|
+
if (legacy !== void 0) throw this.legacyLayout(join(project, legacy.name));
|
|
3532
|
+
return entries.filter((entry) => entry.isDirectory()).map((entry) => join(project, entry.name));
|
|
3533
|
+
}
|
|
3534
|
+
/** Reject a root that already belongs to the other physical encoding. */
|
|
3535
|
+
ensureRootEncoding() {
|
|
3536
|
+
this.rootEncodingCheck ??= this.checkRootEncoding();
|
|
3537
|
+
return this.rootEncodingCheck;
|
|
3538
|
+
}
|
|
3539
|
+
async checkRootEncoding() {
|
|
3540
|
+
await this.mapSessionDirectories(async (dir) => {
|
|
3541
|
+
const incompatible = await this.findOppositeGenerationInDirectory(dir);
|
|
3542
|
+
if (incompatible !== void 0) throw this.encodingMismatch(incompatible);
|
|
3543
|
+
});
|
|
3544
|
+
}
|
|
3545
|
+
async rejectLegacyFlatArtifact(project, id, signal) {
|
|
3546
|
+
signal?.throwIfAborted();
|
|
3547
|
+
const encoded = encodeSegment(id);
|
|
3548
|
+
for (const compression of ["zstd", "none"]) {
|
|
3549
|
+
const path = join(project, encoded + logSuffix(compression));
|
|
3550
|
+
const artifactExists = await this.exists(path);
|
|
3551
|
+
signal?.throwIfAborted();
|
|
3552
|
+
if (artifactExists) throw this.legacyLayout(path);
|
|
3553
|
+
}
|
|
3554
|
+
}
|
|
3555
|
+
async rejectOppositeArtifact(cwd, id) {
|
|
3556
|
+
const path = await this.findOppositeGenerationInDirectory(sessionDir(this.root, cwd, id));
|
|
3557
|
+
if (path !== void 0) throw this.encodingMismatch(path);
|
|
3558
|
+
}
|
|
3559
|
+
/** Return the highest canonical generation encoded with the other configured suffix. */
|
|
3560
|
+
async findOppositeGenerationInDirectory(dir) {
|
|
3561
|
+
let entries;
|
|
3562
|
+
try {
|
|
3563
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
3564
|
+
} catch (error) {
|
|
3565
|
+
if (isENOENT(error)) return void 0;
|
|
3566
|
+
throw error;
|
|
3567
|
+
}
|
|
3568
|
+
const generations = [];
|
|
3569
|
+
for (const entry of entries) {
|
|
3570
|
+
const version = parseGenerationLogFilename(entry.name, this.oppositeCompression());
|
|
3571
|
+
if (version !== void 0) generations.push({
|
|
3572
|
+
name: entry.name,
|
|
3573
|
+
version
|
|
3574
|
+
});
|
|
3575
|
+
}
|
|
3576
|
+
const latest = generations.sort((left, right) => right.version - left.version)[0];
|
|
3577
|
+
return latest === void 0 ? void 0 : join(dir, latest.name);
|
|
3578
|
+
}
|
|
3579
|
+
oppositeCompression() {
|
|
3580
|
+
return this.compression === "zstd" ? "none" : "zstd";
|
|
3581
|
+
}
|
|
3582
|
+
encodingMismatch(path) {
|
|
3583
|
+
return /* @__PURE__ */ new Error(`session artifact ${JSON.stringify(path)} uses ${logSuffix(this.oppositeCompression())}, but this backend is configured for compression ${JSON.stringify(this.compression)}; use a separate root or select the matching compression mode`);
|
|
3584
|
+
}
|
|
3585
|
+
legacyLayout(path) {
|
|
3586
|
+
return /* @__PURE__ */ new Error(`session artifact ${JSON.stringify(path)} uses the unsupported flat-file layout; use a separate root or move it into a project/session directory before loading`);
|
|
3587
|
+
}
|
|
3588
|
+
async exists(path) {
|
|
3589
|
+
try {
|
|
3590
|
+
await (await open(path, "r")).close();
|
|
3591
|
+
return true;
|
|
3592
|
+
} catch (error) {
|
|
3593
|
+
/* v8 ignore else -- Windows reports file-valued parents as ENOENT; POSIX covers direct ENOTDIR. */
|
|
3594
|
+
if (isENOENT(error)) {
|
|
3595
|
+
/* v8 ignore next -- native Windows coverage exercises this platform dispatch; POSIX reports ENOTDIR from open */
|
|
3596
|
+
if (process.platform === "win32") await this.assertLogParentAllowsAbsence(path);
|
|
3597
|
+
return false;
|
|
3598
|
+
}
|
|
3599
|
+
/* v8 ignore next -- Windows repairs ENOTDIR from ENOENT above; POSIX covers direct ENOTDIR. */
|
|
3600
|
+
throw error;
|
|
3601
|
+
}
|
|
3602
|
+
}
|
|
3603
|
+
/* v8 ignore start -- native Windows coverage exercises this repair; POSIX open reports ENOTDIR before this point. */
|
|
3604
|
+
async assertLogParentAllowsAbsence(path) {
|
|
3605
|
+
try {
|
|
3606
|
+
const parent = dirname(path);
|
|
3607
|
+
if ((await stat(parent)).isDirectory()) return;
|
|
3608
|
+
const error = /* @__PURE__ */ new Error(`ENOTDIR: parent path exists but is not a directory: ${parent}`);
|
|
3609
|
+
error.code = "ENOTDIR";
|
|
3610
|
+
error.path = parent;
|
|
3611
|
+
throw error;
|
|
3612
|
+
} catch (error) {
|
|
3613
|
+
if (isENOENT(error)) return;
|
|
3614
|
+
throw error;
|
|
3615
|
+
}
|
|
3616
|
+
}
|
|
3617
|
+
};
|
|
3618
|
+
/** JSONL persistence plugin label. */
|
|
3619
|
+
const name = "session-persistence-jsonl";
|
|
3620
|
+
/** Loader schema for the backend's root, physical encoding, and listing concurrency. */
|
|
3621
|
+
const Config = z.object({
|
|
3622
|
+
root: z.string().required(),
|
|
3623
|
+
compression: JsonlCompressionSchema,
|
|
3624
|
+
listConcurrency: z.natural().min(1).default(DEFAULT_LIST_CONCURRENCY)
|
|
3625
|
+
});
|
|
3626
|
+
/**
|
|
3627
|
+
* Mount persistence with live routing and handles retained through the
|
|
3628
|
+
* consumer unloads triggered by removing this provider. Consumers must own
|
|
3629
|
+
* cleanup in their injecting scope; concurrent root disposal is not ordered.
|
|
3630
|
+
* @param ctx - the owning plugin context.
|
|
3631
|
+
* @param config - the storage root, physical encoding, and listing concurrency.
|
|
3632
|
+
* @returns resolves when the service is ready.
|
|
3633
|
+
*/
|
|
3634
|
+
async function apply(ctx, config) {
|
|
3635
|
+
let service;
|
|
3636
|
+
ctx.effect(function* () {
|
|
3637
|
+
const tracker = new JsonlBackendTracker(name);
|
|
3638
|
+
yield tracker.install(ctx);
|
|
3639
|
+
service = ctx.plugin({
|
|
3640
|
+
name: "session-persistence-jsonl-service",
|
|
3641
|
+
apply(serviceCtx) {
|
|
3642
|
+
new JsonlSessionPersistence(serviceCtx, config, tracker);
|
|
3643
|
+
}
|
|
3644
|
+
});
|
|
3645
|
+
yield service.dispose;
|
|
3646
|
+
}, "session-persistence-jsonl resources");
|
|
3647
|
+
await service.await();
|
|
3648
|
+
}
|
|
3649
|
+
//#endregion
|
|
3650
|
+
export { Config, JsonlCompressionSchema, apply, name };
|