@kangyishuai/dsh-session-delete 0.4.9 → 0.6.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/lib/operations.js CHANGED
@@ -1,18 +1,22 @@
1
1
  // @ts-check
2
2
  // 操作编排层:不依赖 typert,可在单元测试里用假 ctx 跑(真实宿主交互全部经 capability.js 探测)。
3
- import { readdir, readFile, stat } from "node:fs/promises";
3
+ import { readdir, stat } from "node:fs/promises";
4
4
  import { createRequire } from "node:module";
5
5
  import { join } from "node:path";
6
6
  import { setTimeout as delayMs } from "node:timers/promises";
7
7
  import { createAudit } from "./audit.js";
8
8
  import { describeCapabilities, probeCapabilities } from "./capability.js";
9
- import { beginOperation, finishOperation, listPending } from "./journal.js";
9
+ import { beginOperation, finishOperation, listPending, updateOperation } from "./journal.js";
10
10
  import { directorySize, locateSession } from "./locate.js";
11
11
  import { auditPath, requireSessionId, sessionsRoot, trashRoot } from "./paths.js";
12
- import { buildPlan, planExecutable, summarizePlan } from "./plan.js";
12
+ import { buildPlan, digestOfWorkspace, planExecutable, summarizePlan } from "./plan.js";
13
+ import { readPreferences, writePreferences } from "./preferences.js";
13
14
  import { listReceipts, writeReceipt } from "./receipts.js";
14
- import { buildRefs } from "./refs.js";
15
+ import { createRecovery } from "./recovery.js";
16
+ import { buildRefs, removeAllRefs, restoreAllRefs, snapshotAllRefs } from "./refs.js";
17
+ import { describeRestoreSummary, restoreSummary, verifyRestored } from "./restore.js";
15
18
  import { listEntries, moveIntoTrash, purgeEntry, readEntry, restoreEntry } from "./trash.js";
19
+ import { readWorkspaceState } from "./workspace-state.js";
16
20
 
17
21
  const nodeRequire = createRequire(import.meta.url);
18
22
  const pkg = nodeRequire("../package.json");
@@ -21,6 +25,14 @@ const pkg = nodeRequire("../package.json");
21
25
  const SETTLE_MS = 200;
22
26
  /** 移走之后复查原路径的时间点;活句柄迟到写入会在这个窗口里重建目录。 */
23
27
  const REVIVE_CHECK_MS = 1500;
28
+ /**
29
+ * 单次批量 RPC 的条目上限。界面按 BATCH_CHUNK 分批调用,这里只是防御性硬上限:
30
+ * 0.4.x 的上限是 50,用户回收站 80 条时「全选 → 彻底删除」会被整单拒绝,
31
+ * 表现成「点了没反应」——所以上限要远大于一次常见的批量规模。
32
+ */
33
+ const MAX_BATCH_IDS = 200;
34
+ /** 客户端每次批量请求的条数,同时也是这里建议的单批规模。 */
35
+ export const BATCH_CHUNK = 20;
24
36
 
25
37
  /** @param {unknown} error @returns {string} */
26
38
  function messageOf(error) {
@@ -68,17 +80,104 @@ export function normalizeActivity(raw) {
68
80
  * @param {{ ctx: any, dataRoot: string, logger: any }} options
69
81
  */
70
82
  export function createOperations({ ctx, dataRoot, logger }) {
71
- const caps = probeCapabilities(ctx);
83
+ /**
84
+ * 能力探测**不能一次性固化**(USIM-U3-02 的根因):桌面组合里 `workspaceRegistry`
85
+ * 与 `agents` 比 `sessionPersistence` 晚挂载,插件启动对账在后者可用时就跑,
86
+ * 探到的 caps 里 workspace 是 undefined —— 之后每次删除都跳过归档闸门/停止/工作区
87
+ * 记账,每次恢复都把 `workspace-archive` 报成「unarchiveSession unavailable」。
88
+ *
89
+ * 所以 caps 与引用适配器都是**可刷新**的:每次进入操作前重探一次(只是几次属性读取),
90
+ * 服务集合或门禁结果一变就**原地**重建 refs(原地重建让 createRecovery 早先拿到的
91
+ * 数组引用也跟着更新,不需要把 refs 传遍每一层)。
92
+ *
93
+ * 原地重建的前提:`buildRefs()` 的条目**数量与顺序必须稳定**(同一次宿主组合下)。
94
+ * 若以后新增按能力条件增删引用的适配器,就不能再用 length=0/push,要改成 getRefs()。
95
+ */
96
+ let caps = probeCapabilities(ctx);
97
+ const refs = buildRefs(caps, logger, { dataRoot });
98
+
99
+ /**
100
+ * 影响引用适配器行为的探针结果。服务换了身份或门禁结论翻转都要重建适配器。
101
+ * @param {import("./capability.js").Capabilities} value
102
+ * @returns {unknown[]}
103
+ */
104
+ function hostSignature(value) {
105
+ return [
106
+ value.services.persistence,
107
+ value.services.sessions,
108
+ value.services.workspace,
109
+ value.services.storageDomain,
110
+ value.services.agents,
111
+ value.checks["workspace.archive"],
112
+ value.checks["workspace.unarchive"],
113
+ value.checks["workspace.pin"],
114
+ value.checks["workspace.unpin"],
115
+ value.checks["workspace.list"],
116
+ value.checks["storage.domain"],
117
+ value.checks["sessions.detach"],
118
+ value.checks["agents.detach"],
119
+ value.checks["event.session-stop"],
120
+ ];
121
+ }
122
+
123
+ /**
124
+ * 重探宿主能力;有变化就重建引用适配器(原地)。返回最新的 caps。
125
+ * @returns {import("./capability.js").Capabilities}
126
+ */
127
+ function refreshHost() {
128
+ const next = probeCapabilities(ctx);
129
+ const before = hostSignature(caps);
130
+ const after = hostSignature(next);
131
+ let changed = before.length !== after.length;
132
+ for (let index = 0; !changed && index < before.length; index += 1) {
133
+ if (before[index] !== after[index]) changed = true;
134
+ }
135
+ caps = next;
136
+ if (changed) {
137
+ const rebuilt = buildRefs(caps, logger, { dataRoot });
138
+ refs.length = 0;
139
+ refs.push(...rebuilt);
140
+ }
141
+ return caps;
142
+ }
143
+
72
144
  const audit = createAudit(dataRoot);
73
- const refs = buildRefs(caps, logger);
74
145
  /** 当前进程里正在操作中的会话,防止双击/并发把同一个会话删两遍。 */
75
146
  const inFlight = new Set();
147
+ /** 上一次启动对账的结论(内存里一份,磁盘上另有审计)。 @type {any} */
148
+ let lastRecovery = null;
149
+ /** @type {Promise<any> | null} */
150
+ let recoveryInFlight = null;
151
+
152
+ /**
153
+ * 写审计。失败只降级成 logger 告警,绝不静默——但也不让审计故障阻断删除。
154
+ * @param {any} entry
155
+ */
156
+ async function note(entry) {
157
+ const result = await audit.append(entry);
158
+ if (!result.ok) logger.warn(`session-delete: audit append failed: ${result.error}`);
159
+ return result;
160
+ }
161
+
162
+ const recovery = createRecovery({
163
+ dataRoot,
164
+ refs,
165
+ logger,
166
+ audit,
167
+ reconcile: (/** @type {string} */ sessionId, /** @type {any} */ options) =>
168
+ reconcile(sessionId, options),
169
+ });
76
170
 
77
171
  /**
78
172
  * 收集一份完整事实并生成 Plan。
79
173
  * @param {unknown} sessionIdRaw
80
174
  */
81
- async function makePlan(sessionIdRaw) {
175
+ /**
176
+ * @param {unknown} sessionIdRaw
177
+ * @param {{ all?: unknown[] }} [options] all = 预加载的 persistence.list()(工作区批量复用)
178
+ */
179
+ async function makePlan(sessionIdRaw, options = {}) {
180
+ refreshHost();
82
181
  const sessionId = requireSessionId(sessionIdRaw);
83
182
  /** @type {string[]} */
84
183
  const notes = [];
@@ -117,7 +216,8 @@ export function createOperations({ ctx, dataRoot, logger }) {
117
216
  });
118
217
  if (caps.checks["persistence.list"] && caps.services.persistence?.list) {
119
218
  try {
120
- const all = (await caps.services.persistence.list()) ?? [];
219
+ // 工作区批量会把同一个列表复用给每个会话,否则 N 个会话要拉 N 次全量列表。
220
+ const all = options.all ?? (await caps.services.persistence.list()) ?? [];
121
221
  /** @type {Map<string, { id: string, title: string | null }[]>} */
122
222
  const byParent = new Map();
123
223
  for (const entry of all) {
@@ -208,26 +308,21 @@ export function createOperations({ ctx, dataRoot, logger }) {
208
308
  }
209
309
 
210
310
  /**
211
- * 移走之后复查一次原路径;目录若被迟到写入重建,就再移一次并记审计。
212
- * @param {string} sessionId
311
+ * 移走之后复查一次原路径;目录若被迟到的写入重建,就**真的**再移一次(AUD-SD-07)。
312
+ * 只查一次、不循环:活句柄若持续写盘,由「未完成的操作」与体检暴露,而不是互相对抗。
313
+ * @param {import("./plan.js").Plan} plan
213
314
  * @param {string} originalPath
315
+ * @param {string} entryId 本次生成的回收站条目;它被 restore/purge 后守卫必须放手(B2)。
214
316
  */
215
- function scheduleReviveCheck(sessionId, originalPath) {
317
+ function scheduleReviveCheck(plan, originalPath, entryId) {
216
318
  const timer = setTimeout(async () => {
217
319
  try {
218
- const { stat } = await import("node:fs/promises");
219
- const exists = await stat(originalPath)
220
- .then(() => true)
221
- .catch(() => false);
222
- if (!exists) return;
223
- await audit.append({
224
- action: "trash",
225
- result: "ok",
226
- sessionId,
227
- operator: "system",
228
- detail: "会话目录在移走后被重建,已记录(复活守卫)",
320
+ await recovery.reviveGuard({
321
+ sessionId: plan.sessionId,
322
+ originalPath,
323
+ entryId,
324
+ meta: { title: plan.title, cwd: plan.cwd },
229
325
  });
230
- logger.warn(`session-delete: session ${sessionId} was recreated after deletion`);
231
326
  } catch (error) {
232
327
  logger.warn(`session-delete: revive check failed: ${messageOf(error)}`);
233
328
  }
@@ -237,12 +332,34 @@ export function createOperations({ ctx, dataRoot, logger }) {
237
332
 
238
333
  /**
239
334
  * @param {string} sessionIdRaw
240
- * @param {{ digest?: string, title?: string | null, operator?: string, cascade?: boolean, child?: boolean }} request
335
+ * @param {{ digest?: string, title?: string | null, operator?: string, cascade?: boolean, child?: boolean,
336
+ * all?: unknown[] }} request all = 预加载的 persistence.list()(工作区批量复用)
241
337
  */
242
338
  async function trash(sessionIdRaw, request = {}) {
243
- const loaded = await makePlan(sessionIdRaw);
339
+ refreshHost();
340
+ const operator = request.operator ?? "ui";
341
+ /** @type {Awaited<ReturnType<typeof makePlan>>} */
342
+ let loaded;
343
+ try {
344
+ loaded = await makePlan(sessionIdRaw, { all: request.all });
345
+ } catch (error) {
346
+ // AUD-SD-04:plan 阶段的拒绝(not-found / invalid-id)同样是拒绝,必须进审计,
347
+ // 否则「一次拒绝都没有记录过」的取证缺口会一直在。
348
+ const code = /** @type {any} */ (error)?.code;
349
+ if (code === "session/not-found" || code === "session-delete/invalid-id") {
350
+ await note({ action: "trash", result: "refused", operator, detail: `plan:${code}` });
351
+ }
352
+ throw error;
353
+ }
244
354
  const { plan, location, header } = loaded;
245
355
  if (request.digest && request.digest !== plan.digest) {
356
+ await note({
357
+ action: "trash",
358
+ result: "refused",
359
+ sessionId: plan.sessionId,
360
+ operator,
361
+ detail: "stale-plan:会话状态在确认期间发生变化",
362
+ });
246
363
  throw failure(
247
364
  "session-delete/stale-plan",
248
365
  "会话状态在确认期间发生了变化,请重新查看影响面。",
@@ -253,11 +370,11 @@ export function createOperations({ ctx, dataRoot, logger }) {
253
370
  );
254
371
  }
255
372
  if (!planExecutable(plan)) {
256
- await audit.append({
373
+ await note({
257
374
  action: "trash",
258
375
  result: "refused",
259
376
  sessionId: plan.sessionId,
260
- operator: request.operator ?? "ui",
377
+ operator,
261
378
  detail: plan.blockers.map((b) => b.code).join(","),
262
379
  });
263
380
  throw failure("session-delete/blocked", plan.blockers[0].message, {
@@ -272,7 +389,7 @@ export function createOperations({ ctx, dataRoot, logger }) {
272
389
  if (request.cascade === true && request.child !== true) {
273
390
  for (const child of plan.children) {
274
391
  try {
275
- const result = await trash(child.id, { operator: request.operator, child: true });
392
+ const result = await trash(child.id, { operator, child: true });
276
393
  cascaded.push({ id: child.id, ok: true, entryId: result.entryId });
277
394
  } catch (error) {
278
395
  cascaded.push({ id: child.id, ok: false, error: messageOf(error) });
@@ -288,37 +405,33 @@ export function createOperations({ ctx, dataRoot, logger }) {
288
405
  const record = await beginOperation({
289
406
  dataRoot,
290
407
  action: "trash",
291
- extra: { sessionId: plan.sessionId, digest: plan.digest, operator: request.operator ?? "ui" },
408
+ extra: { sessionId: plan.sessionId, digest: plan.digest, operator },
292
409
  });
293
410
 
294
411
  let moved = false;
295
412
  let entryId = "";
413
+ /** @type {{ id: string, label: string, status: string, detail?: string }[]} */
414
+ let removed = [];
296
415
  try {
297
- // 1. 先归档:归档集合就是 provider 的 agent/pre-step 闸门。
416
+ // 1. 先记录引用状态,供恢复时还原 —— **必须早于归档**:
417
+ // 宿主归档会在同一次写里清掉 pin(docs/runtime/0.2.1-rc.5 §6),
418
+ // 归档后再读 storages/workspace.json 只能读到「未置顶」。
419
+ const snapshots = await snapshotAllRefs(refs, plan.sessionId, logger);
420
+ const pinned = snapshots["workspace-pin"]?.pinned;
421
+
422
+ // 2. 归档:归档集合就是 provider 的 agent/pre-step 闸门。
298
423
  if (caps.checks["workspace.archive"]) {
299
424
  await caps.services.workspace.archiveSession(plan.sessionId, { stopActivity: true });
300
425
  }
301
- // 2. 官方停止通道(跑着的轮次、子代理、后台任务、提醒)。
426
+ // 3. 官方停止通道(跑着的轮次、子代理、后台任务、提醒)。
302
427
  if (caps.checks["event.session-stop"]) {
303
428
  await ctx.parallel("workspace/session-stop", { sessionId: plan.sessionId });
304
429
  }
305
- // 3. 落盘并等写入稳定。
430
+ // 4. 落盘并等写入稳定。
306
431
  const live = caps.services.sessions?.get?.(plan.sessionId);
307
432
  if (live && caps.checks["sessions.flush"]) await caps.services.sessions.flush(live);
308
433
  await delayMs(SETTLE_MS);
309
434
 
310
- // 4. 记录引用状态,供恢复时还原。
311
- /** @type {Record<string, any>} */
312
- const snapshots = {};
313
- for (const ref of refs) {
314
- if (typeof ref.snapshot !== "function") continue;
315
- try {
316
- snapshots[ref.id] = await ref.snapshot(plan.sessionId);
317
- } catch (error) {
318
- logger.warn(`session-delete: snapshot ${ref.id} failed: ${messageOf(error)}`);
319
- }
320
- }
321
-
322
435
  // 5. 移入回收站(原子 rename)。
323
436
  const movedResult = await moveIntoTrash({
324
437
  dataRoot,
@@ -333,48 +446,29 @@ export function createOperations({ ctx, dataRoot, logger }) {
333
446
  live: plan.live,
334
447
  children: plan.children,
335
448
  workspaceIds: snapshots["workspace-slot"]?.workspaceIds ?? [],
336
- pinned: null,
449
+ pinned: typeof pinned === "boolean" ? pinned : null,
337
450
  },
338
451
  });
339
452
  moved = true;
340
453
  entryId = movedResult.entryId;
454
+ // AUD-SD-01/03:把 entryId 记进 journal —— 崩溃后启动对账能精确知道是哪一条,
455
+ // 已移动但收尾失败的路径也能写出带 entryId 的 partial 回执。
456
+ await updateOperation(dataRoot, record.id, { entryId });
341
457
 
342
458
  // 6. 摘掉所有还指向它的引用。
343
- /** @type {{ id: string, label: string, status: string, detail?: string }[]} */
344
- const removed = [];
345
- for (const ref of refs) {
346
- if (typeof ref.remove !== "function" || ref.tier === "unknown") {
347
- removed.push({
348
- id: ref.id,
349
- label: ref.label,
350
- status: "skipped",
351
- detail: "当前宿主不提供该接口",
352
- });
353
- continue;
354
- }
355
- try {
356
- await ref.remove(plan.sessionId, snapshots[ref.id] ?? {});
357
- removed.push({ id: ref.id, label: ref.label, status: "ok" });
358
- } catch (error) {
359
- removed.push({
360
- id: ref.id,
361
- label: ref.label,
362
- status: "failed",
363
- detail: messageOf(error),
364
- });
365
- }
366
- }
459
+ removed = await removeAllRefs(refs, plan.sessionId, snapshots);
367
460
 
368
461
  // 7. 复活复查 + 对账回执。
369
- scheduleReviveCheck(plan.sessionId, location.path);
462
+ // 把本次 entryId 交给守卫:它被 restore/purge 之后就不该再移(B2)。
463
+ scheduleReviveCheck(plan, location.path, entryId);
370
464
  const checks = await reconcile(plan.sessionId, { skipDirCheck: true });
371
465
  await finishOperation({ dataRoot, id: record.id, state: "done" });
372
- await audit.append({
466
+ await note({
373
467
  action: "trash",
374
468
  result: "ok",
375
469
  sessionId: plan.sessionId,
376
470
  entryId,
377
- operator: request.operator ?? "ui",
471
+ operator,
378
472
  detail: summarizePlan(plan),
379
473
  });
380
474
  const receiptId = await writeReceipt(dataRoot, {
@@ -408,21 +502,86 @@ export function createOperations({ ctx, dataRoot, logger }) {
408
502
  try {
409
503
  await caps.services.workspace?.unarchiveSession?.(plan.sessionId);
410
504
  } catch {
411
- // 尽力而为。
505
+ // 尽力而为:回滚归档闸门失败不改变「会话没动过」的事实。
412
506
  }
507
+ try {
508
+ await finishOperation({
509
+ dataRoot,
510
+ id: record.id,
511
+ state: "failed",
512
+ detail: messageOf(error),
513
+ });
514
+ } catch (journalError) {
515
+ logger.warn(`session-delete: finishOperation failed: ${messageOf(journalError)}`);
516
+ }
517
+ await note({
518
+ action: "trash",
519
+ result: "failed",
520
+ sessionId: plan.sessionId,
521
+ operator,
522
+ detail: messageOf(error),
523
+ });
524
+ throw failure("session-delete/failed", `删除失败:${messageOf(error)}`, {
525
+ partial: false,
526
+ entryId: null,
527
+ });
528
+ }
529
+ // AUD-SD-03:已移动但收尾失败。磁盘事实是「会话已在回收站」,所以:
530
+ // 审计写明「已进入回收站」,回执标 partial,错误码也单独区分——用户重试会拿到
531
+ // not-found,必须能在回执里看到到底哪一步没做完。
532
+ // 收尾本身也可能坏(例如 journal 目录不可写):每一步都单独兜住,
533
+ // 否则「二次异常」会把真正的 partial 结论和回执一起吞掉。
534
+ try {
535
+ await finishOperation({
536
+ dataRoot,
537
+ id: record.id,
538
+ state: "failed",
539
+ detail: `已移动但收尾失败:${messageOf(error)}`,
540
+ });
541
+ } catch (journalError) {
542
+ logger.warn(`session-delete: partial finishOperation failed: ${messageOf(journalError)}`);
543
+ }
544
+ const checks = await reconcile(plan.sessionId, { skipDirCheck: true }).catch(
545
+ (/** @type {unknown} */ reconcileError) => [
546
+ {
547
+ id: "reconcile",
548
+ label: "对账",
549
+ status: "skipped",
550
+ detail: `对账失败:${messageOf(reconcileError)}`,
551
+ },
552
+ ],
553
+ );
554
+ /** @type {string | undefined} */
555
+ let receiptId;
556
+ try {
557
+ receiptId = await writeReceipt(dataRoot, {
558
+ action: "trash",
559
+ at: new Date().toISOString(),
560
+ sessionId: plan.sessionId,
561
+ entryId,
562
+ title: plan.title,
563
+ sizeBytes: plan.sizeBytes,
564
+ partial: true,
565
+ removed,
566
+ checks,
567
+ });
568
+ } catch (receiptError) {
569
+ logger.warn(`session-delete: partial receipt failed: ${messageOf(receiptError)}`);
413
570
  }
414
- await finishOperation({ dataRoot, id: record.id, state: "failed", detail: messageOf(error) });
415
- await audit.append({
571
+ const cleaned = removed.filter((item) => item.status === "ok").length;
572
+ await note({
416
573
  action: "trash",
417
574
  result: "failed",
418
575
  sessionId: plan.sessionId,
419
- operator: request.operator ?? "ui",
420
- detail: messageOf(error),
421
- });
422
- throw failure("session-delete/failed", `删除失败:${messageOf(error)}`, {
423
- partial: moved,
424
- entryId: moved ? entryId : null,
576
+ entryId,
577
+ operator,
578
+ detail: `已移入回收站(${entryId}),引用清理 ${cleaned}/${removed.length} 项后收尾失败:${messageOf(error)}`,
425
579
  });
580
+ throw failure(
581
+ "session-delete/partial",
582
+ `会话已移入回收站,但收尾未完成:${messageOf(error)}`,
583
+ { partial: true, entryId, receiptId: receiptId ?? null, removed, checks },
584
+ );
426
585
  } finally {
427
586
  inFlight.delete(plan.sessionId);
428
587
  }
@@ -430,10 +589,12 @@ export function createOperations({ ctx, dataRoot, logger }) {
430
589
 
431
590
  /** @param {number} [limit] */
432
591
  async function auditLog(limit = 100) {
592
+ refreshHost();
433
593
  return { path: auditPath(dataRoot), entries: await audit.read(limit) };
434
594
  }
435
595
 
436
596
  async function list() {
597
+ refreshHost();
437
598
  const listed = await listEntries(dataRoot);
438
599
  const pending = await listPending(dataRoot);
439
600
  return {
@@ -448,42 +609,79 @@ export function createOperations({ ctx, dataRoot, logger }) {
448
609
  };
449
610
  }
450
611
 
612
+ /**
613
+ * 恢复删除前的引用快照(只含有恢复动作的引用)。
614
+ * 条目 meta 在最终化时随条目一起删除,所以重检要用回执里留存的那一份。
615
+ * @param {import("./trash.js").TrashMeta} meta
616
+ * @returns {{ workspaceIds: string[], pinned: boolean | null }}
617
+ */
618
+ function restoredSnapshotOf(meta) {
619
+ return {
620
+ workspaceIds: Array.isArray(meta.workspaceIds) ? meta.workspaceIds : [],
621
+ pinned: typeof meta.pinned === "boolean" ? meta.pinned : null,
622
+ };
623
+ }
624
+
625
+ /**
626
+ * 引用恢复 + 自动重试一次(USIM-U3-02)。
627
+ *
628
+ * 为什么重试:失败大多是「宿主刚挂上/写入还在路上」这类瞬时状态,重试一次很便宜;
629
+ * 重试仍然失败的才进回执与界面,并且带上**具体引用名 + 下一步动作**。
630
+ * @param {import("./refs.js").RefSnapshot} snapshot
631
+ * @param {string} sessionId
632
+ */
633
+ async function restoreRefsWithRetry(snapshot, sessionId) {
634
+ refreshHost();
635
+ const first = await restoreAllRefs(refs, sessionId, snapshot);
636
+ const failed = first.filter((item) => item.status === "failed");
637
+ if (failed.length === 0) return first;
638
+ await delayMs(120);
639
+ refreshHost();
640
+ const retried = await restoreAllRefs(refs, sessionId, snapshot, {
641
+ onlyIds: failed.map((item) => item.id),
642
+ retried: true,
643
+ });
644
+ const byId = new Map(retried.map((item) => [item.id, item]));
645
+ return first.map((item) => byId.get(item.id) ?? item);
646
+ }
647
+
451
648
  /**
452
649
  * @param {string} entryId
453
650
  * @param {{ operator?: string }} [request]
454
651
  */
455
652
  async function restore(entryId, request = {}) {
653
+ refreshHost();
456
654
  const meta = await readEntry(dataRoot, entryId);
655
+ const operator = request.operator ?? "ui";
457
656
  const record = await beginOperation({
458
657
  dataRoot,
459
658
  action: "restore",
460
- extra: { sessionId: meta.sessionId, entryId },
659
+ extra: { sessionId: meta.sessionId, entryId, operator },
461
660
  });
462
661
  try {
463
662
  const restored = await restoreEntry({ dataRoot, entryId });
464
- try {
465
- await caps.services.workspace?.unarchiveSession?.(meta.sessionId);
466
- } catch {
467
- // 恢复失败不阻断:文件已经回去了。
468
- }
469
- for (const ref of refs) {
470
- if (typeof ref.restore !== "function") continue;
471
- try {
472
- await ref.restore(meta.sessionId, {
473
- workspaceIds: meta.workspaceIds,
474
- pinned: meta.pinned,
475
- });
476
- } catch (error) {
477
- logger.warn(`session-delete: restore ${ref.id} failed: ${messageOf(error)}`);
478
- }
479
- }
663
+ // 引用恢复逐项记录:文件回来了只是「会话可用」,归属/置顶回来才算「恢复完整」。
664
+ // 单项失败不再静默 —— 进回执、进 checks、进界面(AUD-SD-02)。
665
+ const snapshot = restoredSnapshotOf(meta);
666
+ const refResults = await restoreRefsWithRetry(snapshot, meta.sessionId);
667
+ const checks = await verifyRestored({
668
+ refs,
669
+ sessionId: meta.sessionId,
670
+ restoredTo: restored.restoredTo,
671
+ meta,
672
+ });
673
+ const summary = restoreSummary(refResults, checks);
480
674
  await finishOperation({ dataRoot, id: record.id, state: "done" });
481
- await audit.append({
675
+ await note({
482
676
  action: "restore",
483
677
  result: "ok",
484
678
  sessionId: meta.sessionId,
485
679
  entryId,
486
- operator: request.operator ?? "ui",
680
+ operator,
681
+ title: meta.title ?? null,
682
+ // 审计要能回答「到底是哪一处没通过」(USIM-U3-05):计数不够,写清单。
683
+ detail: describeRestoreSummary(summary),
684
+ failures: summary.failures,
487
685
  });
488
686
  const receiptId = await writeReceipt(dataRoot, {
489
687
  action: "restore",
@@ -492,27 +690,156 @@ export function createOperations({ ctx, dataRoot, logger }) {
492
690
  entryId,
493
691
  title: meta.title,
494
692
  restoredTo: restored.restoredTo,
693
+ // 删除时它是否正在宿主里打开:界面据此提示「仍被标记为忙碌」的下一步。
694
+ wasLive: meta.live === true,
695
+ refs: refResults,
696
+ checks,
697
+ partial: summary.partial,
698
+ // 重检要用的删除前快照:条目已经没了,回执是唯一副本。
699
+ expected: snapshot,
700
+ failures: summary.failures,
495
701
  });
496
- return { ok: true, sessionId: meta.sessionId, restoredTo: restored.restoredTo, receiptId };
702
+ return {
703
+ ok: true,
704
+ sessionId: meta.sessionId,
705
+ title: meta.title ?? null,
706
+ restoredTo: restored.restoredTo,
707
+ wasLive: meta.live === true,
708
+ receiptId,
709
+ refs: refResults,
710
+ checks,
711
+ partial: summary.partial,
712
+ failedRefs: summary.failedRefs,
713
+ failedChecks: summary.failedChecks,
714
+ failures: summary.failures,
715
+ };
497
716
  } catch (error) {
498
- await finishOperation({ dataRoot, id: record.id, state: "failed", detail: messageOf(error) });
499
- await audit.append({
717
+ try {
718
+ await finishOperation({
719
+ dataRoot,
720
+ id: record.id,
721
+ state: "failed",
722
+ detail: messageOf(error),
723
+ });
724
+ } catch (journalError) {
725
+ logger.warn(`session-delete: finishOperation failed: ${messageOf(journalError)}`);
726
+ }
727
+ await note({
500
728
  action: "restore",
501
729
  result: "failed",
502
730
  sessionId: meta.sessionId,
503
731
  entryId,
504
- operator: request.operator ?? "ui",
732
+ operator,
505
733
  detail: messageOf(error),
506
734
  });
507
735
  throw failure("session-delete/restore-failed", `恢复失败:${messageOf(error)}`);
508
736
  }
509
737
  }
510
738
 
739
+ /**
740
+ * 重检一次已完成的恢复(USIM-U3-05 的「可操作」出口):用最近一条 restore 回执里
741
+ * 留存的 `expected` 快照重放引用恢复与校验。失败项仍然失败就照实返回,不伪造成功。
742
+ * @param {{ sessionId?: string, receiptId?: string }} [request]
743
+ */
744
+ async function recheckRestore(request = {}) {
745
+ refreshHost();
746
+ const listed = await listReceipts(dataRoot, 200);
747
+ const candidates = listed.filter(
748
+ (item) => item?.action === "restore" || item?.action === "restore-recheck",
749
+ );
750
+ /** @type {any} */
751
+ let target = null;
752
+ if (typeof request.receiptId === "string" && request.receiptId.length > 0) {
753
+ target = candidates.find((item) => item.id === request.receiptId) ?? null;
754
+ } else if (typeof request.sessionId === "string" && request.sessionId.length > 0) {
755
+ target = candidates.find((item) => item.sessionId === request.sessionId) ?? null;
756
+ }
757
+ if (!target) {
758
+ throw failure(
759
+ "session-delete/not-found",
760
+ "没有找到这次恢复的回执,无法重检(回执可能已被清理)。",
761
+ );
762
+ }
763
+ const sessionId = requireSessionId(target.sessionId);
764
+ // B1(复审):旧版本写的 restore 回执没有 `expected` 快照。用空快照重放会让
765
+ // `workspace-slot` 以「原本不在任何工作区」返回 ok、校验也只给 skipped,
766
+ // 于是「重检通过」变成假绿(正是本批要消灭的「不伪造成功」)。宁可拒绝:
767
+ // 没有依据就不假装重检成功,让用户按回执里的提示手动处理。
768
+ if (!target.expected || typeof target.expected !== "object") {
769
+ throw failure(
770
+ "session-delete/receipt-legacy",
771
+ "这条回执是旧版本写的,没有留存恢复前的引用快照,不能自动重检;" +
772
+ "请按回执里的提示手动把会话挂回工作区(会话右键菜单「归属到项目…」)。",
773
+ );
774
+ }
775
+ // N13(复审):快照可能是很久以前留下的。会话目录已经不在时,重放
776
+ // attachSession/pinSession/unarchiveSession 只会对一个不可用的现场做写操作。
777
+ const restoredTo = typeof target.restoredTo === "string" ? target.restoredTo : "";
778
+ const dirOk = await stat(restoredTo)
779
+ .then((value) => value.isDirectory())
780
+ .catch(() => false);
781
+ if (!dirOk) {
782
+ throw failure(
783
+ "session-delete/receipt-stale",
784
+ `回执里记录的会话目录已不存在(${restoredTo || "未知路径"}),` +
785
+ "会话可能又被删除/移动过;请重新确认回收站状态,不要按旧快照重检。",
786
+ );
787
+ }
788
+ /** @type {{ workspaceIds: string[], pinned: boolean | null }} */
789
+ const expected = {
790
+ workspaceIds: Array.isArray(target.expected.workspaceIds)
791
+ ? target.expected.workspaceIds.map(String)
792
+ : [],
793
+ pinned: typeof target.expected.pinned === "boolean" ? target.expected.pinned : null,
794
+ };
795
+ const refResults = await restoreRefsWithRetry(expected, sessionId);
796
+ const checks = await verifyRestored({
797
+ refs,
798
+ sessionId,
799
+ restoredTo: String(target.restoredTo ?? ""),
800
+ meta: expected,
801
+ });
802
+ const summary = restoreSummary(refResults, checks);
803
+ await note({
804
+ action: "restore-recheck",
805
+ result: "ok",
806
+ sessionId,
807
+ operator: "ui",
808
+ title: target.title ?? null,
809
+ detail: describeRestoreSummary(summary),
810
+ failures: summary.failures,
811
+ });
812
+ const receiptId = await writeReceipt(dataRoot, {
813
+ action: "restore-recheck",
814
+ at: new Date().toISOString(),
815
+ sessionId,
816
+ title: target.title ?? null,
817
+ restoredTo: target.restoredTo ?? null,
818
+ refs: refResults,
819
+ checks,
820
+ partial: summary.partial,
821
+ expected,
822
+ failures: summary.failures,
823
+ });
824
+ return {
825
+ ok: !summary.partial,
826
+ sessionId,
827
+ receiptId,
828
+ refs: refResults,
829
+ checks,
830
+ partial: summary.partial,
831
+ failedRefs: summary.failedRefs,
832
+ failedChecks: summary.failedChecks,
833
+ failures: summary.failures,
834
+ };
835
+ }
836
+
511
837
  /**
512
838
  * @param {string} entryId
513
839
  * @param {{ operator?: string }} [request]
514
840
  */
515
841
  async function purge(entryId, request = {}) {
842
+ refreshHost();
516
843
  const meta = await readEntry(dataRoot, entryId);
517
844
  const record = await beginOperation({
518
845
  dataRoot,
@@ -522,7 +849,7 @@ export function createOperations({ ctx, dataRoot, logger }) {
522
849
  try {
523
850
  const result = await purgeEntry({ dataRoot, entryId });
524
851
  await finishOperation({ dataRoot, id: record.id, state: "done" });
525
- await audit.append({
852
+ await note({
526
853
  action: "purge",
527
854
  result: "ok",
528
855
  entryId,
@@ -539,8 +866,17 @@ export function createOperations({ ctx, dataRoot, logger }) {
539
866
  });
540
867
  return { ok: true, bytes: result.bytes, sessionId: meta.sessionId, receiptId };
541
868
  } catch (error) {
542
- await finishOperation({ dataRoot, id: record.id, state: "failed", detail: messageOf(error) });
543
- await audit.append({
869
+ try {
870
+ await finishOperation({
871
+ dataRoot,
872
+ id: record.id,
873
+ state: "failed",
874
+ detail: messageOf(error),
875
+ });
876
+ } catch (journalError) {
877
+ logger.warn(`session-delete: finishOperation failed: ${messageOf(journalError)}`);
878
+ }
879
+ await note({
544
880
  action: "purge",
545
881
  result: "failed",
546
882
  entryId,
@@ -557,6 +893,7 @@ export function createOperations({ ctx, dataRoot, logger }) {
557
893
  * @param {{ skipDirCheck?: boolean }} [options]
558
894
  */
559
895
  async function reconcile(sessionIdRaw, options = {}) {
896
+ refreshHost();
560
897
  const sessionId = requireSessionId(sessionIdRaw);
561
898
  /** @type {{ id: string, label: string, status: "ok" | "failed" | "skipped", detail: string }[]} */
562
899
  const checks = [];
@@ -593,46 +930,11 @@ export function createOperations({ ctx, dataRoot, logger }) {
593
930
  return checks;
594
931
  }
595
932
 
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
933
  /**
633
934
  * 全库体检:找出指向已不存在会话的登记条目。只读,不修改任何东西。
634
935
  */
635
936
  async function scanHealth() {
937
+ refreshHost();
636
938
  if (!caps.checks["persistence.list"]) {
637
939
  return {
638
940
  ok: false,
@@ -655,7 +957,7 @@ export function createOperations({ ctx, dataRoot, logger }) {
655
957
  }
656
958
  const known = new Set([...storedIds, ...liveIds]);
657
959
 
658
- const state = await readWorkspaceState();
960
+ const state = await readWorkspaceState(dataRoot);
659
961
  /** @type {{ id: string, label: string, severity: "warn" | "info", items: any[] }[]} */
660
962
  const findings = [];
661
963
  /** @type {{ archived: string[], pinned: string[], workspace: { workspaceId: string, sessionId: string }[] }} */
@@ -760,7 +1062,7 @@ export function createOperations({ ctx, dataRoot, logger }) {
760
1062
  if (pending.length > 0) {
761
1063
  findings.push({
762
1064
  id: "pending-operation",
763
- label: "未完成的操作(重启后自愈)",
1065
+ label: "未完成的操作(重启后自动对账;仍未处理需人工核对)",
764
1066
  severity: "info",
765
1067
  items: pending.map((record) => record.id),
766
1068
  });
@@ -793,13 +1095,14 @@ export function createOperations({ ctx, dataRoot, logger }) {
793
1095
  * @param {{ classes?: string[], operator?: string }} [request]
794
1096
  */
795
1097
  async function cleanHealth(request = {}) {
1098
+ refreshHost();
796
1099
  const classes = Array.isArray(request.classes)
797
1100
  ? request.classes
798
1101
  : ["archived", "pinned", "workspace"];
799
1102
  const scan = await scanHealth();
800
1103
  if (!scan.ok)
801
1104
  throw failure("session-delete/health-unavailable", `无法体检:${scan.reason ?? "未知原因"}`);
802
- const state = await readWorkspaceState();
1105
+ const state = await readWorkspaceState(dataRoot);
803
1106
  const counts = { archived: 0, pinned: 0, workspace: 0 };
804
1107
  /** @type {string[]} */
805
1108
  const errors = [];
@@ -843,7 +1146,7 @@ export function createOperations({ ctx, dataRoot, logger }) {
843
1146
  }
844
1147
  }
845
1148
  const total = counts.archived + counts.pinned + counts.workspace;
846
- await audit.append({
1149
+ await note({
847
1150
  action: "health",
848
1151
  result: errors.length > 0 ? "failed" : "ok",
849
1152
  operator: request.operator ?? "ui",
@@ -859,7 +1162,26 @@ export function createOperations({ ctx, dataRoot, logger }) {
859
1162
  return { ok: errors.length === 0, cleaned: counts, total, errors, receiptId };
860
1163
  }
861
1164
 
1165
+ /**
1166
+ * 读取界面偏好(目前只有确认框里「同时删除子会话」的初值)。
1167
+ * 坏文件/坏字段由 preferences.js 统一回落默认值,这里不抛。
1168
+ * @returns {Promise<{ version: number, cascadeChildren: boolean }>}
1169
+ */
1170
+ async function getPrefs() {
1171
+ return readPreferences(dataRoot, logger);
1172
+ }
1173
+
1174
+ /**
1175
+ * 合并写入界面偏好。
1176
+ * @param {Record<string, unknown>} patch
1177
+ * @returns {Promise<{ version: number, cascadeChildren: boolean }>}
1178
+ */
1179
+ async function setPrefs(patch = {}) {
1180
+ return writePreferences(dataRoot, patch, logger);
1181
+ }
1182
+
862
1183
  async function health() {
1184
+ refreshHost();
863
1185
  const pending = await listPending(dataRoot);
864
1186
  return {
865
1187
  plugin: pkg.name,
@@ -869,10 +1191,56 @@ export function createOperations({ ctx, dataRoot, logger }) {
869
1191
  trashRoot: trashRoot(dataRoot),
870
1192
  capabilities: describeCapabilities(caps),
871
1193
  pending: pending.length,
1194
+ // 启动对账的结论(本轮进程内),磁盘上另有 recover 审计可查。
1195
+ lastRecovery,
872
1196
  readOnly: caps.tier === "unknown",
873
1197
  };
874
1198
  }
875
1199
 
1200
+ /**
1201
+ * 启动对账(AUD-SD-01):扫 journal 的未完成记录,按落盘事实补做或回滚。
1202
+ * 幂等,可重复调用;并发调用共用同一次(宿主服务重建时 ctx.inject 会重复触发)。
1203
+ * @param {{ operator?: string }} [options]
1204
+ */
1205
+ async function recoverPending(options = {}) {
1206
+ refreshHost();
1207
+ if (recoveryInFlight) return recoveryInFlight;
1208
+ const job = recovery
1209
+ .recoverPending({ operator: options.operator ?? "system" })
1210
+ .then((summary) => {
1211
+ lastRecovery = summary;
1212
+ if (summary.examined > 0) {
1213
+ logger.info(
1214
+ `session-delete: startup recovery examined ${summary.examined} record(s): ` +
1215
+ `${summary.completed} completed / ${summary.rolledBack} rolled back / ` +
1216
+ `${summary.unresolved} unresolved / ${summary.failed} failed`,
1217
+ );
1218
+ }
1219
+ return summary;
1220
+ })
1221
+ .finally(() => {
1222
+ recoveryInFlight = null;
1223
+ });
1224
+ recoveryInFlight = job;
1225
+ return job;
1226
+ }
1227
+
1228
+ /**
1229
+ * 记录一次「拒绝」(AUD-SD-04)。模型工具的 token/stale-plan 拒绝同样要留痕,
1230
+ * 否则审计里会出现「20 天 0 条 refused」这种取证缺口。
1231
+ * @param {{ sessionId?: string, code?: string, operator?: string, action?: string }} event
1232
+ */
1233
+ async function recordRefusal(event = {}) {
1234
+ const result = await note({
1235
+ action: event.action ?? "trash",
1236
+ result: "refused",
1237
+ sessionId: typeof event.sessionId === "string" ? event.sessionId : undefined,
1238
+ operator: event.operator ?? "agent",
1239
+ detail: event.code ?? "refused",
1240
+ });
1241
+ return { ok: result.ok };
1242
+ }
1243
+
876
1244
  /**
877
1245
  * 批量恢复回收站条目。
878
1246
  * @param {{ entryIds?: string[], operator?: string }} request
@@ -880,13 +1248,24 @@ export function createOperations({ ctx, dataRoot, logger }) {
880
1248
  async function restoreMany(request = {}) {
881
1249
  const ids = Array.isArray(request.entryIds) ? request.entryIds : [];
882
1250
  if (ids.length === 0) throw failure("session-delete/invalid-request", "没有选择任何条目");
883
- if (ids.length > 50) throw failure("session-delete/invalid-request", "一次最多 50 条");
884
- /** @type {{ entryId: string, ok: boolean, sessionId?: string, error?: string }[]} */
1251
+ if (ids.length > MAX_BATCH_IDS) {
1252
+ throw failure(
1253
+ "session-delete/invalid-request",
1254
+ `一次最多 ${MAX_BATCH_IDS} 条(界面会自动分批)`,
1255
+ );
1256
+ }
1257
+ /** @type {{ entryId: string, ok: boolean, sessionId?: string, partial?: boolean, error?: string }[]} */
885
1258
  const results = [];
886
1259
  for (const entryId of ids) {
887
1260
  try {
888
1261
  const result = await restore(entryId, { operator: request.operator ?? "ui" });
889
- results.push({ entryId, ok: true, sessionId: result.sessionId });
1262
+ // partial 也要带出去:批量行要能说「其中 N 条引用没还原」。
1263
+ results.push({
1264
+ entryId,
1265
+ ok: true,
1266
+ sessionId: result.sessionId,
1267
+ partial: result.partial === true,
1268
+ });
890
1269
  } catch (error) {
891
1270
  results.push({ entryId, ok: false, error: messageOf(error) });
892
1271
  }
@@ -902,7 +1281,12 @@ export function createOperations({ ctx, dataRoot, logger }) {
902
1281
  async function purgeMany(request = {}) {
903
1282
  const ids = Array.isArray(request.entryIds) ? request.entryIds : [];
904
1283
  if (ids.length === 0) throw failure("session-delete/invalid-request", "没有选择任何条目");
905
- if (ids.length > 50) throw failure("session-delete/invalid-request", "一次最多 50 条");
1284
+ if (ids.length > MAX_BATCH_IDS) {
1285
+ throw failure(
1286
+ "session-delete/invalid-request",
1287
+ `一次最多 ${MAX_BATCH_IDS} 条(界面会自动分批)`,
1288
+ );
1289
+ }
906
1290
  /** @type {{ entryId: string, ok: boolean, bytes?: number, error?: string }[]} */
907
1291
  const results = [];
908
1292
  for (const entryId of ids) {
@@ -917,13 +1301,197 @@ export function createOperations({ ctx, dataRoot, logger }) {
917
1301
  return { ok: okCount === results.length, total: results.length, succeeded: okCount, results };
918
1302
  }
919
1303
 
1304
+ /**
1305
+ * 工作区记账里的成员会话。侧栏的工作区分组就是这份清单一族(组内 = 这些 id 里
1306
+ * 还能在会话列表里找到的那些),所以「删这个工作区的会话」= 这里返回的 id。
1307
+ * 优先读 host workspaceRegistry(活状态);没有该服务时回落到 workspace.json(只读兜底)。
1308
+ * @param {unknown} workspaceIdRaw
1309
+ * @returns {Promise<{ workspaceId: string, title: string | null, sessionIds: string[] }>}
1310
+ */
1311
+ async function workspaceMembers(workspaceIdRaw) {
1312
+ const workspaceId = typeof workspaceIdRaw === "string" ? workspaceIdRaw.trim() : "";
1313
+ if (workspaceId.length === 0) {
1314
+ throw failure("session-delete/invalid-request", "缺少工作区 id");
1315
+ }
1316
+ const registry = caps.services.workspace;
1317
+ if (typeof registry?.list === "function") {
1318
+ try {
1319
+ const rows = registry.list() ?? [];
1320
+ const found = rows.find((/** @type {any} */ row) => String(row?.id) === workspaceId);
1321
+ if (found) {
1322
+ return {
1323
+ workspaceId,
1324
+ title: typeof found.title === "string" ? found.title : null,
1325
+ sessionIds: Array.isArray(found.sessionIds) ? found.sessionIds.map(String) : [],
1326
+ };
1327
+ }
1328
+ } catch (error) {
1329
+ logger.warn(`session-delete: workspaceRegistry.list failed: ${messageOf(error)}`);
1330
+ }
1331
+ }
1332
+ // 文件兜底:老版本/headless 组合里没有 workspaceRegistry。
1333
+ const state = await readWorkspaceState(dataRoot);
1334
+ const fromFile = state.workspaces.find((row) => row.id === workspaceId);
1335
+ if (fromFile) {
1336
+ return { workspaceId, title: null, sessionIds: fromFile.sessionIds.map(String) };
1337
+ }
1338
+ throw failure("session-delete/not-found", `找不到工作区 ${workspaceId}`, { workspaceId });
1339
+ }
1340
+
1341
+ /**
1342
+ * 工作区级影响面(dry-run)。逐个会话算 plan,跳过已经不存在的(登记表幽灵),
1343
+ * 聚合成一份带 digest 的预览,供确认框一次性展示。
1344
+ * @param {unknown} workspaceIdRaw
1345
+ * @returns {Promise<any>}
1346
+ */
1347
+ async function planWorkspace(workspaceIdRaw) {
1348
+ const workspace = await workspaceMembers(workspaceIdRaw);
1349
+ /** @type {unknown[] | undefined} */
1350
+ let all;
1351
+ if (caps.checks["persistence.list"] && caps.services.persistence?.list) {
1352
+ try {
1353
+ all = (await caps.services.persistence.list()) ?? [];
1354
+ } catch (error) {
1355
+ logger.warn(`session-delete: persistence.list failed: ${messageOf(error)}`);
1356
+ }
1357
+ }
1358
+ /** @type {{ sessionId: string, title: string | null, sizeBytes: number | null, live: boolean,
1359
+ * children: { id: string, title: string | null }[], blockers: { code: string, message: string }[],
1360
+ * digest: string }[]} */
1361
+ const sessions = [];
1362
+ /** @type {string[]} */
1363
+ const missing = [];
1364
+ for (const sessionId of workspace.sessionIds) {
1365
+ try {
1366
+ const { plan } = await makePlan(sessionId, { all });
1367
+ sessions.push({
1368
+ sessionId: plan.sessionId,
1369
+ title: plan.title,
1370
+ sizeBytes: plan.sizeBytes,
1371
+ live: plan.live,
1372
+ children: plan.children,
1373
+ blockers: plan.blockers,
1374
+ digest: plan.digest,
1375
+ });
1376
+ } catch (error) {
1377
+ // 登记表里指向已不存在的会话:跳过而不是整单失败(体检会单独报告它们)。
1378
+ if (/** @type {any} */ (error)?.code === "session/not-found") {
1379
+ missing.push(sessionId);
1380
+ continue;
1381
+ }
1382
+ throw error;
1383
+ }
1384
+ }
1385
+ let sizeBytes = 0;
1386
+ let live = 0;
1387
+ let children = 0;
1388
+ let blocked = 0;
1389
+ for (const session of sessions) {
1390
+ if (typeof session.sizeBytes === "number") sizeBytes += session.sizeBytes;
1391
+ if (session.live) live += 1;
1392
+ children += session.children.length;
1393
+ if (session.blockers.length > 0) blocked += 1;
1394
+ }
1395
+ return {
1396
+ workspaceId: workspace.workspaceId,
1397
+ title: workspace.title,
1398
+ sessions,
1399
+ total: sessions.length,
1400
+ missing,
1401
+ sizeBytes,
1402
+ live,
1403
+ children,
1404
+ blocked,
1405
+ digest: digestOfWorkspace({ workspaceId: workspace.workspaceId, sessions }),
1406
+ };
1407
+ }
1408
+
1409
+ /**
1410
+ * 工作区级批量删除:逐条走既有的 trash(各自的归档闸门、停止、引用清理、审计与回执),
1411
+ * 汇总部分失败而不是中途放弃——一个卡住的会话不应该让其余会话留在磁盘上。
1412
+ * @param {unknown} workspaceIdRaw
1413
+ * @param {{ digest?: string, cascade?: boolean, operator?: string }} [request]
1414
+ * @returns {Promise<any>}
1415
+ */
1416
+ async function trashWorkspace(workspaceIdRaw, request = {}) {
1417
+ const preview = await planWorkspace(workspaceIdRaw);
1418
+ if (request.digest && request.digest !== preview.digest) {
1419
+ throw failure(
1420
+ "session-delete/stale-plan",
1421
+ "这个工作区的会话在确认期间发生了变化,请重新查看影响面。",
1422
+ { workspaceId: preview.workspaceId, expected: preview.digest, actual: request.digest },
1423
+ );
1424
+ }
1425
+ const cascade = request.cascade === true;
1426
+ const operator = request.operator ?? "ui";
1427
+ /** @type {unknown[] | undefined} */
1428
+ let all;
1429
+ if (caps.checks["persistence.list"] && caps.services.persistence?.list) {
1430
+ try {
1431
+ all = (await caps.services.persistence.list()) ?? [];
1432
+ } catch (error) {
1433
+ logger.warn(`session-delete: persistence.list failed: ${messageOf(error)}`);
1434
+ }
1435
+ }
1436
+ /** @type {{ sessionId: string, title: string | null, ok: boolean, entryId?: string, children?: number, error?: string }[]} */
1437
+ const results = [];
1438
+ for (const session of preview.sessions) {
1439
+ try {
1440
+ const result = await trash(session.sessionId, {
1441
+ digest: session.digest,
1442
+ cascade,
1443
+ operator,
1444
+ all,
1445
+ });
1446
+ results.push({
1447
+ sessionId: session.sessionId,
1448
+ title: session.title,
1449
+ ok: true,
1450
+ entryId: result.entryId,
1451
+ children: Array.isArray(result.cascaded) ? result.cascaded.length : 0,
1452
+ });
1453
+ } catch (error) {
1454
+ results.push({
1455
+ sessionId: session.sessionId,
1456
+ title: session.title,
1457
+ ok: false,
1458
+ error: messageOf(error),
1459
+ });
1460
+ }
1461
+ }
1462
+ const okCount = results.filter((item) => item.ok).length;
1463
+ // 一次批量一条汇总审计:逐条的 trash 记录已经在 trash() 里写过了。
1464
+ await audit
1465
+ .append({
1466
+ action: "trash",
1467
+ result: okCount === results.length ? "ok" : "failed",
1468
+ operator,
1469
+ detail: `workspace ${preview.workspaceId}: ${okCount}/${results.length} 个会话,含 ${preview.children} 个子会话,cascade=${cascade}`,
1470
+ })
1471
+ .catch(() => {});
1472
+ return {
1473
+ ok: okCount === results.length,
1474
+ workspaceId: preview.workspaceId,
1475
+ total: results.length,
1476
+ succeeded: okCount,
1477
+ results,
1478
+ };
1479
+ }
1480
+
920
1481
  /** @param {number} [limit] */
921
1482
  async function receipts(limit = 50) {
1483
+ refreshHost();
922
1484
  return { entries: await listReceipts(dataRoot, limit) };
923
1485
  }
924
1486
 
925
1487
  return {
926
- caps,
1488
+ get caps() {
1489
+ return refreshHost();
1490
+ },
1491
+ // 启动对账与复活守卫的实现(暴露出来是为了单测能直接驱动它,不是公开契约)。
1492
+ recovery,
1493
+ recoverPending,
1494
+ recordRefusal,
927
1495
  health,
928
1496
  restoreMany,
929
1497
  purgeMany,
@@ -934,8 +1502,13 @@ export function createOperations({ ctx, dataRoot, logger }) {
934
1502
  trash,
935
1503
  list,
936
1504
  restore,
1505
+ recheckRestore,
937
1506
  purge,
938
1507
  reconcile,
939
1508
  auditLog,
1509
+ getPrefs,
1510
+ setPrefs,
1511
+ planWorkspace,
1512
+ trashWorkspace,
940
1513
  };
941
1514
  }