@kabxx/dsh-message-revision 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,319 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { lstat, mkdir, open, readFile, readdir, realpath, rename, rm, unlink } from 'node:fs/promises';
3
+ import { hostname } from 'node:os';
4
+ import { basename, dirname, join } from 'node:path';
5
+ import manifest from '../package.json' with { type: 'json' };
6
+
7
+ const release = /^v\d+\.\d+\.\d+(?:-[0-9a-z.-]+)?$/iu;
8
+ const sessionFile = /^session\.v4\.jsonl(?:\.zstd)?$/u;
9
+ const digestPattern = /^[a-f0-9]{64}$/u;
10
+ const garbageName = /^discard-[a-f0-9-]{36}$/u;
11
+ const preparationName = /^preparing-[a-f0-9-]{36}$/u;
12
+ const limit = 256 * 1024 * 1024;
13
+ const ownerHost = hostname();
14
+ const busyKey = Symbol.for('dsh-message-revision.active-transactions');
15
+ const active = globalThis[busyKey] ??= new Set();
16
+
17
+ function assert(condition, detail) {
18
+ if (!condition) throw new Error(detail);
19
+ }
20
+
21
+ function optionalStat(path) {
22
+ return lstat(path).catch(error => {
23
+ if (error.code !== 'ENOENT') throw error;
24
+ return undefined;
25
+ });
26
+ }
27
+
28
+ async function assertDirectory(path) {
29
+ const entry = await optionalStat(path);
30
+ if (entry === undefined) return false;
31
+ assert(entry.isDirectory() && await realpath(path) === path, 'Unsafe transaction directory');
32
+ return true;
33
+ }
34
+
35
+ async function syncDirectory(path) {
36
+ if (process.platform === 'win32') return;
37
+ const handle = await open(path, 'r');
38
+ try { await handle.sync(); } finally { await handle.close(); }
39
+ }
40
+
41
+ async function ensureDirectory(path) {
42
+ await mkdir(path, { mode: 0o700 }).catch(error => {
43
+ if (error.code !== 'EEXIST') throw error;
44
+ });
45
+ assert(await assertDirectory(path), 'Missing transaction directory');
46
+ await syncDirectory(dirname(path));
47
+ }
48
+
49
+ async function writeFileDurably(path, bytes) {
50
+ const file = await open(path, 'wx', 0o600);
51
+ try {
52
+ await file.writeFile(bytes);
53
+ await file.sync();
54
+ } finally { await file.close(); }
55
+ }
56
+
57
+ async function readRegular(path, max = limit) {
58
+ const entry = await lstat(path);
59
+ assert(entry.isFile() && entry.size <= max && await realpath(path) === path, 'Unsafe transaction file');
60
+ return readFile(path);
61
+ }
62
+
63
+ const digest = data => createHash('sha256').update(data).digest('hex');
64
+
65
+ function safeComponent(value) {
66
+ return typeof value === 'string' && value.length > 0 && value !== '.' && value !== '..' && !/[\\/\u0000]/u.test(value);
67
+ }
68
+
69
+ function namespace(parentPath) {
70
+ return join(dirname(parentPath), 'plugins', ...manifest.name.split('/'));
71
+ }
72
+
73
+ function childPath(parentPath, child) {
74
+ assert(safeComponent(child.project) && safeComponent(child.directory) && sessionFile.test(child.filename),
75
+ 'Unsafe recorded child path');
76
+ const store = dirname(dirname(dirname(parentPath)));
77
+ const path = join(store, child.project, child.directory, child.filename);
78
+ assert(dirname(path) !== dirname(parentPath), 'Transaction cannot move its parent directory');
79
+ return path;
80
+ }
81
+
82
+ async function moveDirectory(from, to) {
83
+ assert(await assertDirectory(from), 'Transaction source directory disappeared');
84
+ assert(await assertDirectory(dirname(to)), 'Transaction destination parent disappeared');
85
+ assert(!await optionalStat(to), 'Transaction destination is already occupied');
86
+ await rename(from, to);
87
+ await syncDirectory(dirname(from));
88
+ if (dirname(to) !== dirname(from)) await syncDirectory(dirname(to));
89
+ }
90
+
91
+ async function removeRetiredDirectory(directory) {
92
+ if (!await assertDirectory(directory)) return;
93
+ await rm(directory, { recursive: true });
94
+ await syncDirectory(dirname(directory));
95
+ }
96
+
97
+ function assertOwnerReleased(owner) {
98
+ assert(owner?.host === ownerHost && Number.isSafeInteger(owner.pid) && owner.pid > 0,
99
+ 'Transaction belongs to another host or has invalid ownership');
100
+ if (owner.pid === process.pid) return;
101
+ try { process.kill(owner.pid, 0); } catch (error) {
102
+ if (error.code === 'ESRCH') return;
103
+ throw error;
104
+ }
105
+ throw new Error('The process that started this rewrite is still running');
106
+ }
107
+
108
+ async function verifyChildFile(path, expected) {
109
+ const bytes = await readRegular(path);
110
+ assert(digest(bytes) === expected.digest, 'Recorded child data has changed');
111
+ }
112
+
113
+ export async function hasPendingRewrite(parentPath) {
114
+ const root = namespace(parentPath);
115
+ for (const path of [join(dirname(parentPath), 'plugins'), dirname(root), root]) {
116
+ if (!await assertDirectory(path)) return false;
117
+ }
118
+ for (const name of await readdir(root)) {
119
+ if (!release.test(name)) continue;
120
+ const directory = join(root, name);
121
+ if (await assertDirectory(directory) && await assertDirectory(join(directory, 'rewrite'))) return true;
122
+ }
123
+ return false;
124
+ }
125
+
126
+ /** Keep the intent immutable. Publish it and sync its directory before moving any session. */
127
+ export async function prepareRewriteJournal(parent, children, replacement) {
128
+ const parentPath = parent.path;
129
+ const parentId = parent.handle.header.id;
130
+ const root = namespace(parentPath);
131
+ const versionPath = join(root, `v${manifest.version}`);
132
+ for (const path of [join(dirname(parentPath), 'plugins'), dirname(root), root, versionPath]) {
133
+ await ensureDirectory(path);
134
+ }
135
+ assert(!active.has(parentPath) && !await hasPendingRewrite(parentPath), 'A previous rewrite still needs recovery');
136
+ active.add(parentPath);
137
+ const temporary = join(versionPath, `preparing-${randomUUID()}`);
138
+ const directory = join(versionPath, 'rewrite');
139
+ try {
140
+ const records = [];
141
+ for (const child of children) {
142
+ const path = child.path;
143
+ const project = basename(dirname(dirname(path)));
144
+ const localDirectory = basename(dirname(path));
145
+ const { id, parentSession, createdAt } = child.handle.header;
146
+ const record = { id, parentSession, createdAt, project, directory: localDirectory, filename: basename(path),
147
+ digest: digest(await readRegular(path)) };
148
+ assert(childPath(parentPath, record) === path, 'Child and parent use different storage roots');
149
+ records.push(record);
150
+ }
151
+ const candidate = createHash('sha256');
152
+ let size = 0;
153
+ for (const bytes of replacement.buffers) { candidate.update(bytes); size += bytes.length; }
154
+ assert(size <= limit, 'Replacement transcript is too large');
155
+ const intent = {
156
+ format: 1, parentId, filename: basename(parentPath), owner: { host: ownerHost, pid: process.pid },
157
+ original: digest(replacement.original), candidate: { digest: candidate.digest('hex'), size, records: replacement.retained },
158
+ children: records,
159
+ };
160
+ await mkdir(temporary, { mode: 0o700 });
161
+ await writeFileDurably(join(temporary, 'original'), replacement.original);
162
+ await writeFileDurably(join(temporary, 'intent.json'), JSON.stringify(intent));
163
+ await syncDirectory(temporary);
164
+ await moveDirectory(temporary, directory);
165
+ return { directory, intent, parentPath };
166
+ } catch (error) {
167
+ active.delete(parentPath);
168
+ // The preparation directory never contains moved children. Keep an already
169
+ // published intent intact so the next recovery can make the same decision.
170
+ await removeRetiredDirectory(temporary).catch(() => {});
171
+ throw error;
172
+ }
173
+ }
174
+
175
+ export function forgetRewriteJournal(journal) {
176
+ if (journal) active.delete(journal.parentPath);
177
+ }
178
+
179
+ function childLocations(journal, entry, index) {
180
+ const path = childPath(journal.parentPath, entry);
181
+ return { from: dirname(path), to: join(journal.directory, `child-${index}`), path };
182
+ }
183
+
184
+ export async function stageWithdrawnChildren(journal) {
185
+ for (const [index, entry] of journal.intent.children.entries()) {
186
+ const { from, to, path } = childLocations(journal, entry, index);
187
+ await verifyChildFile(path, entry);
188
+ await moveDirectory(from, to);
189
+ }
190
+ }
191
+
192
+ export async function restoreWithdrawnChildren(journal) {
193
+ const restore = [];
194
+ // Validate every move before making any. A repeat after a crash accepts an
195
+ // already restored directory only if it still holds the exact same rollout.
196
+ for (const [index, entry] of journal.intent.children.entries()) {
197
+ const { from, to, path } = childLocations(journal, entry, index);
198
+ const original = await assertDirectory(from);
199
+ const held = await assertDirectory(to);
200
+ assert(original !== held, 'Cannot distinguish the original child directory from a conflict');
201
+ if (original) {
202
+ await verifyChildFile(path, entry);
203
+ } else {
204
+ await verifyChildFile(join(to, entry.filename), entry);
205
+ restore.push({ from, to });
206
+ }
207
+ }
208
+ for (const { from, to } of restore.toReversed()) await moveDirectory(to, from);
209
+ }
210
+
211
+ export async function markRewriteCommitted(journal) {
212
+ // fsync an empty regular marker after the native Agent has accepted the
213
+ // candidate. Once present, recovery can only finish cleanup.
214
+ const temporary = join(journal.directory, `commit-${randomUUID()}.tmp`);
215
+ await writeFileDurably(temporary, Buffer.alloc(0));
216
+ await rename(temporary, join(journal.directory, 'committed'));
217
+ await syncDirectory(journal.directory);
218
+ }
219
+
220
+ export async function clearFailedCommitMarker(journal) {
221
+ try { await unlink(join(journal.directory, 'committed')); }
222
+ catch (error) { if (error.code !== 'ENOENT') throw error; }
223
+ await syncDirectory(journal.directory);
224
+ }
225
+
226
+ export async function retireRewriteJournal(journal) {
227
+ const garbage = join(dirname(journal.directory), `discard-${randomUUID()}`);
228
+ // Rename first. If deletion terminates partway through, startup does not
229
+ // mistake the partial removal for a journal that still needs rollback.
230
+ await moveDirectory(journal.directory, garbage);
231
+ await removeRetiredDirectory(garbage);
232
+ }
233
+
234
+ function validateIntent(intent, snapshot, path) {
235
+ const { id } = snapshot.header;
236
+ assert(intent?.format === 1 && intent.parentId === id && intent.filename === basename(path), 'Unknown transaction format or parent');
237
+ assert(digestPattern.test(intent.original) && digestPattern.test(intent.candidate?.digest)
238
+ && Number.isSafeInteger(intent.candidate.size) && intent.candidate.size > 0 && intent.candidate.size <= limit
239
+ && Number.isSafeInteger(intent.candidate.records) && intent.candidate.records >= 0 && Array.isArray(intent.children),
240
+ 'Invalid transaction hashes or boundaries');
241
+ const ids = new Set([id]);
242
+ const paths = new Set([dirname(path)]);
243
+ for (const child of intent.children) {
244
+ const directory = dirname(childPath(path, child));
245
+ assert(typeof child.id === 'string' && child.id.length > 0 && !ids.has(child.id)
246
+ && ids.has(child.parentSession) && !paths.has(directory) && Number.isSafeInteger(child.createdAt)
247
+ && digestPattern.test(child.digest), 'Invalid recorded child lineage');
248
+ ids.add(child.id);
249
+ paths.add(directory);
250
+ }
251
+ }
252
+
253
+ /** Scan only artifacts located by the native persistence backend. */
254
+ export async function readRewriteJournals(snapshot) {
255
+ const path = snapshot?.location?.path;
256
+ if (snapshot?.location?.kind !== 'jsonl' || typeof path !== 'string' || !sessionFile.test(basename(path))
257
+ || !await assertDirectory(dirname(path))) return [];
258
+ const root = namespace(path);
259
+ for (const directory of [join(dirname(path), 'plugins'), dirname(root), root]) {
260
+ if (!await assertDirectory(directory)) return [];
261
+ }
262
+ if (active.has(path)) return [];
263
+ const journals = [];
264
+ for (const name of await readdir(root)) {
265
+ if (!release.test(name)) continue;
266
+ const versionPath = join(root, name);
267
+ if (!await assertDirectory(versionPath)) continue;
268
+ const directory = join(versionPath, 'rewrite');
269
+ if (await assertDirectory(directory)) {
270
+ const intent = JSON.parse(await readRegular(join(directory, 'intent.json'), 4 * 1024 * 1024));
271
+ validateIntent(intent, snapshot, path);
272
+ assertOwnerReleased(intent.owner);
273
+ const marker = join(directory, 'committed');
274
+ const committed = await optionalStat(marker) !== undefined;
275
+ if (committed) assert((await readRegular(marker, 0)).length === 0, 'Invalid transaction commit marker');
276
+ journals.push({ directory, intent, parentPath: path, committed });
277
+ }
278
+ }
279
+ assert(journals.length <= 1, 'Multiple unresolved rewrites for the same session');
280
+ return journals;
281
+ }
282
+
283
+ /** Enumerate only names this version uses for incomplete preparations or retired journals. */
284
+ export async function listRewriteDebris(path) {
285
+ const root = namespace(path);
286
+ const preparations = [];
287
+ const retired = [];
288
+ for (const directory of [join(dirname(path), 'plugins'), dirname(root), root]) {
289
+ if (!await assertDirectory(directory)) return { preparations, retired };
290
+ }
291
+ for (const name of await readdir(root)) {
292
+ if (!release.test(name)) continue;
293
+ const versionPath = join(root, name);
294
+ if (!await assertDirectory(versionPath)) continue;
295
+ for (const entry of await readdir(versionPath)) {
296
+ if (garbageName.test(entry)) retired.push(join(versionPath, entry));
297
+ else if (preparationName.test(entry)) preparations.push(join(versionPath, entry));
298
+ }
299
+ }
300
+ return { preparations, retired };
301
+ }
302
+
303
+ export async function cleanRewriteDebris(paths) {
304
+ for (const path of paths) await removeRetiredDirectory(path);
305
+ }
306
+
307
+ export async function readRewriteOriginal(journal) {
308
+ const original = await readRegular(join(journal.directory, 'original'));
309
+ assert(digest(original) === journal.intent.original, 'The original transcript copy has changed');
310
+ return original;
311
+ }
312
+
313
+ export async function matchJournalRevision(journal) {
314
+ const raw = await readRegular(journal.parentPath);
315
+ if (digest(raw) === journal.intent.original) return 'original';
316
+ const { size, digest: hash } = journal.intent.candidate;
317
+ if (raw.length >= size && digest(raw.subarray(0, size)) === hash) return 'candidate';
318
+ return 'conflict';
319
+ }