@xsok/dsh-enhanced 0.0.0-stage → 0.2.2-11

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,138 @@
1
+ /**
2
+ * Session log read/write for the pure-JS engine.
3
+ *
4
+ * A session file is a multi-frame zstd container of JSONL rows: the app appends
5
+ * one frame per write, and a frame may hold several rows. The first row of the
6
+ * first frame is the header carrying `id` and `cwd`. Rewriting a session keeps
7
+ * the original frame segmentation and touches only that header row, which is what
8
+ * `dsh-zstd-helper.js copy` does — anything else changes the byte layout the
9
+ * desktop app expects.
10
+ */
11
+ import { promises as fsp } from 'node:fs';
12
+ import path from 'node:path';
13
+ import { decodeFrames, encodeFrame, scanFrames } from './zstd.js';
14
+
15
+ /** Split one frame's plaintext into JSONL rows. */
16
+ function rowsOf(text) {
17
+ return text.split('\n').filter((line) => line !== '');
18
+ }
19
+
20
+ /** Parse one session buffer: header plus per-frame plaintext. */
21
+ export function parseSession(buffer) {
22
+ const frames = scanFrames(buffer);
23
+ if (frames.length === 0) throw Object.assign(new Error('文件中没有完整的 zstd 帧'), { code: 'zstd-empty' });
24
+ const texts = frames.map((frame) => decodeFrames(buffer, [frame]).toString('utf8'));
25
+ const firstRows = rowsOf(texts[0]);
26
+ if (firstRows.length === 0) throw Object.assign(new Error('会话首帧为空'), { code: 'session-empty' });
27
+ let header;
28
+ try {
29
+ header = JSON.parse(firstRows[0]);
30
+ } catch {
31
+ throw Object.assign(new Error('会话首行不是合法 JSON'), { code: 'session-header-invalid' });
32
+ }
33
+ if (header === null || typeof header !== 'object' || typeof header.id !== 'string') {
34
+ throw Object.assign(new Error('会话首行缺少 id'), { code: 'session-header-invalid' });
35
+ }
36
+ return { header, texts, frames: frames.length };
37
+ }
38
+
39
+ /** Read one session file from disk. */
40
+ export async function readSessionFile(file) {
41
+ return parseSession(await fsp.readFile(file));
42
+ }
43
+
44
+ /** Rewrite only the header's cwd, keeping frame boundaries and every other row. */
45
+ export function rewriteCwd(parsed, cwd) {
46
+ const texts = [...parsed.texts];
47
+ const rows = rowsOf(texts[0]);
48
+ const header = { ...JSON.parse(rows[0]), cwd };
49
+ rows[0] = JSON.stringify(header);
50
+ texts[0] = `${rows.join('\n')}\n`;
51
+ return { header, texts };
52
+ }
53
+
54
+ /** Encode per-frame plaintext back into one multi-frame container. */
55
+ export function encodeSession(texts) {
56
+ return Buffer.concat(texts.map((text) => encodeFrame(text)));
57
+ }
58
+
59
+ /** Write rows as a multi-frame container, replacing the target atomically. */
60
+ export async function writeSessionFile(file, texts) {
61
+ const buffer = encodeSession(texts);
62
+ const temporary = `${file}.engine-${String(process.pid)}`;
63
+ await fsp.mkdir(path.dirname(file), { recursive: true });
64
+ await fsp.writeFile(temporary, buffer);
65
+ await fsp.rename(temporary, file);
66
+ return buffer.length;
67
+ }
68
+
69
+ /** Copy one session with a rewritten cwd; frames stay as they were. */
70
+ export async function copySessionWithCwd(sourceFile, targetFile, cwd) {
71
+ const parsed = await readSessionFile(sourceFile);
72
+ const { header, texts } = rewriteCwd(parsed, cwd);
73
+ await writeSessionFile(targetFile, texts);
74
+ return header;
75
+ }
76
+
77
+ /** Last event seq in a session file, or -1 when it cannot be read. */
78
+ export async function lastEventSeq(file) {
79
+ try {
80
+ const buffer = await fsp.readFile(file);
81
+ const frames = scanFrames(buffer);
82
+ if (frames.length === 0) return -1;
83
+ const text = decodeFrames(buffer, [frames[frames.length - 1]]).toString('utf8');
84
+ const rows = text.split('\n').filter((line) => line !== '');
85
+ for (let index = rows.length - 1; index >= 0; index -= 1) {
86
+ try {
87
+ const parsed = JSON.parse(rows[index]);
88
+ if (Number.isInteger(parsed?.seq)) return parsed.seq;
89
+ } catch {
90
+ // A torn row carries no seq; keep looking backwards.
91
+ }
92
+ }
93
+ return -1;
94
+ } catch {
95
+ return -1;
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Seq of the last event that carries conversation content.
101
+ *
102
+ * Bookkeeping events (seed markers, job registration, sandbox or approval state)
103
+ * are appended by the app on its own — opening a session can add one — and must
104
+ * not make a log look newer than the other side.
105
+ */
106
+ const CONTENT_EVENTS = new Set([
107
+ 'user/message',
108
+ 'assistant/message',
109
+ 'tool/call',
110
+ 'tool/result',
111
+ 'developer/message',
112
+ 'system/message',
113
+ 'assistant/attempt',
114
+ ]);
115
+
116
+ export async function lastContentSeq(file) {
117
+ try {
118
+ const buffer = await fsp.readFile(file);
119
+ const frames = scanFrames(buffer);
120
+ if (frames.length === 0) return -1;
121
+ const tail = frames.slice(-12);
122
+ for (let index = tail.length - 1; index >= 0; index -= 1) {
123
+ const text = decodeFrames(buffer, [tail[index]]).toString('utf8');
124
+ const rows = text.split('\n').filter((line) => line !== '');
125
+ for (let row = rows.length - 1; row >= 0; row -= 1) {
126
+ try {
127
+ const parsed = JSON.parse(rows[row]);
128
+ if (CONTENT_EVENTS.has(parsed?.type) && Number.isInteger(parsed?.seq)) return parsed.seq;
129
+ } catch {
130
+ // Torn rows are skipped.
131
+ }
132
+ }
133
+ }
134
+ return -1;
135
+ } catch {
136
+ return -1;
137
+ }
138
+ }
@@ -0,0 +1,395 @@
1
+ /**
2
+ * Session synchronization for the pure-JS engine.
3
+ *
4
+ * Two directions, one arbitration rule: a higher artifact generation always wins,
5
+ * and only equal generations compare by mtime (matching the PowerShell engine).
6
+ * Deletions ride on tombstones, and a copy newer than its tombstone revives it.
7
+ */
8
+ import { promises as fsp } from 'node:fs';
9
+ import { randomUUID } from 'node:crypto';
10
+ import path from 'node:path';
11
+ import { scanSessions, projectKey } from './scan.js';
12
+ import { buildBlankGuard, repairPulledSessions } from './blank-guard.js';
13
+ import { lastContentSeq, readSessionFile, rewriteCwd, writeSessionFile } from './session.js';
14
+ import {
15
+ SESSION_LEDGER,
16
+ mergeJournal,
17
+ readJson as readLedgerJson,
18
+ readLedger,
19
+ writeJsonAtomic,
20
+ writeLedger,
21
+ } from './ledger.js';
22
+
23
+ /**
24
+ * Distinguish "missing" from "corrupt": a damaged tombstone table used to read
25
+ * as empty, which resurrects every deleted session.
26
+ */
27
+ async function readJsonStrict(file) {
28
+ try {
29
+ const text = await fsp.readFile(file, 'utf8');
30
+ return { value: JSON.parse(text), corrupt: false };
31
+ } catch (error) {
32
+ return { value: undefined, corrupt: error?.code !== 'ENOENT' };
33
+ }
34
+ }
35
+
36
+ async function readJson(file, fallback) {
37
+ try {
38
+ return JSON.parse(await fsp.readFile(file, 'utf8'));
39
+ } catch {
40
+ return fallback;
41
+ }
42
+ }
43
+
44
+ async function writeJson(file, value) {
45
+ await fsp.mkdir(path.dirname(file), { recursive: true });
46
+ const temporary = `${file}.${randomUUID()}.tmp`;
47
+ await fsp.writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
48
+ await fsp.rename(temporary, file);
49
+ }
50
+
51
+ /** Delete copies of one session that sit under a different project key. */
52
+ async function dropOtherCopies(localRoot, id, keepDir) {
53
+ let projects;
54
+ try {
55
+ projects = await fsp.readdir(localRoot, { withFileTypes: true });
56
+ } catch {
57
+ return;
58
+ }
59
+ for (const project of projects) {
60
+ if (!project.isDirectory()) continue;
61
+ const candidate = path.join(localRoot, project.name, id);
62
+ if (candidate === keepDir) continue;
63
+ try {
64
+ await fsp.stat(candidate);
65
+ } catch {
66
+ continue;
67
+ }
68
+ await fsp.rm(candidate, { recursive: true, force: true }).catch(() => {});
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Move a shared session copy into the shared recycle bin instead of deleting it.
74
+ * The other machine can then restore the newest content, not just the fact that
75
+ * the session once existed.
76
+ */
77
+ async function sessionTitle(sharedRoot, id) {
78
+ try {
79
+ const file = path.join(path.dirname(sharedRoot), 'config', 'storages', 'session_projcache', 'sessions', `${id}.json`);
80
+ const doc = JSON.parse(await fsp.readFile(file, 'utf8'));
81
+ const value = doc?.record?.rows?.title?.val;
82
+ return typeof value === 'string' && value.trim() !== '' ? value.trim() : '';
83
+ } catch {
84
+ return '';
85
+ }
86
+ }
87
+
88
+ async function moveToTrash(entry, trashRoot, ledgerEntry) {
89
+ const bucketName = typeof ledgerEntry?.workspace === 'string' && ledgerEntry.workspace !== ''
90
+ ? ledgerEntry.workspace
91
+ : '_ungrouped';
92
+ const target = path.join(trashRoot, bucketName, entry.id);
93
+ await fsp.rm(target, { recursive: true, force: true });
94
+ await fsp.mkdir(path.dirname(target), { recursive: true });
95
+ await fsp.cp(entry.dir, path.join(target, 'log'), { recursive: true, force: true });
96
+ await fsp.rm(entry.dir, { recursive: true, force: true }).catch(() => {});
97
+ const title = await sessionTitle(path.dirname(trashRoot), entry.id);
98
+ await writeJsonAtomic(path.join(target, 'meta.json'), {
99
+ version: 1,
100
+ sessionId: entry.id,
101
+ title: title === '' ? entry.id : title,
102
+ workspaceId: bucketName,
103
+ deletedAt: ledgerEntry?.at ?? new Date().toISOString(),
104
+ sizeBytes: ledgerEntry?.size ?? 0,
105
+ mtime: ledgerEntry?.mtime ?? entry.mtime,
106
+ source: 'sync',
107
+ });
108
+ }
109
+
110
+ /** True when `candidate` should replace `current` (generation first, then mtime). */
111
+ export function wins(candidate, current) {
112
+ if (current === undefined) return true;
113
+ if (candidate.generation !== current.generation) return candidate.generation > current.generation;
114
+ // File systems and utimes round sub-millisecond stamps; treat that as a tie.
115
+ return candidate.mtime > current.mtime + 1;
116
+ }
117
+
118
+ /** Copy one session into a target root under the project key of its cwd. */
119
+ async function copySessionTo(source, targetRoot) {
120
+ const parsed = await readSessionFile(source.file);
121
+ const cwd = parsed.header.cwd;
122
+ const key = projectKey(cwd);
123
+ const dir = path.join(targetRoot, key, source.id);
124
+ await fsp.mkdir(dir, { recursive: true });
125
+ const target = path.join(dir, path.basename(source.file));
126
+ await writeSessionFile(target, parsed.texts);
127
+ // Preserve the source timestamp: equal mtimes are what stop push/pull ping-pong.
128
+ const seconds = source.mtime / 1000;
129
+ await fsp.utimes(target, seconds, seconds).catch(() => {});
130
+ return target;
131
+ }
132
+
133
+ /**
134
+ * Run the session half of a sync.
135
+ * @returns counters plus the ids that were skipped or failed.
136
+ */
137
+ export async function syncSessions(deps) {
138
+ const {
139
+ localRoot,
140
+ sharedRoot,
141
+ stateDir,
142
+ machineId,
143
+ resolveCwd = async (cwd) => ({ path: cwd, action: 'existed' }),
144
+ skipIds = new Set(),
145
+ apply = true,
146
+ journalFile = null,
147
+ cacheDir = null,
148
+ guardStateFile = null,
149
+ sharedTrashRoot = path.join(path.dirname(sharedRoot), 'trash'),
150
+ } = deps;
151
+
152
+ const local = await scanSessions(localRoot);
153
+ const shared = await scanSessions(sharedRoot);
154
+ const legacyFile = path.join(stateDir, 'deleted-sessions.json');
155
+ const machineFile = path.join(stateDir, `machine-${machineId}.json`);
156
+
157
+ const ledger = await readLedger(stateDir, SESSION_LEDGER);
158
+ if (journalFile !== null && apply) await mergeJournal(stateDir, journalFile, ledger, 'sessions');
159
+
160
+ // Old tombstone documents only carry an id and a time; fold them in once so a
161
+ // deleted session cannot come back merely because the format changed.
162
+ const legacyRead = await readJsonStrict(legacyFile);
163
+ if (legacyRead.corrupt) {
164
+ throw Object.assign(
165
+ new Error('deleted-sessions.json 已损坏,为避免已删除的会话复活,本轮同步已中止'),
166
+ { code: 'tombstone-corrupt' },
167
+ );
168
+ }
169
+ for (const [id, iso] of Object.entries(legacyRead.value?.deleted ?? {})) {
170
+ if (typeof id !== 'string') continue;
171
+ if (ledger.deleted[id] !== undefined) continue;
172
+ ledger.deleted[id] = { at: String(iso), legacy: true };
173
+ }
174
+
175
+ const previous = await readJson(machineFile, { version: 1, keys: {} });
176
+ const previousIds = new Set(Object.keys(previous.keys ?? {}));
177
+
178
+ let pushed = 0;
179
+ let pulled = 0;
180
+ let skipped = 0;
181
+ let revived = 0;
182
+ let tombstoned = 0;
183
+ const failed = [];
184
+ const pushedIds = [];
185
+ const pulledIds = [];
186
+
187
+ // 1. Local deletions become ledger entries, with the file facts of the copy
188
+ // this machine still knows about (mtime/size) so the recycle bin can pick
189
+ // the newest version later.
190
+ const now = new Date().toISOString();
191
+ for (const id of previousIds) {
192
+ if (local.has(id) || ledger.deleted[id] !== undefined) continue;
193
+ const sharedCopy = shared.get(id);
194
+ ledger.deleted[id] = {
195
+ at: now,
196
+ mtime: sharedCopy?.mtime ?? 0,
197
+ size: sharedCopy?.size ?? 0,
198
+ by: machineId,
199
+ };
200
+ tombstoned += 1;
201
+ }
202
+
203
+ // A run where the local root was unreadable looks exactly like "every session
204
+ // was deleted". Refuse only when the directory cannot be read, or when the whole
205
+ // home looks wiped — deleting the last session must still propagate.
206
+ let readable = true;
207
+ try {
208
+ await fsp.readdir(localRoot);
209
+ } catch {
210
+ readable = false;
211
+ }
212
+ let homeEvidence = false;
213
+ try {
214
+ await fsp.stat(path.join(path.dirname(localRoot), 'storages', 'workspace.json'));
215
+ homeEvidence = true;
216
+ } catch {
217
+ homeEvidence = false;
218
+ }
219
+ if (apply && !readable) {
220
+ return {
221
+ pushed: 0, pulled: 0, skipped: 0, revived: 0, tombstoned: 0,
222
+ created: 0, missing: 0, failed: [],
223
+ aborted: '本机会话目录不可读,已中止并保留删除记录',
224
+ };
225
+ }
226
+ if (apply && previousIds.size > 0 && local.size === 0 && !homeEvidence) {
227
+ return {
228
+ pushed: 0, pulled: 0, skipped: 0, revived: 0, tombstoned: 0,
229
+ created: 0, missing: 0, failed: [],
230
+ aborted: '本机看起来已被清空(缺少 workspace.json),已中止本轮以防误删',
231
+ };
232
+ }
233
+
234
+ // 2. A local copy newer than its deletion record means the user restored it.
235
+ for (const [id, record] of [...Object.entries(ledger.deleted)]) {
236
+ const entry = local.get(id);
237
+ if (entry === undefined) continue;
238
+ const deletedAt = Date.parse(record.at ?? '');
239
+ if (!Number.isFinite(deletedAt) || entry.mtime > deletedAt + 1) {
240
+ delete ledger.deleted[id];
241
+ revived += 1;
242
+ }
243
+ }
244
+
245
+ // 3. Apply the remaining deletions. Shared copies move into the shared recycle
246
+ // bin so the other machine can still restore them; local copies go away.
247
+ for (const [id, record] of Object.entries(ledger.deleted)) {
248
+ const sharedEntry = shared.get(id);
249
+ if (sharedEntry !== undefined) {
250
+ if (apply) await moveToTrash(sharedEntry, sharedTrashRoot, record).catch(() => {});
251
+ shared.delete(id);
252
+ }
253
+ const localEntry = local.get(id);
254
+ if (localEntry !== undefined) {
255
+ if (apply) await fsp.rm(localEntry.dir, { recursive: true, force: true }).catch(() => {});
256
+ local.delete(id);
257
+ }
258
+ }
259
+
260
+ // 3. Push local sessions the share does not have (or has in an older state).
261
+ // A session that was created but never used carries a blank projection
262
+ // shard; letting it reach the share hides the conversation on every machine
263
+ // that later pulls it, so the guard keeps it (and its shard) out. The scan
264
+ // above is reused: no second walk of the sessions root.
265
+ let blankGuard = { skipIds: new Set(), skipped: 0, repaired: 0 };
266
+ if (cacheDir !== null) {
267
+ try {
268
+ blankGuard = await buildBlankGuard({ sessions: local, cacheDir, apply, stateFile: guardStateFile });
269
+ } catch {
270
+ blankGuard = { skipIds: new Set(), skipped: 0, repaired: 0 };
271
+ }
272
+ }
273
+ const guardedIds = new Set([...skipIds, ...blankGuard.skipIds]);
274
+
275
+ for (const [id, entry] of local) {
276
+ if (ledger.deleted[id] !== undefined) continue;
277
+ if (guardedIds.has(id)) {
278
+ skipped += 1;
279
+ continue;
280
+ }
281
+ const sharedEntry = shared.get(id);
282
+ // A session under another workspace folder was moved: the folder says nothing
283
+ // about which copy is newer, so the event count still decides. Treating the
284
+ // local folder as authoritative pushed a stale copy back over a newer share
285
+ // and undid the move.
286
+ const relocated = sharedEntry !== undefined
287
+ && path.basename(path.dirname(entry.file)) !== path.basename(path.dirname(sharedEntry.file));
288
+ // Append-only logs: the one holding more events is the newer one. Upload and
289
+ // download timestamps are meaningless here because each transfer rewrites them.
290
+ if (sharedEntry !== undefined) {
291
+ const localSeq = await lastContentSeq(entry.file);
292
+ const sharedSeq = await lastContentSeq(sharedEntry.file);
293
+ if (sharedSeq >= 0 && localSeq >= 0) {
294
+ if (sharedSeq >= localSeq) {
295
+ // The share is as new or newer — including a moved session it already
296
+ // holds; the pull pass below brings it over and drops the local copy.
297
+ skipped += 1;
298
+ continue;
299
+ }
300
+ } else if (!wins(entry, sharedEntry)) {
301
+ skipped += 1;
302
+ continue;
303
+ }
304
+ }
305
+ try {
306
+ if (apply) {
307
+ const written = await copySessionTo(entry, sharedRoot);
308
+ // A moved session can still exist under its previous project key in the
309
+ // share; leaving it makes every later run look like a push.
310
+ if (relocated && sharedEntry !== undefined) {
311
+ await fsp.rm(sharedEntry.dir, { recursive: true, force: true }).catch(() => {});
312
+ shared.delete(id);
313
+ }
314
+ await dropOtherCopies(sharedRoot, id, path.dirname(written));
315
+ }
316
+ pushed += 1;
317
+ if (pushedIds.length < 300) pushedIds.push(id);
318
+ } catch (error) {
319
+ failed.push({ id, error: String(error?.message ?? error) });
320
+ }
321
+ }
322
+
323
+ const refreshedShare = await scanSessions(sharedRoot);
324
+
325
+ // 4. Pull shared sessions this machine lacks or holds in an older state.
326
+ let created = 0;
327
+ let missing = 0;
328
+ const pulledLocal = [];
329
+ for (const [id, entry] of refreshedShare) {
330
+ if (ledger.deleted[id] !== undefined) continue;
331
+ if (guardedIds.has(id)) continue;
332
+ const localEntry = local.get(id);
333
+ if (localEntry !== undefined) {
334
+ const sharedSeq = await lastContentSeq(entry.file);
335
+ const localSeq = await lastContentSeq(localEntry.file);
336
+ if (sharedSeq >= 0 && localSeq >= 0) {
337
+ // Same event count means the only difference is this machine's cwd, which
338
+ // is not worth a transfer.
339
+ if (sharedSeq <= localSeq) continue;
340
+ } else if (!wins(entry, localEntry)) {
341
+ continue;
342
+ }
343
+ }
344
+ try {
345
+ const parsed = await readSessionFile(entry.file);
346
+ const resolved = await resolveCwd(parsed.header.cwd);
347
+ if (resolved.action === 'created') created += 1;
348
+ if (resolved.action === 'missing') {
349
+ missing += 1;
350
+ continue;
351
+ }
352
+ const texts = rewriteCwd(parsed, resolved.path).texts;
353
+ const dir = path.join(localRoot, projectKey(resolved.path), id);
354
+ const target = path.join(dir, path.basename(entry.file));
355
+ if (apply) await dropOtherCopies(localRoot, id, dir);
356
+ if (apply) {
357
+ await fsp.mkdir(dir, { recursive: true });
358
+ await writeSessionFile(target, texts);
359
+ const seconds = entry.mtime / 1000;
360
+ await fsp.utimes(target, seconds, seconds).catch(() => {});
361
+ pulledLocal.push({ id, file: target });
362
+ }
363
+ pulled += 1;
364
+ if (pulledIds.length < 300) pulledIds.push(id);
365
+ } catch (error) {
366
+ failed.push({ id, error: String(error?.message ?? error) });
367
+ }
368
+ }
369
+
370
+ // The regular guard ran before these sessions existed locally, so a shard that
371
+ // still says "blank" is repaired now, in the same run, before the config phase
372
+ // pushes it back to the share.
373
+ let blankRepaired = 0;
374
+ if (apply && pulledLocal.length > 0) {
375
+ try {
376
+ const fixed = await repairPulledSessions({ items: pulledLocal, cacheDir, apply });
377
+ blankRepaired = fixed.repaired;
378
+ } catch {
379
+ blankRepaired = 0;
380
+ }
381
+ }
382
+
383
+ // 5. Remember what this machine holds so the next run can spot deletions.
384
+ const keys = {};
385
+ for (const [id, entry] of (await scanSessions(localRoot))) keys[id] = new Date(entry.mtime).toISOString();
386
+ if (apply) await writeJson(machineFile, { version: 1, machine: machineId, updatedAt: now, keys });
387
+ if (apply) await writeLedger(stateDir, SESSION_LEDGER, ledger);
388
+ if (apply && (tombstoned > 0 || revived > 0) && legacyRead.value !== undefined) {
389
+ // The legacy document is superseded; keep only its shape so an older build
390
+ // does not treat the missing file as "nothing was ever deleted".
391
+ await writeJsonAtomic(legacyFile, { version: 1, deleted: {} });
392
+ }
393
+
394
+ return { pushed, pulled, skipped, revived, tombstoned, created, missing, failed, trashed: Object.keys(ledger.deleted).length, pushedIds, pulledIds, blankGuard, blankRepaired };
395
+ }