@xsok/dsh-enhanced 0.0.0-stage → 0.2.2-3
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 +149 -2
- package/client.js +2866 -0
- package/cordis.patch.yml +4 -0
- package/host/engine/archive.js +134 -0
- package/host/engine/atomic.js +27 -0
- package/host/engine/attachments.js +102 -0
- package/host/engine/config.js +214 -0
- package/host/engine/index.js +323 -0
- package/host/engine/ledger.js +108 -0
- package/host/engine/paths.js +81 -0
- package/host/engine/pluginlist.js +81 -0
- package/host/engine/projcache.js +165 -0
- package/host/engine/prune.js +187 -0
- package/host/engine/scan.js +177 -0
- package/host/engine/session.js +138 -0
- package/host/engine/sessions.js +346 -0
- package/host/engine/workspace.js +223 -0
- package/host/engine/zstd.js +91 -0
- package/host/envcheck.js +288 -0
- package/host/mirror.js +474 -0
- package/host/move.js +196 -0
- package/host/overwrite.js +305 -0
- package/host/restart.js +158 -0
- package/host/schedule.js +257 -0
- package/host/search.js +182 -0
- package/host/sync.js +593 -0
- package/host/trash.js +738 -0
- package/host/trashsync.js +204 -0
- package/host/webdav.js +429 -0
- package/icon.svg +1 -0
- package/index.js +312 -0
- package/locale/en.json +68 -0
- package/locale/zh.json +68 -0
- package/package.json +70 -4
|
@@ -0,0 +1,346 @@
|
|
|
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 { lastContentSeq, readSessionFile, rewriteCwd, writeSessionFile } from './session.js';
|
|
13
|
+
import {
|
|
14
|
+
SESSION_LEDGER,
|
|
15
|
+
mergeJournal,
|
|
16
|
+
readJson as readLedgerJson,
|
|
17
|
+
readLedger,
|
|
18
|
+
writeJsonAtomic,
|
|
19
|
+
writeLedger,
|
|
20
|
+
} from './ledger.js';
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Distinguish "missing" from "corrupt": a damaged tombstone table used to read
|
|
24
|
+
* as empty, which resurrects every deleted session.
|
|
25
|
+
*/
|
|
26
|
+
async function readJsonStrict(file) {
|
|
27
|
+
try {
|
|
28
|
+
const text = await fsp.readFile(file, 'utf8');
|
|
29
|
+
return { value: JSON.parse(text), corrupt: false };
|
|
30
|
+
} catch (error) {
|
|
31
|
+
return { value: undefined, corrupt: error?.code !== 'ENOENT' };
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async function readJson(file, fallback) {
|
|
36
|
+
try {
|
|
37
|
+
return JSON.parse(await fsp.readFile(file, 'utf8'));
|
|
38
|
+
} catch {
|
|
39
|
+
return fallback;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async function writeJson(file, value) {
|
|
44
|
+
await fsp.mkdir(path.dirname(file), { recursive: true });
|
|
45
|
+
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
46
|
+
await fsp.writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
|
|
47
|
+
await fsp.rename(temporary, file);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Delete copies of one session that sit under a different project key. */
|
|
51
|
+
async function dropOtherCopies(localRoot, id, keepDir) {
|
|
52
|
+
let projects;
|
|
53
|
+
try {
|
|
54
|
+
projects = await fsp.readdir(localRoot, { withFileTypes: true });
|
|
55
|
+
} catch {
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
for (const project of projects) {
|
|
59
|
+
if (!project.isDirectory()) continue;
|
|
60
|
+
const candidate = path.join(localRoot, project.name, id);
|
|
61
|
+
if (candidate === keepDir) continue;
|
|
62
|
+
try {
|
|
63
|
+
await fsp.stat(candidate);
|
|
64
|
+
} catch {
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
await fsp.rm(candidate, { recursive: true, force: true }).catch(() => {});
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Move a shared session copy into the shared recycle bin instead of deleting it.
|
|
73
|
+
* The other machine can then restore the newest content, not just the fact that
|
|
74
|
+
* the session once existed.
|
|
75
|
+
*/
|
|
76
|
+
async function sessionTitle(sharedRoot, id) {
|
|
77
|
+
try {
|
|
78
|
+
const file = path.join(path.dirname(sharedRoot), 'config', 'storages', 'session_projcache', 'sessions', `${id}.json`);
|
|
79
|
+
const doc = JSON.parse(await fsp.readFile(file, 'utf8'));
|
|
80
|
+
const value = doc?.record?.rows?.title?.val;
|
|
81
|
+
return typeof value === 'string' && value.trim() !== '' ? value.trim() : '';
|
|
82
|
+
} catch {
|
|
83
|
+
return '';
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async function moveToTrash(entry, trashRoot, ledgerEntry) {
|
|
88
|
+
const bucketName = typeof ledgerEntry?.workspace === 'string' && ledgerEntry.workspace !== ''
|
|
89
|
+
? ledgerEntry.workspace
|
|
90
|
+
: '_ungrouped';
|
|
91
|
+
const target = path.join(trashRoot, bucketName, entry.id);
|
|
92
|
+
await fsp.rm(target, { recursive: true, force: true });
|
|
93
|
+
await fsp.mkdir(path.dirname(target), { recursive: true });
|
|
94
|
+
await fsp.cp(entry.dir, path.join(target, 'log'), { recursive: true, force: true });
|
|
95
|
+
await fsp.rm(entry.dir, { recursive: true, force: true }).catch(() => {});
|
|
96
|
+
const title = await sessionTitle(path.dirname(trashRoot), entry.id);
|
|
97
|
+
await writeJsonAtomic(path.join(target, 'meta.json'), {
|
|
98
|
+
version: 1,
|
|
99
|
+
sessionId: entry.id,
|
|
100
|
+
title: title === '' ? entry.id : title,
|
|
101
|
+
workspaceId: bucketName,
|
|
102
|
+
deletedAt: ledgerEntry?.at ?? new Date().toISOString(),
|
|
103
|
+
sizeBytes: ledgerEntry?.size ?? 0,
|
|
104
|
+
mtime: ledgerEntry?.mtime ?? entry.mtime,
|
|
105
|
+
source: 'sync',
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** True when `candidate` should replace `current` (generation first, then mtime). */
|
|
110
|
+
export function wins(candidate, current) {
|
|
111
|
+
if (current === undefined) return true;
|
|
112
|
+
if (candidate.generation !== current.generation) return candidate.generation > current.generation;
|
|
113
|
+
// File systems and utimes round sub-millisecond stamps; treat that as a tie.
|
|
114
|
+
return candidate.mtime > current.mtime + 1;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Copy one session into a target root under the project key of its cwd. */
|
|
118
|
+
async function copySessionTo(source, targetRoot) {
|
|
119
|
+
const parsed = await readSessionFile(source.file);
|
|
120
|
+
const cwd = parsed.header.cwd;
|
|
121
|
+
const key = projectKey(cwd);
|
|
122
|
+
const dir = path.join(targetRoot, key, source.id);
|
|
123
|
+
await fsp.mkdir(dir, { recursive: true });
|
|
124
|
+
const target = path.join(dir, path.basename(source.file));
|
|
125
|
+
await writeSessionFile(target, parsed.texts);
|
|
126
|
+
// Preserve the source timestamp: equal mtimes are what stop push/pull ping-pong.
|
|
127
|
+
const seconds = source.mtime / 1000;
|
|
128
|
+
await fsp.utimes(target, seconds, seconds).catch(() => {});
|
|
129
|
+
return target;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Run the session half of a sync.
|
|
134
|
+
* @returns counters plus the ids that were skipped or failed.
|
|
135
|
+
*/
|
|
136
|
+
export async function syncSessions(deps) {
|
|
137
|
+
const {
|
|
138
|
+
localRoot,
|
|
139
|
+
sharedRoot,
|
|
140
|
+
stateDir,
|
|
141
|
+
machineId,
|
|
142
|
+
resolveCwd = async (cwd) => ({ path: cwd, action: 'existed' }),
|
|
143
|
+
skipIds = new Set(),
|
|
144
|
+
apply = true,
|
|
145
|
+
journalFile = null,
|
|
146
|
+
sharedTrashRoot = path.join(path.dirname(sharedRoot), 'trash'),
|
|
147
|
+
} = deps;
|
|
148
|
+
|
|
149
|
+
const local = await scanSessions(localRoot);
|
|
150
|
+
const shared = await scanSessions(sharedRoot);
|
|
151
|
+
const legacyFile = path.join(stateDir, 'deleted-sessions.json');
|
|
152
|
+
const machineFile = path.join(stateDir, `machine-${machineId}.json`);
|
|
153
|
+
|
|
154
|
+
const ledger = await readLedger(stateDir, SESSION_LEDGER);
|
|
155
|
+
if (journalFile !== null && apply) await mergeJournal(stateDir, journalFile, ledger, 'sessions');
|
|
156
|
+
|
|
157
|
+
// Old tombstone documents only carry an id and a time; fold them in once so a
|
|
158
|
+
// deleted session cannot come back merely because the format changed.
|
|
159
|
+
const legacyRead = await readJsonStrict(legacyFile);
|
|
160
|
+
if (legacyRead.corrupt) {
|
|
161
|
+
throw Object.assign(
|
|
162
|
+
new Error('deleted-sessions.json 已损坏,为避免已删除的会话复活,本轮同步已中止'),
|
|
163
|
+
{ code: 'tombstone-corrupt' },
|
|
164
|
+
);
|
|
165
|
+
}
|
|
166
|
+
for (const [id, iso] of Object.entries(legacyRead.value?.deleted ?? {})) {
|
|
167
|
+
if (typeof id !== 'string') continue;
|
|
168
|
+
if (ledger.deleted[id] !== undefined) continue;
|
|
169
|
+
ledger.deleted[id] = { at: String(iso), legacy: true };
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const previous = await readJson(machineFile, { version: 1, keys: {} });
|
|
173
|
+
const previousIds = new Set(Object.keys(previous.keys ?? {}));
|
|
174
|
+
|
|
175
|
+
let pushed = 0;
|
|
176
|
+
let pulled = 0;
|
|
177
|
+
let skipped = 0;
|
|
178
|
+
let revived = 0;
|
|
179
|
+
let tombstoned = 0;
|
|
180
|
+
const failed = [];
|
|
181
|
+
const pushedIds = [];
|
|
182
|
+
const pulledIds = [];
|
|
183
|
+
|
|
184
|
+
// 1. Local deletions become ledger entries, with the file facts of the copy
|
|
185
|
+
// this machine still knows about (mtime/size) so the recycle bin can pick
|
|
186
|
+
// the newest version later.
|
|
187
|
+
const now = new Date().toISOString();
|
|
188
|
+
for (const id of previousIds) {
|
|
189
|
+
if (local.has(id) || ledger.deleted[id] !== undefined) continue;
|
|
190
|
+
const sharedCopy = shared.get(id);
|
|
191
|
+
ledger.deleted[id] = {
|
|
192
|
+
at: now,
|
|
193
|
+
mtime: sharedCopy?.mtime ?? 0,
|
|
194
|
+
size: sharedCopy?.size ?? 0,
|
|
195
|
+
by: machineId,
|
|
196
|
+
};
|
|
197
|
+
tombstoned += 1;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// A run where the local root was unreadable looks exactly like "every session
|
|
201
|
+
// was deleted". Refuse only when the directory cannot be read, or when the whole
|
|
202
|
+
// home looks wiped — deleting the last session must still propagate.
|
|
203
|
+
let readable = true;
|
|
204
|
+
try {
|
|
205
|
+
await fsp.readdir(localRoot);
|
|
206
|
+
} catch {
|
|
207
|
+
readable = false;
|
|
208
|
+
}
|
|
209
|
+
let homeEvidence = false;
|
|
210
|
+
try {
|
|
211
|
+
await fsp.stat(path.join(path.dirname(localRoot), 'storages', 'workspace.json'));
|
|
212
|
+
homeEvidence = true;
|
|
213
|
+
} catch {
|
|
214
|
+
homeEvidence = false;
|
|
215
|
+
}
|
|
216
|
+
if (apply && !readable) {
|
|
217
|
+
return {
|
|
218
|
+
pushed: 0, pulled: 0, skipped: 0, revived: 0, tombstoned: 0,
|
|
219
|
+
created: 0, missing: 0, failed: [],
|
|
220
|
+
aborted: '本机会话目录不可读,已中止并保留删除记录',
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
if (apply && previousIds.size > 0 && local.size === 0 && !homeEvidence) {
|
|
224
|
+
return {
|
|
225
|
+
pushed: 0, pulled: 0, skipped: 0, revived: 0, tombstoned: 0,
|
|
226
|
+
created: 0, missing: 0, failed: [],
|
|
227
|
+
aborted: '本机看起来已被清空(缺少 workspace.json),已中止本轮以防误删',
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// 2. A local copy newer than its deletion record means the user restored it.
|
|
232
|
+
for (const [id, record] of [...Object.entries(ledger.deleted)]) {
|
|
233
|
+
const entry = local.get(id);
|
|
234
|
+
if (entry === undefined) continue;
|
|
235
|
+
const deletedAt = Date.parse(record.at ?? '');
|
|
236
|
+
if (!Number.isFinite(deletedAt) || entry.mtime > deletedAt + 1) {
|
|
237
|
+
delete ledger.deleted[id];
|
|
238
|
+
revived += 1;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// 3. Apply the remaining deletions. Shared copies move into the shared recycle
|
|
243
|
+
// bin so the other machine can still restore them; local copies go away.
|
|
244
|
+
for (const [id, record] of Object.entries(ledger.deleted)) {
|
|
245
|
+
const sharedEntry = shared.get(id);
|
|
246
|
+
if (sharedEntry !== undefined) {
|
|
247
|
+
if (apply) await moveToTrash(sharedEntry, sharedTrashRoot, record).catch(() => {});
|
|
248
|
+
shared.delete(id);
|
|
249
|
+
}
|
|
250
|
+
const localEntry = local.get(id);
|
|
251
|
+
if (localEntry !== undefined) {
|
|
252
|
+
if (apply) await fsp.rm(localEntry.dir, { recursive: true, force: true }).catch(() => {});
|
|
253
|
+
local.delete(id);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// 3. Push local sessions the share does not have (or has in an older state).
|
|
258
|
+
for (const [id, entry] of local) {
|
|
259
|
+
if (ledger.deleted[id] !== undefined) continue;
|
|
260
|
+
if (skipIds.has(id)) {
|
|
261
|
+
skipped += 1;
|
|
262
|
+
continue;
|
|
263
|
+
}
|
|
264
|
+
const sharedEntry = shared.get(id);
|
|
265
|
+
// Append-only logs: the one holding more events is the newer one. Upload and
|
|
266
|
+
// download timestamps are meaningless here because each transfer rewrites them.
|
|
267
|
+
if (sharedEntry !== undefined) {
|
|
268
|
+
const localSeq = await lastContentSeq(entry.file);
|
|
269
|
+
const sharedSeq = await lastContentSeq(sharedEntry.file);
|
|
270
|
+
if (sharedSeq >= 0 && localSeq >= 0) {
|
|
271
|
+
if (sharedSeq >= localSeq) {
|
|
272
|
+
skipped += 1;
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
} else if (!wins(entry, sharedEntry)) {
|
|
276
|
+
skipped += 1;
|
|
277
|
+
continue;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
try {
|
|
281
|
+
if (apply) await copySessionTo(entry, sharedRoot);
|
|
282
|
+
pushed += 1;
|
|
283
|
+
if (pushedIds.length < 300) pushedIds.push(id);
|
|
284
|
+
} catch (error) {
|
|
285
|
+
failed.push({ id, error: String(error?.message ?? error) });
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
const refreshedShare = await scanSessions(sharedRoot);
|
|
290
|
+
|
|
291
|
+
// 4. Pull shared sessions this machine lacks or holds in an older state.
|
|
292
|
+
let created = 0;
|
|
293
|
+
let missing = 0;
|
|
294
|
+
for (const [id, entry] of refreshedShare) {
|
|
295
|
+
if (ledger.deleted[id] !== undefined) continue;
|
|
296
|
+
if (skipIds.has(id)) continue;
|
|
297
|
+
const localEntry = local.get(id);
|
|
298
|
+
if (localEntry !== undefined) {
|
|
299
|
+
const sharedSeq = await lastContentSeq(entry.file);
|
|
300
|
+
const localSeq = await lastContentSeq(localEntry.file);
|
|
301
|
+
if (sharedSeq >= 0 && localSeq >= 0) {
|
|
302
|
+
// Same event count means the only difference is this machine's cwd, which
|
|
303
|
+
// is not worth a transfer.
|
|
304
|
+
if (sharedSeq <= localSeq) continue;
|
|
305
|
+
} else if (!wins(entry, localEntry)) {
|
|
306
|
+
continue;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
try {
|
|
310
|
+
const parsed = await readSessionFile(entry.file);
|
|
311
|
+
const resolved = await resolveCwd(parsed.header.cwd);
|
|
312
|
+
if (resolved.action === 'created') created += 1;
|
|
313
|
+
if (resolved.action === 'missing') {
|
|
314
|
+
missing += 1;
|
|
315
|
+
continue;
|
|
316
|
+
}
|
|
317
|
+
const texts = rewriteCwd(parsed, resolved.path).texts;
|
|
318
|
+
const dir = path.join(localRoot, projectKey(resolved.path), id);
|
|
319
|
+
const target = path.join(dir, path.basename(entry.file));
|
|
320
|
+
if (apply) await dropOtherCopies(localRoot, id, dir);
|
|
321
|
+
if (apply) {
|
|
322
|
+
await fsp.mkdir(dir, { recursive: true });
|
|
323
|
+
await writeSessionFile(target, texts);
|
|
324
|
+
const seconds = entry.mtime / 1000;
|
|
325
|
+
await fsp.utimes(target, seconds, seconds).catch(() => {});
|
|
326
|
+
}
|
|
327
|
+
pulled += 1;
|
|
328
|
+
if (pulledIds.length < 300) pulledIds.push(id);
|
|
329
|
+
} catch (error) {
|
|
330
|
+
failed.push({ id, error: String(error?.message ?? error) });
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// 5. Remember what this machine holds so the next run can spot deletions.
|
|
335
|
+
const keys = {};
|
|
336
|
+
for (const [id, entry] of (await scanSessions(localRoot))) keys[id] = new Date(entry.mtime).toISOString();
|
|
337
|
+
if (apply) await writeJson(machineFile, { version: 1, machine: machineId, updatedAt: now, keys });
|
|
338
|
+
if (apply) await writeLedger(stateDir, SESSION_LEDGER, ledger);
|
|
339
|
+
if (apply && (tombstoned > 0 || revived > 0) && legacyRead.value !== undefined) {
|
|
340
|
+
// The legacy document is superseded; keep only its shape so an older build
|
|
341
|
+
// does not treat the missing file as "nothing was ever deleted".
|
|
342
|
+
await writeJsonAtomic(legacyFile, { version: 1, deleted: {} });
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
return { pushed, pulled, skipped, revived, tombstoned, created, missing, failed, trashed: Object.keys(ledger.deleted).length, pushedIds, pulledIds };
|
|
346
|
+
}
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `storages/workspace.json` merge for the pure-JS engine.
|
|
3
|
+
*
|
|
4
|
+
* Rules, matching `Merge-WorkspaceJson` in the PowerShell engine:
|
|
5
|
+
* - entries join by (localized) path, not by uuid;
|
|
6
|
+
* - the newer `updatedAt` is the base record, older unknowns fill the gaps;
|
|
7
|
+
* - `sessionIds` is a union, `createdAt` the earliest, tombstoned ids dropped;
|
|
8
|
+
* - the share gets every group, this machine only groups whose folder exists;
|
|
9
|
+
* - `global` keeps the union of archived/pinned, unknown fields preserved.
|
|
10
|
+
*/
|
|
11
|
+
import { promises as fsp } from 'node:fs';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
import { WORKSPACE_LEDGER, readJson as readLedgerJson, readLedger, writeJsonAtomic, writeLedger } from './ledger.js';
|
|
14
|
+
|
|
15
|
+
async function readJson(file) {
|
|
16
|
+
try {
|
|
17
|
+
const text = await fsp.readFile(file, 'utf8');
|
|
18
|
+
return { doc: JSON.parse(text), valid: true };
|
|
19
|
+
} catch (error) {
|
|
20
|
+
return { doc: null, valid: error?.code === 'ENOENT' };
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function entriesOf(doc, source) {
|
|
25
|
+
const table = doc?.tables?.workspaces;
|
|
26
|
+
if (table === null || typeof table !== 'object') return [];
|
|
27
|
+
return Object.entries(table).map(([uuid, value]) => ({
|
|
28
|
+
uuid,
|
|
29
|
+
path: typeof value?.path === 'string' ? value.path : '',
|
|
30
|
+
title: typeof value?.title === 'string' ? value.title : '',
|
|
31
|
+
sessionIds: Array.isArray(value?.sessionIds) ? value.sessionIds.filter(Boolean) : [],
|
|
32
|
+
createdAt: typeof value?.createdAt === 'string' ? value.createdAt : '',
|
|
33
|
+
updatedAt: typeof value?.updatedAt === 'string' ? value.updatedAt : '',
|
|
34
|
+
source,
|
|
35
|
+
raw: value,
|
|
36
|
+
}));
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function timeOf(value) {
|
|
40
|
+
const parsed = Date.parse(value ?? '');
|
|
41
|
+
return Number.isFinite(parsed) ? parsed : 0;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function unionInto(target, values) {
|
|
45
|
+
for (const value of values) {
|
|
46
|
+
if (value !== undefined && value !== null && !target.includes(value)) target.push(value);
|
|
47
|
+
}
|
|
48
|
+
return target;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Merge both documents.
|
|
53
|
+
* @param options - `resolvePath` localizes a remote path, `isDirectory` decides
|
|
54
|
+
* whether the group is registered locally, `tombstones` is a Set of session ids.
|
|
55
|
+
*/
|
|
56
|
+
export async function mergeWorkspaceDocuments(localDoc, sharedDoc, options = {}) {
|
|
57
|
+
const {
|
|
58
|
+
resolvePath = (value) => value,
|
|
59
|
+
isDirectory = () => false,
|
|
60
|
+
tombstones = new Set(),
|
|
61
|
+
stateDir = null,
|
|
62
|
+
machineId = null,
|
|
63
|
+
apply = true,
|
|
64
|
+
} = options;
|
|
65
|
+
|
|
66
|
+
// Workspace deletions used to be silent: the other machine's document still
|
|
67
|
+
// listed the path, so the union added it back. A ledger plus a per-machine
|
|
68
|
+
// snapshot fixes that, and a workspace that reappears counts as restored.
|
|
69
|
+
const localEntries = entriesOf(localDoc, 'local');
|
|
70
|
+
let workspaceLedger = { version: 1, deleted: {} };
|
|
71
|
+
let snapshot = { paths: {} };
|
|
72
|
+
if (stateDir !== null && machineId !== null) {
|
|
73
|
+
workspaceLedger = await readLedger(stateDir, WORKSPACE_LEDGER);
|
|
74
|
+
snapshot = (await readLedgerJson(path.join(stateDir, `workspace-${machineId}.json`), undefined)) ?? { paths: {} };
|
|
75
|
+
const localByPath = new Map(localEntries.map((entry) => [entry.path, entry]));
|
|
76
|
+
const now = new Date().toISOString();
|
|
77
|
+
for (const [entryPath, info] of Object.entries(snapshot.paths ?? {})) {
|
|
78
|
+
if (entryPath === '') continue;
|
|
79
|
+
if (localByPath.has(entryPath)) continue;
|
|
80
|
+
const uuid = typeof info?.uuid === 'string' && info.uuid !== '' ? info.uuid : entryPath;
|
|
81
|
+
if (workspaceLedger.deleted[uuid] !== undefined) continue;
|
|
82
|
+
workspaceLedger.deleted[uuid] = { at: now, path: entryPath, title: info?.title ?? '', source: 'local' };
|
|
83
|
+
}
|
|
84
|
+
const localByUuid = new Map(localEntries.map((entry) => [entry.uuid, entry]));
|
|
85
|
+
for (const [uuid, record] of Object.entries(workspaceLedger.deleted)) {
|
|
86
|
+
const entry = localByUuid.get(uuid) ?? localByPath.get(record.path ?? '');
|
|
87
|
+
if (entry === undefined) continue;
|
|
88
|
+
if (timeOf(entry.updatedAt) > timeOf(record.at) + 1) delete workspaceLedger.deleted[uuid];
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const deletedPaths = new Set(Object.values(workspaceLedger.deleted).map((record) => record.path).filter(Boolean));
|
|
93
|
+
const deletedUuids = new Set(Object.keys(workspaceLedger.deleted));
|
|
94
|
+
|
|
95
|
+
const merged = new Map();
|
|
96
|
+
for (const entry of [...localEntries, ...entriesOf(sharedDoc, 'shared')]) {
|
|
97
|
+
if (deletedUuids.has(entry.uuid) || (entry.path !== '' && deletedPaths.has(entry.path))) continue;
|
|
98
|
+
// The resolver is allowed to be async (the JS engine localizes remote
|
|
99
|
+
// paths through `fs.realpath`). Awaiting it is mandatory: a Promise stored
|
|
100
|
+
// in `path` serializes to `{}`, which the host's workspace schema rejects
|
|
101
|
+
// and then refuses to activate the whole registry.
|
|
102
|
+
const key = await resolvePath(entry.path);
|
|
103
|
+
if (typeof key !== 'string' || key === '') continue;
|
|
104
|
+
const current = merged.get(key);
|
|
105
|
+
if (current === undefined) {
|
|
106
|
+
merged.set(key, { ...entry, path: key, others: [] });
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
const newer = timeOf(entry.updatedAt) > timeOf(current.updatedAt);
|
|
110
|
+
if (newer) {
|
|
111
|
+
if (current.raw !== undefined) current.others.push(current.raw);
|
|
112
|
+
current.uuid = entry.uuid;
|
|
113
|
+
current.title = entry.title;
|
|
114
|
+
current.updatedAt = entry.updatedAt;
|
|
115
|
+
current.raw = entry.raw;
|
|
116
|
+
} else if (entry.raw !== undefined) {
|
|
117
|
+
current.others.push(entry.raw);
|
|
118
|
+
}
|
|
119
|
+
unionInto(current.sessionIds, entry.sessionIds);
|
|
120
|
+
if (timeOf(entry.createdAt) < timeOf(current.createdAt)) current.createdAt = entry.createdAt;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const shared = {};
|
|
124
|
+
const local = {};
|
|
125
|
+
const missing = [];
|
|
126
|
+
for (const entry of merged.values()) {
|
|
127
|
+
const ids = entry.sessionIds.filter((id) => !tombstones.has(id));
|
|
128
|
+
const record = { ...(entry.raw ?? {}) };
|
|
129
|
+
for (const other of entry.others) {
|
|
130
|
+
for (const [field, value] of Object.entries(other ?? {})) {
|
|
131
|
+
if (!(field in record)) record[field] = value;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
record.path = entry.path;
|
|
135
|
+
// Never let a non-string path reach the document: the host validates every
|
|
136
|
+
// record with `path: z.string()` at startup, and a single bad value kills
|
|
137
|
+
// the whole workspace registry service.
|
|
138
|
+
if (typeof record.path !== 'string' || record.path === '') continue;
|
|
139
|
+
record.title = entry.title;
|
|
140
|
+
record.sessionIds = ids;
|
|
141
|
+
if (entry.createdAt !== '') record.createdAt = entry.createdAt;
|
|
142
|
+
if (entry.updatedAt !== '') record.updatedAt = entry.updatedAt;
|
|
143
|
+
shared[entry.uuid] = record;
|
|
144
|
+
if (await isDirectory(entry.path)) local[entry.uuid] = record;
|
|
145
|
+
else missing.push({ title: entry.title, path: entry.path });
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const archived = [];
|
|
149
|
+
const pinned = [];
|
|
150
|
+
let initialized = false;
|
|
151
|
+
const extraGlobal = {};
|
|
152
|
+
for (const doc of [localDoc, sharedDoc]) {
|
|
153
|
+
const global = doc?.global;
|
|
154
|
+
if (global === null || typeof global !== 'object') continue;
|
|
155
|
+
if (global.initialized === true) initialized = true;
|
|
156
|
+
unionInto(archived, (Array.isArray(global.archivedSessionIds) ? global.archivedSessionIds : []).filter((id) => id && !tombstones.has(id)));
|
|
157
|
+
unionInto(pinned, (Array.isArray(global.pinnedSessionIds) ? global.pinnedSessionIds : []).filter((id) => id && !tombstones.has(id)));
|
|
158
|
+
for (const [field, value] of Object.entries(global)) {
|
|
159
|
+
if (['initialized', 'workspaceIds', 'archivedSessionIds', 'pinnedSessionIds'].includes(field)) continue;
|
|
160
|
+
if (!(field in extraGlobal)) extraGlobal[field] = value;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// The document schema version must never go backwards: a newer app would
|
|
165
|
+
// otherwise re-run its migration against data it already migrated.
|
|
166
|
+
let unitName = 'workspace';
|
|
167
|
+
let unitVersion = 2;
|
|
168
|
+
for (const doc of [localDoc, sharedDoc]) {
|
|
169
|
+
if (doc?.unit === null || typeof doc?.unit !== 'object') continue;
|
|
170
|
+
if (typeof doc.unit.name === 'string' && doc.unit.name !== '') unitName = doc.unit.name;
|
|
171
|
+
if (Number(doc.unit.version) > unitVersion) unitVersion = Number(doc.unit.version);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const preferredOrder = (() => {
|
|
175
|
+
const fromLocal = Array.isArray(localDoc?.global?.workspaceIds) ? localDoc.global.workspaceIds : [];
|
|
176
|
+
const fromShared = Array.isArray(sharedDoc?.global?.workspaceIds) ? sharedDoc.global.workspaceIds : [];
|
|
177
|
+
return fromLocal.length > 0 ? fromLocal : fromShared;
|
|
178
|
+
})();
|
|
179
|
+
const orderOf = (workspaces) => {
|
|
180
|
+
const present = Object.keys(workspaces);
|
|
181
|
+
const ordered = preferredOrder.filter((id) => present.includes(id));
|
|
182
|
+
for (const id of present) if (!ordered.includes(id)) ordered.push(id);
|
|
183
|
+
return ordered;
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
const build = (workspaces) => {
|
|
187
|
+
const doc = JSON.parse(JSON.stringify(localDoc ?? sharedDoc ?? {}));
|
|
188
|
+
doc.unit = { name: unitName, version: unitVersion };
|
|
189
|
+
doc.tables = doc.tables ?? {};
|
|
190
|
+
doc.tables.workspaces = workspaces;
|
|
191
|
+
doc.global = { ...(doc.global ?? {}), ...extraGlobal, initialized, workspaceIds: orderOf(workspaces), archivedSessionIds: archived, pinnedSessionIds: pinned };
|
|
192
|
+
return doc;
|
|
193
|
+
};
|
|
194
|
+
|
|
195
|
+
if (apply && stateDir !== null && machineId !== null) {
|
|
196
|
+
const pathsNow = {};
|
|
197
|
+
for (const entry of entriesOf(localDoc, 'local')) {
|
|
198
|
+
if (entry.path !== '') pathsNow[entry.path] = { uuid: entry.uuid, title: entry.title };
|
|
199
|
+
}
|
|
200
|
+
// Re-read the local document after the merge so a restored group is recorded.
|
|
201
|
+
for (const value of Object.values(local)) {
|
|
202
|
+
if (typeof value?.path === 'string' && value.path !== '') {
|
|
203
|
+
pathsNow[value.path] = { uuid: pathsNow[value.path]?.uuid ?? '', title: value.title ?? '' };
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
await writeJsonAtomic(path.join(stateDir, `workspace-${machineId}.json`), { version: 1, machine: machineId, paths: pathsNow, updatedAt: new Date().toISOString() });
|
|
207
|
+
await writeLedger(stateDir, WORKSPACE_LEDGER, workspaceLedger);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
return { shared: build(shared), local: build(local), missing, unitVersion, deleted: deletedUuids.size };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Read both files, merge, and return the two documents plus the missing folders. */
|
|
214
|
+
export async function mergeWorkspaceFiles(deps) {
|
|
215
|
+
const { localFile, sharedFile, ...rest } = deps;
|
|
216
|
+
const localRead = await readJson(localFile);
|
|
217
|
+
const sharedRead = await readJson(sharedFile);
|
|
218
|
+
if (!localRead.valid || !sharedRead.valid) {
|
|
219
|
+
return { skipped: 'workspace.json 无效或正在写入,本次不合并', missing: [] };
|
|
220
|
+
}
|
|
221
|
+
if (localRead.doc === null && sharedRead.doc === null) return { skipped: '两侧都没有 workspace.json', missing: [] };
|
|
222
|
+
return await mergeWorkspaceDocuments(localRead.doc, sharedRead.doc, rest);
|
|
223
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Multi-frame zstd container used by DSH session logs.
|
|
3
|
+
*
|
|
4
|
+
* Node's zstd decoder stops at the first frame, so the frame boundaries have to
|
|
5
|
+
* be walked by hand. The algorithm matches `tools/dsh-zstd-helper.js` and DSH's
|
|
6
|
+
* own `scanZstdFrames`: a truncated tail (an append interrupted by a crash) is
|
|
7
|
+
* dropped instead of failing the whole file.
|
|
8
|
+
*/
|
|
9
|
+
import zlib from 'node:zlib';
|
|
10
|
+
|
|
11
|
+
const ZSTD_MAGIC = 4247762216; // 0xFD2FB528 little-endian
|
|
12
|
+
|
|
13
|
+
/** Frame byte ranges of one buffer; empty when the file holds no complete frame. */
|
|
14
|
+
export function scanFrames(buf) {
|
|
15
|
+
const frames = [];
|
|
16
|
+
let offset = 0;
|
|
17
|
+
while (offset < buf.length) {
|
|
18
|
+
const start = offset;
|
|
19
|
+
if (buf.length - offset < 4 || buf.readUInt32LE(offset) !== ZSTD_MAGIC) break;
|
|
20
|
+
offset += 4;
|
|
21
|
+
if (offset === buf.length) break;
|
|
22
|
+
const descriptor = buf.readUInt8(offset);
|
|
23
|
+
offset += 1;
|
|
24
|
+
if ((descriptor & 24) !== 0) break;
|
|
25
|
+
const contentSizeFlag = descriptor >>> 6;
|
|
26
|
+
const singleSegment = (descriptor & 32) !== 0;
|
|
27
|
+
const checksum = (descriptor & 4) !== 0;
|
|
28
|
+
const dictionaryFlag = descriptor & 3;
|
|
29
|
+
const dictionaryBytes = dictionaryFlag === 3 ? 4 : dictionaryFlag;
|
|
30
|
+
const contentSizeBytes = contentSizeFlag === 0 ? (singleSegment ? 1 : 0) : 1 << contentSizeFlag;
|
|
31
|
+
const remainingHeaderBytes = (singleSegment ? 0 : 1) + dictionaryBytes + contentSizeBytes;
|
|
32
|
+
if (buf.length - offset < remainingHeaderBytes) break;
|
|
33
|
+
offset += remainingHeaderBytes;
|
|
34
|
+
for (;;) {
|
|
35
|
+
if (buf.length - offset < 3) return frames;
|
|
36
|
+
const blockHeader = buf.readUIntLE(offset, 3);
|
|
37
|
+
offset += 3;
|
|
38
|
+
const lastBlock = (blockHeader & 1) !== 0;
|
|
39
|
+
const blockType = (blockHeader >>> 1) & 3;
|
|
40
|
+
const blockSize = blockHeader >>> 3;
|
|
41
|
+
if (blockType === 3) return frames;
|
|
42
|
+
const payloadBytes = blockType === 1 ? 1 : blockSize;
|
|
43
|
+
if (buf.length - offset < payloadBytes) return frames;
|
|
44
|
+
offset += payloadBytes;
|
|
45
|
+
if (lastBlock) break;
|
|
46
|
+
}
|
|
47
|
+
if (checksum) {
|
|
48
|
+
if (buf.length - offset < 4) return frames;
|
|
49
|
+
offset += 4;
|
|
50
|
+
}
|
|
51
|
+
frames.push({ start, end: offset });
|
|
52
|
+
}
|
|
53
|
+
return frames;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Concatenated plaintext of every complete frame. */
|
|
57
|
+
export function decodeFrames(buf, frames = scanFrames(buf)) {
|
|
58
|
+
const parts = [];
|
|
59
|
+
for (const frame of frames) {
|
|
60
|
+
parts.push(zlib.zstdDecompressSync(buf.subarray(frame.start, frame.end)));
|
|
61
|
+
}
|
|
62
|
+
return Buffer.concat(parts);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Whole-file decode; a plain .jsonl file is returned as-is. */
|
|
66
|
+
export function decodeBuffer(buf, isZstd = true) {
|
|
67
|
+
if (!isZstd) return buf;
|
|
68
|
+
const frames = scanFrames(buf);
|
|
69
|
+
if (frames.length === 0) throw Object.assign(new Error('文件中没有完整的 zstd 帧(可能是残缺写入)'), { code: 'zstd-empty' });
|
|
70
|
+
return decodeFrames(buf, frames);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Compress one frame's plaintext as a single zstd frame. */
|
|
74
|
+
export function encodeFrame(text) {
|
|
75
|
+
return zlib.zstdCompressSync(Buffer.from(text, 'utf8'));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Compress one line as its own frame, matching the append semantics. */
|
|
79
|
+
export function encodeLine(line) {
|
|
80
|
+
return zlib.zstdCompressSync(Buffer.from(`${line}\n`, 'utf8'));
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Compress a list of lines into one multi-frame container. */
|
|
84
|
+
export function encodeLines(lines) {
|
|
85
|
+
return Buffer.concat(lines.map((line) => encodeLine(line)));
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Split decoded text into non-empty lines. */
|
|
89
|
+
export function splitLines(text) {
|
|
90
|
+
return text.split('\n').filter((line) => line !== '');
|
|
91
|
+
}
|