@xrn1997/dsh-session-delete 0.4.0 → 0.5.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.
Files changed (54) hide show
  1. package/LICENSE +201 -201
  2. package/README.md +141 -135
  3. package/cordis.patch.yml +3 -3
  4. package/lib/client.js +1477 -563
  5. package/lib/index.js +1230 -755
  6. package/lib/types/api/dispatch.d.ts +6 -2
  7. package/lib/types/api/route-table.d.ts +29 -9
  8. package/lib/types/api/trash-rows.d.ts +3 -3
  9. package/lib/types/client/busy-gate.d.ts +6 -2
  10. package/lib/types/client/confirm-close.d.ts +4 -1
  11. package/lib/types/client/context.d.ts +3 -2
  12. package/lib/types/client/copy.d.ts +54 -4
  13. package/lib/types/client/delete-confirm.d.ts +1 -1
  14. package/lib/types/client/delete-menu-item.d.ts +1 -1
  15. package/lib/types/client/host-rows.d.ts +5 -1
  16. package/lib/types/client/markdown.d.ts +6 -7
  17. package/lib/types/client/orphan-maintenance.d.ts +10 -25
  18. package/lib/types/client/receipt.d.ts +3 -1
  19. package/lib/types/client/remote.d.ts +7 -3
  20. package/lib/types/client/store.d.ts +14 -3
  21. package/lib/types/client/trash-detail.d.ts +48 -6
  22. package/lib/types/client/trash-entry.d.ts +1 -1
  23. package/lib/types/client/trash-nav.d.ts +12 -8
  24. package/lib/types/client/ui/Toast.d.ts +3 -1
  25. package/lib/types/client/ui/icons.d.ts +1 -1
  26. package/lib/types/client/undo-toast.d.ts +2 -1
  27. package/lib/types/client/use-maintenance-section.d.ts +52 -0
  28. package/lib/types/client/use-maintenance.d.ts +7 -35
  29. package/lib/types/client/use-trash-panel-controller.d.ts +35 -14
  30. package/lib/types/client/use-trash-query.d.ts +10 -8
  31. package/lib/types/client/use-trash-selection.d.ts +15 -12
  32. package/lib/types/client/write-seats.d.ts +32 -16
  33. package/lib/types/client/write-settlement.d.ts +1 -1
  34. package/lib/types/client/write.d.ts +13 -3
  35. package/lib/types/domain/closure.d.ts +44 -0
  36. package/lib/types/log/zstd-frames.d.ts +2 -3
  37. package/lib/types/ports/fs-port.d.ts +15 -12
  38. package/lib/types/ports/host-port.d.ts +4 -5
  39. package/lib/types/ports/presence-port.d.ts +9 -0
  40. package/lib/types/shared/wire.d.ts +119 -26
  41. package/lib/types/trash/attachments.d.ts +8 -1
  42. package/lib/types/trash/detail.d.ts +32 -22
  43. package/lib/types/trash/entry.d.ts +7 -1
  44. package/lib/types/trash/groups.d.ts +6 -1
  45. package/lib/types/trash/manifest.d.ts +4 -4
  46. package/lib/types/verbs/batch-carried.d.ts +1 -3
  47. package/lib/types/verbs/live-admission.d.ts +1 -1
  48. package/lib/types/verbs/member-presence.d.ts +3 -1
  49. package/lib/types/verbs/move-group.d.ts +2 -1
  50. package/lib/types/verbs/orphan-subagents.d.ts +11 -5
  51. package/lib/types/verbs/permanent-removal.d.ts +39 -10
  52. package/lib/types/verbs/trash-scope.d.ts +36 -0
  53. package/package.json +117 -107
  54. package/lib/types/verbs/purge-trash.d.ts +0 -35
package/lib/index.js CHANGED
@@ -19,41 +19,74 @@ import { homedir } from "node:os";
19
19
  * 撞了就是整棵插件树 boot 失败——所以这条路径是与生态的硬边界,不是显示好不好看的问题。
20
20
  */
21
21
  const SESSION_DELETE_API_PREFIX = "/dsh-session-delete-api";
22
- /** 九个段名(相对前缀)。写动作统一走一段 `/apply`:一次 HTTP 带一组 id、逐条回结果;
22
+ /** 九个段名(相对前缀)。**每项 `{ path, method }` 两键**:某段用什么方法也是线上形状的一部分
23
+ * (ADR-0003),家就在这一张表——路由记录(`src/api/route-table.ts`)逐行投影(`ROUTES.x.method`),
24
+ * 浏览器半的 GET 段同样投影、写段把 `ROUTES.x.method` 交给 `src/client/remote.ts` 的 `post()`,
25
+ * 两半都不逐段手写一份。
26
+ * 写动作统一走一段 `/apply`:一次 HTTP 带一组 id、逐条回结果;
23
27
  * 单条就是长度为 1 的批量,仓里不留第二条执行路径。
24
- * - `GET /list`:对账并读清单(`session-trash/` 里的目录是准)。
25
- * - `GET /ping`:最便宜的在/不在(不碰清册、不碰盘、不进链),供客户端探测。
26
- * - `POST /detail`:单条详情(用 POST 表达一个读,判据在 `src/api/route-table.ts`)。
27
- * - `POST /apply`:批量执行一个动作(`delete` / `restore` / `purge` / `count` / `orphan-clean`),逐条回 `ApplyOutcome`。
28
- * - `POST /empty`:清空回收站(聚合回执,不按条回)。
29
- * - `GET /orphans`:无主子会话的扫描报告(纯读)。清理是 `/apply` 的第五个动作,
28
+ * - `list`:对账并读清单(`session-trash/` 里的目录是准)。
29
+ * - `ping`:最便宜的在/不在(不碰清册、不碰盘、不进链),供客户端探测。
30
+ * - `detail`:单条详情(用 POST 表达一个读,判据在 `src/api/route-table.ts` 的 detail 行)。
31
+ * - `apply`:批量执行一个动作(`delete` / `restore` / `purge` / `count` / `orphan-clean`),逐条回 `ApplyOutcome`。
32
+ * - `empty`:清空回收站(聚合回执,不按条回)。
33
+ * - `orphans`:无主子会话的扫描报告(纯读)。清理是 `/apply` 的第五个动作,
30
34
  * 这一段只负责"有多少、在哪、多大"。
31
- * - `GET /attachment`:附件原始字节(全仓唯一的二进制响应段;失败仍回 JSON 信封)。
32
- * - `GET /attachment-orphans`:无引用图片对象的扫描报告(纯读;数量/字节 + 供预览的对象清单)。
33
- * - `POST /attachment-clean`:清掉报告那一刻无引用的图片对象(聚合回执 `AttachmentCleanupWire`)。 */
35
+ * - `attachment`:附件原始字节(全仓唯一的二进制响应段;失败仍回 JSON 信封)。
36
+ * - `attachmentOrphans`:无引用图片对象的扫描报告(纯读;数量/字节 + 供预览的对象清单)。
37
+ * - `attachmentClean`:清掉报告那一刻无引用的图片对象(聚合回执 `AttachmentCleanupWire`)。 */
34
38
  const ROUTES = {
35
- list: "/list",
39
+ list: {
40
+ path: "/list",
41
+ method: "GET"
42
+ },
36
43
  /** 通道的"在不在"专用:没有入参、没有副作用、没有磁盘读。 */
37
- ping: "/ping",
44
+ ping: {
45
+ path: "/ping",
46
+ method: "GET"
47
+ },
38
48
  /** 单条详情(读回收站目录里那条会话自己的日志)。 */
39
- detail: "/detail",
49
+ detail: {
50
+ path: "/detail",
51
+ method: "POST"
52
+ },
40
53
  /** 一组 id 上的同一个动作;删除确认框那句「含 N 个子会话」也走这里(`action: 'count'`,纯读语义)。 */
41
- apply: "/apply",
54
+ apply: {
55
+ path: "/apply",
56
+ method: "POST"
57
+ },
42
58
  /** 清空回收站。 */
43
- empty: "/empty",
59
+ empty: {
60
+ path: "/empty",
61
+ method: "POST"
62
+ },
44
63
  /** 纯读:扫描回收站之外的无主子会话(父已不在语料/清册)。 */
45
- orphans: "/orphans",
64
+ orphans: {
65
+ path: "/orphans",
66
+ method: "GET"
67
+ },
46
68
  /** 附件字节(图片/普通文件):全仓唯一的二进制响应段,读的是宿主附件库。 */
47
- attachment: "/attachment",
69
+ attachment: {
70
+ path: "/attachment",
71
+ method: "GET"
72
+ },
48
73
  /** 纯读:扫全部引用源与附件库 `objects`,报无引用图片的数量、字节与预览清单。 */
49
- attachmentOrphans: "/attachment-orphans",
74
+ attachmentOrphans: {
75
+ path: "/attachment-orphans",
76
+ method: "GET"
77
+ },
50
78
  /** 聚合清理:只删 `objects` 下无引用的图片,回 `AttachmentCleanupWire`。 */
51
- attachmentClean: "/attachment-clean"
79
+ attachmentClean: {
80
+ path: "/attachment-clean",
81
+ method: "POST"
82
+ }
52
83
  };
53
84
  /** 请求参数名:浏览器半发、Node 半读,同名同义(`empty` 没有入参)。
54
85
  * 附件段是 **query 参数**(GET 二进制响应,没有请求体)。 */
55
86
  const PARAMS = {
56
87
  entryId: "entryId",
88
+ /** `/detail` 的分页游标:只取这个块序号之前的块。缺省 = 从尾部取。 */
89
+ before: "before",
57
90
  action: "action",
58
91
  ids: "ids",
59
92
  attachmentId: "id",
@@ -123,14 +156,21 @@ const HOST_ERROR_CODE = {
123
156
  WorkspaceUnknownSessionError: "not-found",
124
157
  WorkspaceActiveSessionError: "live"
125
158
  };
126
- /** cause 链上第一个**宿主类型化错误**本身(不只它的名字)——它自己身上的字段还要当 `details` 用。
159
+ /** cause 链上第一个**宿主类型化错误**本身(不只它的名字)——它自己身上的字段还要当 `details` 用;
160
+ * 码在 hasOwn 证明的同一处取回(表值恒在,编译器只认贴着取的这一份)。
127
161
  * 深度有界(链坏掉不递归下去);查表必须 `hasOwn`:`in` 会命中 `Object.prototype` 的键。 */
128
162
  function hostErrorOf(error) {
129
163
  let current = error;
130
164
  for (let depth = 0; depth < 8; depth++) {
131
165
  if (current === null || typeof current !== "object") return void 0;
132
166
  const name = current.name;
133
- if (typeof name === "string" && Object.hasOwn(HOST_ERROR_CODE, name)) return current;
167
+ if (typeof name === "string" && Object.hasOwn(HOST_ERROR_CODE, name)) {
168
+ const code = HOST_ERROR_CODE[name];
169
+ if (code !== void 0) return {
170
+ host: current,
171
+ code
172
+ };
173
+ }
134
174
  current = current.cause;
135
175
  }
136
176
  }
@@ -213,12 +253,12 @@ function toRemoteFailure(error) {
213
253
  }
214
254
  const fromVerb = verbCodeOf(error);
215
255
  const host = hostErrorOf(error);
216
- const own = detailsOf(error) ?? (host === void 0 ? void 0 : detailsOf(host));
256
+ const own = detailsOf(error) ?? (host === void 0 ? void 0 : detailsOf(host.host));
217
257
  if (host === void 0 && fromVerb === void 0 && typeof raw === "string" && raw.includes("/")) return {
218
258
  code: SESSION_DELETE_CODES.io,
219
259
  message: messageOf(error)
220
260
  };
221
- const code = host !== void 0 ? HOST_ERROR_CODE[host.name] : fromVerb ?? "io";
261
+ const code = host !== void 0 ? host.code : fromVerb ?? "io";
222
262
  return {
223
263
  code: SESSION_DELETE_CODES[code],
224
264
  message: messageOf(error),
@@ -354,459 +394,151 @@ function judgeRequest(req, facts) {
354
394
  return verdict.kind === "unauthenticated" ? "unauthenticated" : "untrusted";
355
395
  }
356
396
  //#endregion
357
- //#region src/ports/agent-handles.ts
358
- const CAPTURED_AGENT_HANDLES = Symbol.for("dsh-session-delete.captured-agent-handles");
359
- /** 在 `ctx.agents` 上包一层 `resume` / `create`,把返回的 agent handle 的 dispose 按会话 id 记下。
360
- * 服务缺席时走 `ctx.inject(['agents'])` **等服务挂上再装**——live profile 的插件激活顺序可能早于
361
- * `agents` 服务就绪;只在 apply 时 `get` 一次会让捕获静默缺席(真机症状:重启前在回收站的能冷恢复,
362
- * 刚删除的会话恢复后旧 agent 拦住 prompt)。形状不符 / 属性不可写都只是**不捕获**,不影响插件激活。
363
- *
364
- * **安装时机**:先 `get('agents')`,没装成再 `inject(['agents'])`(两者只装一次,符号表兜住)。
365
- * **symbol 表**:句柄表挂在服务实例的 {@link CAPTURED_AGENT_HANDLES} 上;同一个 agents 服务上的第二次
366
- * 安装(`get` 与 `inject` 各一次,或第二个 `createHostPort`)看见它就直接共用,不把 wrapper 套第二层。
367
- * **读回判据**:cordis 的 traceable 服务代理每次读函数都会新包一层(`get` 里的 `createShadowMethod`),
368
- * 所以只能看 own property descriptor 的身份;拿 `service[name]` 读回比身份是必然的假警报。
369
- */
370
- function captureAgentHandles(ctx) {
371
- let handles = /* @__PURE__ */ new Map();
372
- let installed = false;
373
- const install = (candidate) => {
374
- if (installed) return;
375
- const service = candidate;
376
- if (service === void 0 || service === null) return;
377
- const existing = service[CAPTURED_AGENT_HANDLES];
378
- if (existing !== void 0) {
379
- handles = existing;
380
- installed = true;
381
- return;
382
- }
383
- let wrappedCount = 0;
384
- for (const name of ["resume", "create"]) try {
385
- const original = service[name];
386
- if (typeof original !== "function") continue;
387
- const wrapped = function(...args) {
388
- const result = Reflect.apply(original, this, args);
389
- result.then((value) => {
390
- const handle = value;
391
- const id = handle?.agent?.id;
392
- if (typeof id !== "string" || id.length === 0 || typeof handle?.dispose !== "function") return;
393
- handles.set(id, async () => {
394
- await handle.dispose();
395
- });
396
- }, () => void 0);
397
- return result;
398
- };
399
- service[name] = wrapped;
400
- if (Object.getOwnPropertyDescriptor(service, name)?.value !== wrapped) throw new Error(`agents.${name} is not writable`);
401
- wrappedCount += 1;
402
- } catch {}
403
- if (wrappedCount === 0) return;
404
- try {
405
- service[CAPTURED_AGENT_HANDLES] = handles;
406
- } catch {}
407
- installed = true;
408
- };
409
- const service = ctx.get("agents");
410
- if (service !== void 0 && service !== null) install(service);
411
- if (!installed && typeof ctx.inject === "function") try {
412
- ctx.inject(["agents"], (child) => {
413
- install(child.get("agents"));
414
- });
415
- } catch {}
416
- return { async dispose(sessionId) {
417
- const dispose = handles.get(sessionId);
418
- if (dispose === void 0) return;
419
- try {
420
- await dispose();
421
- } finally {
422
- handles.delete(sessionId);
423
- }
424
- } };
425
- }
426
- //#endregion
427
- //#region src/ports/host-port.ts
428
- /** live store 的最小方法面判据(同 `projectionCacheOf` 的手法:按方法面判,不按 constructor.name)。 */
429
- function liveSessionsOf(ctx) {
430
- const store = ctx.get("sessions");
431
- if (store === void 0 || store === null) return void 0;
432
- if (typeof store.get !== "function" || typeof store.liveEntryFor !== "function") return void 0;
433
- return store;
434
- }
435
- /** 官方的「这些父的孩子」那一支:`kind:'parent'` 的判据逐字是 `values.includes(record.header.parentSession ?? null)`。 */
436
- async function filterChildrenOf(sessionQuery, values) {
437
- return sessionQuery.filterSessions([{
438
- kind: "parent",
439
- values: [...values].sort()
440
- }]);
397
+ //#region src/domain/closure.ts
398
+ /** 会话 id 去掉 `session-` 前缀后的形状:同一个会话在两代宿主里写法不同(v3 代 id 不带前缀、
399
+ * 现行代带),归堆、成组、去重一律按这个形状比——两边都归一,不赌调用方传的是哪一代写法。 */
400
+ function bareSessionId(id) {
401
+ return id.startsWith("session-") ? id.slice(8) : id;
441
402
  }
442
- /**
443
- * 从若干根逐层向下问出后代,交回 `父(bare)→ 孩子` 的索引。
444
- * 用 `kind:'parent'` 而不是 traceSession:父进回收站后 traceSession 认不出目标(宿主失败码
445
- * `SESSION_QUERY_SESSION_NOT_FOUND`),而这里要的正是父不在宿主列表之后仍留在盘上的那批。
446
- * 出处:asar `dsh-session-query/lib/index.js` 的 `filterSessions`。一层一次宿主调用,问空即停;
447
- * `seen` 防环;没有 `header.id` 的记录整条跳过(无法作为身份继续下问)。
448
- */
449
- async function descendantsByParent(sessionQuery, roots) {
450
- const children = /* @__PURE__ */ new Map();
451
- const seen = new Set(roots.map(bareSessionId));
452
- let frontier = [...seen];
453
- while (frontier.length > 0) {
454
- const values = [];
455
- for (const bare of frontier) for (const shape of sessionIdShapes(bare)) if (!values.includes(shape)) values.push(shape);
456
- const next = [];
457
- for (const record of await filterChildrenOf(sessionQuery, values)) {
458
- const id = record.header?.id;
459
- const parent = record.header?.parentSession;
460
- if (typeof id !== "string" || id.length === 0) continue;
461
- if (typeof parent !== "string" || parent.length === 0) continue;
462
- const bare = bareSessionId(id);
463
- if (seen.has(bare)) continue;
464
- seen.add(bare);
465
- const cwd = record.header?.cwd;
466
- const descendant = {
467
- id,
468
- bare,
469
- projectDir: cwd === void 0 ? NO_CWD_PROJECT_DIR : projectKey(cwd)
470
- };
471
- const parentBare = bareSessionId(parent);
472
- const siblings = children.get(parentBare);
473
- if (siblings === void 0) children.set(parentBare, [descendant]);
474
- else siblings.push(descendant);
475
- next.push(bare);
476
- }
477
- frontier = next;
478
- }
479
- return children;
403
+ /** 一个 id 的全部可能写法,原写法在前:`session-x` → `[session-x, x]`;`x` → `[x, session-x]`。
404
+ * 逐层问宿主时按这些写法问:宿主那支按 `header.parentSession` 原文比,不替我们归一。 */
405
+ function sessionIdShapes(id) {
406
+ const bare = bareSessionId(id);
407
+ return [.../* @__PURE__ */ new Set([
408
+ id,
409
+ bare,
410
+ `session-${bare}`
411
+ ])];
480
412
  }
481
- /** 某个根在 `descendantsByParent` 那棵树里的全部后代(深度不设上限,同一条只收一次)。 */
482
- function subtreeOf(children, rootBare) {
413
+ /** parent(bare) 到 children 索引上的传递闭包:深度不设上限、防环、首见去重(都按 bare 归一后比)。
414
+ * 根的两种写法都认(内部归一次);结果不含根自己。数据里真出现环时代价是「少数一条」,
415
+ * 不是把清单读挂死——环本来不该出现(parentSession 是一条有向边),出现就是手工改过日志或宿主 bug。 */
416
+ function closureOf(children, root) {
483
417
  const out = [];
484
- const seen = /* @__PURE__ */ new Set([rootBare]);
485
- let frontier = [rootBare];
418
+ const seen = /* @__PURE__ */ new Set([bareSessionId(root)]);
419
+ let frontier = [...seen];
486
420
  while (frontier.length > 0) {
487
421
  const next = [];
488
422
  for (const bare of frontier) for (const kid of children.get(bare) ?? []) {
489
- if (seen.has(kid.bare)) continue;
490
- seen.add(kid.bare);
423
+ const kidBare = bareSessionId(kid.sessionId);
424
+ if (seen.has(kidBare)) continue;
425
+ seen.add(kidBare);
491
426
  out.push(kid);
492
- next.push(kid.bare);
427
+ next.push(kidBare);
493
428
  }
494
429
  frontier = next;
495
430
  }
496
431
  return out;
497
432
  }
498
- function toMember(d) {
499
- return {
500
- sessionId: d.id,
501
- projectDir: d.projectDir
502
- };
503
- }
504
- /** {@link HostCorpusPort.subagentMembersOf} 的那一次 BFS。
505
- * 空清单在调用宿主之前就返回(不为一张空表扫全库)。 */
506
- async function membersFor(sessionQuery, parentIds) {
507
- const wanted = [];
508
- for (const id of parentIds) if (id.length > 0 && !wanted.includes(id)) wanted.push(id);
509
- if (wanted.length === 0) return {};
510
- const children = await descendantsByParent(sessionQuery, wanted);
511
- const out = {};
512
- for (const id of wanted) out[id] = subtreeOf(children, bareSessionId(id));
433
+ /** 同一条记录两代写法只认第一次出现(保原序)。全局去重只有这一处实现:谁要按 bare 去重,
434
+ * 交一条列表进来,别在调用点再手写一个 seen 集合。 */
435
+ function firstByBare(members) {
436
+ const seen = /* @__PURE__ */ new Set();
437
+ const out = [];
438
+ for (const member of members) {
439
+ const bare = bareSessionId(member.sessionId);
440
+ if (seen.has(bare)) continue;
441
+ seen.add(bare);
442
+ out.push(member);
443
+ }
513
444
  return out;
514
445
  }
515
- /** 无 cwd 的会话落在 `_no-cwd/`;`projectDirOf` 与回收站对账共用这个字面量。
516
- * 出处:asar `dsh-session-persistence-jsonl/lib/index.js` 的 `projectDir`(`if (cwd === void 0) return join(root, "_no-cwd");`)。 */
517
- const NO_CWD_PROJECT_DIR = "_no-cwd";
518
- /** 宿主 `projectKey(cwd)` 的逐字镜像:跨插件不能 import,宿主也没把它暴露成服务。
519
- * 出处:asar `dsh-session-persistence-jsonl/lib/index.js` 的 `projectKey`;调用链
520
- * `locate` → `logPath` → `projectDir` → `projectKey`。本机实测 `D:/develop/GitHub/dsh-session-delete`
521
- * → `--D-develop-GitHub-dsh-session-delete--`。`projectDirOf` 与回收站对账重建共用这一份;
522
- * 宿主换代先复核算法。 */
523
- function projectKey(cwd) {
524
- let readable = "";
525
- let separatorRun = false;
526
- for (let i = 0; i < cwd.length; i++) {
527
- const code = cwd.charCodeAt(i);
528
- const ch = String.fromCharCode(code);
529
- if (ch === "/" || ch === "\\" || ch === ":") {
530
- if (!separatorRun) readable += "-";
531
- separatorRun = true;
532
- } else if (ch !== "~" && /^[A-Za-z0-9._-]$/.test(ch)) {
533
- readable += ch;
534
- separatorRun = false;
535
- } else {
536
- readable += `~${code.toString(16).toUpperCase().padStart(4, "0")}`;
537
- separatorRun = false;
446
+ /**
447
+ * 整表语料 → 根闭包组:`parentSessionId` 不在 `known` 里的那些 subagent 各自成一组。`known` 两侧都
448
+ * 归一后再比(传原始 id 即可)。「已知父为什么排除在外」是调用方的领域判据(住
449
+ * `src/verbs/orphan-subagents.ts` 与 `CONTEXT.md` 的「无主子会话」),这一层不替它复述。
450
+ *
451
+ * 组内的后代仍走 `closureOf` 那一份闭包,只是多一条跨组的 `claimed`:一条记录只归第一个认领它的根。
452
+ * 已被前一组收走的那条,连同它整支子树都不再出现在这一组里——后代在那一组已被全部认领,所以
453
+ * 「丢掉已认领的」与「不走进已认领的那支」交回的是同一个集合。环上的代价是「少数一条」,
454
+ * 不是把一次扫描挂死。组序与成员序都按语料原序。
455
+ */
456
+ function orphanRootsOf(corpus, known) {
457
+ const knownBares = /* @__PURE__ */ new Set();
458
+ for (const id of known) knownBares.add(bareSessionId(id));
459
+ const children = /* @__PURE__ */ new Map();
460
+ for (const session of corpus) {
461
+ const parent = session.parentSessionId;
462
+ if (parent === void 0) continue;
463
+ const key = bareSessionId(parent);
464
+ const list = children.get(key);
465
+ if (list === void 0) children.set(key, [session]);
466
+ else list.push(session);
467
+ }
468
+ const claimed = /* @__PURE__ */ new Set();
469
+ const groups = [];
470
+ for (const session of corpus) {
471
+ const parent = session.parentSessionId;
472
+ if (!session.subagent || parent === void 0) continue;
473
+ if (knownBares.has(bareSessionId(parent))) continue;
474
+ const rootBare = bareSessionId(session.sessionId);
475
+ if (claimed.has(rootBare)) continue;
476
+ claimed.add(rootBare);
477
+ const members = [session];
478
+ for (const descendant of closureOf(children, rootBare)) {
479
+ const bare = bareSessionId(descendant.sessionId);
480
+ if (claimed.has(bare)) continue;
481
+ claimed.add(bare);
482
+ members.push(descendant);
538
483
  }
484
+ groups.push({
485
+ root: session,
486
+ parentSessionId: parent,
487
+ members
488
+ });
539
489
  }
540
- return `--${(readable.replace(/^-+/, "") || "root").slice(0, 251)}--`;
490
+ return groups;
541
491
  }
542
- /** 投影缓存服务的最小方法面判据(按方法面判,不按 `constructor.name` 判)。 */
543
- function projectionCacheOf(ctx) {
544
- const cache = ctx.get("sessionProjectionCache");
545
- if (cache === void 0 || cache === null) return void 0;
546
- if (typeof cache.cachedSnapshot !== "function" || typeof cache.cachedPredecessorTitle !== "function") return void 0;
547
- return cache;
492
+ //#endregion
493
+ //#region src/trash/groups.ts
494
+ /** 这些孩子的父。 */
495
+ function kidsOf(rows, parentId) {
496
+ return rows.filter((row) => row.parentEntryId === parentId);
548
497
  }
549
- /** 宿主 `readSessionHeader` 对未知会话抛的是裸 `Error`,只认这句;真存储故障照抛,不能折成未命中。
550
- * 出处:asar `dsh-workspace/lib/types/index.js` 的
551
- * `cannot validate session '${id}': session persistence holds no such session`。
552
- * 同文件有类型的近似句是 `WorkspaceUnknownSessionError`(`hold` 无 `s`),不会误伤。 */
553
- const NO_SUCH_SESSION = "session persistence holds no such session";
554
- /** 只认上面那一句;其余(含非 Error 抛出物)一律**不算未命中**。 */
555
- function isUnknownSession(error) {
556
- return error instanceof Error && error.message.includes(NO_SUCH_SESSION);
498
+ /**
499
+ * 清单露面的一行 = 组根,按清册原序。孩子折进根那一行(宿主的客户端本来就把 `origin:"subagent"`
500
+ * 的行整排藏了 ⇒ 我们若单列就会冒出一堆点不到的行)。
501
+ *
502
+ * 折不进去的那两种孩子(父行不在 / 父行自己也是孩子)**自己站出来占一行**——那正是
503
+ * `visibleGroups` 与 `groupOf` 共用同一条判据的地方。
504
+ */
505
+ function visibleGroups(rows) {
506
+ const byId = new Map(rows.map((row) => [row.id, row]));
507
+ const kidsByRoot = /* @__PURE__ */ new Map();
508
+ const folded = /* @__PURE__ */ new Set();
509
+ for (const row of rows) {
510
+ if (row.parentEntryId === void 0) continue;
511
+ const parent = byId.get(row.parentEntryId);
512
+ if (parent === void 0 || parent.parentEntryId !== void 0) continue;
513
+ folded.add(row.id);
514
+ const siblings = kidsByRoot.get(parent.id);
515
+ if (siblings === void 0) kidsByRoot.set(parent.id, [row]);
516
+ else siblings.push(row);
517
+ }
518
+ return rows.filter((row) => !folded.has(row.id)).map((root) => ({
519
+ root,
520
+ kids: kidsByRoot.get(root.id) ?? []
521
+ }));
557
522
  }
558
- /** 会话 id 去掉 `session-` 前缀后的形状(同一个父在两代里写法不同,见 {@link HostCorpusPort.subagentMembersOf})。 */
559
- function bareSessionId(id) {
560
- return id.startsWith("session-") ? id.slice(8) : id;
561
- }
562
- /** 一个 id 的全部可能写法,原写法在前:`session-x` → `[session-x, x]`;`x` → `[x, session-x]`。 */
563
- function sessionIdShapes(id) {
564
- const bare = bareSessionId(id);
565
- return [.../* @__PURE__ */ new Set([
566
- id,
567
- bare,
568
- `session-${bare}`
569
- ])];
570
- }
571
- /** 宿主会话表的一次取数(`ctx.sessionController.list()` 的两种返回形状都折成数组)。
572
- * 服务没挂 / 形状不对 / 抛错 ⇒ 空表——**这条不替宿主兜错误**:调用方拿空表的语义都是"少发一条通告",
573
- * 不是"恢复失败"。 */
574
- async function controllerItems(host) {
575
- try {
576
- const controller = host.get("sessionController");
577
- if (controller === void 0 || controller === null || typeof controller.list !== "function") return [];
578
- const listed = await controller.list();
579
- const items = Array.isArray(listed) ? listed : listed?.items;
580
- return Array.isArray(items) ? items : [];
581
- } catch {
582
- return [];
583
- }
584
- }
585
- /** 账本里没有那个工作区时 {@link HostPort.attach} / {@link HostPort.detach} 抛的原话开头。
586
- * **原话与判据同住这里**:抛它的是这个端口,认它的也是端口给的那句,调用方不许另抄一份字符串。 */
587
- const WORKSPACE_MISSING_MESSAGE = "workspace not found";
588
- /** 这次失败是不是"账本里没那个工作区"(而不是另有故障)。恢复侧靠它把两种失败分开:
589
- * 前者按「未分组」收,后者照旧回滚报 `io`——不给真故障静默改归属的机会。 */
590
- function isWorkspaceMissingError(error) {
591
- return error instanceof Error && error.message.startsWith(WORKSPACE_MISSING_MESSAGE);
592
- }
593
- /** 宿主服务的真实绑定;出错原样抛,由 `toRemoteFailure` 按 name 映射。
594
- * 各方法调用的服务与方法见上方成员注释;错误映射表住 `src/remote/map-error.ts`。 */
595
- function createHostPort(ctx) {
596
- const host = ctx;
597
- const registry = host.workspaceRegistry;
598
- const agentHandles = captureAgentHandles(host);
599
- return {
600
- /** 账本里记着这个会话的工作区:`registry.list()` 的实体 `sessionIds`(该 getter 已按 canonical cwd 过滤过)。 */
601
- async workspaceOf(sessionId) {
602
- return registry.list().find((workspace) => workspace.sessionIds.includes(sessionId))?.id;
603
- },
604
- /** 账本里还有这个工作区吗:`registry.get(id)` 是 `this.entities.get(id)` 的直通(同步 Map 查找),
605
- * 未知 id 回 `undefined` ⇒ 这里只做一次判别,不抛。 */
606
- async workspaceExists(workspaceId) {
607
- return registry.get(workspaceId) !== void 0;
608
- },
609
- /**
610
- * cwd → 宿主项目目录名;没有 cwd 落到 `_no-cwd`。
611
- * 账本里没有这个会话回 `undefined`(未命中,不是故障);真存储故障照抛。
612
- * 未命中由 `delete-session.ts` 折成 `not-found`,真故障留 `io`——两者不能混。
613
- */
614
- async projectDirOf(sessionId) {
615
- let header;
616
- try {
617
- header = await registry.readSessionHeader(sessionId);
618
- } catch (error) {
619
- if (isUnknownSession(error)) return void 0;
620
- throw error;
621
- }
622
- return header.cwd === void 0 ? NO_CWD_PROJECT_DIR : projectKey(header.cwd);
623
- },
624
- /** 标题走宿主投影缓存;尽力取,取不到返回空串,绝不因此让删除失败。 */
625
- async titleOf(sessionId) {
626
- try {
627
- const header = await registry.readSessionHeader(sessionId);
628
- const cache = projectionCacheOf(host);
629
- const title = (cache?.cachedSnapshot(header, ["title"]) ?? cache?.cachedPredecessorTitle(header))?.values.title;
630
- return typeof title === "string" ? title : "";
631
- } catch {
632
- return "";
633
- }
634
- },
635
- /** 活跃判据走宿主 `workspace/session-activity` waterfall:空数组 = 无活动;
636
- * 与宿主 archiveSession 的准入同源。 */
637
- async isLive(sessionId) {
638
- return (await host.waterfall("workspace/session-activity", { sessionId }, () => Promise.resolve([]))).length > 0;
639
- },
640
- /** registry 全局归档集(数组,`state.archivedSessionIds`)。 */
641
- async isArchived(sessionId) {
642
- return registry.archivedSessionIds.includes(sessionId);
643
- },
644
- /**
645
- * 从 `ctx.sessions` 摘掉会话,并关闭捕获到的 agent handle。
646
- *
647
- * 会话列表 = 磁盘持久化 ∪ 内存活体,搬走文件只清掉一侧;宿主 `SessionController` 会丢掉
648
- * `AgentHandle`,所以 `agent-handles.ts` 按会话 id 留住 handle,这里先 detach 再 dispose。
649
- * 捕获不到 handle(插件激活前已启动,或 `ctx.agents` 形状变化)时只能摘 session,这是已知限制,
650
- * 不拿归档兜底(ADR-0008)。
651
- *
652
- * 三态:读不到 store / 形状不符 / detach 或 dispose 抛 ⇒ `unknown`(不通告);
653
- * 内存里本来没有 ⇒ `not-live`;摘成功 ⇒ `evicted`。任何一步都不抛。
654
- */
655
- async evictLive(sessionId) {
656
- try {
657
- const store = liveSessionsOf(host);
658
- const session = store?.get(sessionId);
659
- if (store === void 0) return "unknown";
660
- if (session === void 0 || session === null) {
661
- await agentHandles.dispose(sessionId);
662
- return "not-live";
663
- }
664
- const entry = store.liveEntryFor(session);
665
- if (entry === void 0 || entry === null || typeof entry.detach !== "function") return "unknown";
666
- entry.detach();
667
- await agentHandles.dispose(sessionId);
668
- return "evicted";
669
- } catch {
670
- return "unknown";
671
- }
672
- },
673
- /**
674
- * 通告客户端这个会话没了:发宿主自己转发的 `api-session/removed`,客户端当场删行。
675
- * 冷会话没有 `session/disposed`,不发这条就只能等重连。
676
- * 只在宿主列表确实已不含它时调用(调用方按 {@link EvictionOutcome} 判);不发假通告。
677
- */
678
- async announceRemoved(sessionId) {
679
- try {
680
- host.emit("api-session/removed", sessionId);
681
- } catch {}
682
- },
683
- /**
684
- * 通告这组会话回来了:拉一次宿主会话表,按 id 逐条发 `api-session/added`。
685
- * 摘要直接用宿主 `sessionController.list()` 的形状;取不到就不发。
686
- * 批量只预取一次,避免按条全表扫。
687
- */
688
- async announceRestored(sessionIds) {
689
- if (sessionIds.length === 0) return;
690
- const summaries = [];
691
- for (const item of await controllerItems(host)) {
692
- const sessionId = item?.sessionId;
693
- if (typeof sessionId === "string") summaries.push({
694
- sessionId,
695
- summary: item
696
- });
697
- }
698
- for (const id of sessionIds) {
699
- const summary = summaries.find((item) => item.sessionId === id)?.summary;
700
- if (summary === void 0) continue;
701
- try {
702
- host.emit("api-session/added", JSON.parse(JSON.stringify(summary)));
703
- } catch {}
704
- }
705
- },
706
- /** 官方 `unarchiveSession(sessionId)`:未归档是幂等 no-op。 */
707
- async unarchive(sessionId) {
708
- await registry.unarchiveSession(sessionId);
709
- },
710
- /** 摘账本:实体方法 `detachSession`(顶层没有);未知工作区**响亮失败**,不静默当成功。 */
711
- async detach(sessionId, workspaceId) {
712
- const workspace = registry.get(workspaceId);
713
- if (workspace === void 0) throw new Error(`${WORKSPACE_MISSING_MESSAGE} (detach): ${workspaceId}`);
714
- await workspace.detachSession(sessionId);
715
- },
716
- /** 挂账本:实体方法 `attachSession`(顶层没有)。 */
717
- async attach(sessionId, workspaceId) {
718
- const workspace = registry.get(workspaceId);
719
- if (workspace === void 0) throw new Error(`${WORKSPACE_MISSING_MESSAGE} (attach): ${workspaceId}`);
720
- await workspace.attachSession(sessionId);
721
- },
722
- /** 确保归档:官方 `archiveSession(sessionId)`。归档是 registry **全局**的,与工作区账目无关
723
- * (JSDoc 原文 "its workspace accounting — or lack of one — is irrelevant"),所以 `workspaceId` 不用
724
- * ——未分组的会话没有工作区可传,签名里它是可选的。
725
- * 不带 `stopActivity` ⇒ 有活动即抛 `WorkspaceActiveSessionError`(→ `sessiondelete/live`,src/shared/wire.ts)。 */
726
- async archive(sessionId) {
727
- await registry.archiveSession(sessionId);
728
- },
729
- async listSessions() {
730
- const sessionQuery = host.get("sessionQuery");
731
- if (typeof sessionQuery?.listSessions !== "function") return { available: false };
732
- const records = await sessionQuery.listSessions();
733
- const out = [];
734
- for (const record of records) {
735
- const id = record.header?.id;
736
- if (typeof id !== "string" || id === "") continue;
737
- const parent = record.header?.parentSession;
738
- const cwd = record.header?.cwd;
739
- out.push({
740
- sessionId: id,
741
- ...typeof parent === "string" && parent !== "" ? { parentSessionId: parent } : {},
742
- projectDir: cwd === void 0 ? NO_CWD_PROJECT_DIR : projectKey(cwd),
743
- subagent: record.header?.origin === "subagent"
744
- });
745
- }
746
- return {
747
- available: true,
748
- value: out
749
- };
750
- },
751
- /**
752
- * 官方 `sessionQuery.filterSessions([{kind:'parent', values}])`,不自扫 `~/.dsh/sessions`。
753
- * 数传递闭包(孩子与孙代),不是直接孩子;`session-` 前缀两边都去掉再比,
754
- * 按调用方给的写法回键。`sessionQuery` 缺席或方法缺失 ⇒ `{available:false}`,
755
- * 不拿空表冒充“没有后代”;服务在场时空入参零宿主调用。
756
- */
757
- async subagentMembersOf(parentIds) {
758
- const sessionQuery = host.get("sessionQuery");
759
- if (typeof sessionQuery?.filterSessions !== "function") return { available: false };
760
- const members = await membersFor(sessionQuery, parentIds);
761
- return {
762
- available: true,
763
- value: Object.fromEntries(Object.entries(members).map(([id, list]) => [id, list.map(toMember)]))
764
- };
765
- }
766
- };
767
- }
768
- //#endregion
769
- //#region src/trash/groups.ts
770
- /** 这些孩子的父。 */
771
- function kidsOf(rows, parentId) {
772
- return rows.filter((row) => row.parentEntryId === parentId);
773
- }
774
- /**
775
- * 清单露面的一行 = 组根,按清册原序。孩子折进根那一行(宿主的客户端本来就把 `origin:"subagent"`
776
- * 的行整排藏了 ⇒ 我们若单列就会冒出一堆点不到的行)。
777
- *
778
- * 折不进去的那两种孩子(父行不在 / 父行自己也是孩子)**自己站出来占一行**——那正是
779
- * `visibleGroups` 与 `groupOf` 共用同一条判据的地方。
780
- */
781
- function visibleGroups(rows) {
782
- const byId = new Map(rows.map((row) => [row.id, row]));
783
- const kidsByRoot = /* @__PURE__ */ new Map();
784
- const folded = /* @__PURE__ */ new Set();
785
- for (const row of rows) {
786
- if (row.parentEntryId === void 0) continue;
787
- const parent = byId.get(row.parentEntryId);
788
- if (parent === void 0 || parent.parentEntryId !== void 0) continue;
789
- folded.add(row.id);
790
- const siblings = kidsByRoot.get(parent.id);
791
- if (siblings === void 0) kidsByRoot.set(parent.id, [row]);
792
- else siblings.push(row);
793
- }
794
- return rows.filter((row) => !folded.has(row.id)).map((root) => ({
795
- root,
796
- kids: kidsByRoot.get(root.id) ?? []
797
- }));
523
+ /**
524
+ * 一条 id 所属的整组。三种形状,三个答案:
525
+ * - **组根** ⇒ 它自己 + 它接住的孩子(UI 点的是父那一行,删除/恢复/彻底删除都按整组走);
526
+ * - **孩子**(自己记着 `parentEntryId`)⇒ **只回它自己**。清单不单独列它,只有手工/降级路径会点到这里;
527
+ * - **清册里没有这一条 id,但还有孩子指向它**(父行已被别的路径摘掉)⇒ 那一批孩子;仍然没有 ⇒ 空数组,
528
+ * 调用方据此报 `trash-empty` / 判"已被同批前一条带走"。
529
+ */
530
+ function groupOf(rows, id) {
531
+ const root = rows.find((row) => row.id === id);
532
+ if (root !== void 0) return root.parentEntryId === void 0 ? [root, ...kidsOf(rows, id)] : [root];
533
+ return kidsOf(rows, id);
798
534
  }
799
535
  /**
800
- * 一条 id 所属的整组。三种形状,三个答案:
801
- * - **组根** ⇒ 它自己 + 它接住的孩子(UI 点的是父那一行,删除/恢复/彻底删除都按整组走);
802
- * - **孩子**(自己记着 `parentEntryId`)⇒ **只回它自己**。清单不单独列它,只有手工/降级路径会点到这里;
803
- * - **清册里没有这一条 id,但还有孩子指向它**(父行已被别的路径摘掉)⇒ 那一批孩子;仍然没有 ⇒ 空数组,
804
- * 调用方据此报 `trash-empty` / 判"已被同批前一条带走"。
536
+ * 把一条 id 所属的**整组**从快照里摘掉,回一份新快照(组语义仍只读 `groupOf`,这一条判据不另写一遍)。
537
+ * 「同批前一条已把这一组带走」的收缩就是它:调用方各自持有那份可变视图,本函数不记账。
805
538
  */
806
- function groupOf(rows, id) {
807
- const root = rows.find((row) => row.id === id);
808
- if (root !== void 0) return root.parentEntryId === void 0 ? [root, ...kidsOf(rows, id)] : [root];
809
- return kidsOf(rows, id);
539
+ function withoutGroup(rows, id) {
540
+ const gone = new Set(groupOf(rows, id).map((row) => row.id));
541
+ return rows.filter((row) => !gone.has(row.id));
810
542
  }
811
543
  /**
812
544
  * 「这条是被**同批前一条**带走的,还是整批开始前就没有,还是仍在?」
@@ -829,14 +561,15 @@ function claimOf(original, current, id) {
829
561
  * **同批已带走集**(「已被同批前一条带走」的 id)的唯一实现(ADR-0002 的内部实现)。
830
562
  *
831
563
  * 两种 id 域各一个 adapter:
832
- * - entry 适配:restore / purge 的条目 id,`claim` 是三态(fresh / carried / absent),组语义仍读
564
+ * - entry 适配:restore 的条目 id,`claim` 是三态(fresh / carried / absent),组语义仍读
833
565
  * `trash/groups.ts`;
834
566
  * - session 适配:delete 的会话 id,`claim` 只有 fresh / carried,集合由动词结果长出。
835
567
  *
836
568
  * entry 适配的三态判据读 `groups.claimOf`;session 适配没有原始清册视图,只记 `take` 过的会话 id。
837
- * 当前只读视图(`rows`)只挂在 entry 域上:只有 purge 要它——盘上后代要按清册里还在的 id 排除。
569
+ * 收缩中的当前只读视图不再外递:purge 那一半连同视图住「清册作用域」(`src/verbs/trash-scope.ts`)。
570
+ * 两个 adapter 只各自**持有**那份视图;按组收缩的判据不抄第二遍,都读 `groups.withoutGroup`。
838
571
  */
839
- /** 恢复 / 彻底删除:原始快照认得、当前视图已经空了 ⇒ 同批前一条带走的。 */
572
+ /** 恢复:原始快照认得、当前视图已经空了 ⇒ 同批前一条带走的。 */
840
573
  function createEntryCarried(original) {
841
574
  let current = [...original];
842
575
  return {
@@ -844,11 +577,8 @@ function createEntryCarried(original) {
844
577
  return claimOf(original, current, id);
845
578
  },
846
579
  take(id) {
847
- const gone = new Set(groupOf(current, id).map((row) => row.id));
848
- if (gone.size === 0) return;
849
- current = current.filter((row) => !gone.has(row.id));
850
- },
851
- rows: () => current
580
+ current = withoutGroup(current, id);
581
+ }
852
582
  };
853
583
  }
854
584
  /** 删除:会话 id 域;`take` 只收这次真的搬走的成员(父 + 盘上的孩子)。 */
@@ -884,6 +614,22 @@ const REQUIRED_ENTRY_FIELDS = {
884
614
  title: "string",
885
615
  sizeBytes: "number"
886
616
  };
617
+ /** 清册行 → 线上清册行形状。**显式字面量、不用 `...row`**:线上多一格必填时这里编译不过。
618
+ * 只搬清册里真有的事实、不带任何只读数;`/list` 的 `toWire` 与详情的子会话摘要共用这一份
619
+ * (否则同一条清册行会有两份会漂移的投影)。 */
620
+ function entryWire(row) {
621
+ return {
622
+ id: row.id,
623
+ sessionId: row.sessionId,
624
+ projectDir: row.projectDir,
625
+ workspaceId: row.workspaceId,
626
+ wasArchived: row.wasArchived,
627
+ deletedAt: row.deletedAt,
628
+ title: row.title,
629
+ sizeBytes: row.sizeBytes,
630
+ ...row.parentEntryId === void 0 ? {} : { parentEntryId: row.parentEntryId }
631
+ };
632
+ }
887
633
  const pad = (n, w = 2) => String(n).padStart(w, "0");
888
634
  function makeEntryId(deletedAt, sessionDirName) {
889
635
  const d = new Date(deletedAt);
@@ -896,6 +642,7 @@ function parseEntryId(id) {
896
642
  const m = ENTRY_ID_RE.exec(id);
897
643
  if (!m) throw new Error(`bad entry id: ${id}`);
898
644
  const [, y, mo, d, h, mi, s, sessionDirName] = m;
645
+ if (y === void 0 || mo === void 0 || d === void 0 || h === void 0 || mi === void 0 || s === void 0 || sessionDirName === void 0) throw new Error(`bad entry id: ${id}`);
899
646
  return {
900
647
  deletedAt: Date.UTC(+y, +mo - 1, +d, +h, +mi, +s),
901
648
  sessionDirName
@@ -1021,7 +768,9 @@ async function assertNoLive(host, sessionIds) {
1021
768
  }
1022
769
  //#endregion
1023
770
  //#region src/verbs/member-presence.ts
1024
- /** 本仓的在场能力实现:端口形状住 `src/ports/presence-port.ts`,这里只做三态与真值表。
771
+ /** 本仓的在场能力实现,也是**全仓唯一的盖章处**:端口形状住 `src/ports/presence-port.ts`,这里只做
772
+ * 三态与真值表。品牌字段是类型层的(unique symbol 不导出、没有运行时值),所以只有这一处显式断言
773
+ * 能把三件方法盖成 `PresenceCapability`——手拼同样的三件满足不了那个面(`tests/deps.test.ts` 钉住)。
1025
774
  * `announceRestored` 直接交宿主那一手:能力面与宿主面同名同签名,再包一层只会多一个转调。 */
1026
775
  function createMemberPresence(host) {
1027
776
  return {
@@ -1289,7 +1038,11 @@ function isMagicAt(raw, at) {
1289
1038
  return MAGIC.every((byte, i) => raw[at + i] === byte);
1290
1039
  }
1291
1040
  function readUint24LE(raw, at) {
1292
- return raw[at] | raw[at + 1] << 8 | raw[at + 2] << 16;
1041
+ const b0 = raw[at];
1042
+ const b1 = raw[at + 1];
1043
+ const b2 = raw[at + 2];
1044
+ if (b0 === void 0 || b1 === void 0 || b2 === void 0) return void 0;
1045
+ return b0 | b1 << 8 | b2 << 16;
1293
1046
  }
1294
1047
  /** 块体之后有没有那 4 字节尾巴:只有"跳过它之后仍是帧头或到 EOF"才认。 */
1295
1048
  function withFrameTail(raw, at) {
@@ -1319,7 +1072,7 @@ function frameRanges(raw) {
1319
1072
  for (;;) {
1320
1073
  const blockHeader = readUint24LE(raw, cursor);
1321
1074
  cursor += BLOCK_HEADER_BYTES;
1322
- if (cursor > raw.length) throw new Error(`zstd 块头越界:帧起于 ${at},读到偏移 ${cursor}(文件长 ${raw.length})`);
1075
+ if (blockHeader === void 0 || cursor > raw.length) throw new Error(`zstd 块头越界:帧起于 ${at},读到偏移 ${cursor}(文件长 ${raw.length})`);
1323
1076
  const blockType = blockHeader >> BLOCK_TYPE_SHIFT & 3;
1324
1077
  const blockSize = blockHeader >> BLOCK_SIZE_SHIFT & BLOCK_SIZE_MASK;
1325
1078
  if (blockType === BLOCK_RESERVED) throw new Error(`zstd 保留块类型:帧起于 ${at},偏移 ${cursor - BLOCK_HEADER_BYTES} 的块头 type=3(规范 Reserved,对面解不开)`);
@@ -1420,7 +1173,7 @@ function walkSessionLog(raw, onRecord) {
1420
1173
  try {
1421
1174
  plain = zlib.zstdDecompressSync(raw.subarray(start, end));
1422
1175
  } catch (error) {
1423
- throw new Error(`回收站日志第 ${stats.frames} 帧解压失败:${String(error)}`);
1176
+ throw new Error(`回收站日志第 ${stats.frames} 帧解压失败:${String(error)}`, { cause: error });
1424
1177
  }
1425
1178
  const merged = carry.length === 0 ? plain : Buffer.concat([carry, plain]);
1426
1179
  const cut = merged.lastIndexOf(NEWLINE);
@@ -1464,8 +1217,14 @@ function readSessionHeader(raw) {
1464
1217
  * ② 只要剩余引用源读不出来,就整体跳过(fail closed)——宁可留孤儿,不许删共享。
1465
1218
  * 引用源"读不出来"包括:目录/文件读失败、目录非空却没有规范 zstd 日志(明文/陌生布局)、
1466
1219
  * JSON 超出扫描上限、日志有坏行或尾巴被截断。
1220
+ * 宿主的内核写锁 `session.lock` 例外:它不是会话内容,恒为 0 字节时既不算读不懂、也不算
1221
+ * "目录里有东西";非空才回落到上面的 fail closed(判据见 `imageIdsOfDir`)。
1467
1222
  */
1468
1223
  const ATTACHMENT_ID = /^sha256:[0-9a-f]{64}$/u;
1224
+ /** 合法附件 ID:形状是 `sha256:` + 64 位小写十六进制。
1225
+ * 谓词必须收成**模板字面量形状**而不是 `string`:`attachmentPathOf` 里 `!isAttachmentId(id)` 的
1226
+ * 假支若按「是 string」取反会被 TS 收成 `never`(参数本来就是 string),插值就成了 never 读数。
1227
+ * 这里判的仍是同一条正则,谓词只是把「形状」写进类型面。 */
1469
1228
  function isAttachmentId(value) {
1470
1229
  return typeof value === "string" && ATTACHMENT_ID.test(value);
1471
1230
  }
@@ -1543,8 +1302,15 @@ function scanImageIdsInLog(raw) {
1543
1302
  }
1544
1303
  /** 宿主写日志时的临时名:`session.vN.jsonl.zstd.<hash>.tmp`(内容写完后才 rename 成规范名)。 */
1545
1304
  const TEMP_LOG_NAME = /^session(?:\.v[1-9][0-9]*)?\.jsonl(?:\.zstd)?\.[0-9a-f]+\.tmp$/u;
1305
+ /**
1306
+ * 宿主的内核写锁:宿主以写方式打开它即截断、**从不写入内容**、释放也从不删除(POSIX 上是
1307
+ * `flock(2)` 的目标,Windows 上没有这个文件)——所以每个已实体化的会话目录、以及跟着搬进
1308
+ * 回收站的条目里,它都与日志常态并存。锁只表达"谁在写",不承载会话记录。
1309
+ */
1310
+ const LOCK_NAME = "session.lock";
1546
1311
  /** 规范日志之外允许并存的两类文件:更老一代的规范日志(新代包含旧代)与 0 字节临时日志(没有消息)。
1547
- * 其余任何文件都可能是规范日志没覆盖到的引用(例如写入中的非空临时日志),一律按不可读处理。 */
1312
+ * 其余任何文件都可能是规范日志没覆盖到的引用(例如写入中的非空临时日志),一律按不可读处理。
1313
+ * 宿主的 `session.lock` 到不了这里——它在 `imageIdsOfDir` 挑名单时就按"不是会话内容"剥掉了。 */
1548
1314
  async function unreadableExtraFile(deps, dir, names) {
1549
1315
  for (const name of names) {
1550
1316
  if (isCanonicalSessionLogName(name)) continue;
@@ -1559,13 +1325,28 @@ async function unreadableExtraFile(deps, dir, names) {
1559
1325
  * 同样按不可读处理(宁可留下对象等维护卡兜底,不冒"没引用")。
1560
1326
  * **规范日志旁的文件也要过关**:老一代规范日志可以并存(新代包含旧代);0 字节临时日志是
1561
1327
  * 写盘未完成的空产物,也没有引用。非空临时日志、明文日志或其他任何文件仍按不可读处理(fail closed)。
1328
+ * **宿主的内核写锁不是会话内容**:0 字节的锁在判目录形状之前先剥掉——不然每个已实体化的会话目录
1329
+ * (含搬进回收站的条目)都会被读成"读不懂",整份引用扫描在真机上恒跳过;没有日志的锁目录因此与
1330
+ * 空目录同判。非空的锁说明我们对这个文件的理解失效(宿主不会往里写字节),仍按不可读处理。
1562
1331
  */
1563
1332
  async function imageIdsOfDir(deps, dir) {
1564
1333
  if (!await deps.fs.exists(dir)) return { ids: /* @__PURE__ */ new Set() };
1565
1334
  let names;
1566
1335
  try {
1567
1336
  names = await deps.fs.listFiles(dir);
1568
- } catch (error) {
1337
+ const withoutLock = [];
1338
+ for (const name of names) {
1339
+ if (name !== LOCK_NAME) {
1340
+ withoutLock.push(name);
1341
+ continue;
1342
+ }
1343
+ if ((await deps.fs.statFile(`${dir}/${name}`)).size > 0) return {
1344
+ ids: /* @__PURE__ */ new Set(),
1345
+ unreadable: `${dir}: 锁文件 ${name} 非空,无法确认里面没有引用`
1346
+ };
1347
+ }
1348
+ names = withoutLock;
1349
+ } catch (error) {
1569
1350
  return {
1570
1351
  ids: /* @__PURE__ */ new Set(),
1571
1352
  unreadable: String(error)
@@ -1878,7 +1659,11 @@ async function cleanOrphanImageAttachments(deps) {
1878
1659
  //#region src/verbs/permanent-removal.ts
1879
1660
  /**
1880
1661
  * 永久删除的测量、计划与执行:先记录目录/字节/账本归属,再按计划动盘。
1881
- * 计划函数只读;活体准入在计划阶段、任何写之前完成。
1662
+ * 计划函数只读;活体准入在计划阶段、任何写之前完成,执行器动第一笔写前再查一次。
1663
+ *
1664
+ * 测量与补账本归属**分家**:`/list` 的只读计划只吃 {@link measureMembers}(零账本读,不再为每个
1665
+ * 盘上后代问一次 `workspaceOf`,`/list` 的失败面不再含账本归属读);`workspaceOf` 只有
1666
+ * purge / orphan-clean 的删除计划({@link planMemberRemovals})才付——executor 摘账本要用它。
1882
1667
  */
1883
1668
  /** `exists → sizeOfDir` 的唯一一条度量口径(成员目录与回收站目录共用):先问在不在,再量字节;
1884
1669
  * ENOENT 是唯一一种当"不在"的失败,别的错误照旧响亮。别再在调用点各写一遍这段 try/catch。
@@ -1916,18 +1701,32 @@ async function measureMemberDir(deps, member) {
1916
1701
  bytes: probe.bytes
1917
1702
  } : void 0;
1918
1703
  }
1919
- /** 把一组成员折成"删之前要记下的计划";目录不在的成员跳过(记录与盘不一致是那条成员自己的事)。
1920
- * `purge` 的盘上后代、`orphan-clean` 的整组与 `/list` 的盘上残留都走这一处,别再各写一遍
1921
- * measure + workspaceOf。 */
1922
- async function planMemberRemovals(deps, members) {
1923
- const plans = [];
1704
+ /** 只测量(目录 + 实测字节):`/list` 的只读计划只吃这一支,零账本读。目录不在的成员跳过
1705
+ * (记录与盘不一致是那条成员自己的事)。为什么不顺手把归属也问了:`/list` 投影只用字节与条数,
1706
+ * 那一格立刻被丢弃——每开一次回收站为它付 N 次宿主调用,还把账本归属读拉进 `/list` 的失败面。 */
1707
+ async function measureMembers(deps, members) {
1708
+ const out = [];
1924
1709
  for (const member of members) {
1925
1710
  const measured = await measureMemberDir(deps, member);
1926
1711
  if (measured === void 0) continue;
1927
- const workspaceId = await deps.host.workspaceOf(member.sessionId);
1928
- plans.push({
1712
+ out.push({
1929
1713
  sessionId: member.sessionId,
1930
- ...measured,
1714
+ projectDir: member.projectDir,
1715
+ ...measured
1716
+ });
1717
+ }
1718
+ return out;
1719
+ }
1720
+ /** 把一组成员折成"删之前要记下的计划":{@link measureMembers} 的测量之外**逐成员补账本归属**
1721
+ * (`workspaceOf`)——executor 摘账本要用。`/list` 不走这里(它只吃 measureMembers,零账本读)。 */
1722
+ async function planMemberRemovals(deps, members) {
1723
+ const plans = [];
1724
+ for (const measured of await measureMembers(deps, members)) {
1725
+ const workspaceId = await deps.host.workspaceOf(measured.sessionId);
1726
+ plans.push({
1727
+ sessionId: measured.sessionId,
1728
+ dir: measured.dir,
1729
+ bytes: measured.bytes,
1931
1730
  ...workspaceId === void 0 ? {} : { workspaceId }
1932
1731
  });
1933
1732
  }
@@ -1947,7 +1746,7 @@ async function measureTrashRow(deps, entry) {
1947
1746
  /**
1948
1747
  * 盘上后代的选择判据(`/list` 与 purge 的删除计划共用这一份):`subagentMembersOf` 一次问全部父,
1949
1748
  * 再按 `bareSessionId` **排除全部清册 id**(跟着父进来的孩子不按盘上残留再算一遍),同一个 bare id 只认
1950
- * **遍历顺序里第一次**出现的那条(同一个会话在两代宿主里的写法不同)。
1749
+ * **遍历顺序里第一次**出现的那条(同一个会话在两代宿主里的写法不同;去重口径住 `src/domain/closure.ts` 的 `firstByBare`)。
1951
1750
  *
1952
1751
  * 语料看不见(`available: false`)⇒ 每个根都按空成员收:`/list` 与 purge 只许静默降级,
1953
1752
  * 盘上残留留给 `GET /orphans` 兜底。
@@ -1962,32 +1761,41 @@ async function measureTrashRow(deps, entry) {
1962
1761
  async function selectStrandedMembers(host, manifest, parentIds) {
1963
1762
  const manifestIds = new Set(manifest.map((row) => bareSessionId(row.sessionId)));
1964
1763
  const read = await host.subagentMembersOf(parentIds);
1965
- const seen = /* @__PURE__ */ new Set();
1966
- return parentIds.map((parentId) => {
1967
- const wanted = [];
1968
- if (!read.available) return wanted;
1764
+ if (!read.available) return parentIds.map(() => []);
1765
+ const flat = [];
1766
+ parentIds.forEach((parentId, groupIndex) => {
1969
1767
  for (const member of read.value[parentId] ?? []) {
1970
- const bare = bareSessionId(member.sessionId);
1971
- if (manifestIds.has(bare) || seen.has(bare)) continue;
1972
- seen.add(bare);
1973
- wanted.push(member);
1768
+ if (manifestIds.has(bareSessionId(member.sessionId))) continue;
1769
+ flat.push({
1770
+ sessionId: member.sessionId,
1771
+ projectDir: member.projectDir,
1772
+ member,
1773
+ groupIndex
1774
+ });
1974
1775
  }
1975
- return wanted;
1976
1776
  });
1777
+ const out = parentIds.map(() => []);
1778
+ for (const entry of firstByBare(flat)) {
1779
+ const bucket = out[entry.groupIndex];
1780
+ if (bucket === void 0) throw verbError("io", `子会话分组越界:${entry.member.sessionId}`);
1781
+ bucket.push(entry.member);
1782
+ }
1783
+ return out;
1977
1784
  }
1978
1785
  /**
1979
1786
  * `/list` 的只读计划:一行 = 一组。释放量与 purge 用同一条口径——回收站目录与成员目录**现测**,
1980
1787
  * 不用清册里记的 `sizeBytes`(那是删除那一刻的事实,盘上早就变了)。
1981
1788
  *
1982
1789
  * 盘上后代经 `selectStrandedMembers` 选出(排除全部清册 id、bare id 全局只算一次);目录不在的成员
1983
- * 不进 `members`(与 `planMemberRemovals` 同口径)。
1790
+ * 不进 `members`(与 purge 计划同口径)。成员只吃 {@link measureMembers}:**零账本读**——不再为每个
1791
+ * 盘上后代问一次 `workspaceOf`,`/list` 的失败面不再含账本归属读(归属只有 purge 摘账本才付)。
1984
1792
  */
1985
1793
  async function planVisibleTrash(deps, rows, groups) {
1986
1794
  const candidates = await selectStrandedMembers(deps.host, rows, groups.map((group) => group.root.sessionId));
1987
1795
  return await Promise.all(groups.map(async ({ root, kids }, index) => {
1988
1796
  const rootRow = await measureTrashRow(deps, root);
1989
1797
  const kidRows = await Promise.all(kids.map((kid) => measureTrashRow(deps, kid)));
1990
- const members = await planMemberRemovals(deps, candidates[index] ?? []);
1798
+ const members = await measureMembers(deps, candidates[index] ?? []);
1991
1799
  const subagentBytes = kidRows.reduce((total, row) => total + row.bytes, 0);
1992
1800
  const strandedBytes = members.reduce((total, member) => total + member.bytes, 0);
1993
1801
  return {
@@ -2007,7 +1815,8 @@ function totalBytes(items) {
2007
1815
  }
2008
1816
  /**
2009
1817
  * purge 的删除计划:`targets` 由调用方按组语义(`trash/groups.ts`)选好,这里只量、只筛、只查活体。
2010
- * **计划函数就是执行前的闸**——调用方拿到计划才允许写,所以准入必须发生在任何写之前。
1818
+ * **计划函数是执行前的第一道闸**——调用方拿到计划才允许写;计划与第一笔写之间的窗口由
1819
+ * `executeRemoval` 在首笔写前复查(见该函数头注)。
2011
1820
  *
2012
1821
  * - `trash` 按 targets 原序逐个实测(目录缺席的行 `present:false` / 0 字节,但清册行仍要摘)。
2013
1822
  * - 盘上后代经 `selectStrandedMembers` 选出(一次问全部 targets、排除全部清册 id、bare id 全局只计划一次)。
@@ -2016,7 +1825,7 @@ function totalBytes(items) {
2016
1825
  * - `attachments` 由被删目录(targets + 这些成员)里的图片引用与全部剩余引用源算独占;共享的保留、
2017
1826
  * 剩余引用源读不出就整体跳过(判据住 `trash/attachments.ts`,这里只接线)。
2018
1827
  * - 活体准入在量目录与任何写之前逐个查 targets 与**全部枚举到的**盘上后代;任一在跑就整条拒绝、
2019
- * 零副作用。没有跳过它的开关——计划就是执行前的闸(ADR-0006)。
1828
+ * 零副作用。没有跳过它的开关;执行器首笔写前还会用计划里的 `unarchive` 名单复查(ADR-0027)。
2020
1829
  * - `sessionQuery` 缺席时端口回 `{ available: false }` ⇒ members 为空、不抛(盘上残留留给 `GET /orphans` 兜底)。
2021
1830
  */
2022
1831
  async function planTrashRemoval(deps, rows, targets) {
@@ -2059,8 +1868,15 @@ async function planOrphanRemoval(deps, members) {
2059
1868
  };
2060
1869
  }
2061
1870
  /**
2062
- * 按计划执行一次永久删除:只写、不再量、不再判活体(计划就是执行前的闸)。回执的字节念计划
2063
- * (`plan.bytes`),执行期不再累加一遍。
1871
+ * 按计划执行一次永久删除:不再量。回执的字节念计划(`plan.bytes`),执行期不再累加一遍。
1872
+ *
1873
+ * **计划 + 执行器、准入查两遍**(ADR-0027):计划期准入证明计划成立时没有会话在跑;执行器首笔写前
1874
+ * 再用同一份名单复查,补上附件扫描撑开的窗口。
1875
+ *
1876
+ * 计划期准入与第一笔写之间还隔着附件引用的全 home 扫描(`planImageAttachmentRemoval`),大 home
1877
+ * 上那是秒级窗口——期间用户 resume 一个会话,它的目录随后仍会被删。所以动任何写之前用计划里同一份
1878
+ * 会话名单**再查一次活体**(只读、廉价);这一查失败仍然零写入。名单取 `plan.unarchive`:
1879
+ * 它覆盖所有会被删目录的会话(回收站行与盘上成员),目录已不在的成员没有可删的东西。
2064
1880
  *
2065
1881
  * 顺序:整批摘归档集 → 摘有账本的成员的账本 → 逐条回收站行
2066
1882
  * (在才删目录 → 摘清册行 → 通告成员离场)→ 逐条盘上成员(删目录 → 通告成员离场)→ 逐条附件对象。
@@ -2077,6 +1893,7 @@ async function planOrphanRemoval(deps, members) {
2077
1893
  * 通告只经 `member-presence`(摘活体三态 + `api-session/removed`),不在这里另写一份。
2078
1894
  */
2079
1895
  async function executeRemoval(deps, plan) {
1896
+ await assertNoLive(deps.host, plan.unarchive);
2080
1897
  const presence = deps.presence;
2081
1898
  let removed = 0;
2082
1899
  /** 删到这一刻已经腾出的**进度**:只喂 `orphan` 的部分回执;成功回执念计划的合计(`plan.bytes`)。 */
@@ -2123,7 +1940,7 @@ async function executeRemoval(deps, plan) {
2123
1940
  try {
2124
1941
  await deps.ledger.remove(row.entry.id);
2125
1942
  } catch (error) {
2126
- fail("删除回收站目录失败", error, row.entry.sessionId);
1943
+ fail("摘除回收站条目失败", error, row.entry.sessionId);
2127
1944
  }
2128
1945
  removed += 1;
2129
1946
  await presence.memberGone(row.entry.sessionId);
@@ -2158,47 +1975,13 @@ async function executeRemoval(deps, plan) {
2158
1975
  * 彻底删除(组语义见 `src/trash/groups.ts`),把它的根当孤儿删掉就是**替用户做了一个没人点过的决定**。孤儿只
2159
1976
  * 有一种来路:父被彻底删掉了(或被手工从盘上清掉了),清册里再也没有这一行。
2160
1977
  *
2161
- * 根按**传递闭包**收全部后代(与 `HostCorpusPort.subagentMembersOf` 同一口径:孩子与孙代都算,深度不设上限),
2162
- * 同一条记录只归一组(`claimed`)——数据里真出现环时结果是"少数一条",不是把一个会话删两遍。
1978
+ * 根按**传递闭包**收全部后代(与 `HostCorpusPort.subagentMembersOf` 同一实现:闭包核心住
1979
+ * `src/domain/closure.ts` 的 `orphanRootsOf`,孩子与孙代都算,深度不设上限),同一条记录只归一组
1980
+ * (`claimed`)——数据里真出现环时结果是"少数一条",不是把一个会话删两遍。
2163
1981
  * 归堆与去重**两边都去 `session-` 前缀**:同一个父在两代宿主里写法不同(见 `bareSessionId` 的来历)。
2164
1982
  */
2165
1983
  function orphanGroupsOf(corpus, trashSessionIds) {
2166
- const known = /* @__PURE__ */ new Set();
2167
- for (const session of corpus) known.add(bareSessionId(session.sessionId));
2168
- for (const id of trashSessionIds) known.add(bareSessionId(id));
2169
- const children = /* @__PURE__ */ new Map();
2170
- for (const session of corpus) {
2171
- const parent = session.parentSessionId;
2172
- if (parent === void 0) continue;
2173
- const key = bareSessionId(parent);
2174
- const list = children.get(key);
2175
- if (list === void 0) children.set(key, [session]);
2176
- else list.push(session);
2177
- }
2178
- const claimed = /* @__PURE__ */ new Set();
2179
- const groups = [];
2180
- for (const session of corpus) {
2181
- const parent = session.parentSessionId;
2182
- if (!session.subagent || parent === void 0) continue;
2183
- if (known.has(bareSessionId(parent))) continue;
2184
- if (claimed.has(bareSessionId(session.sessionId))) continue;
2185
- const members = [];
2186
- const queue = [session];
2187
- for (let i = 0; i < queue.length; i += 1) {
2188
- const current = queue[i];
2189
- const id = bareSessionId(current.sessionId);
2190
- if (claimed.has(id)) continue;
2191
- claimed.add(id);
2192
- members.push(current);
2193
- for (const child of children.get(id) ?? []) queue.push(child);
2194
- }
2195
- groups.push({
2196
- root: session,
2197
- parentSessionId: parent,
2198
- members
2199
- });
2200
- }
2201
- return groups;
1984
+ return orphanRootsOf(corpus, [...corpus.map((session) => session.sessionId), ...trashSessionIds]);
2202
1985
  }
2203
1986
  /** **本函数是纯扫描,不对账、不写清册行**(`/orphans` 声明为 pure,一次扫描不能顺手写行)。
2204
1987
  * 清册行由调用方选好再交进来:`/orphans` 交 `read.rows()`(raw 索引),`orphan-clean` 交
@@ -2207,12 +1990,17 @@ function orphanGroupsOf(corpus, trashSessionIds) {
2207
1990
  *
2208
1991
  * `listSessions()` 回 `{ available: false }` 时**必须抛**:那是宿主的会话语料服务没挂,不是"这个家没有孤儿"。
2209
1992
  * 拿缺席当空语料 ⇒ 报告说"零条孤儿"、界面上一句"没有要清理的",而盘上真有几百 MB——那是假话,
2210
- * 所以这里按 `io` 响亮失败(AGENTS.md:`available: false` 意味着服务缺席,扫描方不许冒充读数)。 */
2211
- async function loadOrphanGroups(deps, trash) {
1993
+ * 所以这里按 `io` 响亮失败(AGENTS.md:`available: false` 意味着服务缺席,扫描方不许冒充读数)。
1994
+ *
1995
+ * `roots` 只收请求点名的那几组、**在量字节之前过滤**:`/orphans` 不传(报告全部),
1996
+ * `orphan-clean` 传这次的根——否则点一组会把整个家所有孤儿的树都递归量一遍。 */
1997
+ async function loadOrphanGroups(deps, trash, roots) {
2212
1998
  const read = await deps.host.listSessions();
2213
1999
  if (!read.available) throw verbError("io", "无主子会话扫描需要宿主的 sessionQuery.listSessions");
2214
2000
  const corpus = read.value;
2215
- const groups = orphanGroupsOf(corpus, trash.map((entry) => entry.sessionId));
2001
+ const all = orphanGroupsOf(corpus, trash.map((entry) => entry.sessionId));
2002
+ const wanted = roots === void 0 ? void 0 : new Set(roots.map((root) => bareSessionId(root)));
2003
+ const groups = wanted === void 0 ? all : all.filter((group) => wanted.has(bareSessionId(group.root.sessionId)));
2216
2004
  const out = [];
2217
2005
  for (const group of groups) {
2218
2006
  const members = [];
@@ -2224,85 +2012,435 @@ async function loadOrphanGroups(deps, trash) {
2224
2012
  bytes: measured?.bytes ?? 0
2225
2013
  });
2226
2014
  }
2227
- out.push({
2228
- root: members[0],
2229
- parentSessionId: group.parentSessionId,
2230
- members
2231
- });
2232
- }
2233
- return out;
2234
- }
2235
- /** 把一组组收成那份报告:根清单 + 闭包总数/总字节 + 失踪父的**去重计数** + 按项目目录的分摊。
2236
- * `groups` 按字节从多到少排(界面上"哪家还剩得最多"要看第一行)。 */
2237
- function reportOrphans(groups) {
2238
- const projects = /* @__PURE__ */ new Map();
2239
- let totalSessions = 0;
2240
- let totalBytes = 0;
2241
- for (const group of groups) for (const member of group.members) {
2242
- totalSessions += 1;
2243
- totalBytes += member.bytes;
2244
- const row = projects.get(member.projectDir) ?? {
2245
- sessions: 0,
2246
- bytes: 0
2247
- };
2248
- row.sessions += 1;
2249
- row.bytes += member.bytes;
2250
- projects.set(member.projectDir, row);
2251
- }
2252
- return {
2253
- roots: groups.map((group) => group.root.sessionId),
2254
- totalSessions,
2255
- totalBytes,
2256
- missingParents: new Set(groups.map((group) => bareSessionId(group.parentSessionId))).size,
2257
- groups: [...projects].map(([projectDir, value]) => ({
2258
- projectDir,
2259
- ...value
2260
- })).sort((a, b) => b.bytes - a.bytes)
2261
- };
2262
- }
2263
- /**
2264
- * 清一组:`planOrphanRemoval`(只读计划,整组 live 准入在一切写之前)→ `executeRemoval`(只写)。
2265
- * 量目录、摘归档集与账本、删目录与成员通告的顺序和失败形状都住 `verbs/permanent-removal.ts`;
2266
- * 这里只把这一组接上去,别在这再长出一段手写步骤(purge 走的是同一条路)。
2267
- *
2268
- * 顺序与删除那一半是**对偶**的,但不是照抄:
2269
- * - 删除那一半不再用归档藏会话(ADR-0008):它摘账本、搬目录,最后才摘活体。这里目录是**删掉**
2270
- * 不是搬走,藏不藏都不影响可见性 ⇒ 归档集反而**在写之前整批摘掉**:失败时目录还在,下一次还能重试,
2271
- * 不会留下"会话没了但还在归档集里挂着"的幽灵 id。
2272
- * - `unarchive` 对未归档的会话是官方幂等 no-op(`registry.unarchiveSession`),所以这里不需要那次
2273
- * `wasArchived` 读——这里没有"还原到删除前"的义务。
2274
- * - 摘账本只在账本真记着它时做(`workspaceOf` 未命中 = 本来就是「未分组」,不是故障)。
2275
- * - 独占图片的剩余引用源由附件域自己扫:活动会话 + 全部 session-trash + storages/cache。
2276
- */
2277
- async function cleanOrphanGroup(deps, group) {
2278
- return await executeRemoval(deps, await planOrphanRemoval(deps, group.members));
2279
- }
2280
- //#endregion
2281
- //#region src/verbs/purge-trash.ts
2282
- /**
2283
- * 彻底删除:从回收站里**真的**抹掉一条(或整组、或整站),并连带那些"还留在盘上、没被带走"的后代。
2284
- *
2285
- * 与另外两个动词的关系(ADR-0002):它的 interface 是"这一组目标 + 一份只读清册快照
2286
- *(targets 缺席 = 清空)";目标由 `verbs/batch-carried.ts` 按组语义算好,批量的"已被同批前一条
2287
- * 带走"判据不在这里。`requestedId` 是唯一的例外参数,但它**不参与任何判据**:只是让
2288
- * `trash-empty` 的原文点得出用户点的是哪一条(原文要上屏,点名承重),批量语义仍在批量层。
2289
- *
2290
- * **这条动词只做两件事:拿目标、把计划交给执行器**。量目录、筛盘上后代、活体准入与"先退归档集、
2291
- * 再摘账本、最后删目录"的顺序都住 `verbs/permanent-removal.ts`——计划只读,执行器只写,计划就是
2292
- * 执行前的闸(别在这里再长出一段手写步骤)。
2293
- *
2294
- * **这条动词不做回滚**:目录删掉就没有"退回去"这回事(删到一半失败时已删目录不回滚;
2295
- * 带部分计数的 `details` 回执只属于 `orphan-clean`,purge 的 `removed` / `freedBytes` 仍只在成功回执里给)。
2296
- * 对应地,`kind:'trash'` 的计划失败时执行器只抛那一步的 `io` 与原文、不带 details。
2297
- *
2298
- * 回执里的 `attachments` 原样来自执行器:独占图片在会话目录删完之后才清,附件失败只计数、不改
2299
- * `removed` / `freedBytes`(`skipped` = 有候选或剩余引用源读不出、这一轮部分或整体没清,原因上屏)。
2300
- */
2301
- function purgeTrash(deps) {
2302
- return async function purgeTrash(targets, rows, requestedId) {
2303
- const selected = targets ?? rows;
2304
- if (targets !== void 0 && selected.length === 0) throw trashEmpty(requestedId);
2305
- return await executeRemoval(deps, await planTrashRemoval(deps, rows, selected));
2015
+ const root = members[0];
2016
+ if (root === void 0) throw verbError("io", `无主子会话组没有成员(父 ${group.parentSessionId})`);
2017
+ out.push({
2018
+ root,
2019
+ parentSessionId: group.parentSessionId,
2020
+ members
2021
+ });
2022
+ }
2023
+ return out;
2024
+ }
2025
+ /** 把一组组收成那份报告:根清单 + 闭包总数/总字节 + 失踪父的**去重计数** + 按项目目录的分摊。
2026
+ * `groups` 按字节从多到少排(界面上"哪家还剩得最多"要看第一行)。 */
2027
+ function reportOrphans(groups) {
2028
+ const projects = /* @__PURE__ */ new Map();
2029
+ let totalSessions = 0;
2030
+ let totalBytes = 0;
2031
+ for (const group of groups) for (const member of group.members) {
2032
+ totalSessions += 1;
2033
+ totalBytes += member.bytes;
2034
+ const row = projects.get(member.projectDir) ?? {
2035
+ sessions: 0,
2036
+ bytes: 0
2037
+ };
2038
+ row.sessions += 1;
2039
+ row.bytes += member.bytes;
2040
+ projects.set(member.projectDir, row);
2041
+ }
2042
+ return {
2043
+ roots: groups.map((group) => group.root.sessionId),
2044
+ totalSessions,
2045
+ totalBytes,
2046
+ missingParents: new Set(groups.map((group) => bareSessionId(group.parentSessionId))).size,
2047
+ groups: [...projects].map(([projectDir, value]) => ({
2048
+ projectDir,
2049
+ ...value
2050
+ })).sort((a, b) => b.bytes - a.bytes)
2051
+ };
2052
+ }
2053
+ /**
2054
+ * 清一组:`planOrphanRemoval`(只读计划,整组 live 准入在一切写之前)→ `executeRemoval`(只写)。
2055
+ * 量目录、摘归档集与账本、删目录与成员通告的顺序和失败形状都住 `verbs/permanent-removal.ts`;
2056
+ * 这里只把这一组接上去,别在这再长出一段手写步骤(purge 走的是同一条路)。
2057
+ *
2058
+ * 顺序与删除那一半是**对偶**的,但不是照抄:
2059
+ * - 删除那一半不再用归档藏会话(ADR-0008):它摘账本、搬目录,最后才摘活体。这里目录是**删掉**
2060
+ * 不是搬走,藏不藏都不影响可见性 ⇒ 归档集反而**在写之前整批摘掉**:失败时目录还在,下一次还能重试,
2061
+ * 不会留下"会话没了但还在归档集里挂着"的幽灵 id。
2062
+ * - `unarchive` 对未归档的会话是官方幂等 no-op(`registry.unarchiveSession`),所以这里不需要那次
2063
+ * `wasArchived` 读——这里没有"还原到删除前"的义务。
2064
+ * - 摘账本只在账本真记着它时做(`workspaceOf` 未命中 = 本来就是「未分组」,不是故障)。
2065
+ * - 独占图片的剩余引用源由附件域自己扫:活动会话 + 全部 session-trash + storages/cache。
2066
+ */
2067
+ async function cleanOrphanGroup(deps, group) {
2068
+ return await executeRemoval(deps, await planOrphanRemoval(deps, group.members));
2069
+ }
2070
+ //#endregion
2071
+ //#region src/ports/agent-handles.ts
2072
+ const CAPTURED_AGENT_HANDLES = Symbol.for("dsh-session-delete.captured-agent-handles");
2073
+ /** 在 `ctx.agents` 上包一层 `resume` / `create`,把返回的 agent handle 的 dispose 按会话 id 记下。
2074
+ * 服务缺席时走 `ctx.inject(['agents'])` **等服务挂上再装**——live profile 的插件激活顺序可能早于
2075
+ * `agents` 服务就绪;只在 apply 时 `get` 一次会让捕获静默缺席(真机症状:重启前在回收站的能冷恢复,
2076
+ * 刚删除的会话恢复后旧 agent 拦住 prompt)。形状不符 / 属性不可写都只是**不捕获**,不影响插件激活。
2077
+ *
2078
+ * **安装时机**:先 `get('agents')`,没装成再 `inject(['agents'])`(两者只装一次,符号表兜住)。
2079
+ * **symbol 表**:句柄表挂在服务实例的 {@link CAPTURED_AGENT_HANDLES} 上;同一个 agents 服务上的第二次
2080
+ * 安装(`get` 与 `inject` 各一次,或第二个 `createHostPort`)看见它就直接共用,不把 wrapper 套第二层。
2081
+ * **读回判据**:cordis 的 traceable 服务代理每次读函数都会新包一层(`get` 里的 `createShadowMethod`),
2082
+ * 所以只能看 own property descriptor 的身份;拿 `service[name]` 读回比身份是必然的假警报。
2083
+ */
2084
+ function captureAgentHandles(ctx) {
2085
+ let handles = /* @__PURE__ */ new Map();
2086
+ let installed = false;
2087
+ const install = (candidate) => {
2088
+ if (installed) return;
2089
+ const service = candidate;
2090
+ if (service === void 0 || service === null) return;
2091
+ const existing = service[CAPTURED_AGENT_HANDLES];
2092
+ if (existing !== void 0) {
2093
+ handles = existing;
2094
+ installed = true;
2095
+ return;
2096
+ }
2097
+ let wrappedCount = 0;
2098
+ for (const name of ["resume", "create"]) try {
2099
+ const original = service[name];
2100
+ if (typeof original !== "function") continue;
2101
+ const wrapped = function(...args) {
2102
+ const result = Reflect.apply(original, this, args);
2103
+ result.then((value) => {
2104
+ const handle = value;
2105
+ const id = handle?.agent?.id;
2106
+ const dispose = handle?.dispose;
2107
+ if (typeof id !== "string" || id.length === 0 || typeof dispose !== "function") return;
2108
+ handles.set(id, async () => {
2109
+ await dispose.call(handle);
2110
+ });
2111
+ }, () => void 0);
2112
+ return result;
2113
+ };
2114
+ service[name] = wrapped;
2115
+ if (Object.getOwnPropertyDescriptor(service, name)?.value !== wrapped) throw new Error(`agents.${name} is not writable`);
2116
+ wrappedCount += 1;
2117
+ } catch {}
2118
+ if (wrappedCount === 0) return;
2119
+ try {
2120
+ service[CAPTURED_AGENT_HANDLES] = handles;
2121
+ } catch {}
2122
+ installed = true;
2123
+ };
2124
+ const service = ctx.get("agents");
2125
+ if (service !== void 0 && service !== null) install(service);
2126
+ if (!installed && typeof ctx.inject === "function") try {
2127
+ ctx.inject(["agents"], (child) => {
2128
+ install(child.get("agents"));
2129
+ });
2130
+ } catch {}
2131
+ return { async dispose(sessionId) {
2132
+ const dispose = handles.get(sessionId);
2133
+ if (dispose === void 0) return;
2134
+ try {
2135
+ await dispose();
2136
+ } finally {
2137
+ handles.delete(sessionId);
2138
+ }
2139
+ } };
2140
+ }
2141
+ //#endregion
2142
+ //#region src/ports/host-port.ts
2143
+ /** live store 的最小方法面判据(同 `projectionCacheOf` 的手法:按方法面判,不按 constructor.name)。 */
2144
+ function liveSessionsOf(ctx) {
2145
+ const store = ctx.get("sessions");
2146
+ if (store === void 0 || store === null) return void 0;
2147
+ if (typeof store.get !== "function" || typeof store.liveEntryFor !== "function") return void 0;
2148
+ return store;
2149
+ }
2150
+ /** 官方的「这些父的孩子」那一支:`kind:'parent'` 的判据逐字是 `values.includes(record.header.parentSession ?? null)`。 */
2151
+ async function filterChildrenOf(sessionQuery, values) {
2152
+ return sessionQuery.filterSessions([{
2153
+ kind: "parent",
2154
+ values: [...values].sort()
2155
+ }]);
2156
+ }
2157
+ /**
2158
+ * 从若干根逐层向下问出后代,交回 `父(bare)→ 孩子` 的索引。
2159
+ * 用 `kind:'parent'` 而不是 traceSession:父进回收站后 traceSession 认不出目标(宿主失败码
2160
+ * `SESSION_QUERY_SESSION_NOT_FOUND`),而这里要的正是父不在宿主列表之后仍留在盘上的那批。
2161
+ * 出处:asar `dsh-session-query/lib/index.js` 的 `filterSessions`。一层一次宿主调用,问空即停;
2162
+ * `seen` 防环;没有 `header.id` 的记录整条跳过(无法作为身份继续下问)。
2163
+ */
2164
+ async function descendantsByParent(sessionQuery, roots) {
2165
+ const children = /* @__PURE__ */ new Map();
2166
+ const seen = new Set(roots.map(bareSessionId));
2167
+ let frontier = [...seen];
2168
+ while (frontier.length > 0) {
2169
+ const values = [];
2170
+ for (const bare of frontier) for (const shape of sessionIdShapes(bare)) if (!values.includes(shape)) values.push(shape);
2171
+ const next = [];
2172
+ for (const record of await filterChildrenOf(sessionQuery, values)) {
2173
+ const id = record.header?.id;
2174
+ const parent = record.header?.parentSession;
2175
+ if (typeof id !== "string" || id.length === 0) continue;
2176
+ if (typeof parent !== "string" || parent.length === 0) continue;
2177
+ const bare = bareSessionId(id);
2178
+ if (seen.has(bare)) continue;
2179
+ seen.add(bare);
2180
+ const cwd = record.header?.cwd;
2181
+ const descendant = {
2182
+ sessionId: id,
2183
+ projectDir: cwd === void 0 ? NO_CWD_PROJECT_DIR : projectKey(cwd)
2184
+ };
2185
+ const parentBare = bareSessionId(parent);
2186
+ const siblings = children.get(parentBare);
2187
+ if (siblings === void 0) children.set(parentBare, [descendant]);
2188
+ else siblings.push(descendant);
2189
+ next.push(bare);
2190
+ }
2191
+ frontier = next;
2192
+ }
2193
+ return children;
2194
+ }
2195
+ /** {@link HostCorpusPort.subagentMembersOf} 的那一次 BFS:这里只负责问宿主,某个根的后代闭包
2196
+ * 由纯部件的 `closureOf` 在交回的索引上收(深度不设上限、防环、首见去重都在那一处)。
2197
+ * 空清单在调用宿主之前就返回(不为一张空表扫全库)。 */
2198
+ async function membersFor(sessionQuery, parentIds) {
2199
+ const wanted = [];
2200
+ for (const id of parentIds) if (id.length > 0 && !wanted.includes(id)) wanted.push(id);
2201
+ if (wanted.length === 0) return {};
2202
+ const children = await descendantsByParent(sessionQuery, wanted);
2203
+ const out = {};
2204
+ for (const id of wanted) out[id] = closureOf(children, id);
2205
+ return out;
2206
+ }
2207
+ /** 无 cwd 的会话落在 `_no-cwd/`;`projectDirOf` 与回收站对账共用这个字面量。
2208
+ * 出处:asar `dsh-session-persistence-jsonl/lib/index.js` 的 `projectDir`(`if (cwd === void 0) return join(root, "_no-cwd");`)。 */
2209
+ const NO_CWD_PROJECT_DIR = "_no-cwd";
2210
+ /** 宿主 `projectKey(cwd)` 的逐字镜像:跨插件不能 import,宿主也没把它暴露成服务。
2211
+ * 出处:asar `dsh-session-persistence-jsonl/lib/index.js` 的 `projectKey`;调用链
2212
+ * `locate` → `logPath` → `projectDir` → `projectKey`。本机实测 `D:/develop/GitHub/dsh-session-delete`
2213
+ * → `--D-develop-GitHub-dsh-session-delete--`。`projectDirOf` 与回收站对账重建共用这一份;
2214
+ * 宿主换代先复核算法。 */
2215
+ function projectKey(cwd) {
2216
+ let readable = "";
2217
+ let separatorRun = false;
2218
+ for (let i = 0; i < cwd.length; i++) {
2219
+ const code = cwd.charCodeAt(i);
2220
+ const ch = String.fromCharCode(code);
2221
+ if (ch === "/" || ch === "\\" || ch === ":") {
2222
+ if (!separatorRun) readable += "-";
2223
+ separatorRun = true;
2224
+ } else if (ch !== "~" && /^[A-Za-z0-9._-]$/.test(ch)) {
2225
+ readable += ch;
2226
+ separatorRun = false;
2227
+ } else {
2228
+ readable += `~${code.toString(16).toUpperCase().padStart(4, "0")}`;
2229
+ separatorRun = false;
2230
+ }
2231
+ }
2232
+ return `--${(readable.replace(/^-+/, "") || "root").slice(0, 251)}--`;
2233
+ }
2234
+ /** 投影缓存服务的最小方法面判据(按方法面判,不按 `constructor.name` 判)。 */
2235
+ function projectionCacheOf(ctx) {
2236
+ const cache = ctx.get("sessionProjectionCache");
2237
+ if (cache === void 0 || cache === null) return void 0;
2238
+ if (typeof cache.cachedSnapshot !== "function" || typeof cache.cachedPredecessorTitle !== "function") return void 0;
2239
+ return cache;
2240
+ }
2241
+ /** 宿主 `readSessionHeader` 对未知会话抛的是裸 `Error`,只认这句;真存储故障照抛,不能折成未命中。
2242
+ * 出处:asar `dsh-workspace/lib/types/index.js` 的
2243
+ * `cannot validate session '${id}': session persistence holds no such session`。
2244
+ * 同文件有类型的近似句是 `WorkspaceUnknownSessionError`(`hold` 无 `s`),不会误伤。 */
2245
+ const NO_SUCH_SESSION = "session persistence holds no such session";
2246
+ /** 只认上面那一句;其余(含非 Error 抛出物)一律**不算未命中**。 */
2247
+ function isUnknownSession(error) {
2248
+ return error instanceof Error && error.message.includes(NO_SUCH_SESSION);
2249
+ }
2250
+ /** 宿主会话表的一次取数(`ctx.sessionController.list()` 的两种返回形状都折成数组)。
2251
+ * 服务没挂 / 形状不对 / 抛错 ⇒ 空表——**这条不替宿主兜错误**:调用方拿空表的语义都是"少发一条通告",
2252
+ * 不是"恢复失败"。 */
2253
+ async function controllerItems(host) {
2254
+ try {
2255
+ const controller = host.get("sessionController");
2256
+ if (controller === void 0 || controller === null || typeof controller.list !== "function") return [];
2257
+ const listed = await controller.list();
2258
+ const items = Array.isArray(listed) ? listed : listed?.items;
2259
+ return Array.isArray(items) ? items.map((item) => item) : [];
2260
+ } catch {
2261
+ return [];
2262
+ }
2263
+ }
2264
+ /** 账本里没有那个工作区时 {@link HostPort.attach} / {@link HostPort.detach} 抛的原话开头。
2265
+ * **原话与判据同住这里**:抛它的是这个端口,认它的也是端口给的那句,调用方不许另抄一份字符串。 */
2266
+ const WORKSPACE_MISSING_MESSAGE = "workspace not found";
2267
+ /** 这次失败是不是"账本里没那个工作区"(而不是另有故障)。恢复侧靠它把两种失败分开:
2268
+ * 前者按「未分组」收,后者照旧回滚报 `io`——不给真故障静默改归属的机会。 */
2269
+ function isWorkspaceMissingError(error) {
2270
+ return error instanceof Error && error.message.startsWith(WORKSPACE_MISSING_MESSAGE);
2271
+ }
2272
+ /** 宿主服务的真实绑定;出错原样抛,由 `toRemoteFailure` 按 name 映射。
2273
+ * 各方法调用的服务与方法见上方成员注释;错误映射表住 `src/remote/map-error.ts`。 */
2274
+ function createHostPort(ctx) {
2275
+ const host = ctx;
2276
+ const registry = host.workspaceRegistry;
2277
+ const agentHandles = captureAgentHandles(host);
2278
+ return {
2279
+ /** 账本里记着这个会话的工作区:`registry.list()` 的实体 `sessionIds`(该 getter 已按 canonical cwd 过滤过)。 */
2280
+ async workspaceOf(sessionId) {
2281
+ return registry.list().find((workspace) => workspace.sessionIds.includes(sessionId))?.id;
2282
+ },
2283
+ /** 账本里还有这个工作区吗:`registry.get(id)` 是 `this.entities.get(id)` 的直通(同步 Map 查找),
2284
+ * 未知 id 回 `undefined` ⇒ 这里只做一次判别,不抛。 */
2285
+ async workspaceExists(workspaceId) {
2286
+ return registry.get(workspaceId) !== void 0;
2287
+ },
2288
+ /**
2289
+ * cwd → 宿主项目目录名;没有 cwd 落到 `_no-cwd`。
2290
+ * 账本里没有这个会话回 `undefined`(未命中,不是故障);真存储故障照抛。
2291
+ * 未命中由 `delete-session.ts` 折成 `not-found`,真故障留 `io`——两者不能混。
2292
+ */
2293
+ async projectDirOf(sessionId) {
2294
+ let header;
2295
+ try {
2296
+ header = await registry.readSessionHeader(sessionId);
2297
+ } catch (error) {
2298
+ if (isUnknownSession(error)) return void 0;
2299
+ throw error;
2300
+ }
2301
+ return header.cwd === void 0 ? NO_CWD_PROJECT_DIR : projectKey(header.cwd);
2302
+ },
2303
+ /** 标题走宿主投影缓存;尽力取,取不到返回空串,绝不因此让删除失败。 */
2304
+ async titleOf(sessionId) {
2305
+ try {
2306
+ const header = await registry.readSessionHeader(sessionId);
2307
+ const cache = projectionCacheOf(host);
2308
+ const title = (cache?.cachedSnapshot(header, ["title"]) ?? cache?.cachedPredecessorTitle(header))?.values.title;
2309
+ return typeof title === "string" ? title : "";
2310
+ } catch {
2311
+ return "";
2312
+ }
2313
+ },
2314
+ /** 活跃判据走宿主 `workspace/session-activity` waterfall:空数组 = 无活动;
2315
+ * 与宿主 archiveSession 的准入同源。 */
2316
+ async isLive(sessionId) {
2317
+ return (await host.waterfall("workspace/session-activity", { sessionId }, () => Promise.resolve([]))).length > 0;
2318
+ },
2319
+ /** registry 全局归档集(数组,`state.archivedSessionIds`)。 */
2320
+ async isArchived(sessionId) {
2321
+ return registry.archivedSessionIds.includes(sessionId);
2322
+ },
2323
+ /**
2324
+ * 从 `ctx.sessions` 摘掉会话,并关闭捕获到的 agent handle。
2325
+ *
2326
+ * 会话列表 = 磁盘持久化 ∪ 内存活体,搬走文件只清掉一侧;宿主 `SessionController` 会丢掉
2327
+ * `AgentHandle`,所以 `agent-handles.ts` 按会话 id 留住 handle,这里先 detach 再 dispose。
2328
+ * 捕获不到 handle(插件激活前已启动,或 `ctx.agents` 形状变化)时只能摘 session,这是已知限制,
2329
+ * 不拿归档兜底(ADR-0008)。
2330
+ *
2331
+ * 三态:读不到 store / 形状不符 / detach 或 dispose 抛 ⇒ `unknown`(不通告);
2332
+ * 内存里本来没有 ⇒ `not-live`;摘成功 ⇒ `evicted`。任何一步都不抛。
2333
+ */
2334
+ async evictLive(sessionId) {
2335
+ try {
2336
+ const store = liveSessionsOf(host);
2337
+ const session = store?.get(sessionId);
2338
+ if (store === void 0) return "unknown";
2339
+ if (session === void 0 || session === null) {
2340
+ await agentHandles.dispose(sessionId);
2341
+ return "not-live";
2342
+ }
2343
+ const entry = store.liveEntryFor(session);
2344
+ if (entry === void 0 || entry === null || typeof entry.detach !== "function") return "unknown";
2345
+ entry.detach();
2346
+ await agentHandles.dispose(sessionId);
2347
+ return "evicted";
2348
+ } catch {
2349
+ return "unknown";
2350
+ }
2351
+ },
2352
+ /**
2353
+ * 通告客户端这个会话没了:发宿主自己转发的 `api-session/removed`,客户端当场删行。
2354
+ * 冷会话没有 `session/disposed`,不发这条就只能等重连。
2355
+ * 只在宿主列表确实已不含它时调用(调用方按 {@link EvictionOutcome} 判);不发假通告。
2356
+ */
2357
+ async announceRemoved(sessionId) {
2358
+ try {
2359
+ host.emit("api-session/removed", sessionId);
2360
+ } catch {}
2361
+ },
2362
+ /**
2363
+ * 通告这组会话回来了:拉一次宿主会话表,按 id 逐条发 `api-session/added`。
2364
+ * 摘要直接用宿主 `sessionController.list()` 的形状;取不到就不发。
2365
+ * 批量只预取一次,避免按条全表扫。
2366
+ */
2367
+ async announceRestored(sessionIds) {
2368
+ if (sessionIds.length === 0) return;
2369
+ const summaries = [];
2370
+ for (const item of await controllerItems(host)) {
2371
+ const sessionId = item?.sessionId;
2372
+ if (typeof sessionId === "string") summaries.push({
2373
+ sessionId,
2374
+ summary: item
2375
+ });
2376
+ }
2377
+ for (const id of sessionIds) {
2378
+ const summary = summaries.find((item) => item.sessionId === id)?.summary;
2379
+ if (summary === void 0) continue;
2380
+ try {
2381
+ host.emit("api-session/added", JSON.parse(JSON.stringify(summary)));
2382
+ } catch {}
2383
+ }
2384
+ },
2385
+ /** 官方 `unarchiveSession(sessionId)`:未归档是幂等 no-op。 */
2386
+ async unarchive(sessionId) {
2387
+ await registry.unarchiveSession(sessionId);
2388
+ },
2389
+ /** 摘账本:实体方法 `detachSession`(顶层没有);未知工作区**响亮失败**,不静默当成功。 */
2390
+ async detach(sessionId, workspaceId) {
2391
+ const workspace = registry.get(workspaceId);
2392
+ if (workspace === void 0) throw new Error(`${WORKSPACE_MISSING_MESSAGE} (detach): ${workspaceId}`);
2393
+ await workspace.detachSession(sessionId);
2394
+ },
2395
+ /** 挂账本:实体方法 `attachSession`(顶层没有)。 */
2396
+ async attach(sessionId, workspaceId) {
2397
+ const workspace = registry.get(workspaceId);
2398
+ if (workspace === void 0) throw new Error(`${WORKSPACE_MISSING_MESSAGE} (attach): ${workspaceId}`);
2399
+ await workspace.attachSession(sessionId);
2400
+ },
2401
+ /** 确保归档:官方 `archiveSession(sessionId)`。归档是 registry **全局**的,与工作区账目无关
2402
+ * (JSDoc 原文 "its workspace accounting — or lack of one — is irrelevant")⇒ 没有工作区入参,
2403
+ * 调用方也不许再传(传了就是暗示一个从不生效的作用域)。
2404
+ * 不带 `stopActivity` ⇒ 有活动即抛 `WorkspaceActiveSessionError`(→ `sessiondelete/live`,src/shared/wire.ts)。 */
2405
+ async archive(sessionId) {
2406
+ await registry.archiveSession(sessionId);
2407
+ },
2408
+ async listSessions() {
2409
+ const sessionQuery = host.get("sessionQuery");
2410
+ if (typeof sessionQuery?.listSessions !== "function") return { available: false };
2411
+ const records = await sessionQuery.listSessions();
2412
+ const out = [];
2413
+ for (const record of records) {
2414
+ const id = record.header?.id;
2415
+ if (typeof id !== "string" || id === "") continue;
2416
+ const parent = record.header?.parentSession;
2417
+ const cwd = record.header?.cwd;
2418
+ out.push({
2419
+ sessionId: id,
2420
+ ...typeof parent === "string" && parent !== "" ? { parentSessionId: parent } : {},
2421
+ projectDir: cwd === void 0 ? NO_CWD_PROJECT_DIR : projectKey(cwd),
2422
+ subagent: record.header?.origin === "subagent"
2423
+ });
2424
+ }
2425
+ return {
2426
+ available: true,
2427
+ value: out
2428
+ };
2429
+ },
2430
+ /**
2431
+ * 官方 `sessionQuery.filterSessions([{kind:'parent', values}])`,不自扫 `~/.dsh/sessions`。
2432
+ * 数传递闭包(孩子与孙代),不是直接孩子;`session-` 前缀两边都去掉再比,
2433
+ * 按调用方给的写法回键。`sessionQuery` 缺席或方法缺失 ⇒ `{available:false}`,
2434
+ * 不拿空表冒充“没有后代”;服务在场时空入参零宿主调用。
2435
+ */
2436
+ async subagentMembersOf(parentIds) {
2437
+ const sessionQuery = host.get("sessionQuery");
2438
+ if (typeof sessionQuery?.filterSessions !== "function") return { available: false };
2439
+ return {
2440
+ available: true,
2441
+ value: await membersFor(sessionQuery, parentIds)
2442
+ };
2443
+ }
2306
2444
  };
2307
2445
  }
2308
2446
  //#endregion
@@ -2416,7 +2554,7 @@ async function memberRestore(deps, presence, entry) {
2416
2554
  run: async () => {
2417
2555
  await deps.host.unarchive(entry.sessionId);
2418
2556
  },
2419
- undo: () => stepUndo("重新归档失败", () => deps.host.archive(entry.sessionId, workspaceId))
2557
+ undo: () => stepUndo("重新归档失败", () => deps.host.archive(entry.sessionId))
2420
2558
  }],
2421
2559
  {
2422
2560
  key: "manifest",
@@ -2435,6 +2573,43 @@ async function memberRestore(deps, presence, entry) {
2435
2573
  }) };
2436
2574
  }
2437
2575
  //#endregion
2576
+ //#region src/verbs/trash-scope.ts
2577
+ function createTrashScope(deps, rows) {
2578
+ const original = rows;
2579
+ let current = [...rows];
2580
+ /** 拿目标、把计划交给执行器:`targets` 缺席(`undefined`)= 清空。计划只读——活体准入在**一切写
2581
+ * 之前**(任一在跑就整条拒绝、零副作用)。盘上后代按**当前视图里还在的 id** 排除(跟着父进来的
2582
+ * 孩子不按"盘上残留"再删一遍);`sessionQuery` 缺席时端口回 `{ available: false }` ⇒ 这次只清
2583
+ * 清册里的那部分,盘上残留留给 `GET /orphans` 兜底(与 delete 的降级一致,不折成失败)。 */
2584
+ async function purgeGroup(targets, requestedId) {
2585
+ const selected = targets ?? current;
2586
+ if (targets !== void 0 && selected.length === 0) throw trashEmpty(requestedId);
2587
+ return await executeRemoval(deps, await planTrashRemoval(deps, current, selected));
2588
+ }
2589
+ /** 收缩是内部闭包、不外露:唯一的观察面是后续 `purge` / `purgeAll` / `orphanGroups` 看见的当前视图。 */
2590
+ const take = (id) => {
2591
+ current = withoutGroup(current, id);
2592
+ };
2593
+ return {
2594
+ purge: async (id) => {
2595
+ const claim = claimOf(original, current, id);
2596
+ if (claim.verdict === "carried") return {
2597
+ removed: 0,
2598
+ freedBytes: 0
2599
+ };
2600
+ const stats = await purgeGroup(claim.verdict === "fresh" ? claim.group : [], id);
2601
+ take(id);
2602
+ return stats;
2603
+ },
2604
+ purgeAll: async () => {
2605
+ const stats = await purgeGroup(void 0);
2606
+ current = [];
2607
+ return stats;
2608
+ },
2609
+ orphanGroups: (roots) => loadOrphanGroups(deps, current, roots)
2610
+ };
2611
+ }
2612
+ //#endregion
2438
2613
  //#region src/verbs/batch.ts
2439
2614
  /**
2440
2615
  * 「这一批」的唯一实现(ADR-0002):POST /apply 的落点——一组 id 上的同一个动作。
@@ -2445,7 +2620,8 @@ async function memberRestore(deps, presence, entry) {
2445
2620
  * - 恢复通告攒到批尾,一次 announceRestored(ids)。
2446
2621
  *
2447
2622
  * 「已被同批前一条带走」是幂等成功(delete/restore 回 null,purge 回 0),不是失败;
2448
- * 判据在 trash/groups.ts,同批已带走集在 batch-carried.ts。
2623
+ * 判据在 trash/groups.ts,同批已带走集:delete / restore 在 batch-carried.ts,purge 的那份连同
2624
+ * 收缩视图住 trash-scope.ts(清册作用域)。
2449
2625
  */
2450
2626
  function failure(id, action, error) {
2451
2627
  return {
@@ -2498,8 +2674,8 @@ async function applyDelete(deps, ids) {
2498
2674
  return entry;
2499
2675
  });
2500
2676
  }
2501
- /** 「这条是不是被同批前一条带走了」与视图收缩都归 `batch-carried.ts`;`apply` 整批只读一次清册,
2502
- * 动词只拿它交回的只读组与当前清册。 */
2677
+ /** restore 的「这条是不是被同批前一条带走了」与视图收缩都归 `batch-carried.ts`(purge 那一半归
2678
+ * `trash-scope.ts`);`apply` 整批只读一次清册,动词只拿它交回的只读组与当前清册。 */
2503
2679
  async function applyRestore(deps, ids) {
2504
2680
  const carried = createEntryCarried(await deps.ledger.list());
2505
2681
  const run = restoreSession(deps);
@@ -2516,20 +2692,12 @@ async function applyRestore(deps, ids) {
2516
2692
  if (restored.length > 0) await deps.presence.announceRestored(restored);
2517
2693
  return outcomes;
2518
2694
  }
2695
+ /** purge 的整批语义收进清册作用域:选组、收缩视图、同批带走的幂等(回 0)与 absent 的
2696
+ * trash-empty(原文点名)都在 `scope.purge(id)` 里——这里整批只读一次清册、逐 id 只交一个 id,
2697
+ * 两份数组(算好的组 + 收缩中的视图)不再从批量层递两遍。 */
2519
2698
  async function applyPurge(deps, ids) {
2520
- const carried = createEntryCarried(await deps.ledger.list());
2521
- const run = purgeTrash(deps);
2522
- return forEachId("purge", ids, async (entryId) => {
2523
- const claim = carried.claim(entryId);
2524
- if (claim.verdict === "carried") return {
2525
- removed: 0,
2526
- freedBytes: 0
2527
- };
2528
- const group = claim.verdict === "fresh" ? claim.group : [];
2529
- const stats = await run(group, carried.rows(), entryId);
2530
- carried.take(entryId);
2531
- return stats;
2532
- });
2699
+ const scope = createTrashScope(deps, await deps.ledger.list());
2700
+ return forEachId("purge", ids, (entryId) => scope.purge(entryId));
2533
2701
  }
2534
2702
  /** 删除确认框那句「含 N 个子会话」:一次问完整批(`subagentMembersOf` 本来就是批量口)。
2535
2703
  * 宿主口缺席(`available:false`)时按 0(这里不再有"空表"这一步);真读失败则整次调用失败,
@@ -2551,7 +2719,7 @@ async function applyCount(deps, ids) {
2551
2719
  * 点过的决定(那种组该跟着父恢复或彻底删除)。
2552
2720
  */
2553
2721
  async function applyOrphanClean(deps, ids) {
2554
- const groups = await loadOrphanGroups(deps, await deps.ledger.list());
2722
+ const groups = await createTrashScope(deps, await deps.ledger.list()).orphanGroups(ids);
2555
2723
  const byRoot = new Map(groups.map((group) => [bareSessionId(group.root.sessionId), group]));
2556
2724
  return forEachId("orphan-clean", ids, async (id) => {
2557
2725
  const group = byRoot.get(bareSessionId(id));
@@ -2571,38 +2739,42 @@ function applyActions(deps, action, ids) {
2571
2739
  //#endregion
2572
2740
  //#region src/trash/detail.ts
2573
2741
  /**
2574
- * 回收站**单条详情**:从回收站目录里那条会话自己的日志读出元信息与正文(用例见 `tests/trash-detail.test.ts`)。
2742
+ * 回收站**单条详情**:从回收站目录里那条会话自己的日志读出元信息与正文块(用例见 `tests/trash-detail.test.ts`)。
2575
2743
  *
2576
2744
  * 三层里的策略层——编解码在 `src/log/*`,这里只回答"给谁看、给多少、算不算失败"。
2577
2745
  *
2578
- * 三条硬口径,都不是口味:
2746
+ * 四条硬口径,都不是口味:
2579
2747
  * ① **寻址只认清册(raw 索引)**:`entryId` 先在对账之外的 raw 索引里查,目录一律由 `trashDirOf(record.id, home)` 推
2580
2748
  * ⇒ 外部输入进不了文件系统寻址(不给"传个路径就读任意目录"留缝)。
2581
- * ② **正文只认 `source.kind === "user"`**:`user/message` 里绝大多数是宿主注入的上下文
2582
- * (本机实测一条会话:真实提问 21 条、注入 241 条),不过滤就被淹掉;注入条数照样上线
2583
- * (`injectedCount`),让"为什么少了这么多条"能与页面上的数字对账。
2584
- * ③ **两个闸是载荷闸,不是读盘闸**:每条 3 000 字符、累计 50 万字符(CJK 最坏 ≈ 1.5 MB UTF-8)。
2585
- * 本机存量一条都触发不了(量级随盘上会话数摆动,不在这里钉数)⇒ 它们是防异常
2586
- * 膨胀的;**不设"文件太大就拒绝"**,那种阈值只会把真读得出来的正文挡在外面。
2587
- *
2588
- * 计数与正文**同源过滤、各过各的闸**:`user/message` 先要求 `source.kind === 'user'`,两类都过"空文本**且**
2589
- * 无附件"过滤;`userMessageCount` / `assistantMessageCount` 数的是通过过滤的条数,**不受载荷闸影响**。正文再受
2590
- * 单条/累计两个闸:单条超限截断并把那一条标成 `truncated`,累计到上限后剩下的整条不再收、只累进
2591
- * `omittedByPayloadCap`——所以计数可以大于正文条数,详情里两件事分开说。
2592
- * 附件随消息一起收(`attachmentsInContent`),也有两个闸:每条 20、总量 200;超出的**静默丢**,
2593
- * 不累进 `omittedByPayloadCap`——那个计数说的是"整条正文没进来",拿它兼报少了几张附件会让两个数都对不上。
2594
- */
2595
- /** 每条文字的上限(字符)。超出即截断并置 `truncated`。 */
2596
- const PER_MESSAGE_CHAR_CAP = 3e3;
2597
- /** 一次回信的正文总量上限(字符)。 */
2598
- const TOTAL_CHAR_CAP = 5e5;
2599
- /** 一条消息带多少张附件上线。 */
2600
- const MAX_ATTACHMENTS_PER_MESSAGE = 20;
2601
- /** 一次回信的附件总量上限。 */
2602
- const MAX_ATTACHMENTS_TOTAL = 200;
2749
+ * ② **正文是块,不是消息**:`user/message` 按 `source.kind` 拆成 user / injection;`assistant/message.content`
2750
+ * 按 `text` / `reasoning` 拆块,附件并进相邻的文字块;`tool/call` 建工具块、`tool/result` 按 `callId` 回填;
2751
+ * `system/message` 与 `compaction/summary` 各成一块。turn/step/job/request 这类簿记事件不进正文——它们不是
2752
+ * "用户想看的对话",铺进来只会把真正的提问和回复淹掉。
2753
+ * ③ **分页是游标,不是总量闸**:一次只回尾部一页,`olderCursor` 指页首;客户端把游标原样回传取更早一页。
2754
+ * 页有两道闸:块数 `pageBlocks` 与正文总量 `pageChars`(单块超字符闸仍保留一块,游标才能前进);
2755
+ * 每块另有 `perBlockChars` 的单块闸(正文与工具参数/结果各自算),超了标 `truncated`。
2756
+ * 构建时用**有界缓冲只留当前页**,不把整条日志的正文堆在内存里;工具结果可能落在游标之后,
2757
+ * 仍会回填到页内那个调用块(别把"已完成"误报成"未完成")。
2758
+ * ④ **计数与正文同源过滤、各过各的闸**:`userMessageCount` / `injectedCount` 只数建了块的;`assistantMessageCount`
2759
+ * 数**每一条** assistant/message(含只带 reasoning / tool-call 的);`toolCallCount` 数每一条 tool/call。
2760
+ * 计数是整条日志的,不受分页与任何字符闸影响。
2761
+ *
2762
+ * 附件随块一起收(`attachmentsInContent`):每块最多 20、每页最多 200;超出的**静默丢**,不另立计数——
2763
+ * "少了几张图"与"这块被截断"不是同一件事,拿一个数兼报会让两个数都对不上。
2764
+ */
2765
+ /** 每块文字的上限(字符)。正文、工具参数、工具结果各自吃这一刀。 */
2766
+ const PER_BLOCK_CHAR_CAP = 16e3;
2767
+ /** 一页正文的总字符上限(块按日志顺序累计;单块超闸时仍保留一块)。 */
2768
+ const PAGE_CHAR_LIMIT = 5e5;
2769
+ /** 一块最多带多少张附件上线。 */
2770
+ const MAX_ATTACHMENTS_PER_BLOCK = 20;
2771
+ /** 一页最多带多少张附件上线。 */
2772
+ const MAX_ATTACHMENTS_PER_PAGE = 200;
2603
2773
  const DEFAULT_LIMITS = {
2604
- perMessageChars: PER_MESSAGE_CHAR_CAP,
2605
- totalChars: TOTAL_CHAR_CAP
2774
+ perBlockChars: PER_BLOCK_CHAR_CAP,
2775
+ pageBlocks: 30,
2776
+ pageChars: PAGE_CHAR_LIMIT,
2777
+ subagents: 200
2606
2778
  };
2607
2779
  /** 一条记录里那些 `content[]` 段的文字拼起来(`\n` 分隔;非 text 段一律不参与)。 */
2608
2780
  function textOf(content) {
@@ -2621,9 +2793,195 @@ function attachmentWires(content) {
2621
2793
  ...ref.kind === "image" && ref.height !== void 0 ? { height: ref.height } : {}
2622
2794
  }));
2623
2795
  }
2796
+ /** 单块闸:超过上限就截一刀并置标记。 */
2797
+ function clip(text, cap) {
2798
+ return text.length > cap ? {
2799
+ text: text.slice(0, cap),
2800
+ truncated: true
2801
+ } : {
2802
+ text,
2803
+ truncated: false
2804
+ };
2805
+ }
2806
+ /** 「这块有没有内容」的**唯一判据**:非空正文或至少一个附件。建块(`blockBody`)与出线收尾
2807
+ * (`PageBuilder.finish` 的附件总量闸之后)都认这一支——判据写两遍就是两份会漂移的抄本,
2808
+ * 渲染侧因此不必、也不许再兜空块。 */
2809
+ function hasContent(text, attachments) {
2810
+ return text !== "" || attachments.length > 0;
2811
+ }
2812
+ /** 一块的正文:没内容 ⇒ 这块不建;否则过单块闸截一刀。 */
2813
+ function blockBody(rawText, attachments, cap) {
2814
+ const text = rawText.trim();
2815
+ const kept = attachments.slice(0, MAX_ATTACHMENTS_PER_BLOCK);
2816
+ if (!hasContent(text, kept)) return void 0;
2817
+ const clipped = clip(text, cap);
2818
+ return {
2819
+ text: clipped.text,
2820
+ truncated: clipped.truncated,
2821
+ attachments: kept
2822
+ };
2823
+ }
2824
+ function textBlock(kind, time, rawText, attachments, cap) {
2825
+ const body = blockBody(rawText, attachments, cap);
2826
+ return body === void 0 ? void 0 : {
2827
+ kind,
2828
+ id: "",
2829
+ time,
2830
+ ...body
2831
+ };
2832
+ }
2833
+ function injectionBlock(time, sourceKind, rawText, attachments, cap) {
2834
+ const body = blockBody(rawText, attachments, cap);
2835
+ return body === void 0 ? void 0 : {
2836
+ kind: "injection",
2837
+ id: "",
2838
+ time,
2839
+ sourceKind,
2840
+ ...body
2841
+ };
2842
+ }
2843
+ /** 一块在页级字符闸里占多少字符:正文与工具参数/结果都算;截断标记与附件元数据不计。 */
2844
+ function blockChars(block) {
2845
+ switch (block.kind) {
2846
+ case "tool": return block.args.length + block.result.length;
2847
+ case "user":
2848
+ case "assistant":
2849
+ case "reasoning":
2850
+ case "injection":
2851
+ case "system":
2852
+ case "compaction": return block.text.length;
2853
+ default: return unhandledChars(block);
2854
+ }
2855
+ }
2856
+ /** 新块类型没登记字符口径时编译失败;运行时(前后半版本错配)按 0 计。 */
2857
+ function unhandledChars(block) {
2858
+ return 0;
2859
+ }
2860
+ /**
2861
+ * 一页的有界缓冲:只留游标之前**最后** `pageBlocks` 块,且正文总量不超过 `pageChars`。
2862
+ *
2863
+ * `nextIndex` 数的是整条日志的块序(包括游标之后的块),`buffer` 只装本页。工具结果可能落在
2864
+ * 游标之后:`toolByCallId` 让它在页内那个调用块上回填。
2865
+ *
2866
+ * 配对认的是**块对象**,不是 callId 这一格:宿主重试会让同一个 callId 建出两块,按 callId 摘映射
2867
+ * 会把仍然在页内的另一块误摘成「未完成」——ADR-0026 决定 3 明令不许。所以每个 callId 挂一串页内
2868
+ * 块(按日志顺序),挤出谁就摘谁。本机回收站与 live 日志实测:callId 与结果一比一、无重复、无逆序,
2869
+ * 这一串常态只有一个元素;串与下面的配法是给非常态兜底的。
2870
+ */
2871
+ var PageBuilder = class PageBuilder {
2872
+ buffer = [];
2873
+ toolByCallId = /* @__PURE__ */ new Map();
2874
+ nextIndex = 0;
2875
+ chars = 0;
2876
+ /** `end` 是本页的右边界(不含):块序号大于等于它的不入页;`Infinity` = 从尾部取。 */
2877
+ end;
2878
+ limit;
2879
+ cap;
2880
+ pageChars;
2881
+ constructor(end, limit, cap, pageChars) {
2882
+ this.end = end;
2883
+ this.limit = limit;
2884
+ this.cap = cap;
2885
+ this.pageChars = pageChars;
2886
+ }
2887
+ /** 追加一块:id 用整条日志的块序号盖,页内只留最后 `limit` 块 / `pageChars` 字符。 */
2888
+ add(block) {
2889
+ const index = this.nextIndex++;
2890
+ if (index >= this.end) return;
2891
+ block.id = String(index);
2892
+ const chars = blockChars(block);
2893
+ this.buffer.push({
2894
+ index,
2895
+ block,
2896
+ chars
2897
+ });
2898
+ this.chars += chars;
2899
+ this.trim();
2900
+ if (block.kind === "tool") this.hook(block);
2901
+ }
2902
+ /** 挤出页首:块数超限,或正文超字符闸(但至少留一块,游标才能前进)。 */
2903
+ trim() {
2904
+ while (this.buffer.length > this.limit || this.buffer.length > 1 && this.chars > this.pageChars) {
2905
+ const evicted = this.buffer.shift();
2906
+ if (evicted === void 0) return;
2907
+ this.chars -= evicted.chars;
2908
+ if (evicted.block.kind === "tool") this.unhook(evicted.block);
2909
+ }
2910
+ }
2911
+ /** 没带 callId 的调用块无从配对:照常入页(界面念「未完成」),只是不进配对串。 */
2912
+ static pairable(block) {
2913
+ return block.callId !== "";
2914
+ }
2915
+ hook(block) {
2916
+ if (!PageBuilder.pairable(block)) return;
2917
+ const queued = this.toolByCallId.get(block.callId);
2918
+ if (queued === void 0) this.toolByCallId.set(block.callId, [block]);
2919
+ else queued.push(block);
2920
+ }
2921
+ /** 挤出页的块从它的配对串里按对象摘掉;串空了连 key 一起摘,不留空串。 */
2922
+ unhook(block) {
2923
+ if (!PageBuilder.pairable(block)) return;
2924
+ const queued = this.toolByCallId.get(block.callId);
2925
+ if (queued === void 0) return;
2926
+ const at = queued.indexOf(block);
2927
+ if (at < 0) return;
2928
+ if (queued.length === 1) this.toolByCallId.delete(block.callId);
2929
+ else queued.splice(at, 1);
2930
+ }
2931
+ /**
2932
+ * `tool/result` 回填:配给这一串里**最早那还没有结果**的调用块(同一个 callId 出两块时,结果按
2933
+ * 到达顺序配给先出的调用,两块各留一个读数)。
2934
+ *
2935
+ * 两种情况落不了点,都不改写已经配上结果的块:调用块在更早的页里(那一页自己走一趟时配上);
2936
+ * 结果条数多过页内待配的调用块(一次调用一个读数,后到的不覆盖先配上的)。口径见
2937
+ * `tests/trash-detail.test.ts` 的工具配对那几例。
2938
+ *
2939
+ * 落不了点就丢,不缓存:日志按时间落盘、结果恒在它的调用之后,逆序时这条结果无家可归、块停在
2940
+ * 未完成——为它把游标之后的结果正文留在手里,就拆掉了「只留当前页」这个内存界(ADR-0026 决定 3)。
2941
+ *
2942
+ * 同一 callId 的前一块已被挤出页时,结果会配给页内后一块,后一块自己的结果随之落空:宿主重试
2943
+ * 造出的双块没有可区分的结果序,宁可配对错位也不把仍在页内的块报成「未完成」。这是非常态兜底的
2944
+ * 代价,不另开缓存去修(那会重新把游标之后的正文留在手里)。
2945
+ *
2946
+ * 回填的正文也要计入页级字符闸:超了就挤页首,被挤掉的调用块会随更早一页重新走一遍日志、
2947
+ * 在那一页里配上同一个结果,不会丢成「未完成」。
2948
+ */
2949
+ result(callId, rawResult, isError, attachments) {
2950
+ const queued = this.toolByCallId.get(callId);
2951
+ if (queued === void 0) return;
2952
+ const block = queued.find((candidate) => candidate.status === "unfinished");
2953
+ if (block === void 0) return;
2954
+ const clipped = clip(rawResult.trim(), this.cap);
2955
+ block.result = clipped.text;
2956
+ block.resultTruncated = clipped.truncated;
2957
+ block.status = isError ? "error" : "ok";
2958
+ block.attachments = attachments.slice(0, MAX_ATTACHMENTS_PER_BLOCK);
2959
+ const entry = this.buffer.find((candidate) => candidate.block === block);
2960
+ if (entry !== void 0) {
2961
+ const chars = blockChars(block);
2962
+ this.chars += chars - entry.chars;
2963
+ entry.chars = chars;
2964
+ this.trim();
2965
+ }
2966
+ }
2967
+ finish() {
2968
+ let used = 0;
2969
+ for (const { block } of this.buffer) {
2970
+ const room = Math.max(0, Math.min(block.attachments.length, MAX_ATTACHMENTS_PER_PAGE - used));
2971
+ block.attachments = block.attachments.slice(0, room);
2972
+ used += room;
2973
+ }
2974
+ const first = this.buffer[0];
2975
+ return {
2976
+ blocks: this.buffer.map(({ block }) => block).filter((block) => block.kind === "tool" || hasContent(block.text, block.attachments)),
2977
+ olderCursor: first !== void 0 && first.index > 0 ? first.index : null
2978
+ };
2979
+ }
2980
+ };
2624
2981
  function readTrashDetail(deps, limits = DEFAULT_LIMITS) {
2625
- return async function readTrashDetail(entryId) {
2626
- const record = (await deps.rows()).find((e) => e.id === entryId);
2982
+ return async function readTrashDetail(entryId, before) {
2983
+ const all = await deps.rows();
2984
+ const record = all.find((e) => e.id === entryId);
2627
2985
  if (record === void 0) throw trashEmpty(entryId);
2628
2986
  const dir = trashDirOf(record.id, deps.home);
2629
2987
  if (!await deps.fs.exists(dir)) throw verbError("io", `回收站目录不在:${dir}`);
@@ -2648,42 +3006,16 @@ function readTrashDetail(deps, limits = DEFAULT_LIMITS) {
2648
3006
  assistantMessageCount: 0,
2649
3007
  toolCallCount: 0,
2650
3008
  injectedCount: 0,
2651
- messages: [],
2652
- omittedByPayloadCap: 0
3009
+ blocks: [],
3010
+ olderCursor: null
2653
3011
  };
2654
3012
  const models = /* @__PURE__ */ new Set();
2655
- let usedChars = 0;
2656
- let usedAttachments = 0;
2657
- let capped = false;
2658
- /** 收进正文,顺带管两个闸:截到单条上限,累计到总量就停;附件另有 20/200 两道闸。 */
2659
- function push(role, time, text, attachments) {
2660
- if (capped) {
2661
- detail.omittedByPayloadCap += 1;
2662
- return;
2663
- }
2664
- const truncated = text.length > limits.perMessageChars;
2665
- const kept = truncated ? text.slice(0, limits.perMessageChars) : text;
2666
- if (usedChars + kept.length > limits.totalChars) {
2667
- capped = true;
2668
- detail.omittedByPayloadCap += 1;
2669
- return;
2670
- }
2671
- usedChars += kept.length;
2672
- const room = Math.max(0, Math.min(MAX_ATTACHMENTS_PER_MESSAGE, MAX_ATTACHMENTS_TOTAL - usedAttachments));
2673
- const keptAttachments = attachments.slice(0, room);
2674
- usedAttachments += keptAttachments.length;
2675
- detail.messages.push({
2676
- role,
2677
- time,
2678
- text: kept,
2679
- truncated,
2680
- attachments: keptAttachments
2681
- });
2682
- }
3013
+ const page = new PageBuilder(before ?? Number.POSITIVE_INFINITY, Math.max(1, limits.pageBlocks), limits.perBlockChars, Math.max(1, limits.pageChars ?? 5e5));
2683
3014
  try {
2684
3015
  walkSessionLog(raw, (r) => {
2685
3016
  if (typeof r.time === "number" && r.time > detail.lastActivity) detail.lastActivity = r.time;
2686
3017
  const data = r.data ?? {};
3018
+ const time = r.time ?? 0;
2687
3019
  switch (r.type) {
2688
3020
  case "session":
2689
3021
  if (typeof r.cwd === "string") detail.cwd = r.cwd;
@@ -2695,30 +3027,95 @@ function readTrashDetail(deps, limits = DEFAULT_LIMITS) {
2695
3027
  case "turn/start":
2696
3028
  detail.turnCount += 1;
2697
3029
  return;
2698
- case "tool/call":
2699
- detail.toolCallCount += 1;
2700
- return;
2701
3030
  case "user/message": {
2702
- if ((data.source ?? {}).kind !== "user") {
2703
- detail.injectedCount += 1;
2704
- return;
2705
- }
3031
+ const source = data.source ?? {};
3032
+ const sourceKind = typeof source.kind === "string" ? source.kind : "";
2706
3033
  const text = textOf(data.content);
2707
3034
  const attachments = attachmentWires(data.content);
2708
- if (text === "" && attachments.length === 0) return;
2709
- detail.userMessageCount += 1;
2710
- push("user", r.time ?? 0, text, attachments);
3035
+ if (sourceKind === "user") {
3036
+ const block = textBlock("user", time, text, attachments, limits.perBlockChars);
3037
+ if (block !== void 0) {
3038
+ detail.userMessageCount += 1;
3039
+ page.add(block);
3040
+ }
3041
+ return;
3042
+ }
3043
+ const block = injectionBlock(time, sourceKind, text, attachments, limits.perBlockChars);
3044
+ if (block !== void 0) {
3045
+ detail.injectedCount += 1;
3046
+ page.add(block);
3047
+ }
2711
3048
  return;
2712
3049
  }
2713
3050
  case "assistant/message": {
3051
+ detail.assistantMessageCount += 1;
2714
3052
  const message = data.message ?? {};
2715
3053
  const source = message.source ?? {};
2716
3054
  if (typeof source.model === "string") models.add(source.model);
2717
- const text = textOf(message.content);
2718
- const attachments = attachmentWires(message.content);
2719
- if (text === "" && attachments.length === 0) return;
2720
- detail.assistantMessageCount += 1;
2721
- push("assistant", r.time ?? 0, text, attachments);
3055
+ const parts = Array.isArray(message.content) ? message.content : [];
3056
+ let pendingText = [];
3057
+ let pendingAttachments = [];
3058
+ const flush = () => {
3059
+ const block = textBlock("assistant", time, pendingText.join("\n"), pendingAttachments, limits.perBlockChars);
3060
+ if (block !== void 0) page.add(block);
3061
+ pendingText = [];
3062
+ pendingAttachments = [];
3063
+ };
3064
+ for (const part of parts) {
3065
+ if (part?.type === "text" && typeof part.text === "string") {
3066
+ pendingText.push(part.text);
3067
+ continue;
3068
+ }
3069
+ if (part?.type === "reasoning" && typeof part.text === "string") {
3070
+ flush();
3071
+ const block = textBlock("reasoning", time, part.text, [], limits.perBlockChars);
3072
+ if (block !== void 0) page.add(block);
3073
+ continue;
3074
+ }
3075
+ if (part?.type === "image" || part?.type === "file") {
3076
+ pendingAttachments.push(...attachmentWires([part]));
3077
+ continue;
3078
+ }
3079
+ }
3080
+ flush();
3081
+ return;
3082
+ }
3083
+ case "tool/call": {
3084
+ detail.toolCallCount += 1;
3085
+ const callId = typeof data.callId === "string" ? data.callId : "";
3086
+ const name = typeof data.name === "string" ? data.name : "";
3087
+ const args = clip(typeof data.arguments === "string" ? data.arguments : "", limits.perBlockChars);
3088
+ page.add({
3089
+ kind: "tool",
3090
+ id: "",
3091
+ time,
3092
+ callId,
3093
+ name,
3094
+ status: "unfinished",
3095
+ args: args.text,
3096
+ argsTruncated: args.truncated,
3097
+ result: "",
3098
+ resultTruncated: false,
3099
+ attachments: []
3100
+ });
3101
+ return;
3102
+ }
3103
+ case "tool/result": {
3104
+ const message = data.message ?? {};
3105
+ const callId = typeof message.toolCallId === "string" ? message.toolCallId : "";
3106
+ if (callId === "") return;
3107
+ page.result(callId, textOf(message.content), message.isError === true, attachmentWires(message.content));
3108
+ return;
3109
+ }
3110
+ case "system/message": {
3111
+ const message = data.message ?? {};
3112
+ const block = textBlock("system", time, textOf(message.content), attachmentWires(message.content), limits.perBlockChars);
3113
+ if (block !== void 0) page.add(block);
3114
+ return;
3115
+ }
3116
+ case "compaction/summary": {
3117
+ const block = textBlock("compaction", time, textOf(data.summary), [], limits.perBlockChars);
3118
+ if (block !== void 0) page.add(block);
2722
3119
  return;
2723
3120
  }
2724
3121
  default: return;
@@ -2727,7 +3124,16 @@ function readTrashDetail(deps, limits = DEFAULT_LIMITS) {
2727
3124
  } catch (error) {
2728
3125
  throw verbError("io", error instanceof Error ? `读回收站日志失败:${error.message}` : `读回收站日志失败:${String(error)}`, error);
2729
3126
  }
3127
+ const finished = page.finish();
3128
+ detail.blocks = finished.blocks;
3129
+ detail.olderCursor = finished.olderCursor;
2730
3130
  detail.models = [...models];
3131
+ const kids = visibleGroups(all).find((group) => group.root.id === record.id)?.kids ?? [];
3132
+ if (kids.length > 0) {
3133
+ const limit = limits.subagents ?? 200;
3134
+ detail.subagents = kids.slice(0, limit).map(entryWire);
3135
+ if (kids.length > limit) detail.subagentsTotal = kids.length;
3136
+ }
2731
3137
  return detail;
2732
3138
  };
2733
3139
  }
@@ -2758,7 +3164,8 @@ function sniffImage(bytes) {
2758
3164
  * 否则 `encodeURIComponent` 会在写头时抛)。
2759
3165
  */
2760
3166
  function safeFilename(name, fallback) {
2761
- const base = [...name === null || name === "" ? fallback : name].slice(0, 120).join("").replace(/[\\/:*?"<>|\u0000-\u001f\uD800-\uDFFF]/gu, "_").replace(/\.\./gu, "_");
3167
+ const raw = name === null || name === "" ? fallback : name;
3168
+ const base = Array.from(raw).slice(0, 120).join("").replace(/[\\/:*?"<>|\u0000-\u001f\uD800-\uDFFF]/gu, "_").replace(/\.\./gu, "_");
2762
3169
  return base === "" ? fallback : base;
2763
3170
  }
2764
3171
  async function readAttachmentResponse(deps, query) {
@@ -2822,21 +3229,13 @@ async function reportAttachmentOrphans(deps) {
2822
3229
  //#endregion
2823
3230
  //#region src/api/trash-rows.ts
2824
3231
  /**
2825
- * 清册那一行 → 线上那一行。**显式字面量、不用 `...row`**:线上形状多一个必填字段时,这里编译不过,
2826
- * 于是"线上多了一格却没人填"不可能悄悄发生(`...row` 会把它带过去,看上去一切正常)。
3232
+ * 清册那一行 → 线上那一行。清册字段走 `entryWire` 那份显式字面量(线上形状多一个必填字段时编译不过,
3233
+ * `...row` 会把它带过去),这里只补 `/list` 的只读数。
2827
3234
  */
2828
3235
  function toWire(row, readouts) {
2829
3236
  return {
2830
- id: row.id,
2831
- sessionId: row.sessionId,
2832
- projectDir: row.projectDir,
2833
- workspaceId: row.workspaceId,
2834
- wasArchived: row.wasArchived,
2835
- deletedAt: row.deletedAt,
2836
- title: row.title,
2837
- sizeBytes: row.sizeBytes,
3237
+ ...entryWire(row),
2838
3238
  releaseBytes: readouts.releaseBytes,
2839
- ...row.parentEntryId === void 0 ? {} : { parentEntryId: row.parentEntryId },
2840
3239
  ...readouts.subagentCount === void 0 ? {} : { subagentCount: readouts.subagentCount },
2841
3240
  ...readouts.subagentBytes === void 0 ? {} : { subagentBytes: readouts.subagentBytes },
2842
3241
  ...readouts.strandedSubagents === void 0 ? {} : { strandedSubagents: readouts.strandedSubagents },
@@ -2873,15 +3272,17 @@ async function assembleTrashRows(deps, rows) {
2873
3272
  //#endregion
2874
3273
  //#region src/api/route-table.ts
2875
3274
  /**
2876
- * 路由表(ADR-0004):段名 → { 方法, 纯度, 读面, body, 处理 }。一条记录,两个消费者。
3275
+ * 路由表(ADR-0004;deps 切片见 ADR-0032):段名 → { 方法, 纯度, 读面, body, deps 切片, 处理 }。一条记录,两个消费者。
2877
3276
  *
2878
3277
  * 一致性要求:
2879
3278
  * - 该纯的判成写 ⇒ 探测/正文读/扫描被堵在串行链后;
2880
3279
  * - 该写的判成纯 ⇒ 写动作绕开到达序链,与对账交错;
2881
- * - body 该读没读 ⇒ 下游拿到 null;读两遍 ⇒ 流已被消费。
3280
+ * - body 该读没读 ⇒ 下游拿到 null;读两遍 ⇒ 流已被消费;
3281
+ * - 切片声明宽了 ⇒ 危险能力(删目录 / 时钟)漏进读段的 run;窄了 ⇒ 写段的处理编译不过。
2882
3282
  *
2883
3283
  * 这张表不放 shared/wire.ts:处理函数会 import 动词与 node:fs,而浏览器半要 import wire.ts。
2884
- * 段名与动作仍住 wire.ts;这张表只回答“怎么处理”。
3284
+ * 段名、方法与动作仍住 wire.ts(`ROUTES` 每项 `{ path, method }`,本表的 method 只投影、不写第二份字面量);
3285
+ * 这张表只回答“怎么处理”。
2885
3286
  */
2886
3287
  /** 必填的非空字符串字段(缺、空串、类型不对都是**同一句话**:说清是哪个字段)。 */
2887
3288
  function requireString(body, field) {
@@ -2889,9 +3290,17 @@ function requireString(body, field) {
2889
3290
  if (typeof value !== "string" || value === "") throw routeError("bad-request", 400, `请求体需带非空字符串字段 ${field}`);
2890
3291
  return value;
2891
3292
  }
3293
+ /** `/detail` 的分页游标:缺省 = 从尾部取;给了就必须是非负整数(负数、小数、字符串都算请求不对)。 */
3294
+ function optionalCursor(body) {
3295
+ const value = body?.[PARAMS.before];
3296
+ if (value === void 0) return void 0;
3297
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0) throw routeError("bad-request", 400, `请求体字段 ${PARAMS.before} 需是非负整数`);
3298
+ return value;
3299
+ }
2892
3300
  /**
2893
- * `/apply` 的五个动作与各自的**静态纯度**。一张表两个用途:动作名单由键派生,纯度也从同一格读——
2894
- * 新增动作必须同时给出纯度,漏了编译不过;新加一个纯读动作也不会再静默落进 `chained`。
3301
+ * `/apply` 的五个动作与各自的**静态纯度**。一张表三个用途:动作名单由键派生,纯度从同一格读,
3302
+ * 唯一识别器(`actionOf`)也只认这些键——新增动作必须同时给出纯度,漏了编译不过;
3303
+ * 新加一个纯读动作也不会再静默落进 `chained`。
2895
3304
  */
2896
3305
  const APPLY_ACTION_TABLE = {
2897
3306
  delete: "chained",
@@ -2901,15 +3310,21 @@ const APPLY_ACTION_TABLE = {
2901
3310
  "orphan-clean": "chained"
2902
3311
  };
2903
3312
  const APPLY_ACTIONS = Object.keys(APPLY_ACTION_TABLE);
2904
- /** 认不认得这个动作:`/apply` 的纯度与拒否共用同一条判据,名单只有上面那一张。 */
2905
- function isApplyAction(value) {
2906
- return typeof value === "string" && Object.hasOwn(APPLY_ACTION_TABLE, value);
3313
+ /**
3314
+ * `/apply` 的动作:**全仓唯一识别器**——纯度函数与动作拒否都从这里过,
3315
+ * 不各解析一遍动作。不抛:缺动作 / 不是字符串 / 不在名单,一律回 `undefined`;
3316
+ * 抛不抛、抛哪句话归 `requireAction`。
3317
+ */
3318
+ function actionOf(body) {
3319
+ const value = body?.[PARAMS.action];
3320
+ if (typeof value !== "string" || !Object.hasOwn(APPLY_ACTION_TABLE, value)) return void 0;
3321
+ return value;
2907
3322
  }
2908
3323
  /** `/apply` 的动作:认不得的一律点名拒掉,不折成"空批量"糊弄过去。 */
2909
3324
  function requireAction(body) {
2910
- const value = body?.[PARAMS.action];
2911
- if (!isApplyAction(value)) throw routeError("bad-request", 400, `批量动作不认识:需是 ${APPLY_ACTIONS.join(" / ")} 之一`);
2912
- return value;
3325
+ const action = actionOf(body);
3326
+ if (action === void 0) throw routeError("bad-request", 400, `批量动作不认识:需是 ${APPLY_ACTIONS.join(" / ")} 之一`);
3327
+ return action;
2913
3328
  }
2914
3329
  /** `/apply` 的 id 组:必须是非空字符串数组(空数组不是"什么都不做",是调用方自己没组好)。 */
2915
3330
  function requireIdArray(body) {
@@ -2918,81 +3333,90 @@ function requireIdArray(body) {
2918
3333
  return value;
2919
3334
  }
2920
3335
  /**
2921
- * 九个段名各一行。`Record<段名, RouteSpec>` 是闸:`wire.ts` 加了段名而这里没加,编译不过。
3336
+ * 九个段名各一行。`Record<段名, AnyRouteSpec>` 是闸:`wire.ts` 加了段名而这里没加,编译不过;
3337
+ * 每行的 `slice` 又把该行的 `run` 钉在自己那一格 deps 上(ADR-0032)。
2922
3338
  */
2923
3339
  const ROUTE_TABLE = {
2924
- [ROUTES.list]: {
2925
- method: "GET",
3340
+ [ROUTES.list.path]: {
3341
+ slice: "core",
3342
+ method: ROUTES.list.method,
2926
3343
  body: "none",
2927
3344
  purity: "chained",
2928
3345
  read: "list",
2929
3346
  response: "json",
2930
3347
  run: async (deps, _body, read) => assembleTrashRows(deps, await read.rows())
2931
3348
  },
2932
- [ROUTES.ping]: {
2933
- method: "GET",
3349
+ [ROUTES.ping.path]: {
3350
+ slice: "core",
3351
+ method: ROUTES.ping.method,
2934
3352
  body: "none",
2935
3353
  purity: "pure",
2936
3354
  read: "none",
2937
3355
  response: "json",
2938
3356
  run: async () => "pong"
2939
3357
  },
2940
- [ROUTES.attachment]: {
2941
- method: "GET",
3358
+ [ROUTES.attachment.path]: {
3359
+ slice: "core",
3360
+ method: ROUTES.attachment.method,
2942
3361
  body: "none",
2943
3362
  purity: "pure",
2944
3363
  read: "none",
2945
3364
  response: "binary",
2946
3365
  run: async (deps, _body, _read, query) => readAttachmentResponse(deps, query)
2947
3366
  },
2948
- [ROUTES.attachmentOrphans]: {
2949
- method: "GET",
3367
+ [ROUTES.attachmentOrphans.path]: {
3368
+ slice: "core",
3369
+ method: ROUTES.attachmentOrphans.method,
2950
3370
  body: "none",
2951
3371
  purity: "pure",
2952
3372
  read: "none",
2953
3373
  response: "json",
2954
3374
  run: async (deps) => reportAttachmentOrphans(deps)
2955
3375
  },
2956
- [ROUTES.attachmentClean]: {
2957
- method: "POST",
3376
+ [ROUTES.attachmentClean.path]: {
3377
+ slice: "removal",
3378
+ method: ROUTES.attachmentClean.method,
2958
3379
  body: "none",
2959
3380
  purity: "chained",
2960
3381
  read: "none",
2961
3382
  response: "json",
2962
3383
  run: async (deps) => cleanOrphanImageAttachments(deps)
2963
3384
  },
2964
- [ROUTES.orphans]: {
2965
- method: "GET",
3385
+ [ROUTES.orphans.path]: {
3386
+ slice: "core",
3387
+ method: ROUTES.orphans.method,
2966
3388
  body: "none",
2967
3389
  purity: "pure",
2968
3390
  read: "raw",
2969
3391
  response: "json",
2970
3392
  run: async (deps, _body, read) => reportOrphans(await loadOrphanGroups(deps, await read.rows()))
2971
3393
  },
2972
- [ROUTES.apply]: {
2973
- method: "POST",
3394
+ [ROUTES.apply.path]: {
3395
+ slice: "full",
3396
+ method: ROUTES.apply.method,
2974
3397
  body: "json",
2975
3398
  purity: (body) => {
2976
- const action = body?.[PARAMS.action];
2977
- return isApplyAction(action) ? APPLY_ACTION_TABLE[action] : "chained";
3399
+ const action = actionOf(body);
3400
+ return action === void 0 ? "chained" : APPLY_ACTION_TABLE[action];
2978
3401
  },
2979
3402
  read: "none",
2980
3403
  response: "json",
2981
3404
  run: async (deps, body) => applyActions(deps, requireAction(body), requireIdArray(body))
2982
3405
  },
2983
- [ROUTES.empty]: {
2984
- method: "POST",
3406
+ [ROUTES.empty.path]: {
3407
+ slice: "removal",
3408
+ method: ROUTES.empty.method,
2985
3409
  body: "none",
2986
3410
  purity: "chained",
2987
3411
  read: "list",
2988
3412
  response: "json",
2989
3413
  run: async (deps, _body, read) => {
2990
- const rows = await read.rows();
2991
- return await purgeTrash(deps)(void 0, rows);
3414
+ return await createTrashScope(deps, await read.rows()).purgeAll();
2992
3415
  }
2993
3416
  },
2994
- [ROUTES.detail]: {
2995
- method: "POST",
3417
+ [ROUTES.detail.path]: {
3418
+ slice: "core",
3419
+ method: ROUTES.detail.method,
2996
3420
  body: "json",
2997
3421
  purity: "pure",
2998
3422
  read: "raw",
@@ -3001,7 +3425,7 @@ const ROUTE_TABLE = {
3001
3425
  fs: deps.fs,
3002
3426
  rows: () => read.rows(),
3003
3427
  home: deps.home
3004
- })(requireString(body, PARAMS.entryId))
3428
+ })(requireString(body, PARAMS.entryId), optionalCursor(body))
3005
3429
  }
3006
3430
  };
3007
3431
  /** 段名 → 那一行;不认识的段名回 `undefined`(调用方抛 404,并带出原路径)。 */
@@ -3093,7 +3517,56 @@ function isPure(purity, body) {
3093
3517
  function readBodyFor(kind, req) {
3094
3518
  return kind === "json" ? readJsonBody(req) : null;
3095
3519
  }
3520
+ /**
3521
+ * 全量面按行收窄(ADR-0032):组合根装出的 {@link DeleteDeps} 只交给 `/apply`;每一段只拿到
3522
+ * 自己声明的那一格(路由表的 `slice`)。收窄是**运行期事实**,不是类型投影:`core` 拿到的是
3523
+ * 新建的 `CoreFsPort` 面,`removeDir` / `removeFile` 根本不在对象上;`now` 也不在 `core` / `removal`
3524
+ * 上。三格逐行 `satisfies` 是闸:全量面必须结构满足每一格;`coreOf` 的 fs 字面量又逼着
3525
+ * `CoreFsPort` 新增方法时同步补进来——漏了编译不过,而不是等某个段的 `run` 静默拿到超面。
3526
+ */
3527
+ function coreOf(full) {
3528
+ return {
3529
+ fs: {
3530
+ exists: (p) => full.fs.exists(p),
3531
+ ensureDir: (p) => full.fs.ensureDir(p),
3532
+ rename: (from, to) => full.fs.rename(from, to),
3533
+ sizeOfDir: (p) => full.fs.sizeOfDir(p),
3534
+ listFiles: (p) => full.fs.listFiles(p),
3535
+ listDirs: (p) => full.fs.listDirs(p),
3536
+ realpath: (p) => full.fs.realpath(p),
3537
+ readFile: (p) => full.fs.readFile(p),
3538
+ statFile: (p) => full.fs.statFile(p)
3539
+ },
3540
+ host: full.host,
3541
+ ledger: full.ledger,
3542
+ home: full.home,
3543
+ presence: full.presence
3544
+ };
3545
+ }
3546
+ /** `removal` 保留删除能力,但不带会话删除的时钟;`full` 只给 `/apply`。 */
3547
+ function removalOf(full) {
3548
+ return {
3549
+ fs: full.fs,
3550
+ host: full.host,
3551
+ ledger: full.ledger,
3552
+ home: full.home,
3553
+ presence: full.presence
3554
+ };
3555
+ }
3556
+ /** 三格只建一次:收窄对象在 handler 构造期固定,请求路径只做引用选择。 */
3557
+ function slicesOf(full) {
3558
+ return {
3559
+ core: coreOf(full),
3560
+ removal: removalOf(full),
3561
+ full
3562
+ };
3563
+ }
3564
+ /** 按行选格:`spec.slice` 与三格的键同域,查表结果的类型由 `S` 直接给出。 */
3565
+ function depsFor(spec, slices) {
3566
+ return slices[spec.slice];
3567
+ }
3096
3568
  function createApiHandler(deps, trust) {
3569
+ const slices = slicesOf(deps);
3097
3570
  /**
3098
3571
  * 到达序串行链(见文件头):路由表里 `purity === 'chained'` 的请求一个跑完再放下一个。
3099
3572
  * `tail` 由构造保证**永不 reject**(每个任务自己的失败留在交回给那次请求的那个 promise 上),
@@ -3126,7 +3599,7 @@ function createApiHandler(deps, trust) {
3126
3599
  rowsPromise ??= kind === "list" ? deps.ledger.list() : deps.ledger.raw();
3127
3600
  return rowsPromise;
3128
3601
  } };
3129
- const task = () => spec.run(deps, body, read, url.searchParams);
3602
+ const task = () => spec.run(depsFor(spec, slices), body, read, url.searchParams);
3130
3603
  const result = await (isPure(spec.purity, body) ? task() : throughChain(task));
3131
3604
  if (spec.response === "binary") writeBinary(res, result);
3132
3605
  else writeOk(res, result);
@@ -3405,8 +3878,10 @@ function domainTable(schema) {
3405
3878
  function defineDomain(spec) {
3406
3879
  if (!UNIT_NAME_RE.test(spec.name)) throw new Error(`domain name '${spec.name}' must match ${UNIT_NAME_RE}`);
3407
3880
  if (!Number.isInteger(spec.version) || spec.version < 0) throw new Error(`domain '${spec.name}' version must be a non-negative integer, got ${spec.version}`);
3408
- if (spec.layout !== void 0 && spec.layout !== "single" && spec.layout !== "per-record") throw new Error(`domain '${spec.name}' layout must be 'single' or 'per-record', got ${spec.layout}`);
3409
- if (spec.invalidRecords !== void 0 && spec.invalidRecords !== "backup-and-skip") throw new Error(`domain '${spec.name}' invalidRecords must be 'backup-and-skip' when present`);
3881
+ const layout = spec.layout;
3882
+ if (layout !== void 0 && layout !== "single" && layout !== "per-record") throw new Error(`domain '${spec.name}' layout must be 'single' or 'per-record', got ${layout}`);
3883
+ const invalidRecords = spec.invalidRecords;
3884
+ if (invalidRecords !== void 0 && invalidRecords !== "backup-and-skip") throw new Error(`domain '${spec.name}' invalidRecords must be 'backup-and-skip' when present`);
3410
3885
  for (const table of Object.keys(spec.tables)) if (!UNIT_NAME_RE.test(table)) throw new Error(`domain '${spec.name}' table name '${table}' must match ${UNIT_NAME_RE}`);
3411
3886
  return spec;
3412
3887
  }