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

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/host/trash.js ADDED
@@ -0,0 +1,738 @@
1
+ /**
2
+ * Local session recycle bin for DSH增强.
3
+ *
4
+ * A deleted session keeps its full local log, so the only work a delete does is:
5
+ * detach the workspace accounting through the official registry write path,
6
+ * move the session directory into the recycle bin, and drop the projection cache
7
+ * shard. Nothing here edits `workspace.json` directly: the workspace domain is
8
+ * memory-authoritative, so every reference change goes through
9
+ * `workspaceRegistry` and its domain write chain.
10
+ *
11
+ * Layout under `<DSH_HOME>/dsh-enhanced`:
12
+ *
13
+ * settings.json
14
+ * trash/index.json derived summary, rebuildable
15
+ * trash/<workspaceId>/<sessionId>/meta.json
16
+ * trash/<workspaceId>/<sessionId>/log/...
17
+ */
18
+ import { promises as fsp } from 'node:fs';
19
+ import path from 'node:path';
20
+ import os from 'node:os';
21
+
22
+ export const SETTINGS_VERSION = 1;
23
+
24
+ export const DEFAULT_SETTINGS = Object.freeze({
25
+ version: SETTINGS_VERSION,
26
+ deleteEnabled: true,
27
+ trashEnabled: true,
28
+ searchEnabled: true,
29
+ moveEnabled: true,
30
+ autoLoadEnabled: true,
31
+ syncEnabled: false,
32
+ syncDir: '',
33
+ syncScript: '',
34
+ syncMachineId: '',
35
+ syncSkipAttachments: false,
36
+ syncIntervalMinutes: 0,
37
+ syncDailyAt: '',
38
+ syncOnIdle: true,
39
+ syncCooldownMinutes: 5,
40
+ syncMode: 'local',
41
+ webdavUrl: '',
42
+ webdavUser: '',
43
+ webdavPassword: '',
44
+ webdavRoot: '',
45
+ webdavProfiles: [],
46
+ webdavAutoCreate: true,
47
+ mirrorDir: path.join(os.homedir(), 'AppData', 'Local', 'dsh-enhanced', 'webdav-mirror'),
48
+ matchTitle: true,
49
+ matchBody: true,
50
+ matchTools: false,
51
+ retentionDays: 60,
52
+ });
53
+
54
+ const SETTINGS_LIMITS = {
55
+ retentionDays: { min: 0, max: 3650 },
56
+ syncIntervalMinutes: { min: 0, max: 1440 },
57
+ syncCooldownMinutes: { min: 1, max: 240 },
58
+ };
59
+
60
+ const UNGROUPED = '_ungrouped';
61
+
62
+ /** Create one stable coded error the route turns into a client message. */
63
+ export function failure(code, message, details) {
64
+ const error = new Error(message);
65
+ error.code = code;
66
+ if (details !== undefined) error.details = details;
67
+ return error;
68
+ }
69
+
70
+ /** Resolve the harness home directory the same way the Host was launched. */
71
+ export function resolveHome(config = {}) {
72
+ if (typeof config.root === 'string' && config.root.trim() !== '') return path.resolve(config.root);
73
+ const fromEnv = process.env.DSH_HOME;
74
+ if (typeof fromEnv === 'string' && fromEnv.trim() !== '') return path.resolve(fromEnv);
75
+ return path.join(os.homedir(), '.dsh');
76
+ }
77
+
78
+ /** Every path this plugin touches, derived once per call site. */
79
+ export function resolvePaths(config = {}) {
80
+ const home = resolveHome(config);
81
+ const base = path.join(home, 'dsh-enhanced');
82
+ return {
83
+ home,
84
+ base,
85
+ settingsFile: path.join(base, 'settings.json'),
86
+ trashDir: path.join(base, 'trash'),
87
+ indexFile: path.join(base, 'trash', 'index.json'),
88
+ sessionsRoot: typeof config.sessionsRoot === 'string' && config.sessionsRoot.trim() !== ''
89
+ ? path.resolve(config.sessionsRoot)
90
+ : path.join(home, 'sessions'),
91
+ projcacheRoot: typeof config.projcacheRoot === 'string' && config.projcacheRoot.trim() !== ''
92
+ ? path.resolve(config.projcacheRoot)
93
+ : path.join(home, 'storages', 'session_projcache'),
94
+ };
95
+ }
96
+
97
+ async function readJson(file) {
98
+ try {
99
+ const text = await fsp.readFile(file, 'utf8');
100
+ return JSON.parse(text);
101
+ } catch {
102
+ return undefined;
103
+ }
104
+ }
105
+
106
+ async function writeJsonAtomic(file, value) {
107
+ await fsp.mkdir(path.dirname(file), { recursive: true });
108
+ const temporary = `${file}.${process.pid}.${Date.now()}.tmp`;
109
+ await fsp.writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
110
+ await fsp.rename(temporary, file);
111
+ }
112
+
113
+ async function readDirSafe(dir) {
114
+ try {
115
+ return await fsp.readdir(dir, { withFileTypes: true });
116
+ } catch {
117
+ return [];
118
+ }
119
+ }
120
+
121
+ function clampInteger(value, fallback, limits) {
122
+ const number = typeof value === 'number' ? value : Number.parseInt(String(value ?? ''), 10);
123
+ if (!Number.isFinite(number)) return fallback;
124
+ const rounded = Math.round(number);
125
+ return Math.min(limits.max, Math.max(limits.min, rounded));
126
+ }
127
+
128
+ function normalizeBoolean(value, fallback) {
129
+ return typeof value === 'boolean' ? value : fallback;
130
+ }
131
+
132
+ /** Trimmed string with the fallback for a missing or empty value. */
133
+ function normalizeText(value, fallback) {
134
+ if (typeof value !== 'string') return fallback;
135
+ const trimmed = value.trim();
136
+ return trimmed === '' ? fallback : trimmed;
137
+ }
138
+
139
+ /** `HH:MM` in 24-hour form, or an empty string when unset or malformed. */
140
+ function normalizeClock(value) {
141
+ if (typeof value !== 'string') return '';
142
+ const match = /^(\d{1,2}):(\d{2})$/u.exec(value.trim());
143
+ if (match === null) return '';
144
+ const hours = Number(match[1]);
145
+ const minutes = Number(match[2]);
146
+ if (hours > 23 || minutes > 59) return '';
147
+ return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`;
148
+ }
149
+
150
+ /** Merge a stored or patched document over the defaults, field by field. */
151
+ export function normalizeSettings(raw) {
152
+ const source = raw !== null && typeof raw === 'object' ? raw : {};
153
+ return {
154
+ version: SETTINGS_VERSION,
155
+ deleteEnabled: normalizeBoolean(source.deleteEnabled, DEFAULT_SETTINGS.deleteEnabled),
156
+ trashEnabled: normalizeBoolean(source.trashEnabled, DEFAULT_SETTINGS.trashEnabled),
157
+ searchEnabled: normalizeBoolean(source.searchEnabled, DEFAULT_SETTINGS.searchEnabled),
158
+ moveEnabled: normalizeBoolean(source.moveEnabled, DEFAULT_SETTINGS.moveEnabled),
159
+ autoLoadEnabled: normalizeBoolean(source.autoLoadEnabled, DEFAULT_SETTINGS.autoLoadEnabled),
160
+ syncEnabled: normalizeBoolean(source.syncEnabled, DEFAULT_SETTINGS.syncEnabled),
161
+ syncSkipAttachments: normalizeBoolean(source.syncSkipAttachments, DEFAULT_SETTINGS.syncSkipAttachments),
162
+ syncDir: normalizeText(source.syncDir, DEFAULT_SETTINGS.syncDir),
163
+ syncScript: normalizeText(source.syncScript, DEFAULT_SETTINGS.syncScript),
164
+ syncMachineId: normalizeText(source.syncMachineId, DEFAULT_SETTINGS.syncMachineId),
165
+ syncOnIdle: normalizeBoolean(source.syncOnIdle, DEFAULT_SETTINGS.syncOnIdle),
166
+ syncDailyAt: normalizeClock(source.syncDailyAt), syncIntervalMinutes: clampInteger(source.syncIntervalMinutes, DEFAULT_SETTINGS.syncIntervalMinutes, SETTINGS_LIMITS.syncIntervalMinutes),
167
+ syncCooldownMinutes: clampInteger(source.syncCooldownMinutes, DEFAULT_SETTINGS.syncCooldownMinutes, SETTINGS_LIMITS.syncCooldownMinutes),
168
+ syncMode: source.syncMode === 'webdav' ? 'webdav' : 'local',
169
+ webdavUrl: normalizeText(source.webdavUrl, ''),
170
+ webdavUser: normalizeText(source.webdavUser, ''),
171
+ webdavPassword: typeof source.webdavPassword === 'string' ? source.webdavPassword : '',
172
+ webdavRoot: normalizeText(source.webdavRoot, ''),
173
+ webdavProfiles: normalizeWebdavProfiles(source.webdavProfiles),
174
+ webdavAutoCreate: normalizeBoolean(source.webdavAutoCreate, DEFAULT_SETTINGS.webdavAutoCreate),
175
+ mirrorDir: normalizeText(source.mirrorDir, DEFAULT_SETTINGS.mirrorDir),
176
+ matchTitle: normalizeBoolean(source.matchTitle, DEFAULT_SETTINGS.matchTitle),
177
+ matchBody: normalizeBoolean(source.matchBody, DEFAULT_SETTINGS.matchBody),
178
+ matchTools: normalizeBoolean(source.matchTools, DEFAULT_SETTINGS.matchTools),
179
+ retentionDays: clampInteger(source.retentionDays, DEFAULT_SETTINGS.retentionDays, SETTINGS_LIMITS.retentionDays),
180
+ };
181
+ }
182
+
183
+ /** Keep at most three saved WebDAV presets, each with the four connection fields. */
184
+ function normalizeWebdavProfiles(value) {
185
+ if (!Array.isArray(value)) return [];
186
+ const out = [];
187
+ for (const item of value) {
188
+ if (item === null || typeof item !== 'object') continue;
189
+ const url = normalizeText(item.url, '');
190
+ if (url === '') continue;
191
+ out.push({
192
+ id: normalizeText(item.id, '') || `p${String(out.length + 1)}`,
193
+ name: normalizeText(item.name, '') || 'WebDAV',
194
+ url,
195
+ user: normalizeText(item.user, ''),
196
+ password: typeof item.password === 'string' ? item.password : '',
197
+ root: normalizeText(item.root, ''),
198
+ custom: item.custom === true,
199
+ });
200
+ if (out.length === 3) break;
201
+ }
202
+ return out;
203
+ }
204
+
205
+ /** Read the persisted settings document, falling back to defaults. */
206
+ export async function readSettings(paths) {
207
+ const stored = await readJson(paths.settingsFile);
208
+ return normalizeSettings(stored);
209
+ }
210
+
211
+ /** Persist one settings patch and return the complete normalized document. */
212
+ export async function writeSettings(paths, patch) {
213
+ const current = await readSettings(paths);
214
+ const next = normalizeSettings({ ...current, ...(patch ?? {}) });
215
+ await writeJsonAtomic(paths.settingsFile, next);
216
+ return next;
217
+ }
218
+
219
+ /** Plain-data snapshot of one workspace entity, tolerating a missing registry. */
220
+ export function workspaceSnapshot(workspace) {
221
+ if (workspace === undefined || workspace === null) return undefined;
222
+ try {
223
+ return {
224
+ id: workspace.id,
225
+ title: typeof workspace.title === 'string' && workspace.title.trim() !== '' ? workspace.title : workspace.path,
226
+ path: workspace.path,
227
+ sessionIds: Array.isArray(workspace.sessionIds) ? workspace.sessionIds : [],
228
+ };
229
+ } catch {
230
+ return undefined;
231
+ }
232
+ }
233
+
234
+ /** The workspace currently accounting for one session, if any. */
235
+ export function findOwningWorkspace(registry, sessionId) {
236
+ if (registry === undefined) return undefined;
237
+ try {
238
+ for (const workspace of registry.list()) {
239
+ const snapshot = workspaceSnapshot(workspace);
240
+ if (snapshot !== undefined && snapshot.sessionIds.includes(sessionId)) return workspace;
241
+ }
242
+ } catch {
243
+ return undefined;
244
+ }
245
+ return undefined;
246
+ }
247
+
248
+ /** Find the on-disk directory of one stored session by scanning project dirs. */
249
+ export async function locateSessionDir(paths, sessionId) {
250
+ for (const entry of await readDirSafe(paths.sessionsRoot)) {
251
+ if (!entry.isDirectory()) continue;
252
+ const candidate = path.join(paths.sessionsRoot, entry.name, sessionId);
253
+ try {
254
+ const stat = await fsp.stat(candidate);
255
+ if (stat.isDirectory()) return candidate;
256
+ } catch {
257
+ // Not this project directory.
258
+ }
259
+ }
260
+ return undefined;
261
+ }
262
+
263
+ async function directorySize(dir) {
264
+ let total = 0;
265
+ for (const entry of await readDirSafe(dir)) {
266
+ const target = path.join(dir, entry.name);
267
+ try {
268
+ if (entry.isDirectory()) total += await directorySize(target);
269
+ else if (entry.isFile()) total += (await fsp.stat(target)).size;
270
+ } catch {
271
+ // A file that vanished mid-walk contributes nothing.
272
+ }
273
+ }
274
+ return total;
275
+ }
276
+
277
+ async function newestMtime(dir) {
278
+ let newest = 0;
279
+ for (const entry of await readDirSafe(dir)) {
280
+ const target = path.join(dir, entry.name);
281
+ try {
282
+ if (entry.isDirectory()) newest = Math.max(newest, await newestMtime(target));
283
+ else newest = Math.max(newest, (await fsp.stat(target)).mtimeMs);
284
+ } catch {
285
+ // Ignore vanished entries.
286
+ }
287
+ }
288
+ return newest;
289
+ }
290
+
291
+ /** Read the latest durable title, preferring the query service when present. */
292
+ async function readTitle(query, persistence, sessionId) {
293
+ try {
294
+ if (query !== undefined && typeof query.readTitle === 'function') {
295
+ const snapshot = await query.readTitle(sessionId);
296
+ if (snapshot !== undefined && typeof snapshot.title === 'string' && snapshot.title.trim() !== '') {
297
+ return snapshot.title.trim();
298
+ }
299
+ }
300
+ } catch {
301
+ // Fall through to a header-only best effort.
302
+ }
303
+ return '';
304
+ }
305
+
306
+ /** Group key and display title for one stored workspace id. */
307
+ function bucketOf(meta, registry) {
308
+ const workspaceId = typeof meta.workspaceId === 'string' && meta.workspaceId !== '' ? meta.workspaceId : UNGROUPED;
309
+ if (workspaceId === UNGROUPED) return { workspaceId: UNGROUPED, workspaceTitle: '' };
310
+ let title = typeof meta.workspaceTitle === 'string' ? meta.workspaceTitle : '';
311
+ try {
312
+ const workspace = registry?.get?.(workspaceId);
313
+ if (workspace !== undefined) title = workspace.title;
314
+ } catch {
315
+ // Keep the recorded title.
316
+ }
317
+ return { workspaceId, workspaceTitle: title };
318
+ }
319
+
320
+ function entryDirOf(paths, workspaceId, sessionId) {
321
+ return path.join(paths.trashDir, workspaceId, sessionId);
322
+ }
323
+
324
+ async function scanEntries(paths, registry) {
325
+ const buckets = await readDirSafe(paths.trashDir);
326
+ const entries = [];
327
+ for (const bucket of buckets) {
328
+ if (!bucket.isDirectory()) continue;
329
+ const bucketDir = path.join(paths.trashDir, bucket.name);
330
+ for (const item of await readDirSafe(bucketDir)) {
331
+ if (!item.isDirectory()) continue;
332
+ const entryDir = path.join(bucketDir, item.name);
333
+ const meta = await readJson(path.join(entryDir, 'meta.json'));
334
+ if (meta === undefined || typeof meta.sessionId !== 'string') {
335
+ await fsp.rm(entryDir, { recursive: true, force: true });
336
+ continue;
337
+ }
338
+ entries.push({ entryDir, meta });
339
+ }
340
+ }
341
+ return entries;
342
+ }
343
+
344
+ /** Whether a stored entry should be dropped because its workspace is gone. */
345
+ function workspaceLost(meta, registry) {
346
+ const workspaceId = typeof meta.workspaceId === 'string' ? meta.workspaceId : '';
347
+ if (workspaceId === '' || workspaceId === UNGROUPED) return false;
348
+ if (registry === undefined) return false;
349
+ try {
350
+ return registry.get(workspaceId) === undefined;
351
+ } catch {
352
+ return false;
353
+ }
354
+ }
355
+
356
+ function expired(meta, retentionDays) {
357
+ if (retentionDays <= 0) return false;
358
+ const deletedAt = typeof meta.deletedAt === 'string' ? Date.parse(meta.deletedAt) : Number.NaN;
359
+ if (!Number.isFinite(deletedAt)) return false;
360
+ return Date.now() - deletedAt > retentionDays * 24 * 60 * 60 * 1000;
361
+ }
362
+
363
+ /**
364
+ * Delete one session into the recycle bin, or remove it for good.
365
+ *
366
+ * The workspace reference is released before the files move, so the sidebar
367
+ * stops listing the session as soon as the registry write commits. Only a
368
+ * session with an active turn is refused: a resident but idle agent is not
369
+ * appending, so its log can be moved safely.
370
+ *
371
+ * @param deps - Host services and paths.
372
+ * @param sessionId - stored session to remove.
373
+ * @param options - `permanent` skips the recycle bin; `ignoreSettings` lets the
374
+ * session-move flow reuse this path regardless of the delete switch.
375
+ */
376
+ export async function deleteSession(deps, sessionId, options = {}) {
377
+ const { paths, registry, persistence, query, agents } = deps;
378
+ const settings = options.ignoreSettings === true ? { ...deps.settings, deleteEnabled: true } : deps.settings;
379
+ const permanent = options.permanent === true;
380
+ if (settings.deleteEnabled !== true) throw failure('delete-disabled', '会话删除已在设置中关闭。');
381
+ if (agents !== undefined && typeof agents.get === 'function') {
382
+ const agent = agents.get(sessionId);
383
+ if (agent !== undefined && agent?.status === 'running') {
384
+ throw failure('session-live', '该会话正在运行任务,等它结束或停止后再删除。');
385
+ }
386
+ }
387
+ const snapshot = await persistence.stat(sessionId);
388
+ if (snapshot === undefined) throw failure('session-missing', '会话不存在或已被删除。');
389
+ const sessionDir = await locateSessionDir(paths, sessionId);
390
+ if (sessionDir === undefined) throw failure('session-dir-missing', '找不到该会话的本机目录。');
391
+
392
+ const workspace = findOwningWorkspace(registry, sessionId);
393
+ const workspaceInfo = workspaceSnapshot(workspace);
394
+ const ordered = workspaceInfo?.sessionIds ?? [];
395
+ const at = ordered.indexOf(sessionId);
396
+ const position = at < 0
397
+ ? { prev: undefined, next: undefined }
398
+ : { prev: ordered[at - 1], next: ordered[at + 1] };
399
+
400
+ const title = await readTitle(query, persistence, sessionId);
401
+ const workspaceId = workspaceInfo?.id ?? UNGROUPED;
402
+
403
+ // 1. Release the durable workspace accounting last: the workspace write is what
404
+ // makes the sidebar re-query the session list, so the files and the cached
405
+ // projection must already be gone by then.
406
+ const releaseWorkspace = async () => {
407
+ try {
408
+ await registry.unpinSession(sessionId);
409
+ await registry.unarchiveSession(sessionId);
410
+ if (workspace !== undefined) await workspace.detachSession(sessionId);
411
+ } catch (error) {
412
+ return `会话已删除,但从工作区移除失败:${error.message}`;
413
+ }
414
+ return undefined;
415
+ };
416
+
417
+ const shard = path.join(paths.projcacheRoot, 'sessions', `${sessionId}.json`);
418
+
419
+ if (permanent) {
420
+ const lastUpdatedAt = await newestMtime(sessionDir);
421
+ const sizeBytes = await directorySize(sessionDir);
422
+ try {
423
+ await fsp.rm(sessionDir, { recursive: true, force: true });
424
+ } catch (error) {
425
+ throw failure('session-remove-failed', `无法删除会话目录:${error.message}`);
426
+ }
427
+ try {
428
+ await fsp.rm(shard, { force: true });
429
+ } catch {
430
+ // A locked shard stays behind and is ignored as stale.
431
+ }
432
+ const warning = await releaseWorkspace();
433
+ // A permanent removal (the move flow) has to be announced to the next sync as
434
+ // well: without the journal entry the engine relies on its own snapshot, and a
435
+ // machine without one would pull the cloud copy back as a second session.
436
+ await appendDeleteJournal(deps, {
437
+ kind: 'sessions',
438
+ key: sessionId,
439
+ value: {
440
+ at: new Date().toISOString(),
441
+ workspace: workspaceId,
442
+ mtime: lastUpdatedAt > 0 ? lastUpdatedAt : Date.now(),
443
+ size: sizeBytes,
444
+ by: 'local',
445
+ reason: options.reason ?? 'deleted',
446
+ },
447
+ });
448
+ return { sessionId, title: title !== '' ? title : '未命名会话', workspaceId, permanent: true, warning, reason: options.reason ?? 'deleted' };
449
+ }
450
+
451
+ const lastUpdatedAt = await newestMtime(sessionDir);
452
+ const sizeBytes = await directorySize(sessionDir);
453
+ const originalPath = path.relative(paths.sessionsRoot, sessionDir);
454
+ if (originalPath.startsWith('..')) throw failure('session-path', '会话目录不在预期的存储根目录下,已拒绝删除。');
455
+
456
+ const deletedAt = new Date().toISOString();
457
+ const entryDir = entryDirOf(paths, workspaceId, sessionId);
458
+ const stagingDir = `${entryDir}.staging-${process.pid}`;
459
+
460
+ // 2. Move the log into the recycle bin (same volume: one rename, no copy).
461
+ await fsp.mkdir(path.dirname(stagingDir), { recursive: true });
462
+ await fsp.rm(stagingDir, { recursive: true, force: true });
463
+ await fsp.mkdir(stagingDir, { recursive: true });
464
+ try {
465
+ await fsp.rename(sessionDir, path.join(stagingDir, 'log'));
466
+ } catch (error) {
467
+ await fsp.rm(stagingDir, { recursive: true, force: true });
468
+ throw failure('session-move-failed', `无法移动会话目录:${error.message}`);
469
+ }
470
+
471
+ // 3. Drop the projection cache shard; it is derived from the log.
472
+ try {
473
+ await fsp.rm(shard, { force: true });
474
+ } catch {
475
+ // A locked shard stays behind and is ignored as stale.
476
+ }
477
+
478
+ const meta = {
479
+ version: 1,
480
+ sessionId,
481
+ title: title !== '' ? title : '未命名会话',
482
+ cwd: typeof snapshot.header.cwd === 'string' ? snapshot.header.cwd : undefined,
483
+ workspaceId,
484
+ workspaceTitle: workspaceInfo?.title,
485
+ originalPath,
486
+ position,
487
+ deletedAt,
488
+ lastUpdatedAt: lastUpdatedAt > 0 ? new Date(lastUpdatedAt).toISOString() : undefined,
489
+ sizeBytes,
490
+ appVersion: process.env.DSH_CLIENT_VERSION,
491
+ };
492
+ await writeJsonAtomic(path.join(stagingDir, 'meta.json'), meta);
493
+ await fsp.rm(entryDir, { recursive: true, force: true });
494
+ await fsp.rename(stagingDir, entryDir);
495
+
496
+ // Record the deletion so the next sync announces it to the cloud instead of
497
+ // guessing from "the file is gone".
498
+ await appendDeleteJournal(deps, {
499
+ kind: 'sessions',
500
+ key: sessionId,
501
+ value: {
502
+ at: deletedAt,
503
+ workspace: workspaceId,
504
+ mtime: lastUpdatedAt > 0 ? lastUpdatedAt : Date.now(),
505
+ size: sizeBytes,
506
+ by: 'local',
507
+ },
508
+ });
509
+
510
+ const warning = await releaseWorkspace();
511
+ return { sessionId, title: meta.title, workspaceId, deletedAt, sizeBytes, warning };
512
+ }
513
+
514
+ /** Append one offline deletion to the journal merged at the next sync. */
515
+ async function appendDeleteJournal(deps, entry) {
516
+ const file = path.join(deps.paths.base, 'delete-journal.json');
517
+ let doc;
518
+ try {
519
+ doc = JSON.parse(await fsp.readFile(file, 'utf8'));
520
+ } catch {
521
+ doc = { version: 1, sessions: {}, workspaces: {} };
522
+ }
523
+ const bucket = doc[entry.kind] ?? {};
524
+ bucket[entry.key] = entry.value;
525
+ doc[entry.kind] = bucket;
526
+ doc.version = 1;
527
+ await writeJsonAtomic(file, doc);
528
+ }
529
+
530
+ /** Drop entries whose retention window passed or whose workspace is gone. */
531
+ export async function purgeExpired(deps) {
532
+ const { paths, registry, settings } = deps;
533
+ if (settings.trashEnabled !== true) return 0;
534
+ const entries = await scanEntries(paths, registry);
535
+ let removed = 0;
536
+ for (const entry of entries) {
537
+ if (workspaceLost(entry.meta, registry) || expired(entry.meta, settings.retentionDays)) {
538
+ await fsp.rm(entry.entryDir, { recursive: true, force: true }).catch(() => {});
539
+ removed += 1;
540
+ }
541
+ }
542
+ return removed;
543
+ }
544
+
545
+ /** List refresh also enforces workspace cascade and retention. */
546
+ export async function listTrash(deps, scope = {}) {
547
+ const { paths, registry, settings } = deps;
548
+ const entries = await scanEntries(paths, registry);
549
+ const kept = [];
550
+ let changed = false;
551
+ for (const entry of entries) {
552
+ if (workspaceLost(entry.meta, registry) || expired(entry.meta, settings.retentionDays)) {
553
+ await fsp.rm(entry.entryDir, { recursive: true, force: true });
554
+ changed = true;
555
+ continue;
556
+ }
557
+ kept.push(entry);
558
+ }
559
+
560
+ let order = new Map();
561
+ try {
562
+ order = new Map((registry?.list?.() ?? []).map((workspace, index) => [workspace.id, index]));
563
+ } catch {
564
+ order = new Map();
565
+ }
566
+
567
+ const groups = new Map();
568
+ for (const entry of kept) {
569
+ const bucket = bucketOf(entry.meta, registry);
570
+ const key = bucket.workspaceId;
571
+ let group = groups.get(key);
572
+ if (group === undefined) {
573
+ group = { workspaceId: key, workspaceTitle: bucket.workspaceTitle, items: [] };
574
+ groups.set(key, group);
575
+ }
576
+ group.items.push({
577
+ sessionId: entry.meta.sessionId,
578
+ title: entry.meta.title,
579
+ deletedAt: entry.meta.deletedAt,
580
+ lastUpdatedAt: entry.meta.lastUpdatedAt,
581
+ sizeBytes: entry.meta.sizeBytes,
582
+ cwd: entry.meta.cwd,
583
+ position: entry.meta.position,
584
+ workspaceTitle: bucket.workspaceTitle,
585
+ });
586
+ }
587
+
588
+ const list = [...groups.values()];
589
+ for (const group of list) group.items.sort((a, b) => String(b.deletedAt).localeCompare(String(a.deletedAt)));
590
+ list.sort((a, b) => (order.get(a.workspaceId) ?? 9999) - (order.get(b.workspaceId) ?? 9999));
591
+
592
+ // A Session-menu entry scopes the dialog to that Session's workspace.
593
+ let scoped = list;
594
+ if (typeof scope.workspaceId === 'string' && scope.workspaceId !== '') {
595
+ scoped = list.filter((group) => group.workspaceId === scope.workspaceId);
596
+ } else if (typeof scope.sessionId === 'string' && scope.sessionId !== '') {
597
+ let target;
598
+ try {
599
+ target = findOwningWorkspace(registry, scope.sessionId)?.id ?? UNGROUPED;
600
+ } catch {
601
+ target = UNGROUPED;
602
+ }
603
+ scoped = list.filter((group) => group.workspaceId === target);
604
+ }
605
+
606
+ const count = scoped.reduce((total, group) => total + group.items.length, 0);
607
+ const size = scoped.reduce((total, group) => total + group.items.reduce((sum, item) => sum + (Number(item.sizeBytes) || 0), 0), 0);
608
+ if (changed) await writeJsonAtomic(paths.indexFile, { version: 1, updatedAt: new Date().toISOString(), count });
609
+ return { groups: scoped, count, size };
610
+ }
611
+
612
+ /** Drop every recycle-bin record that belonged to one deleted workspace. */
613
+ export async function purgeWorkspace(paths, workspaceId) {
614
+ if (typeof workspaceId !== 'string' || workspaceId === '' || workspaceId === UNGROUPED) return { removed: false };
615
+ const bucket = path.join(paths.trashDir, workspaceId);
616
+ try {
617
+ await fsp.rm(bucket, { recursive: true, force: true });
618
+ return { removed: true };
619
+ } catch {
620
+ return { removed: false };
621
+ }
622
+ }
623
+
624
+ /** Locate one entry across all buckets by session id. */
625
+ async function findEntry(paths, registry, sessionId) {
626
+ for (const entry of await scanEntries(paths, registry)) {
627
+ if (entry.meta.sessionId === sessionId) return entry;
628
+ }
629
+ return undefined;
630
+ }
631
+
632
+ /** Restamp every file under one restored session directory with the current time. */
633
+ async function touchTree(dir) {
634
+ const now = new Date();
635
+ for (const entry of await readDirSafe(dir)) {
636
+ const target = path.join(dir, entry.name);
637
+ try {
638
+ if (entry.isDirectory()) await touchTree(target);
639
+ await fsp.utimes(target, now, now);
640
+ } catch {
641
+ // A file that vanished or is locked keeps its old timestamp.
642
+ }
643
+ }
644
+ try {
645
+ await fsp.utimes(dir, now, now);
646
+ } catch {
647
+ // The directory timestamp is not used by the engine.
648
+ }
649
+ }
650
+
651
+ /** Move one entry's log back and re-account it in its original workspace. */export async function restoreSession(deps, sessionId) {
652
+ const { paths, registry, settings } = deps;
653
+ if (settings.trashEnabled !== true) throw failure('trash-disabled', '会话找回已在设置中关闭。');
654
+ const entry = await findEntry(paths, registry, sessionId);
655
+ if (entry === undefined) throw failure('trash-missing', '回收站中找不到该会话。');
656
+ const meta = entry.meta;
657
+ const originalPath = typeof meta.originalPath === 'string' ? meta.originalPath : undefined;
658
+ if (originalPath === undefined || originalPath.startsWith('..') || path.isAbsolute(originalPath)) {
659
+ throw failure('trash-corrupt', '删除记录的原始路径无效,无法恢复。');
660
+ }
661
+ const target = path.join(paths.sessionsRoot, originalPath);
662
+ await fsp.mkdir(path.dirname(target), { recursive: true });
663
+ await fsp.rename(path.join(entry.entryDir, 'log'), target);
664
+ // The sync engine revives a session instead of deleting it when its log is
665
+ // newer than the deletion tombstone; a restored log inherits the original
666
+ // mtime, so stamp it now to make the restore visible across machines.
667
+ await touchTree(target);
668
+
669
+ let attached = false;
670
+ let warning;
671
+ let workspace;
672
+ try {
673
+ workspace = registry?.get?.(meta.workspaceId);
674
+ } catch {
675
+ workspace = undefined;
676
+ }
677
+ if (workspace === undefined && typeof meta.cwd === 'string' && meta.cwd !== '') {
678
+ // Workspace ids can differ between machines after a workspace.json merge;
679
+ // fall back to the recorded directory.
680
+ try {
681
+ workspace = registry?.resolveByPath?.(meta.cwd);
682
+ } catch {
683
+ workspace = undefined;
684
+ }
685
+ }
686
+ if (workspace === undefined) {
687
+ warning = meta.workspaceId === UNGROUPED ? undefined : '原工作区已不存在,会话已恢复为未分组状态。';
688
+ } else {
689
+ try {
690
+ await workspace.attachSession(sessionId);
691
+ attached = true;
692
+ } catch (error) {
693
+ warning = `会话已恢复,但无法挂回原工作区:${error.message}`;
694
+ }
695
+ }
696
+ if (attached && typeof meta.position?.next === 'string') {
697
+ try {
698
+ await workspace.insertSessionBefore(sessionId, meta.position.next);
699
+ } catch {
700
+ // Order restoration is best effort; membership already succeeded.
701
+ }
702
+ }
703
+ await fsp.rm(entry.entryDir, { recursive: true, force: true });
704
+ return { sessionId, workspaceId: meta.workspaceId, attached, warning };
705
+ }
706
+
707
+ /** Remove one entry's files for good. */
708
+ export async function purgeSession(deps, sessionId) {
709
+ const { paths, registry } = deps;
710
+ const entry = await findEntry(paths, registry, sessionId);
711
+ if (entry === undefined) throw failure('trash-missing', '回收站中找不到该会话。');
712
+ await fsp.rm(entry.entryDir, { recursive: true, force: true });
713
+ return { sessionId };
714
+ }
715
+
716
+ /** Remove every entry, or every entry of one workspace. */
717
+ export async function clearTrash(deps, scope = {}) {
718
+ const { paths, registry } = deps;
719
+ const workspaceId = typeof scope.workspaceId === 'string' ? scope.workspaceId : '';
720
+ if (workspaceId !== '') {
721
+ if (!/^[A-Za-z0-9._-]+$/u.test(workspaceId)) throw failure('bad-workspace-id', '工作区标识无效。');
722
+ const bucket = path.join(paths.trashDir, workspaceId);
723
+ let removed = 0;
724
+ for (const item of await readDirSafe(bucket)) {
725
+ if (!item.isDirectory()) continue;
726
+ await fsp.rm(path.join(bucket, item.name), { recursive: true, force: true });
727
+ removed += 1;
728
+ }
729
+ return { removed };
730
+ }
731
+ const entries = await scanEntries(paths, registry);
732
+ let removed = 0;
733
+ for (const entry of entries) {
734
+ await fsp.rm(entry.entryDir, { recursive: true, force: true });
735
+ removed += 1;
736
+ }
737
+ return { removed };
738
+ }