@kangyishuai/dsh-session-delete 0.1.0 → 0.3.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.
- package/README.md +9 -7
- package/README.zh-CN.md +9 -7
- package/lib/agent-tool.js +173 -0
- package/lib/capability.js +2 -0
- package/lib/client.js +345 -1
- package/lib/index.js +3 -2
- package/lib/operations.js +375 -7
- package/lib/receipts.js +65 -0
- package/lib/service.js +149 -1
- package/lib/trash.js +5 -1
- package/locale/en.json +17 -1
- package/locale/zh.json +17 -1
- package/package.json +1 -1
package/lib/operations.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
// @ts-check
|
|
2
2
|
// 操作编排层:不依赖 typert,可在单元测试里用假 ctx 跑(真实宿主交互全部经 capability.js 探测)。
|
|
3
|
+
import { readdir, readFile, stat } from "node:fs/promises";
|
|
3
4
|
import { createRequire } from "node:module";
|
|
5
|
+
import { join } from "node:path";
|
|
4
6
|
import { setTimeout as delayMs } from "node:timers/promises";
|
|
5
7
|
import { createAudit } from "./audit.js";
|
|
6
8
|
import { describeCapabilities, probeCapabilities } from "./capability.js";
|
|
@@ -8,6 +10,7 @@ import { beginOperation, finishOperation, listPending } from "./journal.js";
|
|
|
8
10
|
import { directorySize, locateSession } from "./locate.js";
|
|
9
11
|
import { auditPath, requireSessionId, sessionsRoot, trashRoot } from "./paths.js";
|
|
10
12
|
import { buildPlan, planExecutable, summarizePlan } from "./plan.js";
|
|
13
|
+
import { listReceipts, writeReceipt } from "./receipts.js";
|
|
11
14
|
import { buildRefs } from "./refs.js";
|
|
12
15
|
import { listEntries, moveIntoTrash, purgeEntry, readEntry, restoreEntry } from "./trash.js";
|
|
13
16
|
|
|
@@ -102,11 +105,49 @@ export function createOperations({ ctx, dataRoot, logger }) {
|
|
|
102
105
|
}
|
|
103
106
|
}
|
|
104
107
|
const activity = normalizeActivity(rawActivity);
|
|
108
|
+
|
|
109
|
+
// 子会话 = live 活动里的 subagent + 持久层 header.parentSession 血缘(任意深度)。
|
|
110
|
+
// 后者需要 persistence.list():对当前格式是 O(1) 级别,对历史格式可能按会话数扫描,
|
|
111
|
+
// 因此只在真的删除/预览时调用,不参与面板等批量路径。
|
|
112
|
+
/** @type {Map<string, { id: string, title: string | null }>} */
|
|
113
|
+
const childMap = new Map();
|
|
105
114
|
const subagents = activity.find((group) => group.kind === "subagent");
|
|
106
|
-
|
|
107
|
-
id,
|
|
108
|
-
|
|
109
|
-
|
|
115
|
+
(subagents?.ids ?? []).forEach((id, index) => {
|
|
116
|
+
childMap.set(id, { id, title: subagents?.labels[index] ?? null });
|
|
117
|
+
});
|
|
118
|
+
if (caps.checks["persistence.list"] && caps.services.persistence?.list) {
|
|
119
|
+
try {
|
|
120
|
+
const all = (await caps.services.persistence.list()) ?? [];
|
|
121
|
+
/** @type {Map<string, { id: string, title: string | null }[]>} */
|
|
122
|
+
const byParent = new Map();
|
|
123
|
+
for (const entry of all) {
|
|
124
|
+
const id = String(entry?.id ?? entry?.header?.id ?? "");
|
|
125
|
+
const parent = entry?.header?.parentSession;
|
|
126
|
+
if (!id || typeof parent !== "string" || parent.length === 0) continue;
|
|
127
|
+
const list = byParent.get(parent) ?? [];
|
|
128
|
+
list.push({
|
|
129
|
+
id,
|
|
130
|
+
title: typeof entry?.header?.title === "string" ? entry.header.title : null,
|
|
131
|
+
});
|
|
132
|
+
byParent.set(parent, list);
|
|
133
|
+
}
|
|
134
|
+
const queue = [sessionId];
|
|
135
|
+
const seen = new Set([sessionId]);
|
|
136
|
+
while (queue.length > 0) {
|
|
137
|
+
const current = /** @type {string} */ (queue.shift());
|
|
138
|
+
for (const child of byParent.get(current) ?? []) {
|
|
139
|
+
if (seen.has(child.id)) continue;
|
|
140
|
+
seen.add(child.id);
|
|
141
|
+
childMap.set(child.id, child);
|
|
142
|
+
queue.push(child.id);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
} catch (error) {
|
|
146
|
+
notes.push("lineage unavailable: " + messageOf(error));
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
childMap.delete(sessionId);
|
|
150
|
+
const children = [...childMap.values()];
|
|
110
151
|
|
|
111
152
|
const located = await locateSession({
|
|
112
153
|
dataRoot,
|
|
@@ -196,7 +237,7 @@ export function createOperations({ ctx, dataRoot, logger }) {
|
|
|
196
237
|
|
|
197
238
|
/**
|
|
198
239
|
* @param {string} sessionIdRaw
|
|
199
|
-
* @param {{ digest?: string, title?: string | null, operator?: string }} request
|
|
240
|
+
* @param {{ digest?: string, title?: string | null, operator?: string, cascade?: boolean, child?: boolean }} request
|
|
200
241
|
*/
|
|
201
242
|
async function trash(sessionIdRaw, request = {}) {
|
|
202
243
|
const loaded = await makePlan(sessionIdRaw);
|
|
@@ -225,6 +266,20 @@ export function createOperations({ ctx, dataRoot, logger }) {
|
|
|
225
266
|
});
|
|
226
267
|
}
|
|
227
268
|
if (!location) throw failure("session-delete/location-unknown", "没有可移动的会话目录");
|
|
269
|
+
|
|
270
|
+
/** @type {{ id: string, ok: boolean, entryId?: string, error?: string }[]} */
|
|
271
|
+
const cascaded = [];
|
|
272
|
+
if (request.cascade === true && request.child !== true) {
|
|
273
|
+
for (const child of plan.children) {
|
|
274
|
+
try {
|
|
275
|
+
const result = await trash(child.id, { operator: request.operator, child: true });
|
|
276
|
+
cascaded.push({ id: child.id, ok: true, entryId: result.entryId });
|
|
277
|
+
} catch (error) {
|
|
278
|
+
cascaded.push({ id: child.id, ok: false, error: messageOf(error) });
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
228
283
|
if (inFlight.has(plan.sessionId)) {
|
|
229
284
|
throw failure("session-delete/busy", "这个会话正在被另一个删除操作处理。");
|
|
230
285
|
}
|
|
@@ -322,9 +377,25 @@ export function createOperations({ ctx, dataRoot, logger }) {
|
|
|
322
377
|
operator: request.operator ?? "ui",
|
|
323
378
|
detail: summarizePlan(plan),
|
|
324
379
|
});
|
|
380
|
+
const receiptId = await writeReceipt(dataRoot, {
|
|
381
|
+
action: "trash",
|
|
382
|
+
at: new Date().toISOString(),
|
|
383
|
+
sessionId: plan.sessionId,
|
|
384
|
+
entryId,
|
|
385
|
+
title: plan.title ?? (typeof request.title === "string" ? request.title : null),
|
|
386
|
+
sizeBytes: plan.sizeBytes,
|
|
387
|
+
digest: plan.digest,
|
|
388
|
+
live: plan.live,
|
|
389
|
+
children: plan.children,
|
|
390
|
+
cascaded,
|
|
391
|
+
removed,
|
|
392
|
+
checks,
|
|
393
|
+
});
|
|
325
394
|
return {
|
|
326
395
|
ok: true,
|
|
327
396
|
entryId,
|
|
397
|
+
receiptId,
|
|
398
|
+
cascaded,
|
|
328
399
|
sessionId: plan.sessionId,
|
|
329
400
|
digest: plan.digest,
|
|
330
401
|
title: plan.title ?? (typeof request.title === "string" ? request.title : null),
|
|
@@ -414,7 +485,15 @@ export function createOperations({ ctx, dataRoot, logger }) {
|
|
|
414
485
|
entryId,
|
|
415
486
|
operator: request.operator ?? "ui",
|
|
416
487
|
});
|
|
417
|
-
|
|
488
|
+
const receiptId = await writeReceipt(dataRoot, {
|
|
489
|
+
action: "restore",
|
|
490
|
+
at: new Date().toISOString(),
|
|
491
|
+
sessionId: meta.sessionId,
|
|
492
|
+
entryId,
|
|
493
|
+
title: meta.title,
|
|
494
|
+
restoredTo: restored.restoredTo,
|
|
495
|
+
});
|
|
496
|
+
return { ok: true, sessionId: meta.sessionId, restoredTo: restored.restoredTo, receiptId };
|
|
418
497
|
} catch (error) {
|
|
419
498
|
await finishOperation({ dataRoot, id: record.id, state: "failed", detail: messageOf(error) });
|
|
420
499
|
await audit.append({
|
|
@@ -450,7 +529,15 @@ export function createOperations({ ctx, dataRoot, logger }) {
|
|
|
450
529
|
operator: request.operator ?? "ui",
|
|
451
530
|
detail: "释放约 " + result.bytes + " 字节",
|
|
452
531
|
});
|
|
453
|
-
|
|
532
|
+
const receiptId = await writeReceipt(dataRoot, {
|
|
533
|
+
action: "purge",
|
|
534
|
+
at: new Date().toISOString(),
|
|
535
|
+
sessionId: meta.sessionId,
|
|
536
|
+
entryId,
|
|
537
|
+
title: meta.title,
|
|
538
|
+
bytes: result.bytes,
|
|
539
|
+
});
|
|
540
|
+
return { ok: true, bytes: result.bytes, sessionId: meta.sessionId, receiptId };
|
|
454
541
|
} catch (error) {
|
|
455
542
|
await finishOperation({ dataRoot, id: record.id, state: "failed", detail: messageOf(error) });
|
|
456
543
|
await audit.append({
|
|
@@ -506,6 +593,279 @@ export function createOperations({ ctx, dataRoot, logger }) {
|
|
|
506
593
|
return checks;
|
|
507
594
|
}
|
|
508
595
|
|
|
596
|
+
/**
|
|
597
|
+
* 读取 workspace 存储快照(只读)。这是文件级兜底:
|
|
598
|
+
* 归档/置顶集合没有公开的读接口,只能读 storages/workspace.json。
|
|
599
|
+
* @returns {Promise<{ ok: boolean, reason?: string, archivedIds: string[], pinnedIds: string[],
|
|
600
|
+
* workspaces: { id: string, sessionIds: string[] }[] }>}
|
|
601
|
+
*/
|
|
602
|
+
async function readWorkspaceState() {
|
|
603
|
+
const file = join(dataRoot, "storages", "workspace.json");
|
|
604
|
+
let parsed;
|
|
605
|
+
try {
|
|
606
|
+
parsed = JSON.parse(await readFile(file, "utf8"));
|
|
607
|
+
} catch (error) {
|
|
608
|
+
return {
|
|
609
|
+
ok: false,
|
|
610
|
+
reason: "无法读取 " + file + ":" + messageOf(error),
|
|
611
|
+
archivedIds: [],
|
|
612
|
+
pinnedIds: [],
|
|
613
|
+
workspaces: [],
|
|
614
|
+
};
|
|
615
|
+
}
|
|
616
|
+
const global = parsed?.global ?? {};
|
|
617
|
+
const tables = parsed?.tables ?? {};
|
|
618
|
+
const workspaces = Object.entries(tables.workspaces ?? {}).map(([id, value]) => ({
|
|
619
|
+
id,
|
|
620
|
+
sessionIds: Array.isArray(value?.sessionIds) ? value.sessionIds.map(String) : [],
|
|
621
|
+
}));
|
|
622
|
+
return {
|
|
623
|
+
ok: true,
|
|
624
|
+
archivedIds: Array.isArray(global.archivedSessionIds)
|
|
625
|
+
? global.archivedSessionIds.map(String)
|
|
626
|
+
: [],
|
|
627
|
+
pinnedIds: Array.isArray(global.pinnedSessionIds) ? global.pinnedSessionIds.map(String) : [],
|
|
628
|
+
workspaces,
|
|
629
|
+
};
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
/**
|
|
633
|
+
* 全库体检:找出指向已不存在会话的登记条目。只读,不修改任何东西。
|
|
634
|
+
*/
|
|
635
|
+
async function scanHealth() {
|
|
636
|
+
if (!caps.checks["persistence.list"]) {
|
|
637
|
+
return {
|
|
638
|
+
ok: false,
|
|
639
|
+
reason: "当前宿主没有 sessionPersistence.list,无法枚举已存会话。",
|
|
640
|
+
findings: [],
|
|
641
|
+
inventory: null,
|
|
642
|
+
};
|
|
643
|
+
}
|
|
644
|
+
const persisted = (await caps.services.persistence.list()) ?? [];
|
|
645
|
+
const storedIds = new Set(
|
|
646
|
+
persisted
|
|
647
|
+
.map((/** @type {any} */ entry) => String(entry?.id ?? entry?.header?.id ?? ""))
|
|
648
|
+
.filter(Boolean),
|
|
649
|
+
);
|
|
650
|
+
const liveIds = new Set();
|
|
651
|
+
try {
|
|
652
|
+
for (const id of caps.services.sessions?.store?.keys?.() ?? []) liveIds.add(String(id));
|
|
653
|
+
} catch {
|
|
654
|
+
/* store 不可枚举时忽略 */
|
|
655
|
+
}
|
|
656
|
+
const known = new Set([...storedIds, ...liveIds]);
|
|
657
|
+
|
|
658
|
+
const state = await readWorkspaceState();
|
|
659
|
+
/** @type {{ id: string, label: string, severity: "warn" | "info", items: any[] }[]} */
|
|
660
|
+
const findings = [];
|
|
661
|
+
/** @type {{ archived: string[], pinned: string[], workspace: { workspaceId: string, sessionId: string }[] }} */
|
|
662
|
+
const cleanable = { archived: [], pinned: [], workspace: [] };
|
|
663
|
+
|
|
664
|
+
if (state.ok) {
|
|
665
|
+
const archivedGhosts = state.archivedIds.filter((id) => !known.has(id));
|
|
666
|
+
const pinnedGhosts = state.pinnedIds.filter((id) => !known.has(id));
|
|
667
|
+
const workspaceGhosts = [];
|
|
668
|
+
for (const workspace of state.workspaces) {
|
|
669
|
+
for (const sessionId of workspace.sessionIds) {
|
|
670
|
+
if (!known.has(sessionId)) workspaceGhosts.push({ workspaceId: workspace.id, sessionId });
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
if (archivedGhosts.length > 0) {
|
|
674
|
+
findings.push({
|
|
675
|
+
id: "archived-ghost",
|
|
676
|
+
label: "归档集合里的失效条目",
|
|
677
|
+
severity: "warn",
|
|
678
|
+
items: archivedGhosts,
|
|
679
|
+
});
|
|
680
|
+
cleanable.archived = archivedGhosts;
|
|
681
|
+
}
|
|
682
|
+
if (pinnedGhosts.length > 0) {
|
|
683
|
+
findings.push({
|
|
684
|
+
id: "pinned-ghost",
|
|
685
|
+
label: "置顶集合里的失效条目",
|
|
686
|
+
severity: "warn",
|
|
687
|
+
items: pinnedGhosts,
|
|
688
|
+
});
|
|
689
|
+
cleanable.pinned = pinnedGhosts;
|
|
690
|
+
}
|
|
691
|
+
if (workspaceGhosts.length > 0) {
|
|
692
|
+
findings.push({
|
|
693
|
+
id: "workspace-ghost",
|
|
694
|
+
label: "工作区记账里的失效会话",
|
|
695
|
+
severity: "warn",
|
|
696
|
+
items: workspaceGhosts,
|
|
697
|
+
});
|
|
698
|
+
cleanable.workspace = workspaceGhosts;
|
|
699
|
+
}
|
|
700
|
+
} else {
|
|
701
|
+
findings.push({
|
|
702
|
+
id: "workspace-unreadable",
|
|
703
|
+
label: "无法读取 workspace 存储",
|
|
704
|
+
severity: "info",
|
|
705
|
+
items: [state.reason],
|
|
706
|
+
});
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
// 孤儿会话目录:磁盘上有、但持久层与 live 都不认识。仅报告,绝不自动删。
|
|
710
|
+
/** @type {string[]} */
|
|
711
|
+
const orphanDirs = [];
|
|
712
|
+
try {
|
|
713
|
+
const projects = await readdir(sessionsRoot(dataRoot), { withFileTypes: true });
|
|
714
|
+
for (const project of projects) {
|
|
715
|
+
if (!project.isDirectory()) continue;
|
|
716
|
+
const entries = await readdir(join(sessionsRoot(dataRoot), project.name), {
|
|
717
|
+
withFileTypes: true,
|
|
718
|
+
});
|
|
719
|
+
for (const entry of entries) {
|
|
720
|
+
if (!entry.isDirectory()) continue;
|
|
721
|
+
const looksLikeSession =
|
|
722
|
+
/^[A-Za-z0-9][A-Za-z0-9_$.-]{0,127}$/u.test(entry.name) || entry.name.includes("~");
|
|
723
|
+
if (looksLikeSession && !known.has(entry.name)) {
|
|
724
|
+
orphanDirs.push(join(project.name, entry.name));
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
} catch {
|
|
729
|
+
/* sessions 根不存在时忽略 */
|
|
730
|
+
}
|
|
731
|
+
if (orphanDirs.length > 0) {
|
|
732
|
+
findings.push({
|
|
733
|
+
id: "orphan-session-dir",
|
|
734
|
+
label: "磁盘上的孤儿会话目录(仅报告)",
|
|
735
|
+
severity: "info",
|
|
736
|
+
items: orphanDirs,
|
|
737
|
+
});
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
// 回收站一致性:有 meta 没 data
|
|
741
|
+
/** @type {string[]} */
|
|
742
|
+
const brokenTrash = [];
|
|
743
|
+
const listed = await listEntries(dataRoot);
|
|
744
|
+
for (const entry of listed.entries) {
|
|
745
|
+
const exists = await stat(join(trashRoot(dataRoot), entry.entryId, "data"))
|
|
746
|
+
.then((value) => value.isDirectory())
|
|
747
|
+
.catch(() => false);
|
|
748
|
+
if (!exists) brokenTrash.push(entry.entryId);
|
|
749
|
+
}
|
|
750
|
+
if (brokenTrash.length > 0 || listed.unknown.length > 0) {
|
|
751
|
+
findings.push({
|
|
752
|
+
id: "trash-inconsistent",
|
|
753
|
+
label: "回收站条目与实际数据不一致",
|
|
754
|
+
severity: "warn",
|
|
755
|
+
items: [...brokenTrash, ...listed.unknown],
|
|
756
|
+
});
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
const pending = await listPending(dataRoot);
|
|
760
|
+
if (pending.length > 0) {
|
|
761
|
+
findings.push({
|
|
762
|
+
id: "pending-operation",
|
|
763
|
+
label: "未完成的操作(重启后自愈)",
|
|
764
|
+
severity: "info",
|
|
765
|
+
items: pending.map((record) => record.id),
|
|
766
|
+
});
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
return {
|
|
770
|
+
ok: true,
|
|
771
|
+
generatedAt: new Date().toISOString(),
|
|
772
|
+
inventory: {
|
|
773
|
+
stored: storedIds.size,
|
|
774
|
+
live: liveIds.size,
|
|
775
|
+
archived: state.archivedIds.length,
|
|
776
|
+
pinned: state.pinnedIds.length,
|
|
777
|
+
workspaces: state.workspaces.length,
|
|
778
|
+
trash: listed.entries.length,
|
|
779
|
+
pending: pending.length,
|
|
780
|
+
},
|
|
781
|
+
findings,
|
|
782
|
+
cleanable: {
|
|
783
|
+
archived: cleanable.archived.length,
|
|
784
|
+
pinned: cleanable.pinned.length,
|
|
785
|
+
workspace: cleanable.workspace.length,
|
|
786
|
+
total: cleanable.archived.length + cleanable.pinned.length + cleanable.workspace.length,
|
|
787
|
+
},
|
|
788
|
+
};
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
/**
|
|
792
|
+
* 清理体检发现的失效引用(只动登记表,不碰会话文件)。
|
|
793
|
+
* @param {{ classes?: string[], operator?: string }} [request]
|
|
794
|
+
*/
|
|
795
|
+
async function cleanHealth(request = {}) {
|
|
796
|
+
const classes = Array.isArray(request.classes)
|
|
797
|
+
? request.classes
|
|
798
|
+
: ["archived", "pinned", "workspace"];
|
|
799
|
+
const scan = await scanHealth();
|
|
800
|
+
if (!scan.ok)
|
|
801
|
+
throw failure(
|
|
802
|
+
"session-delete/health-unavailable",
|
|
803
|
+
"无法体检:" + (scan.reason ?? "未知原因"),
|
|
804
|
+
);
|
|
805
|
+
const state = await readWorkspaceState();
|
|
806
|
+
const counts = { archived: 0, pinned: 0, workspace: 0 };
|
|
807
|
+
/** @type {string[]} */
|
|
808
|
+
const errors = [];
|
|
809
|
+
if (classes.includes("archived")) {
|
|
810
|
+
for (const id of state.archivedIds) {
|
|
811
|
+
if (scan.findings.find((f) => f.id === "archived-ghost")?.items.includes(id) !== true)
|
|
812
|
+
continue;
|
|
813
|
+
try {
|
|
814
|
+
await caps.services.workspace?.unarchiveSession?.(id);
|
|
815
|
+
counts.archived += 1;
|
|
816
|
+
} catch (error) {
|
|
817
|
+
errors.push("unarchive " + id + ": " + messageOf(error));
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
if (classes.includes("pinned")) {
|
|
822
|
+
for (const id of state.pinnedIds) {
|
|
823
|
+
if (scan.findings.find((f) => f.id === "pinned-ghost")?.items.includes(id) !== true)
|
|
824
|
+
continue;
|
|
825
|
+
try {
|
|
826
|
+
await caps.services.workspace?.unpinSession?.(id);
|
|
827
|
+
counts.pinned += 1;
|
|
828
|
+
} catch (error) {
|
|
829
|
+
errors.push("unpin " + id + ": " + messageOf(error));
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
if (classes.includes("workspace")) {
|
|
834
|
+
const ghost = scan.findings.find((f) => f.id === "workspace-ghost");
|
|
835
|
+
for (const item of ghost?.items ?? []) {
|
|
836
|
+
const workspace = (caps.services.workspace?.list?.() ?? []).find(
|
|
837
|
+
(/** @type {any} */ candidate) => String(candidate.id) === String(item.workspaceId),
|
|
838
|
+
);
|
|
839
|
+
if (!workspace || typeof workspace.detachSession !== "function") continue;
|
|
840
|
+
try {
|
|
841
|
+
await workspace.detachSession(item.sessionId);
|
|
842
|
+
counts.workspace += 1;
|
|
843
|
+
} catch (error) {
|
|
844
|
+
errors.push("detach " + item.sessionId + ": " + messageOf(error));
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
const total = counts.archived + counts.pinned + counts.workspace;
|
|
849
|
+
await audit.append({
|
|
850
|
+
action: "health",
|
|
851
|
+
result: errors.length > 0 ? "failed" : "ok",
|
|
852
|
+
operator: request.operator ?? "ui",
|
|
853
|
+
detail:
|
|
854
|
+
"清理失效引用 " +
|
|
855
|
+
total +
|
|
856
|
+
" 条" +
|
|
857
|
+
(errors.length > 0 ? ",失败 " + errors.length + " 条" : ""),
|
|
858
|
+
});
|
|
859
|
+
const receiptId = await writeReceipt(dataRoot, {
|
|
860
|
+
action: "health",
|
|
861
|
+
at: new Date().toISOString(),
|
|
862
|
+
cleaned: counts,
|
|
863
|
+
total,
|
|
864
|
+
errors,
|
|
865
|
+
});
|
|
866
|
+
return { ok: errors.length === 0, cleaned: counts, total, errors, receiptId };
|
|
867
|
+
}
|
|
868
|
+
|
|
509
869
|
async function health() {
|
|
510
870
|
const pending = await listPending(dataRoot);
|
|
511
871
|
return {
|
|
@@ -520,9 +880,17 @@ export function createOperations({ ctx, dataRoot, logger }) {
|
|
|
520
880
|
};
|
|
521
881
|
}
|
|
522
882
|
|
|
883
|
+
/** @param {number} [limit] */
|
|
884
|
+
async function receipts(limit = 50) {
|
|
885
|
+
return { entries: await listReceipts(dataRoot, limit) };
|
|
886
|
+
}
|
|
887
|
+
|
|
523
888
|
return {
|
|
524
889
|
caps,
|
|
525
890
|
health,
|
|
891
|
+
receipts,
|
|
892
|
+
scanHealth,
|
|
893
|
+
cleanHealth,
|
|
526
894
|
plan: /** @param {unknown} sessionId */ async (sessionId) => (await makePlan(sessionId)).plan,
|
|
527
895
|
trash,
|
|
528
896
|
list,
|
package/lib/receipts.js
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// 删除回执:每次破坏性操作落一份 JSON,供界面展示与事后核对。
|
|
3
|
+
// 位于 <data-root>/session-trash/receipts/,与回收站条目分开,条目被彻底删除也不影响回执。
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
5
|
+
import { mkdir, readdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { requireInside, trashRoot } from "./paths.js";
|
|
8
|
+
|
|
9
|
+
export const RECEIPT_SCHEMA = 1;
|
|
10
|
+
|
|
11
|
+
/** @param {string} dataRoot @returns {string} */
|
|
12
|
+
export function receiptsDir(dataRoot) {
|
|
13
|
+
return join(trashRoot(dataRoot), "receipts");
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* 写入一份回执,返回回执 id。
|
|
18
|
+
* @param {string} dataRoot
|
|
19
|
+
* @param {Record<string, unknown>} record
|
|
20
|
+
* @returns {Promise<string>}
|
|
21
|
+
*/
|
|
22
|
+
export async function writeReceipt(dataRoot, record) {
|
|
23
|
+
const dir = receiptsDir(dataRoot);
|
|
24
|
+
const id =
|
|
25
|
+
typeof record.id === "string" && record.id.length > 0
|
|
26
|
+
? record.id
|
|
27
|
+
: Date.now().toString(36) + "-" + randomUUID().slice(0, 6);
|
|
28
|
+
const file = join(dir, id + ".json");
|
|
29
|
+
requireInside(dataRoot, file);
|
|
30
|
+
await mkdir(dir, { recursive: true });
|
|
31
|
+
await writeFile(
|
|
32
|
+
file + ".tmp",
|
|
33
|
+
JSON.stringify({ ...record, schema: RECEIPT_SCHEMA, id }, null, 2),
|
|
34
|
+
);
|
|
35
|
+
await rename(file + ".tmp", file);
|
|
36
|
+
return id;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* 最近的回执(新的在前)。
|
|
41
|
+
* @param {string} dataRoot
|
|
42
|
+
* @param {number} [limit]
|
|
43
|
+
* @returns {Promise<any[]>}
|
|
44
|
+
*/
|
|
45
|
+
export async function listReceipts(dataRoot, limit = 50) {
|
|
46
|
+
const dir = receiptsDir(dataRoot);
|
|
47
|
+
/** @type {string[]} */
|
|
48
|
+
let names = [];
|
|
49
|
+
try {
|
|
50
|
+
names = (await readdir(dir)).filter((name) => name.endsWith(".json"));
|
|
51
|
+
} catch {
|
|
52
|
+
return [];
|
|
53
|
+
}
|
|
54
|
+
names.sort((a, b) => b.localeCompare(a));
|
|
55
|
+
/** @type {any[]} */
|
|
56
|
+
const out = [];
|
|
57
|
+
for (const name of names.slice(0, Math.max(1, limit))) {
|
|
58
|
+
try {
|
|
59
|
+
out.push(JSON.parse(await readFile(join(dir, name), "utf8")));
|
|
60
|
+
} catch {
|
|
61
|
+
// 单份回执损坏不影响列表
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return out;
|
|
65
|
+
}
|