@kangyishuai/dsh-session-delete 0.1.0 → 0.2.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 CHANGED
@@ -6,7 +6,7 @@
6
6
 
7
7
  Unofficial plugin for [DeepSeek Harness (DSH)](https://github.com/deepseek-ai). Not affiliated with DeepSeek.
8
8
 
9
- > **Status: v0.1, early.** Verified on DSH 0.2.1-rc.5 with `pnpm smoke:session-delete` (19 end-to-end assertions) plus a manual pass in the desktop GUI. Treat it as young software and keep backups of anything you cannot lose.
9
+ > **Status: v0.2, early.** Verified on DSH 0.2.1-rc.5 with `pnpm smoke:session-delete` (21 end-to-end assertions) plus a manual pass in the desktop GUI. Treat it as young software and keep backups of anything you cannot lose.
10
10
 
11
11
  ## What it does
12
12
 
@@ -58,6 +58,8 @@ Everything starts from a session row in the sidebar:
58
58
  - **purge** it permanently;
59
59
  - read the audit log.
60
60
 
61
+ **Health check**: the trash panel has a third tab. It reconciles the session store against the workspace bookkeeping and reports dangling references (archived/pinned ghosts, workspace membership, orphan session dirs, broken trash entries, unfinished operations). Cleaning removes **bookkeeping only** — session files are never touched.
62
+
61
63
  ## Side effects & risks
62
64
 
63
65
  Files and directories it touches:
@@ -93,7 +95,7 @@ v0.1 declares no `engines.dsh` range. Instead there are three layers of defense:
93
95
 
94
96
  | Plugin | Verified on DSH | Notes |
95
97
  | ------ | ------------------------ | ------------------------------------------------------------------------------------------- |
96
- | 0.1.0 | **0.2.1-rc.5** (desktop) | `pnpm smoke:session-delete`: 19 assertions green; manual GUI pass on the same host version. |
98
+ | 0.2.0 | **0.2.1-rc.5** (desktop) | `pnpm smoke:session-delete`: 21 assertions green; manual GUI pass on the same host version. |
97
99
 
98
100
  After a DSH upgrade: restart, then open the plugin status (settings → plugins). If it reports read-only mode, the host API changed — upgrade the plugin or report the version pair; don't force it.
99
101
 
package/README.zh-CN.md CHANGED
@@ -6,7 +6,7 @@
6
6
 
7
7
  非官方 [DeepSeek Harness (DSH)](https://github.com/deepseek-ai) 插件,与 DeepSeek 无关。
8
8
 
9
- > **状态:v0.1,早期可用。** 已在 DSH 0.2.1-rc.5 上用 `pnpm smoke:session-delete`(19 项端到端断言)加一轮桌面版人工验收。仍是年轻软件,重要数据请自行备份。
9
+ > **状态:v0.2,早期可用。** 已在 DSH 0.2.1-rc.5 上用 `pnpm smoke:session-delete`(21 项端到端断言)加一轮桌面版人工验收。仍是年轻软件,重要数据请自行备份。
10
10
 
11
11
  ## 做什么
12
12
 
@@ -58,6 +58,8 @@ dsh plugin --profile desktop add /tmp/kangyishuai-dsh-session-delete-*.tgz
58
58
  - **彻底删除**(不可恢复);
59
59
  - 查看审计日志。
60
60
 
61
+ **体检**:回收站面板有第三个页签。它把会话存储与工作区记账对账,列出失效引用(归档/置顶幽灵、工作区记账、孤儿会话目录、损坏的回收站条目、未完成操作)。清理**只动登记表**,绝不删会话文件。
62
+
61
63
  ## 副作用与风险
62
64
 
63
65
  会读写这些路径:
@@ -93,7 +95,7 @@ v0.1 没有声明 `engines.dsh` 版本范围,改用三层防线:
93
95
 
94
96
  | 插件版本 | 已验证的 DSH 版本 | 说明 |
95
97
  | -------- | ------------------------ | -------------------------------------------------------------------------------- |
96
- | 0.1.0 | **0.2.1-rc.5**(桌面版) | `pnpm smoke:session-delete` 19 项断言全绿,并在同一版本桌面版做过人工 GUI 验收。 |
98
+ | 0.2.0 | **0.2.1-rc.5**(桌面版) | `pnpm smoke:session-delete` 21 项断言全绿,并在同一版本桌面版做过人工 GUI 验收。 |
97
99
 
98
100
  DSH 升级之后:重启,然后看插件的状态条(设置 → 插件)。如果显示只读模式,说明宿主 API 变了——升级插件,或者把两个版本号一起报上来,别硬用。
99
101
 
package/lib/capability.js CHANGED
@@ -51,6 +51,7 @@ export function probeCapabilities(ctx) {
51
51
  const checks = {
52
52
  "persistence.stat": callable(persistence, "stat"),
53
53
  "persistence.locate": callable(persistence, "locate"),
54
+ "persistence.list": callable(persistence, "list"),
54
55
  "event.session-stop": typeof ctx?.parallel === "function",
55
56
  "event.session-activity": typeof ctx?.waterfall === "function",
56
57
  "sessions.get": callable(sessions, "get"),
@@ -76,6 +77,7 @@ export function probeCapabilities(ctx) {
76
77
  let tier = "api";
77
78
  const essential = ["persistence.stat", "workspace.archive", "workspace.unarchive"];
78
79
  const convenient = [
80
+ "persistence.list",
79
81
  "persistence.locate",
80
82
  "storage.domain",
81
83
  "sessions.detach",
package/lib/client.js CHANGED
@@ -67,6 +67,19 @@ window.__ModuleLoader__.load({
67
67
  "panel.title": "会话回收站",
68
68
  "panel.tabTrash": "回收站",
69
69
  "panel.tabAudit": "审计",
70
+ "panel.tabHealth": "体检",
71
+ "panel.tabReceipts": "回执",
72
+ "receipts.empty": "还没有操作回执。",
73
+ "receipts.restored": "已移回原位置",
74
+ "health.loading": "正在检查…",
75
+ "health.inventory":
76
+ "已存 {stored} · live {live} · 归档 {archived} · 回收站 {trash} · 待处理 {pending}",
77
+ "health.ok": "未发现失效引用。",
78
+ "health.items": "{n} 条",
79
+ "health.unavailable": "无法体检:{reason}",
80
+ "health.clean": "清理失效引用({n})",
81
+ "health.cleanConfirm": "确认清理 {n} 条?只动登记表,不碰会话文件",
82
+ "health.cleanDone": "已清理 {n} 条",
70
83
  "panel.empty": "回收站是空的。",
71
84
  "panel.auditEmpty": "还没有审计记录。",
72
85
  "panel.restore": "恢复",
@@ -104,6 +117,19 @@ window.__ModuleLoader__.load({
104
117
  "panel.title": "Session trash",
105
118
  "panel.tabTrash": "Trash",
106
119
  "panel.tabAudit": "Audit",
120
+ "panel.tabHealth": "Health",
121
+ "panel.tabReceipts": "Receipts",
122
+ "receipts.empty": "No operation receipts yet.",
123
+ "receipts.restored": "restored",
124
+ "health.loading": "Checking…",
125
+ "health.inventory":
126
+ "stored {stored} · live {live} · archived {archived} · trash {trash} · pending {pending}",
127
+ "health.ok": "No dangling references found.",
128
+ "health.items": "{n} item(s)",
129
+ "health.unavailable": "Cannot run the check: {reason}",
130
+ "health.clean": "Clean dangling references ({n})",
131
+ "health.cleanConfirm": "Clean {n} dangling reference(s)? Bookkeeping only, no session files.",
132
+ "health.cleanDone": "Cleaned {n}",
107
133
  "panel.empty": "The trash is empty.",
108
134
  "panel.auditEmpty": "No audit entries yet.",
109
135
  "panel.restore": "Restore",
@@ -568,6 +594,43 @@ window.__ModuleLoader__.load({
568
594
  var purgeState = React.useState(null);
569
595
  var confirmPurge = purgeState[0];
570
596
  var setConfirmPurge = purgeState[1];
597
+ var scanState = React.useState(null);
598
+ var scan = scanState[0];
599
+ var setScan = scanState[1];
600
+ var scanErrorState = React.useState(null);
601
+ var scanError = scanErrorState[0];
602
+ var setScanError = scanErrorState[1];
603
+ var cleanState = React.useState(false);
604
+ var cleaning = cleanState[0];
605
+ var setCleaning = cleanState[1];
606
+ var cleanMsgState = React.useState("");
607
+ var cleanMsg = cleanMsgState[0];
608
+ var setCleanMsg = cleanMsgState[1];
609
+ var receiptsState = React.useState(null);
610
+ var receipts = receiptsState[0];
611
+ var setReceipts = receiptsState[1];
612
+
613
+ const loadReceipts = React.useCallback(() => {
614
+ props
615
+ .call("receipts", { limit: 50 })
616
+ .then((/** @type {any} */ value) => {
617
+ setReceipts(value && value.entries ? value.entries : []);
618
+ })
619
+ .catch(() => setReceipts([]));
620
+ }, []);
621
+
622
+ const loadHealth = React.useCallback(() => {
623
+ setScan(null);
624
+ setScanError(null);
625
+ props
626
+ .call("healthScan")
627
+ .then((/** @type {any} */ value) => {
628
+ setScan(value);
629
+ })
630
+ .catch((/** @type {any} */ reason) => {
631
+ setScanError(errorText(reason));
632
+ });
633
+ }, []);
571
634
 
572
635
  const loadAudit = React.useCallback(() => {
573
636
  props
@@ -711,10 +774,213 @@ window.__ModuleLoader__.load({
711
774
  },
712
775
  props.t("panel.tabAudit"),
713
776
  ),
777
+ h(
778
+ Btn,
779
+ {
780
+ onClick: () => {
781
+ setTab("health");
782
+ loadHealth();
783
+ },
784
+ },
785
+ props.t("panel.tabHealth"),
786
+ ),
787
+ h(
788
+ Btn,
789
+ {
790
+ onClick: () => {
791
+ setTab("receipts");
792
+ loadReceipts();
793
+ },
794
+ },
795
+ props.t("panel.tabReceipts"),
796
+ ),
714
797
  ),
715
798
  );
716
799
 
717
- if (tab === "trash") {
800
+ if (tab === "receipts") {
801
+ if (!receipts || receipts.length === 0) {
802
+ content.push(
803
+ h(
804
+ "div",
805
+ { key: "receipts-empty", style: { color: T.dim, padding: "8px 0" } },
806
+ props.t("receipts.empty"),
807
+ ),
808
+ );
809
+ } else {
810
+ receipts.forEach((/** @type {any} */ receipt, /** @type {any} */ index) => {
811
+ const removed = receipt.removed || [];
812
+ const okCount = removed.filter(
813
+ (/** @type {any} */ item) => item.status === "ok",
814
+ ).length;
815
+ const detail =
816
+ receipt.action === "trash"
817
+ ? formatBytes(receipt.sizeBytes || 0) + " · " + okCount + "/" + removed.length
818
+ : receipt.action === "restore"
819
+ ? props.t("receipts.restored")
820
+ : receipt.action === "purge"
821
+ ? formatBytes(receipt.bytes || 0)
822
+ : String(receipt.total || 0);
823
+ content.push(
824
+ h(
825
+ "div",
826
+ {
827
+ key: "receipt-" + index,
828
+ title: String(receipt.sessionId || ""),
829
+ style: {
830
+ borderTop: "1px solid " + T.border,
831
+ padding: "7px 0",
832
+ fontSize: "12px",
833
+ display: "flex",
834
+ alignItems: "baseline",
835
+ gap: "6px",
836
+ },
837
+ },
838
+ h(
839
+ "span",
840
+ { style: { color: T.faint, whiteSpace: "nowrap" } },
841
+ formatTime(receipt.at),
842
+ ),
843
+ h(
844
+ "span",
845
+ { style: { fontWeight: 600, whiteSpace: "nowrap" } },
846
+ String(receipt.action || ""),
847
+ ),
848
+ h(
849
+ "span",
850
+ {
851
+ style: {
852
+ flex: 1,
853
+ minWidth: 0,
854
+ color: T.dim,
855
+ overflow: "hidden",
856
+ textOverflow: "ellipsis",
857
+ whiteSpace: "nowrap",
858
+ },
859
+ },
860
+ String(receipt.title || receipt.sessionId || "—"),
861
+ ),
862
+ h("span", { style: { color: T.faint, whiteSpace: "nowrap" } }, detail),
863
+ ),
864
+ );
865
+ });
866
+ }
867
+ } else if (tab === "health") {
868
+ if (scanError) {
869
+ content.push(
870
+ h("div", { key: "scan-err", style: { color: T.danger, padding: "8px 0" } }, scanError),
871
+ );
872
+ } else if (!scan) {
873
+ content.push(
874
+ h(
875
+ "div",
876
+ { key: "scan-loading", style: { color: T.dim, padding: "8px 0" } },
877
+ props.t("health.loading"),
878
+ ),
879
+ );
880
+ } else if (!scan.ok) {
881
+ content.push(
882
+ h(
883
+ "div",
884
+ { key: "scan-na", style: { color: T.dim, padding: "8px 0" } },
885
+ props.t("health.unavailable", { reason: scan.reason || "" }),
886
+ ),
887
+ );
888
+ } else {
889
+ content.push(
890
+ h(
891
+ "div",
892
+ { key: "scan-inventory", style: { color: T.dim, fontSize: "12px" } },
893
+ props.t("health.inventory", scan.inventory || {}),
894
+ ),
895
+ );
896
+ if (scan.findings.length === 0) {
897
+ content.push(
898
+ h("div", { key: "scan-ok", style: { padding: "8px 0" } }, props.t("health.ok")),
899
+ );
900
+ }
901
+ scan.findings.forEach((/** @type {any} */ finding, /** @type {any} */ index) => {
902
+ content.push(
903
+ h(
904
+ "div",
905
+ {
906
+ key: "finding-" + index,
907
+ style: {
908
+ borderTop: "1px solid " + T.border,
909
+ padding: "8px 0",
910
+ color: finding.severity === "warn" ? T.text : T.dim,
911
+ },
912
+ },
913
+ h(
914
+ "div",
915
+ { style: { fontWeight: 600 } },
916
+ finding.label + " · " + props.t("health.items", { n: finding.items.length }),
917
+ ),
918
+ h(
919
+ "div",
920
+ { style: { color: T.faint, fontSize: "12px", wordBreak: "break-all" } },
921
+ finding.items
922
+ .slice(0, 6)
923
+ .map((/** @type {any} */ item) =>
924
+ typeof item === "string" ? item : JSON.stringify(item),
925
+ )
926
+ .join(" · "),
927
+ ),
928
+ ),
929
+ );
930
+ });
931
+ if (scan.cleanable && scan.cleanable.total > 0) {
932
+ content.push(
933
+ h(
934
+ "div",
935
+ {
936
+ key: "scan-clean",
937
+ style: { marginTop: "10px", display: "flex", gap: "8px", alignItems: "center" },
938
+ },
939
+ confirmPurge === "__health__"
940
+ ? h(
941
+ Btn,
942
+ {
943
+ danger: true,
944
+ disabled: cleaning,
945
+ onClick: () => {
946
+ setCleaning(true);
947
+ setCleanMsg("");
948
+ props
949
+ .call("cleanHealth", { classes: ["archived", "pinned", "workspace"] })
950
+ .then((/** @type {any} */ result) => {
951
+ setCleaning(false);
952
+ setConfirmPurge(null);
953
+ setCleanMsg(props.t("health.cleanDone", { n: result.total }));
954
+ loadHealth();
955
+ props.bump?.();
956
+ })
957
+ .catch((/** @type {any} */ reason) => {
958
+ setCleaning(false);
959
+ setCleanMsg(errorText(reason));
960
+ });
961
+ },
962
+ },
963
+ props.t("health.cleanConfirm", { n: scan.cleanable.total }),
964
+ )
965
+ : h(
966
+ Btn,
967
+ { onClick: () => setConfirmPurge("__health__") },
968
+ props.t("health.clean", { n: scan.cleanable.total }),
969
+ ),
970
+ ),
971
+ );
972
+ }
973
+ if (cleanMsg) {
974
+ content.push(
975
+ h(
976
+ "div",
977
+ { key: "scan-msg", style: { color: T.dim, marginTop: "8px", fontSize: "12px" } },
978
+ cleanMsg,
979
+ ),
980
+ );
981
+ }
982
+ }
983
+ } else if (tab === "trash") {
718
984
  if (entries.length === 0) {
719
985
  content.push(
720
986
  h(
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
 
@@ -322,9 +325,23 @@ export function createOperations({ ctx, dataRoot, logger }) {
322
325
  operator: request.operator ?? "ui",
323
326
  detail: summarizePlan(plan),
324
327
  });
328
+ const receiptId = await writeReceipt(dataRoot, {
329
+ action: "trash",
330
+ at: new Date().toISOString(),
331
+ sessionId: plan.sessionId,
332
+ entryId,
333
+ title: plan.title ?? (typeof request.title === "string" ? request.title : null),
334
+ sizeBytes: plan.sizeBytes,
335
+ digest: plan.digest,
336
+ live: plan.live,
337
+ children: plan.children,
338
+ removed,
339
+ checks,
340
+ });
325
341
  return {
326
342
  ok: true,
327
343
  entryId,
344
+ receiptId,
328
345
  sessionId: plan.sessionId,
329
346
  digest: plan.digest,
330
347
  title: plan.title ?? (typeof request.title === "string" ? request.title : null),
@@ -414,7 +431,15 @@ export function createOperations({ ctx, dataRoot, logger }) {
414
431
  entryId,
415
432
  operator: request.operator ?? "ui",
416
433
  });
417
- return { ok: true, sessionId: meta.sessionId, restoredTo: restored.restoredTo };
434
+ const receiptId = await writeReceipt(dataRoot, {
435
+ action: "restore",
436
+ at: new Date().toISOString(),
437
+ sessionId: meta.sessionId,
438
+ entryId,
439
+ title: meta.title,
440
+ restoredTo: restored.restoredTo,
441
+ });
442
+ return { ok: true, sessionId: meta.sessionId, restoredTo: restored.restoredTo, receiptId };
418
443
  } catch (error) {
419
444
  await finishOperation({ dataRoot, id: record.id, state: "failed", detail: messageOf(error) });
420
445
  await audit.append({
@@ -450,7 +475,15 @@ export function createOperations({ ctx, dataRoot, logger }) {
450
475
  operator: request.operator ?? "ui",
451
476
  detail: "释放约 " + result.bytes + " 字节",
452
477
  });
453
- return { ok: true, bytes: result.bytes, sessionId: meta.sessionId };
478
+ const receiptId = await writeReceipt(dataRoot, {
479
+ action: "purge",
480
+ at: new Date().toISOString(),
481
+ sessionId: meta.sessionId,
482
+ entryId,
483
+ title: meta.title,
484
+ bytes: result.bytes,
485
+ });
486
+ return { ok: true, bytes: result.bytes, sessionId: meta.sessionId, receiptId };
454
487
  } catch (error) {
455
488
  await finishOperation({ dataRoot, id: record.id, state: "failed", detail: messageOf(error) });
456
489
  await audit.append({
@@ -506,6 +539,279 @@ export function createOperations({ ctx, dataRoot, logger }) {
506
539
  return checks;
507
540
  }
508
541
 
542
+ /**
543
+ * 读取 workspace 存储快照(只读)。这是文件级兜底:
544
+ * 归档/置顶集合没有公开的读接口,只能读 storages/workspace.json。
545
+ * @returns {Promise<{ ok: boolean, reason?: string, archivedIds: string[], pinnedIds: string[],
546
+ * workspaces: { id: string, sessionIds: string[] }[] }>}
547
+ */
548
+ async function readWorkspaceState() {
549
+ const file = join(dataRoot, "storages", "workspace.json");
550
+ let parsed;
551
+ try {
552
+ parsed = JSON.parse(await readFile(file, "utf8"));
553
+ } catch (error) {
554
+ return {
555
+ ok: false,
556
+ reason: "无法读取 " + file + ":" + messageOf(error),
557
+ archivedIds: [],
558
+ pinnedIds: [],
559
+ workspaces: [],
560
+ };
561
+ }
562
+ const global = parsed?.global ?? {};
563
+ const tables = parsed?.tables ?? {};
564
+ const workspaces = Object.entries(tables.workspaces ?? {}).map(([id, value]) => ({
565
+ id,
566
+ sessionIds: Array.isArray(value?.sessionIds) ? value.sessionIds.map(String) : [],
567
+ }));
568
+ return {
569
+ ok: true,
570
+ archivedIds: Array.isArray(global.archivedSessionIds)
571
+ ? global.archivedSessionIds.map(String)
572
+ : [],
573
+ pinnedIds: Array.isArray(global.pinnedSessionIds) ? global.pinnedSessionIds.map(String) : [],
574
+ workspaces,
575
+ };
576
+ }
577
+
578
+ /**
579
+ * 全库体检:找出指向已不存在会话的登记条目。只读,不修改任何东西。
580
+ */
581
+ async function scanHealth() {
582
+ if (!caps.checks["persistence.list"]) {
583
+ return {
584
+ ok: false,
585
+ reason: "当前宿主没有 sessionPersistence.list,无法枚举已存会话。",
586
+ findings: [],
587
+ inventory: null,
588
+ };
589
+ }
590
+ const persisted = (await caps.services.persistence.list()) ?? [];
591
+ const storedIds = new Set(
592
+ persisted
593
+ .map((/** @type {any} */ entry) => String(entry?.id ?? entry?.header?.id ?? ""))
594
+ .filter(Boolean),
595
+ );
596
+ const liveIds = new Set();
597
+ try {
598
+ for (const id of caps.services.sessions?.store?.keys?.() ?? []) liveIds.add(String(id));
599
+ } catch {
600
+ /* store 不可枚举时忽略 */
601
+ }
602
+ const known = new Set([...storedIds, ...liveIds]);
603
+
604
+ const state = await readWorkspaceState();
605
+ /** @type {{ id: string, label: string, severity: "warn" | "info", items: any[] }[]} */
606
+ const findings = [];
607
+ /** @type {{ archived: string[], pinned: string[], workspace: { workspaceId: string, sessionId: string }[] }} */
608
+ const cleanable = { archived: [], pinned: [], workspace: [] };
609
+
610
+ if (state.ok) {
611
+ const archivedGhosts = state.archivedIds.filter((id) => !known.has(id));
612
+ const pinnedGhosts = state.pinnedIds.filter((id) => !known.has(id));
613
+ const workspaceGhosts = [];
614
+ for (const workspace of state.workspaces) {
615
+ for (const sessionId of workspace.sessionIds) {
616
+ if (!known.has(sessionId)) workspaceGhosts.push({ workspaceId: workspace.id, sessionId });
617
+ }
618
+ }
619
+ if (archivedGhosts.length > 0) {
620
+ findings.push({
621
+ id: "archived-ghost",
622
+ label: "归档集合里的失效条目",
623
+ severity: "warn",
624
+ items: archivedGhosts,
625
+ });
626
+ cleanable.archived = archivedGhosts;
627
+ }
628
+ if (pinnedGhosts.length > 0) {
629
+ findings.push({
630
+ id: "pinned-ghost",
631
+ label: "置顶集合里的失效条目",
632
+ severity: "warn",
633
+ items: pinnedGhosts,
634
+ });
635
+ cleanable.pinned = pinnedGhosts;
636
+ }
637
+ if (workspaceGhosts.length > 0) {
638
+ findings.push({
639
+ id: "workspace-ghost",
640
+ label: "工作区记账里的失效会话",
641
+ severity: "warn",
642
+ items: workspaceGhosts,
643
+ });
644
+ cleanable.workspace = workspaceGhosts;
645
+ }
646
+ } else {
647
+ findings.push({
648
+ id: "workspace-unreadable",
649
+ label: "无法读取 workspace 存储",
650
+ severity: "info",
651
+ items: [state.reason],
652
+ });
653
+ }
654
+
655
+ // 孤儿会话目录:磁盘上有、但持久层与 live 都不认识。仅报告,绝不自动删。
656
+ /** @type {string[]} */
657
+ const orphanDirs = [];
658
+ try {
659
+ const projects = await readdir(sessionsRoot(dataRoot), { withFileTypes: true });
660
+ for (const project of projects) {
661
+ if (!project.isDirectory()) continue;
662
+ const entries = await readdir(join(sessionsRoot(dataRoot), project.name), {
663
+ withFileTypes: true,
664
+ });
665
+ for (const entry of entries) {
666
+ if (!entry.isDirectory()) continue;
667
+ const looksLikeSession =
668
+ /^[A-Za-z0-9][A-Za-z0-9_$.-]{0,127}$/u.test(entry.name) || entry.name.includes("~");
669
+ if (looksLikeSession && !known.has(entry.name)) {
670
+ orphanDirs.push(join(project.name, entry.name));
671
+ }
672
+ }
673
+ }
674
+ } catch {
675
+ /* sessions 根不存在时忽略 */
676
+ }
677
+ if (orphanDirs.length > 0) {
678
+ findings.push({
679
+ id: "orphan-session-dir",
680
+ label: "磁盘上的孤儿会话目录(仅报告)",
681
+ severity: "info",
682
+ items: orphanDirs,
683
+ });
684
+ }
685
+
686
+ // 回收站一致性:有 meta 没 data
687
+ /** @type {string[]} */
688
+ const brokenTrash = [];
689
+ const listed = await listEntries(dataRoot);
690
+ for (const entry of listed.entries) {
691
+ const exists = await stat(join(trashRoot(dataRoot), entry.entryId, "data"))
692
+ .then((value) => value.isDirectory())
693
+ .catch(() => false);
694
+ if (!exists) brokenTrash.push(entry.entryId);
695
+ }
696
+ if (brokenTrash.length > 0 || listed.unknown.length > 0) {
697
+ findings.push({
698
+ id: "trash-inconsistent",
699
+ label: "回收站条目与实际数据不一致",
700
+ severity: "warn",
701
+ items: [...brokenTrash, ...listed.unknown],
702
+ });
703
+ }
704
+
705
+ const pending = await listPending(dataRoot);
706
+ if (pending.length > 0) {
707
+ findings.push({
708
+ id: "pending-operation",
709
+ label: "未完成的操作(重启后自愈)",
710
+ severity: "info",
711
+ items: pending.map((record) => record.id),
712
+ });
713
+ }
714
+
715
+ return {
716
+ ok: true,
717
+ generatedAt: new Date().toISOString(),
718
+ inventory: {
719
+ stored: storedIds.size,
720
+ live: liveIds.size,
721
+ archived: state.archivedIds.length,
722
+ pinned: state.pinnedIds.length,
723
+ workspaces: state.workspaces.length,
724
+ trash: listed.entries.length,
725
+ pending: pending.length,
726
+ },
727
+ findings,
728
+ cleanable: {
729
+ archived: cleanable.archived.length,
730
+ pinned: cleanable.pinned.length,
731
+ workspace: cleanable.workspace.length,
732
+ total: cleanable.archived.length + cleanable.pinned.length + cleanable.workspace.length,
733
+ },
734
+ };
735
+ }
736
+
737
+ /**
738
+ * 清理体检发现的失效引用(只动登记表,不碰会话文件)。
739
+ * @param {{ classes?: string[], operator?: string }} [request]
740
+ */
741
+ async function cleanHealth(request = {}) {
742
+ const classes = Array.isArray(request.classes)
743
+ ? request.classes
744
+ : ["archived", "pinned", "workspace"];
745
+ const scan = await scanHealth();
746
+ if (!scan.ok)
747
+ throw failure(
748
+ "session-delete/health-unavailable",
749
+ "无法体检:" + (scan.reason ?? "未知原因"),
750
+ );
751
+ const state = await readWorkspaceState();
752
+ const counts = { archived: 0, pinned: 0, workspace: 0 };
753
+ /** @type {string[]} */
754
+ const errors = [];
755
+ if (classes.includes("archived")) {
756
+ for (const id of state.archivedIds) {
757
+ if (scan.findings.find((f) => f.id === "archived-ghost")?.items.includes(id) !== true)
758
+ continue;
759
+ try {
760
+ await caps.services.workspace?.unarchiveSession?.(id);
761
+ counts.archived += 1;
762
+ } catch (error) {
763
+ errors.push("unarchive " + id + ": " + messageOf(error));
764
+ }
765
+ }
766
+ }
767
+ if (classes.includes("pinned")) {
768
+ for (const id of state.pinnedIds) {
769
+ if (scan.findings.find((f) => f.id === "pinned-ghost")?.items.includes(id) !== true)
770
+ continue;
771
+ try {
772
+ await caps.services.workspace?.unpinSession?.(id);
773
+ counts.pinned += 1;
774
+ } catch (error) {
775
+ errors.push("unpin " + id + ": " + messageOf(error));
776
+ }
777
+ }
778
+ }
779
+ if (classes.includes("workspace")) {
780
+ const ghost = scan.findings.find((f) => f.id === "workspace-ghost");
781
+ for (const item of ghost?.items ?? []) {
782
+ const workspace = (caps.services.workspace?.list?.() ?? []).find(
783
+ (/** @type {any} */ candidate) => String(candidate.id) === String(item.workspaceId),
784
+ );
785
+ if (!workspace || typeof workspace.detachSession !== "function") continue;
786
+ try {
787
+ await workspace.detachSession(item.sessionId);
788
+ counts.workspace += 1;
789
+ } catch (error) {
790
+ errors.push("detach " + item.sessionId + ": " + messageOf(error));
791
+ }
792
+ }
793
+ }
794
+ const total = counts.archived + counts.pinned + counts.workspace;
795
+ await audit.append({
796
+ action: "health",
797
+ result: errors.length > 0 ? "failed" : "ok",
798
+ operator: request.operator ?? "ui",
799
+ detail:
800
+ "清理失效引用 " +
801
+ total +
802
+ " 条" +
803
+ (errors.length > 0 ? ",失败 " + errors.length + " 条" : ""),
804
+ });
805
+ const receiptId = await writeReceipt(dataRoot, {
806
+ action: "health",
807
+ at: new Date().toISOString(),
808
+ cleaned: counts,
809
+ total,
810
+ errors,
811
+ });
812
+ return { ok: errors.length === 0, cleaned: counts, total, errors, receiptId };
813
+ }
814
+
509
815
  async function health() {
510
816
  const pending = await listPending(dataRoot);
511
817
  return {
@@ -520,9 +826,17 @@ export function createOperations({ ctx, dataRoot, logger }) {
520
826
  };
521
827
  }
522
828
 
829
+ /** @param {number} [limit] */
830
+ async function receipts(limit = 50) {
831
+ return { entries: await listReceipts(dataRoot, limit) };
832
+ }
833
+
523
834
  return {
524
835
  caps,
525
836
  health,
837
+ receipts,
838
+ scanHealth,
839
+ cleanHealth,
526
840
  plan: /** @param {unknown} sessionId */ async (sessionId) => (await makePlan(sessionId)).plan,
527
841
  trash,
528
842
  list,
@@ -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
+ }
package/lib/service.js CHANGED
@@ -144,6 +144,39 @@ export class SessionDeleteService extends TypertRemoteService {
144
144
  }
145
145
  }
146
146
 
147
+ /**
148
+ * 最近的操作回执。
149
+ * @param {{ limit?: number }} [request]
150
+ */
151
+ async receipts(request) {
152
+ try {
153
+ return await this.ops.receipts(request?.limit ?? 50);
154
+ } catch (error) {
155
+ rethrow(error);
156
+ }
157
+ }
158
+
159
+ /** 全库体检:只读。 */
160
+ async healthScan() {
161
+ try {
162
+ return await this.ops.scanHealth();
163
+ } catch (error) {
164
+ rethrow(error);
165
+ }
166
+ }
167
+
168
+ /**
169
+ * 清理体检发现的失效引用(只动登记表)。
170
+ * @param {{ classes?: string[] }} [request]
171
+ */
172
+ async cleanHealth(request) {
173
+ try {
174
+ return await this.ops.cleanHealth({ classes: request?.classes, operator: "ui" });
175
+ } catch (error) {
176
+ rethrow(error);
177
+ }
178
+ }
179
+
147
180
  /**
148
181
  * @param {{ sessionId: string }} request
149
182
  */
@@ -163,4 +196,7 @@ declareRemote(SessionDeleteService, "list");
163
196
  declareRemote(SessionDeleteService, "restore");
164
197
  declareRemote(SessionDeleteService, "purge");
165
198
  declareRemote(SessionDeleteService, "audit");
199
+ declareRemote(SessionDeleteService, "receipts");
200
+ declareRemote(SessionDeleteService, "healthScan");
201
+ declareRemote(SessionDeleteService, "cleanHealth");
166
202
  declareRemote(SessionDeleteService, "reconcile");
package/lib/trash.js CHANGED
@@ -167,7 +167,11 @@ export async function listEntries(dataRoot) {
167
167
  try {
168
168
  names = (await readdir(root, { withFileTypes: true }))
169
169
  .filter(
170
- (entry) => entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "journal",
170
+ (entry) =>
171
+ entry.isDirectory() &&
172
+ !entry.name.startsWith(".") &&
173
+ entry.name !== "journal" &&
174
+ entry.name !== "receipts",
171
175
  )
172
176
  .map((entry) => entry.name);
173
177
  } catch {
package/locale/en.json CHANGED
@@ -32,6 +32,18 @@
32
32
  "panel.readOnly": "Read-only: this DSH version is missing required APIs; deletion is disabled.",
33
33
  "panel.close": "Close",
34
34
  "toast.failed": "Operation failed: {message}",
35
- "footer.trash": "Trash"
35
+ "footer.trash": "Trash",
36
+ "panel.tabHealth": "Health",
37
+ "health.loading": "Checking…",
38
+ "health.inventory": "stored {stored} · live {live} · archived {archived} · trash {trash} · pending {pending}",
39
+ "health.ok": "No dangling references found.",
40
+ "health.items": "{n} item(s)",
41
+ "health.unavailable": "Cannot run the check: {reason}",
42
+ "health.clean": "Clean dangling references ({n})",
43
+ "health.cleanConfirm": "Clean {n} dangling reference(s)? Bookkeeping only, no session files.",
44
+ "health.cleanDone": "Cleaned {n}",
45
+ "panel.tabReceipts": "Receipts",
46
+ "receipts.empty": "No operation receipts yet.",
47
+ "receipts.restored": "restored"
36
48
  }
37
49
  }
package/locale/zh.json CHANGED
@@ -32,6 +32,18 @@
32
32
  "panel.readOnly": "只读模式:当前 DSH 版本缺少依赖接口,删除功能已禁用。",
33
33
  "panel.close": "关闭",
34
34
  "toast.failed": "操作失败:{message}",
35
- "footer.trash": "回收站"
35
+ "footer.trash": "回收站",
36
+ "panel.tabHealth": "体检",
37
+ "health.loading": "正在检查…",
38
+ "health.inventory": "已存 {stored} · live {live} · 归档 {archived} · 回收站 {trash} · 待处理 {pending}",
39
+ "health.ok": "未发现失效引用。",
40
+ "health.items": "{n} 条",
41
+ "health.unavailable": "无法体检:{reason}",
42
+ "health.clean": "清理失效引用({n})",
43
+ "health.cleanConfirm": "确认清理 {n} 条?只动登记表,不碰会话文件",
44
+ "health.cleanDone": "已清理 {n}",
45
+ "panel.tabReceipts": "回执",
46
+ "receipts.empty": "还没有操作回执。",
47
+ "receipts.restored": "已移回原位置"
36
48
  }
37
49
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kangyishuai/dsh-session-delete",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Real session deletion for DSH: trash by default, plan before delete, audit log, residue receipt",
5
5
  "keywords": [
6
6
  "dsh",