@xrn1997/dsh-session-delete 0.11.0 → 0.13.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 (85) hide show
  1. package/LICENSE +201 -201
  2. package/README.md +20 -19
  3. package/THIRD_PARTY_NOTICES.md +2 -2
  4. package/cordis.patch.yml +7 -7
  5. package/docs/DETAIL.md +1 -1
  6. package/docs/DETAIL.zh.md +1 -1
  7. package/docs/screenshots/screenshot-01.png +0 -0
  8. package/docs/screenshots/screenshot-02.png +0 -0
  9. package/lib/client.js +4295 -2160
  10. package/lib/index.js +1273 -243
  11. package/lib/types/api/archive-rows.d.ts +1 -1
  12. package/lib/types/api/project-ranks.d.ts +3 -0
  13. package/lib/types/api/route-table.d.ts +2 -1
  14. package/lib/types/api/search.d.ts +7 -0
  15. package/lib/types/api/trash-rows.d.ts +1 -1
  16. package/lib/types/client/archive-detail.d.ts +7 -2
  17. package/lib/types/client/archive-pane.d.ts +26 -7
  18. package/lib/types/client/archive-store.d.ts +2 -0
  19. package/lib/types/client/attachment-view.d.ts +1 -1
  20. package/lib/types/client/batch-bar.d.ts +1 -1
  21. package/lib/types/client/batch-select.d.ts +2 -2
  22. package/lib/types/client/batch-selection-store.d.ts +7 -8
  23. package/lib/types/client/confirm-dialog.d.ts +6 -2
  24. package/lib/types/client/context.d.ts +11 -3
  25. package/lib/types/client/copy.d.ts +58 -23
  26. package/lib/types/client/delete-action.d.ts +23 -0
  27. package/lib/types/client/delete-menu-item.d.ts +3 -3
  28. package/lib/types/client/drop-machine.d.ts +1 -1
  29. package/lib/types/client/markdown.d.ts +1 -1
  30. package/lib/types/client/panel-tab.d.ts +25 -3
  31. package/lib/types/client/receipt.d.ts +1 -1
  32. package/lib/types/client/remote.d.ts +23 -2
  33. package/lib/types/client/scene.d.ts +5 -7
  34. package/lib/types/client/search-box.d.ts +24 -0
  35. package/lib/types/client/search-preview.d.ts +46 -0
  36. package/lib/types/client/search-results.d.ts +62 -0
  37. package/lib/types/client/search-text.d.ts +13 -0
  38. package/lib/types/client/session-detail.d.ts +17 -1
  39. package/lib/types/client/subagent-section.d.ts +2 -2
  40. package/lib/types/client/trash-detail.d.ts +7 -2
  41. package/lib/types/client/trash-drop.d.ts +3 -3
  42. package/lib/types/client/trash-entry.d.ts +1 -1
  43. package/lib/types/client/trash-store.d.ts +2 -0
  44. package/lib/types/client/trash-tab.d.ts +21 -1
  45. package/lib/types/client/trash-view.d.ts +7 -6
  46. package/lib/types/client/ui/Modal.d.ts +5 -4
  47. package/lib/types/client/ui/Toast.d.ts +13 -3
  48. package/lib/types/client/ui/anchor-fit.d.ts +42 -0
  49. package/lib/types/client/ui/icons.d.ts +13 -2
  50. package/lib/types/client/undo-notices.d.ts +26 -28
  51. package/lib/types/client/undo-toast.d.ts +0 -6
  52. package/lib/types/client/use-archive-panel-controller.d.ts +5 -6
  53. package/lib/types/client/use-detail-rail.d.ts +2 -0
  54. package/lib/types/client/use-gated-refresh.d.ts +7 -1
  55. package/lib/types/client/use-panel-tab.d.ts +1 -1
  56. package/lib/types/client/use-search-view.d.ts +59 -0
  57. package/lib/types/client/use-search.d.ts +62 -0
  58. package/lib/types/client/use-trash-panel-controller.d.ts +6 -0
  59. package/lib/types/client/view-switches.d.ts +29 -0
  60. package/lib/types/client/write-seats.d.ts +21 -13
  61. package/lib/types/log/session-log.d.ts +4 -1
  62. package/lib/types/ports/agent-handles.d.ts +3 -2
  63. package/lib/types/ports/home.d.ts +1 -1
  64. package/lib/types/ports/host-port.d.ts +7 -2
  65. package/lib/types/shared/wire.d.ts +142 -3
  66. package/lib/types/trash/attachments.d.ts +5 -1
  67. package/lib/types/trash/content-text.d.ts +10 -0
  68. package/lib/types/trash/groups.d.ts +18 -6
  69. package/lib/types/trash/search-corpus.d.ts +40 -0
  70. package/lib/types/trash/search-text.d.ts +43 -0
  71. package/lib/types/trash/shrinking-view.d.ts +6 -4
  72. package/lib/types/verbs/batch.d.ts +10 -7
  73. package/lib/types/verbs/delete-session.d.ts +1 -1
  74. package/lib/types/verbs/member-journal.d.ts +1 -1
  75. package/lib/types/verbs/move-directory.d.ts +10 -0
  76. package/lib/types/verbs/orphan-subagents.d.ts +2 -2
  77. package/lib/types/verbs/permanent-removal.d.ts +23 -7
  78. package/lib/types/verbs/restore-session.d.ts +3 -3
  79. package/lib/types/verbs/search.d.ts +53 -0
  80. package/lib/types/verbs/trash-scope.d.ts +5 -1
  81. package/locale/en.json +1 -1
  82. package/locale/zh.json +1 -1
  83. package/package.json +2 -2
  84. package/lib/types/client/batch-confirm.d.ts +0 -36
  85. package/lib/types/client/delete-confirm.d.ts +0 -52
package/lib/index.js CHANGED
@@ -147,7 +147,7 @@ const ROUTES = {
147
147
  method: "POST",
148
148
  body: "entry"
149
149
  },
150
- /** 一组 id 上的同一个动作;删除确认框那句「含 N 个子会话」也走这里(`action: 'count'`,纯读语义)。 */
150
+ /** 一组 id 上的同一个动作;批量已选清单的子会话计数也走这里(`action: 'count'`,纯读语义)。 */
151
151
  apply: {
152
152
  path: "/apply",
153
153
  method: "POST",
@@ -214,6 +214,30 @@ const ROUTES = {
214
214
  path: "/progress",
215
215
  method: "GET",
216
216
  body: "none"
217
+ },
218
+ /** 纯读:**回收站档**按查询串扫一页(标题命中首页给全 + 正文命中一页 + 续扫游标)。不建索引、不缓存、零写入。 */
219
+ search: {
220
+ path: "/search",
221
+ method: "POST",
222
+ body: "search"
223
+ },
224
+ /** 纯读:**归档档**按查询串扫一页;语料是「归档集 ∩ 会话」,读面是宿主 `readSession`,**不碰回收站清册**。 */
225
+ archiveSearch: {
226
+ path: "/archive-search",
227
+ method: "POST",
228
+ body: "search"
229
+ },
230
+ /** 纯读:回收站档一条正文命中的窗口(前邻 / 命中 / 后邻)与本会话命中序号 / 相邻命中下标。 */
231
+ searchPreview: {
232
+ path: "/search-preview",
233
+ method: "POST",
234
+ body: "searchPreview"
235
+ },
236
+ /** 纯读:归档档一条正文命中的窗口;每次重校验归档集成员(ADR-0061 寻址边界)。 */
237
+ archiveSearchPreview: {
238
+ path: "/archive-search-preview",
239
+ method: "POST",
240
+ body: "searchPreview"
217
241
  }
218
242
  };
219
243
  /** 三只可调项的接受范围;表单与归一共用这一格,各写一份就会「表单说能存、激活时说越界」。 */
@@ -231,6 +255,8 @@ const CONFIG_LIMITS = {
231
255
  max: 104857600
232
256
  }
233
257
  };
258
+ /** 检索范围名单:**唯一一处**(游标编码 / 解码与客户端选段都投影它,不各写一份字面量)。 */
259
+ const SEARCH_SCOPES = ["trash", "archive"];
234
260
  /** 请求参数名:浏览器半发、Node 半读,同名同义;附件段是 query 参数。 */
235
261
  const PARAMS = {
236
262
  entryId: "entryId",
@@ -250,7 +276,15 @@ const PARAMS = {
250
276
  /** 字节数:图片支与文件支都带,先过 `maxAttachmentBytes` 闸再让宿主读。 */
251
277
  attachmentBytes: "bytes",
252
278
  attachmentWidth: "width",
253
- attachmentHeight: "height"
279
+ attachmentHeight: "height",
280
+ /** 检索的查询串(浏览器半去抖后原样发来;Node 半归一后匹配)。 */
281
+ query: "query",
282
+ /** 正文命中续扫游标:上一页回的 `cursor` 原样带回;缺省 = 首页。 */
283
+ cursor: "cursor",
284
+ /** 命中预览的寻址键:命中所在行(回收站条目 id / 归档 sessionId)。 */
285
+ rowId: "rowId",
286
+ /** 命中预览要取的那条消息在会话抽取序里的下标。 */
287
+ messageIndex: "messageIndex"
254
288
  };
255
289
  /** 段名表每格 `body` → 字段组;`config` 的三只旋钮由 `src/verbs/config.ts` 自己校验,路由层不重复拦。 */
256
290
  const BODY_GROUPS = {
@@ -269,8 +303,23 @@ const BODY_GROUPS = {
269
303
  [PARAMS.sessionId]: "requiredString",
270
304
  [PARAMS.before]: "optionalCursor",
271
305
  [PARAMS.rootSessionId]: "optionalString"
306
+ },
307
+ /** 检索一页:查询串必填、游标缺省 = 首页;语料由**段名**(`/search` vs `/archive-search`)决定,不在请求体里再带一次范围。 */
308
+ search: {
309
+ [PARAMS.query]: "requiredString",
310
+ [PARAMS.cursor]: "optionalString"
311
+ },
312
+ /** 命中预览:寻址键 + 消息下标;语料同样由段名决定。 */
313
+ searchPreview: {
314
+ [PARAMS.query]: "requiredString",
315
+ [PARAMS.rowId]: "requiredString",
316
+ [PARAMS.messageIndex]: "requiredNumber"
272
317
  }
273
318
  };
319
+ /** 失败信封 `details` 里的附件读数格:批内失败条目也带走自己组的读数(ADR-0070 边界),键名与成功回执的
320
+ * `value.attachments` 同字、同 schema(字段清单住 `ATTACHMENT_CLEANUP_SCHEMA`)。两半只投影这一枚常量,
321
+ * 写侧装配与读侧取数都不各写一份字面量。 */
322
+ const FAILURE_DETAILS_ATTACHMENTS_KEY = "attachments";
274
323
  /** 进程内判别「这已经是一次失败」:按标记位认,不按 `instanceof`(跨 realm / 跨 bundle 不成立)。
275
324
  * 标记位只由宿主服务抛出的 `RemoteError` 自带;线上 JSON 不跟着过线,生产侧不造它。 */
276
325
  function isDSHRemoteError(value) {
@@ -426,7 +475,9 @@ function createFsPort() {
426
475
  if (!entry.isSymbolicLink()) continue;
427
476
  try {
428
477
  if ((await stat(join(p, entry.name))).isDirectory()) dirs.push(entry.name);
429
- } catch {}
478
+ } catch (error) {
479
+ if (!isAbsentPath(error)) throw error;
480
+ }
430
481
  }
431
482
  return dirs;
432
483
  },
@@ -828,64 +879,6 @@ function trashDirOf(entryId, home) {
828
879
  assertSingleSegment(entryId, "回收站条目 id");
829
880
  return `${home}/${TRASH_DIR_NAME}/${entryId}`;
830
881
  }
831
- //#endregion
832
- //#region src/trash/groups.ts
833
- /** 这些孩子的父。 */
834
- function kidsOf(rows, parentId) {
835
- return rows.filter((row) => row.parentEntryId === parentId);
836
- }
837
- /**
838
- * 清单露面的一行 = 组根,按清册原序。孩子折进根那一行(宿主的客户端本来就把 `origin:"subagent"` 的行整排藏了 ⇒ 单列会冒出一堆点不到的行)。
839
- * 折不进去的那两种孩子(父行不在 / 父行自己也是孩子)**自己站出来占一行**——`visibleGroups` 与 `groupOf` 共用这条判据。
840
- */
841
- function visibleGroups(rows) {
842
- const byId = new Map(rows.map((row) => [row.id, row]));
843
- const kidsByRoot = /* @__PURE__ */ new Map();
844
- const folded = /* @__PURE__ */ new Set();
845
- for (const row of rows) {
846
- if (row.parentEntryId === void 0) continue;
847
- const parent = byId.get(row.parentEntryId);
848
- if (parent === void 0 || parent.parentEntryId !== void 0) continue;
849
- folded.add(row.id);
850
- const siblings = kidsByRoot.get(parent.id);
851
- if (siblings === void 0) kidsByRoot.set(parent.id, [row]);
852
- else siblings.push(row);
853
- }
854
- return rows.filter((row) => !folded.has(row.id)).map((root) => ({
855
- root,
856
- kids: kidsByRoot.get(root.id) ?? []
857
- }));
858
- }
859
- /**
860
- * 一条 id 所属的整组。三种形状,三个答案:**组根** ⇒ 它自己 + 它接住的孩子(UI 点的是父那一行,删除/恢复/彻底删除都按整组走);
861
- * **孩子** ⇒ **只回它自己**(清单不单独列它,只有手工/降级路径会点到这里);**清册里没有这一条 id,但还有孩子指向它** ⇒ 那一批孩子;
862
- * 都没有 ⇒ 空数组,调用方据此报 `trash-empty` / 判"已被同批前一条带走"。
863
- */
864
- function groupOf(rows, id) {
865
- const root = rows.find((row) => row.id === id);
866
- if (root !== void 0) return root.parentEntryId === void 0 ? [root, ...kidsOf(rows, id)] : [root];
867
- return kidsOf(rows, id);
868
- }
869
- /**
870
- * 把一条 id 所属的**整组**从快照里摘掉,回一份新快照(组语义仍只读 `groupOf`)。「同批前一条已把这一组带走」的收缩就是它;
871
- * 调用方各自持有那份可变视图,本函数不记账。
872
- */
873
- function withoutGroup(rows, id) {
874
- const gone = new Set(groupOf(rows, id).map((row) => row.id));
875
- return rows.filter((row) => !gone.has(row.id));
876
- }
877
- /**
878
- * 「这条是被**同批前一条**带走的,还是整批开始前就没有,还是仍在?」幂等语义只属于 `carried`:后来者本来就不在清册里(用户点了条幽灵 id、
879
- * 或对账刚摘掉它)必须照样响亮报 `trash-empty`。**所以判据是快照的原始形状,不是当前形状**:原始快照里认得出而当前视图已空 ⇒ 同批带走的。
880
- */
881
- function claimOf(original, current, id) {
882
- if (groupOf(original, id).length === 0) return { verdict: "absent" };
883
- const group = groupOf(current, id);
884
- return group.length === 0 ? { verdict: "carried" } : {
885
- verdict: "fresh",
886
- group
887
- };
888
- }
889
882
  /** 批量面:三个读面各读一次、零逐行读;大小读面抛错按策略折成整档缺席(null)或原样上抛。 */
890
883
  async function readRowSurfaces(deps, ids, policy) {
891
884
  return {
@@ -1595,8 +1588,12 @@ async function planBatchImageAttachmentRemoval(deps, groups) {
1595
1588
  const skipReasons = [];
1596
1589
  if (unreadableCandidates > 0) skipReasons.push(unreadableCandidatesReason(unreadableCandidates));
1597
1590
  const unreadableObjectsByGroup = /* @__PURE__ */ new Map();
1591
+ const candidateGroupIds = /* @__PURE__ */ new Set();
1598
1592
  const candidates = /* @__PURE__ */ new Set();
1599
- for (const ids of candidatesByGroup.values()) for (const id of ids) candidates.add(id);
1593
+ for (const [groupId, ids] of candidatesByGroup) {
1594
+ if (ids.size > 0) candidateGroupIds.add(groupId);
1595
+ for (const id of ids) candidates.add(id);
1596
+ }
1600
1597
  if (candidates.size === 0) return {
1601
1598
  plan: {
1602
1599
  entries: [],
@@ -1606,6 +1603,7 @@ async function planBatchImageAttachmentRemoval(deps, groups) {
1606
1603
  byGroup: /* @__PURE__ */ new Map(),
1607
1604
  unreadableCandidatesByGroup,
1608
1605
  unreadableObjectsByGroup,
1606
+ candidateGroupIds,
1609
1607
  presentDirs
1610
1608
  };
1611
1609
  const scanned = await remainingRefsFailClosed(deps, groups.flatMap((group) => [...group.dirs]), "读不到剩余引用源,无法证明独占");
@@ -1618,6 +1616,7 @@ async function planBatchImageAttachmentRemoval(deps, groups) {
1618
1616
  byGroup: /* @__PURE__ */ new Map(),
1619
1617
  unreadableCandidatesByGroup,
1620
1618
  unreadableObjectsByGroup,
1619
+ candidateGroupIds,
1621
1620
  presentDirs,
1622
1621
  sharedSkipped: scanned.reason
1623
1622
  };
@@ -1663,6 +1662,7 @@ async function planBatchImageAttachmentRemoval(deps, groups) {
1663
1662
  byGroup,
1664
1663
  unreadableCandidatesByGroup,
1665
1664
  unreadableObjectsByGroup,
1665
+ candidateGroupIds,
1666
1666
  presentDirs
1667
1667
  };
1668
1668
  }
@@ -1806,39 +1806,119 @@ async function cleanOrphanImageAttachments(deps) {
1806
1806
  };
1807
1807
  }
1808
1808
  //#endregion
1809
+ //#region src/trash/groups.ts
1810
+ /** 组根判据:自己不记 `parentEntryId` 的那一行。`visibleGroups` / `groupOf` / `rootIdOf` 共用这一条。 */
1811
+ function isRoot(row) {
1812
+ return row.parentEntryId === void 0;
1813
+ }
1814
+ /** 把一份快照索引一次:`byId` 第一行胜(清册是存储域主键 KV,id 应唯一;首行胜与前实现的后者胜只在这类
1815
+ * 不可达输入上不同,`visibleGroups` / `rootIdOf` 共用这一份)。 */
1816
+ function indexGroups(rows) {
1817
+ const byId = /* @__PURE__ */ new Map();
1818
+ const kidsByParent = /* @__PURE__ */ new Map();
1819
+ for (const row of rows) {
1820
+ if (!byId.has(row.id)) byId.set(row.id, row);
1821
+ if (row.parentEntryId === void 0) continue;
1822
+ const kids = kidsByParent.get(row.parentEntryId);
1823
+ if (kids === void 0) kidsByParent.set(row.parentEntryId, [row]);
1824
+ else kids.push(row);
1825
+ }
1826
+ return {
1827
+ byId,
1828
+ kidsByParent
1829
+ };
1830
+ }
1831
+ /**
1832
+ * 清单露面的一行 = 组根,按清册原序。孩子折进根那一行(宿主的客户端本来就把 `origin:"subagent"` 的行整排藏了 ⇒ 单列会冒出一堆点不到的行)。
1833
+ * 折不进去的那两种孩子(父行不在 / 父行自己也是孩子)**自己站出来占一行**——`visibleGroups` 与 `groupOf` 共用这条判据。
1834
+ */
1835
+ function visibleGroups(rows) {
1836
+ const { byId, kidsByParent } = indexGroups(rows);
1837
+ const groups = [];
1838
+ for (const root of rows) {
1839
+ const parent = root.parentEntryId === void 0 ? void 0 : byId.get(root.parentEntryId);
1840
+ if (parent !== void 0 && isRoot(parent)) continue;
1841
+ groups.push({
1842
+ root,
1843
+ kids: isRoot(root) ? kidsByParent.get(root.id) ?? [] : []
1844
+ });
1845
+ }
1846
+ return groups;
1847
+ }
1848
+ /**
1849
+ * 一条 id 所属的整组。三种形状,三个答案:**组根** ⇒ 它自己 + 它接住的孩子(UI 点的是父那一行,删除/恢复/彻底删除都按整组走);
1850
+ * **孩子** ⇒ **只回它自己**(清单不单独列它,只有手工/降级路径会点到这里);**清册里没有这一条 id,但还有孩子指向它** ⇒ 那一批孩子;
1851
+ * 都没有 ⇒ 空数组,调用方据此报 `trash-empty` / 判"已被同批前一条带走"。
1852
+ *
1853
+ * `present` 只用于收缩视图:当前视图里已经不在的行不算进组(默认全在)。
1854
+ */
1855
+ function groupOf(index, id, present = () => true) {
1856
+ const root = present(id) ? index.byId.get(id) : void 0;
1857
+ if (root !== void 0 && !isRoot(root)) return [root];
1858
+ const group = root === void 0 ? [] : [root];
1859
+ for (const kid of index.kidsByParent.get(id) ?? []) if (present(kid.id)) group.push(kid);
1860
+ return group;
1861
+ }
1862
+ /**
1863
+ * 一条 id 的**可见组根**:与 {@link visibleGroups} 的折叠判据同一份——能折进根的孩子归它,折不进去的
1864
+ * (父不在 / 父自己也是孩子)自己就是根。检索把子会话的命中并到组根、预览报归属都用这一份,
1865
+ * 不复刻一遍「沿 parentEntryId 一直上溯」的第二种判据。id 不在快照里回它自己。
1866
+ */
1867
+ function rootIdOf(rows, id) {
1868
+ const index = indexGroups(rows);
1869
+ const row = index.byId.get(id);
1870
+ if (row === void 0 || isRoot(row)) return id;
1871
+ const parent = row.parentEntryId === void 0 ? void 0 : index.byId.get(row.parentEntryId);
1872
+ return parent !== void 0 && isRoot(parent) ? parent.id : row.id;
1873
+ }
1874
+ /**
1875
+ * 「这条是被**同批前一条**带走的,还是整批开始前就没有,还是仍在?」幂等语义只属于 `carried`:后来者本来就不在清册里(用户点了条幽灵 id、
1876
+ * 或对账刚摘掉它)必须照样响亮报 `trash-empty`。**所以判据是快照的原始形状,不是当前形状**:原始快照里认得出而当前视图已空 ⇒ 同批带走的。
1877
+ */
1878
+ function claimOf(index, id, present) {
1879
+ if (!index.byId.has(id) && !index.kidsByParent.has(id)) return { verdict: "absent" };
1880
+ const group = groupOf(index, id, present);
1881
+ return group.length === 0 ? { verdict: "carried" } : {
1882
+ verdict: "fresh",
1883
+ group
1884
+ };
1885
+ }
1886
+ //#endregion
1809
1887
  //#region src/trash/shrinking-view.ts
1810
1888
  /**
1811
1889
  * 开工时把整批的原始快照捕下来(三态判据的「整批开始前的样子」),当前视图从它出发、按组收缩。
1812
1890
  * 调用纪律:`take` / `takeAll` 都在动作**成功之后**才调——清完才收缩,失败时视图不动、下一次重试还能看见这一组。
1813
- * 什么时候收缩、把实例放在哪里仍归调用方:本函数只持有原始与当前两份行,不记账。
1891
+ * 什么时候收缩、把实例放在哪里仍归调用方:本函数只记录哪些行仍在,不改清册。
1814
1892
  */
1815
1893
  function createShrinkingView(rows) {
1816
- const original = rows;
1817
- let current = [...rows];
1894
+ const index = indexGroups(rows);
1895
+ const remaining = new Set(index.byId.keys());
1896
+ const present = (id) => remaining.has(id);
1818
1897
  return {
1819
- claim: (id) => claimOf(original, current, id),
1898
+ claim: (id) => claimOf(index, id, present),
1820
1899
  claimAll: (ids) => {
1821
- let judging = [...current];
1900
+ const predicted = /* @__PURE__ */ new Set();
1901
+ const visible = (id) => present(id) && !predicted.has(id);
1822
1902
  return ids.map((id) => {
1823
- const claim = claimOf(original, judging, id);
1824
- if (claim.verdict === "fresh") judging = withoutGroup(judging, id);
1903
+ const claim = claimOf(index, id, visible);
1904
+ if (claim.verdict === "fresh") for (const row of claim.group) predicted.add(row.id);
1825
1905
  return {
1826
1906
  id,
1827
1907
  ...claim
1828
1908
  };
1829
1909
  });
1830
1910
  },
1911
+ originalGroup: (id) => groupOf(index, id),
1831
1912
  take: (id) => {
1832
- current = withoutGroup(current, id);
1913
+ for (const row of groupOf(index, id, present)) remaining.delete(row.id);
1833
1914
  },
1834
1915
  takeRows: (rowIds) => {
1835
- const gone = new Set(rowIds);
1836
- current = current.filter((row) => !gone.has(row.id));
1916
+ for (const id of rowIds) remaining.delete(id);
1837
1917
  },
1838
1918
  takeAll: () => {
1839
- current = [];
1919
+ remaining.clear();
1840
1920
  },
1841
- view: () => current
1921
+ view: () => rows.filter((row) => present(row.id))
1842
1922
  };
1843
1923
  }
1844
1924
  //#endregion
@@ -1966,7 +2046,7 @@ async function stepUndo(label, run) {
1966
2046
  }
1967
2047
  /**
1968
2048
  * **组级回滚**:把已经做成的成员按相反顺序退回;某一步退不干净时把失败并进原错误的
1969
- * `details.rollbackFailures`,绝不让原错误独走。删除与恢复两个按组走的动词共用这一处。
2049
+ * `details.rollbackFailures`,绝不让原错误独走。移入回收站与恢复两个按组走的动词共用这一处。
1970
2050
  */
1971
2051
  async function rollbackJournals(journals, error) {
1972
2052
  const failures = [];
@@ -2037,6 +2117,47 @@ function withPresenceTail(presence, journal, tail) {
2037
2117
  };
2038
2118
  }
2039
2119
  //#endregion
2120
+ //#region src/verbs/move-directory.ts
2121
+ /**
2122
+ * 会话目录搬移的**瞬态占用重试**(ADR-0073):`sessions/` 与 `session-trash/` 之间整目录 `rename` 时,
2123
+ * Windows 只要目录里有任何一个文件被打开(宿主会话 / 日志句柄、索引或杀软扫描)就回 `EPERM` / `EBUSY` /
2124
+ * `EACCES`。这些是短命竞争,不是"权限配错了";同一次真机批量里一条成员被占用、另一条正常搬走。
2125
+ *
2126
+ * 判据只住这一处:最多 3 次尝试(首发 + 两次重试),间隔 50 / 150ms,只对上面三种码重试;耗尽后**原样抛
2127
+ * 最后一个错误**,信封与文案仍由动词的 journal 折(`sessiondelete/io`)。目标已存在、跨卷 `EXDEV` 与其余
2128
+ * 错误都不重试——那三个是判据错误,不是瞬态(见 `src/ports/fs-port.ts` 的 `rename`)。
2129
+ *
2130
+ * **不是锁、不是退避框架**:不替代留出主视图 / 活体摘除(ADR-0008),不无限重试,也不做"复制 + 删源"的
2131
+ * 降级(那会把原子搬移换成可能半途而废的复制)。`sleep` 只为测试可注入;生产不传。
2132
+ */
2133
+ const RETRYABLE_RENAME_CODES = /* @__PURE__ */ new Set([
2134
+ "EPERM",
2135
+ "EBUSY",
2136
+ "EACCES"
2137
+ ]);
2138
+ /** 重试间隔(毫秒):第 n 个间隔对应第 n 次重试。导出给测试与 ADR 引用的读数,不在调用点另抄一份。 */
2139
+ const MOVE_DIR_RETRY_DELAYS_MS = [50, 150];
2140
+ const defaultSleep = (ms) => new Promise((resolve) => {
2141
+ setTimeout(resolve, ms);
2142
+ });
2143
+ function isRetryableRenameError(error) {
2144
+ const code = error?.code;
2145
+ return typeof code === "string" && RETRYABLE_RENAME_CODES.has(code);
2146
+ }
2147
+ /** 搬目录:瞬态占用按固定小步数重试;判据错误与非瞬态码一次都不重试。 */
2148
+ async function moveDirectoryWithRetry(rename, from, to, options = {}) {
2149
+ const delays = options.delaysMs ?? MOVE_DIR_RETRY_DELAYS_MS;
2150
+ const sleep = options.sleep ?? defaultSleep;
2151
+ for (let attempt = 0;; attempt += 1) try {
2152
+ await rename(from, to);
2153
+ return;
2154
+ } catch (error) {
2155
+ const delay = delays[attempt];
2156
+ if (delay === void 0 || !isRetryableRenameError(error)) throw error;
2157
+ await sleep(delay);
2158
+ }
2159
+ }
2160
+ //#endregion
2040
2161
  //#region src/verbs/move-group.ts
2041
2162
  /**
2042
2163
  * 组级成员移动:组根先跑,跟随者按序拿到根结果;任一失败就把**已经做成**的按相反顺序退回。
@@ -2100,7 +2221,7 @@ function readWriteProgress() {
2100
2221
  //#endregion
2101
2222
  //#region src/verbs/delete-session.ts
2102
2223
  /**
2103
- * 删除 = 移入回收站,**按组走**:用户点掉一条父会话时宿主把 `origin:"subagent"` 的孩子整排藏了 ⇒ 那些目录既看不见也继续占字节,
2224
+ * **移入回收站**(线上动作名仍是 `delete`),**按组走**:用户点掉一条父会话时宿主把 `origin:"subagent"` 的孩子整排藏了 ⇒ 那些目录既看不见也继续占字节,
2104
2225
  * 所以父在盘上的孩子一起搬进来,各自一行,清册用 `parentEntryId` 记归属。
2105
2226
  *
2106
2227
  * 三段,顺序承重(成员循环与整组回滚住 `verbs/move-group.ts`):
@@ -2118,7 +2239,8 @@ function deleteSession(deps) {
2118
2239
  const kids = read.available ? read.value[sessionId] ?? [] : [];
2119
2240
  const parentProjectDir = await deps.host.projectDirOf(sessionId);
2120
2241
  if (parentProjectDir === void 0) throw verbError("not-found", `宿主的持久化里没有这个会话:${sessionId}`);
2121
- await assertNoLive(deps.host, [sessionId, ...kids.map((kid) => kid.sessionId)]);
2242
+ const groupIds = [sessionId, ...kids.map((kid) => kid.sessionId)];
2243
+ await assertNoLive(deps.host, groupIds);
2122
2244
  const parentDir = sessionDirForId(parentProjectDir, sessionId, deps.home);
2123
2245
  if (!await deps.fs.exists(parentDir)) throw verbError("not-found", `会话目录不存在:${parentDir}`);
2124
2246
  const parent = {
@@ -2137,7 +2259,8 @@ function deleteSession(deps) {
2137
2259
  followers: members.slice(1),
2138
2260
  move: async (member, rootResult) => {
2139
2261
  const parentEntryId = rootResult?.id;
2140
- const move = await memberMove(deps, presence, member, deletedAt, parentEntryId);
2262
+ const recheckIds = rootResult === void 0 ? groupIds : [member.sessionId];
2263
+ const move = await memberMove(deps, presence, member, deletedAt, parentEntryId, recheckIds);
2141
2264
  return {
2142
2265
  journal: move.journal,
2143
2266
  result: move.entry
@@ -2150,7 +2273,7 @@ function deleteSession(deps) {
2150
2273
  }
2151
2274
  /**
2152
2275
  * 一个成员的步骤(顺序承重):读现场 → 摘账本 → 搬目录 → 写清册行;搬完由 `memberGone` 关掉活体(session + agent)。
2153
- * **删除不碰归档**——回收站与归档是两套状态,归档只在用户自己归档过时保留。
2276
+ * **移入回收站不碰归档**——回收站与归档是两套状态,归档只在用户自己归档过时保留。
2154
2277
  *
2155
2278
  * **已知窗口**:摘账本之后、`memberGone` 之前活体短暂无主;这是 ADR-0008 去掉归档后的已知代价。`memberGone` 不能提前到
2156
2279
  * 文件/清册写成功之前,否则一次失败回滚会留下"文件在、agent 已关"的半个世界。
@@ -2158,7 +2281,7 @@ function deleteSession(deps) {
2158
2281
  * 每一步的反向动作都是"把这件写退回原样";清册行是最后一件写,失败时 journal 把目录搬回去、账本挂回去;
2159
2282
  * 它的反向动作带闸:**回收站目录还没搬回来就不摘那一行**,留着行至少元数据还在。
2160
2283
  */
2161
- async function memberMove(deps, presence, member, deletedAt, parentEntryId) {
2284
+ async function memberMove(deps, presence, member, deletedAt, parentEntryId, recheckIds) {
2162
2285
  const { sessionId, projectDir } = member;
2163
2286
  const workspaceId = await deps.host.workspaceOf(sessionId);
2164
2287
  const sessionDirName = sessionDirSegmentOf(sessionId);
@@ -2187,6 +2310,7 @@ async function memberMove(deps, presence, member, deletedAt, parentEntryId) {
2187
2310
  writeProgress.step("measuring");
2188
2311
  entry.title = await deps.host.titleOf(sessionId);
2189
2312
  entry.sizeBytes = await deps.fs.sizeOfDir(sessionDir);
2313
+ await assertNoLive(deps.host, recheckIds);
2190
2314
  }
2191
2315
  },
2192
2316
  ...workspaceId === void 0 ? [] : [{
@@ -2205,7 +2329,7 @@ async function memberMove(deps, presence, member, deletedAt, parentEntryId) {
2205
2329
  run: async () => {
2206
2330
  writeProgress.step("moving");
2207
2331
  await deps.fs.ensureDir(`${deps.home}/${TRASH_DIR_NAME}`);
2208
- await deps.fs.rename(sessionDir, trashDir);
2332
+ await moveDirectoryWithRetry(deps.fs.rename, sessionDir, trashDir);
2209
2333
  moved = true;
2210
2334
  try {
2211
2335
  writeProgress.step("ledger");
@@ -2219,7 +2343,7 @@ async function memberMove(deps, presence, member, deletedAt, parentEntryId) {
2219
2343
  restored: true,
2220
2344
  failures: []
2221
2345
  };
2222
- const directory = await stepUndo("目录搬回失败", () => deps.fs.rename(trashDir, sessionDir));
2346
+ const directory = await stepUndo("目录搬回失败", () => moveDirectoryWithRetry(deps.fs.rename, trashDir, sessionDir));
2223
2347
  const failures = [...directory.failures];
2224
2348
  if (directory.restored) failures.push(...await attempt("清册行摘除失败", () => deps.ledger.remove(entry.id)));
2225
2349
  return {
@@ -2348,7 +2472,8 @@ async function dropDeletedSessionCache(deps, sessionId) {
2348
2472
  /**
2349
2473
  * 永久删除的测量、计划与执行:先记录目录/字节/账本归属,再按计划动盘。计划函数只读;活体准入在计划阶段、任何写之前完成,
2350
2474
  * 执行器动第一笔写前再查一次(ADR-0027)。
2351
- * 测量与补账本归属**分家**:`/list` 的只读计划只吃 `measureMembers`(零账本读);`workspaceOf` 只有 purge / orphan-clean 的删除计划才付。
2475
+ * 测量与补账本归属**分家**:`/list` 的只读计划只吃 `measureMembers`(零账本读);`workspaceOf` 只由 purge / orphan-clean
2476
+ * 的删除计划与执行器的归属复核付(`/list` 不吃)。
2352
2477
  *
2353
2478
  * **批级扫描 + 尾只带走真删掉的目录**:独占图片的候选与剩余引用扫描提到**批级**(`planBatchImageAttachmentRemoval`,
2354
2479
  * 全批两趟读:计划一趟、复核一趟),逐组计划只吐本组被删目录(`attachmentDirs`);附件尾 `executeAttachmentTail`
@@ -2357,10 +2482,10 @@ async function dropDeletedSessionCache(deps, sessionId) {
2357
2482
  * (活体准入复查 → 摘归档集 → 摘账本 → 删目录 → 摘清册行 → 通告离场 → 清缓存)顺序与回滚语义一格不动。
2358
2483
  */
2359
2484
  /** `exists → sizeOfDir` 的唯一一条度量口径(成员目录与回收站目录共用):先问在不在,再量字节;缺席(ENOENT / ENOTDIR)才是不在,
2360
- * 别的错误照旧响亮(ADR-0039)。**已知粒度**:`sizeOfDir` 递归里撞到的缺席与"目录本身没了"是同一个码,所以文件恰在这一拍消失时
2361
- * 整条目录会被记成「不在」(清册行照旧摘——盘上留下的目录由下一次 `reconcile` 重建成行,自愈、不丢数据);复核一次 `exists`
2362
- * 会把正常竞态打红,这里选自愈不选响亮。 */
2363
- async function probeDir(deps, dir) {
2485
+ * 别的错误照旧响亮(ADR-0039)。**递归里撞到的 ENOENT 不等于根目录没了**:子文件恰在这一拍消失时会报同一个码。
2486
+ * 写计划(`race: 'throw'`)要再确认根目录也不在——否则跳过删目录、照样摘清册行,留下「行没了、目录还在」的孤儿;
2487
+ * 读路径(`race: 'absent'`)没有删除动作,沿用 ADR-0027 的折叠:清单面板不因一次瞬态竞态整张读失败。 */
2488
+ async function probeDir(deps, dir, race) {
2364
2489
  if (!await deps.fs.exists(dir)) return {
2365
2490
  present: false,
2366
2491
  bytes: 0
@@ -2371,17 +2496,18 @@ async function probeDir(deps, dir) {
2371
2496
  bytes: await deps.fs.sizeOfDir(dir)
2372
2497
  };
2373
2498
  } catch (error) {
2374
- if (isMissing(error)) return {
2499
+ if (isMissing(error) && (race === "absent" || !await deps.fs.exists(dir))) return {
2375
2500
  present: false,
2376
2501
  bytes: 0
2377
2502
  };
2378
2503
  throw error;
2379
2504
  }
2380
2505
  }
2381
- /** 成员的盘上目录与字节(扫描、清单与 purge 共用一条口径);目录缺席回 `undefined`,不拿旧读数冒充盘上残留。 */
2382
- async function measureMemberDir(deps, member) {
2506
+ /** 成员的盘上目录与字节(扫描、清单与 purge 共用一条口径);目录缺席回 `undefined`,不拿旧读数冒充盘上残留。
2507
+ * `race` 决定递归 ENOENT 的处置(ADR-0078):读路径 `'absent'`,删除计划 `'throw'`。 */
2508
+ async function measureMemberDir(deps, member, race) {
2383
2509
  const dir = sessionDirForId(member.projectDir, member.sessionId, deps.home);
2384
- const probe = await probeDir(deps, dir);
2510
+ const probe = await probeDir(deps, dir, race);
2385
2511
  return probe.present ? {
2386
2512
  dir,
2387
2513
  bytes: probe.bytes
@@ -2389,10 +2515,10 @@ async function measureMemberDir(deps, member) {
2389
2515
  }
2390
2516
  /** 只测量(目录 + 实测字节):`/list` 的只读计划只吃这一支,零账本读;目录不在的成员跳过。为什么不顺手问归属:
2391
2517
  * `/list` 只用字节与条数,那一格立刻被丢弃——每开一次回收站为它付 N 次宿主调用,还把账本归属读拉进失败面。 */
2392
- async function measureMembers(deps, members) {
2518
+ async function measureMembers(deps, members, race) {
2393
2519
  const out = [];
2394
2520
  for (const member of members) {
2395
- const measured = await measureMemberDir(deps, member);
2521
+ const measured = await measureMemberDir(deps, member, race);
2396
2522
  if (measured === void 0) continue;
2397
2523
  out.push({
2398
2524
  sessionId: member.sessionId,
@@ -2405,7 +2531,7 @@ async function measureMembers(deps, members) {
2405
2531
  /** 把一组成员折成删除计划:`measureMembers` 之外**逐成员补账本归属**(`workspaceOf`)——executor 摘账本要用。 */
2406
2532
  async function planMemberRemovals(deps, members) {
2407
2533
  const plans = [];
2408
- for (const measured of await measureMembers(deps, members)) {
2534
+ for (const measured of await measureMembers(deps, members, "throw")) {
2409
2535
  const workspaceId = await deps.host.workspaceOf(measured.sessionId);
2410
2536
  plans.push({
2411
2537
  sessionId: measured.sessionId,
@@ -2416,10 +2542,10 @@ async function planMemberRemovals(deps, members) {
2416
2542
  }
2417
2543
  return plans;
2418
2544
  }
2419
- /** 量一条回收站行;目录不在回 `present: false` / 0 字节(目录不在不等于清册行不用摘)。 */
2420
- async function measureTrashRow(deps, entry) {
2545
+ /** 量一条回收站行;目录不在回 `present: false` / 0 字节(目录不在不等于清册行不用摘)。`race` 同 {@link measureMemberDir}。 */
2546
+ async function measureTrashRow(deps, entry, race) {
2421
2547
  const dir = trashDirOf(entry.id, deps.home);
2422
- const probe = await probeDir(deps, dir);
2548
+ const probe = await probeDir(deps, dir, race);
2423
2549
  return {
2424
2550
  entry,
2425
2551
  dir,
@@ -2427,6 +2553,10 @@ async function measureTrashRow(deps, entry) {
2427
2553
  bytes: probe.bytes
2428
2554
  };
2429
2555
  }
2556
+ /** 一份清册快照里的会话 id 集(bare 归一)。批量面一次算好、多处复用,避免每个组重建一份 n 行的 Set。 */
2557
+ function manifestSessionIds(rows) {
2558
+ return new Set(rows.map((row) => bareSessionId(row.sessionId)));
2559
+ }
2430
2560
  /**
2431
2561
  * 盘上后代的选择判据(`/list` 与 purge 共用):`subagentMembersOf` 一次问全部父,再按 `bareSessionId` **排除全部清册 id**,
2432
2562
  * 同一个 bare id 只认**遍历顺序里第一次**出现的那条(去重口径住 `firstByBare`)。语料看不见 ⇒ 每个根按空成员收(盘上残留留给 `GET /orphans`)。
@@ -2435,8 +2565,7 @@ async function measureTrashRow(deps, entry) {
2435
2565
  * **单行读数与单行回执可能差一条**:同一个 bare id 挂在两个组根下时,全局去重只把它算给第一个根;单独 purge 那一组时它仍算进那一组
2436
2566
  * ⇒ 那条的 `releaseBytes` 与 `freedBytes` 在共享后代上可以不等(全部可见行之和与 `/empty` 的回执仍相等)。数据有环或两代写法混杂才撞上。
2437
2567
  */
2438
- async function selectStrandedMembers(host, manifest, parentIds) {
2439
- const manifestIds = new Set(manifest.map((row) => bareSessionId(row.sessionId)));
2568
+ async function selectStrandedMembers(host, manifestIds, parentIds) {
2440
2569
  const read = await host.subagentMembersOf(parentIds);
2441
2570
  if (!read.available) return parentIds.map(() => []);
2442
2571
  const flat = [];
@@ -2459,8 +2588,9 @@ async function selectStrandedMembers(host, manifest, parentIds) {
2459
2588
  }
2460
2589
  return out;
2461
2590
  }
2462
- /** `/list` 只读计划的盘上测量预算(组与组内 kids 两级共用):`/list` 一次可能几百组、每组几百孩子,无界 `Promise.all`
2463
- * 会把上千个 `exists` / `sizeOfDir` 挂起抢同一个盘;它与逐行读数的旋钮分家(那边是宿主投影读,同一个数没有同一条理由)。 */
2591
+ /** `/list` 只读计划的盘上测量预算:`/list` 一次可能几百组、每组几百孩子,无界 `Promise.all`
2592
+ * 会把上千个 `exists` / `sizeOfDir` 挂起抢同一个盘;它与逐行读数的旋钮分家(那边是宿主投影读,同一个数没有同一条理由)。
2593
+ * 组与组内孩子排同一条队列,成员组随后另起一条(各 ≤8),不再叠出「8 组 × 8 孩子」。 */
2464
2594
  const VISIBLE_MEASURE_CONCURRENCY = 8;
2465
2595
  /**
2466
2596
  * `/list` 的只读计划:一行 = 一组。释放量与 purge 同口径——回收站目录与成员目录**现测**,不用清册记的 `sizeBytes`(盘上早变了)。
@@ -2468,20 +2598,23 @@ const VISIBLE_MEASURE_CONCURRENCY = 8;
2468
2598
  * 两级都有界(`VISIBLE_MEASURE_CONCURRENCY`);输出按 `groups` 原序(`mapLimit` 按 index 落位),首个失败原样抛。
2469
2599
  */
2470
2600
  async function planVisibleTrash(deps, rows, groups) {
2471
- const candidates = await selectStrandedMembers(deps.host, rows, groups.map((group) => group.root.sessionId));
2472
- return await mapLimit(groups, VISIBLE_MEASURE_CONCURRENCY, async ({ root, kids }, index) => {
2473
- const rootRow = await measureTrashRow(deps, root);
2474
- const kidRows = await mapLimit(kids, VISIBLE_MEASURE_CONCURRENCY, (kid) => measureTrashRow(deps, kid));
2475
- const members = await measureMembers(deps, candidates[index] ?? []);
2476
- const subagentBytes = kidRows.reduce((total, row) => total + row.bytes, 0);
2477
- const strandedBytes = members.reduce((total, member) => total + member.bytes, 0);
2601
+ const manifestIds = manifestSessionIds(rows);
2602
+ const candidates = await selectStrandedMembers(deps.host, manifestIds, groups.map((group) => group.root.sessionId));
2603
+ const measured = await mapLimit(groups.flatMap(({ root, kids }) => [root, ...kids]), VISIBLE_MEASURE_CONCURRENCY, (entry) => measureTrashRow(deps, entry, "absent"));
2604
+ const memberGroups = await mapLimit(candidates, VISIBLE_MEASURE_CONCURRENCY, (group) => measureMembers(deps, group, "absent"));
2605
+ let offset = 0;
2606
+ return groups.map(({ root, kids }, index) => {
2607
+ const trash = measured.slice(offset, offset + 1 + kids.length);
2608
+ offset += trash.length;
2609
+ const members = memberGroups[index] ?? [];
2610
+ const strandedBytes = totalBytes(members);
2478
2611
  return {
2479
2612
  root,
2480
2613
  kids,
2481
- trash: [rootRow, ...kidRows],
2614
+ trash,
2482
2615
  members,
2483
- releaseBytes: rootRow.bytes + subagentBytes + strandedBytes,
2484
- subagentBytes,
2616
+ releaseBytes: totalBytes(trash) + strandedBytes,
2617
+ subagentBytes: totalBytes(trash.slice(1)),
2485
2618
  strandedBytes,
2486
2619
  strandedCount: members.length
2487
2620
  };
@@ -2500,11 +2633,11 @@ function totalBytes(items) {
2500
2633
  * - 活体准入在量目录与任何写之前逐个查 targets 与**全部枚举到的**盘上后代;没有跳过它的开关(执行器首笔写前还会复查)。
2501
2634
  * - `sessionQuery` 缺席 ⇒ members 为空、不抛(盘上残留留给 `GET /orphans` 兜底)。
2502
2635
  */
2503
- async function planTrashRemoval(deps, rows, targets) {
2636
+ async function planTrashRemoval(deps, rows, targets, manifestIds = manifestSessionIds(rows)) {
2504
2637
  writeProgress.step("measuring");
2505
- const candidates = (await selectStrandedMembers(deps.host, rows, targets.map((entry) => entry.sessionId))).flat();
2638
+ const candidates = (await selectStrandedMembers(deps.host, manifestIds, targets.map((entry) => entry.sessionId))).flat();
2506
2639
  await assertNoLive(deps.host, [...targets.map((entry) => entry.sessionId), ...candidates.map((member) => member.sessionId)]);
2507
- const trash = await mapLimit(targets, VISIBLE_MEASURE_CONCURRENCY, (entry) => measureTrashRow(deps, entry));
2640
+ const trash = await mapLimit(targets, VISIBLE_MEASURE_CONCURRENCY, (entry) => measureTrashRow(deps, entry, "throw"));
2508
2641
  const members = await planMemberRemovals(deps, candidates);
2509
2642
  const attachmentDirs = [...trash.map((row) => row.dir), ...members.map((member) => member.dir)];
2510
2643
  return {
@@ -2524,10 +2657,10 @@ async function planTrashRemoval(deps, rows, targets) {
2524
2657
  * 盘上后代读不出时 `complete: false`、只交行目录:调用方要据此把该组的第二波补跑判失败(留着让人重试),
2525
2658
  * 不能让它删掉一批没进过扫描面的目录——那才是孤儿附件的来源。
2526
2659
  */
2527
- async function plannedAttachmentDirs(deps, rows, targets) {
2660
+ async function plannedAttachmentDirs(deps, rows, targets, manifestIds = manifestSessionIds(rows)) {
2528
2661
  const dirs = targets.map((entry) => trashDirOf(entry.id, deps.home));
2529
2662
  try {
2530
- const members = await measureMembers(deps, (await selectStrandedMembers(deps.host, rows, targets.map((entry) => entry.sessionId))).flat());
2663
+ const members = await measureMembers(deps, (await selectStrandedMembers(deps.host, manifestIds, targets.map((entry) => entry.sessionId))).flat(), "throw");
2531
2664
  return {
2532
2665
  dirs: [...dirs, ...members.map((member) => member.dir)],
2533
2666
  complete: true
@@ -2567,6 +2700,11 @@ async function planOrphanRemoval(deps, members) {
2567
2700
  * 目录删掉就没有"退回去"这回事,中途失败**不回滚目录**;已删的由计数器如实交回。附件对象不在这条管线里——
2568
2701
  * 归批级尾(`executeAttachmentTail`),见文件头注的口径。
2569
2702
  *
2703
+ * **账本与工作区归属**(ADR-0077):摘账本前对每个计划成员复核一次 `workspaceOf`——执行时已无归属就跳过
2704
+ * (同批先手已摘 / 用户解绑 / 工作区已删,`detach` 本就是空转),有归属但与计划不一致则响亮失败等重试。
2705
+ * 失败出口按 detach 记录的反向顺序,对目录仍在的成员 `attach(..., 'if-unassigned')` 补回原工作区
2706
+ * (已删目录 / 用户已重新归组 / 工作区已删都跳过);回滚失败与归档回滚一样进 `details.rollbackFailures`。
2707
+ *
2570
2708
  * **归档态回滚**:`unarchive` 排在所有删除之前,所以失败时目录还在、归档位却已摘。失败出口把**目录还在**的那些按删除前的读数
2571
2709
  * 重新归档(预读 `isArchived`,不按 `wasArchived` 猜),目录不在的跳过——否则会造幽灵 id。回滚失败走 `details.rollbackFailures`(ADR-0040)。
2572
2710
  *
@@ -2614,6 +2752,8 @@ async function executeRemoval(deps, plan, options) {
2614
2752
  const onDisk = /* @__PURE__ */ new Set([...plan.trash.filter((row) => row.present).map((row) => row.entry.sessionId), ...plan.members.map((member) => member.sessionId)]);
2615
2753
  /** 目录已经真删掉的 id:没有归档态可放回去,跳过——否则会在 registry 里留下幽灵 id。 */
2616
2754
  const deleted = /* @__PURE__ */ new Set();
2755
+ /** 走到过 `detach` 这一步的成员(含失败那一条):失败时按它补回工作区归属。 */
2756
+ const detaching = [];
2617
2757
  try {
2618
2758
  for (const sessionId of plan.unarchive) {
2619
2759
  unarchived.push(sessionId);
@@ -2621,10 +2761,19 @@ async function executeRemoval(deps, plan, options) {
2621
2761
  await step("取消归档失败", sessionId, () => deps.host.unarchive(sessionId));
2622
2762
  }
2623
2763
  for (const member of plan.members) {
2624
- const workspaceId = member.workspaceId;
2625
- if (workspaceId === void 0) continue;
2626
- writeProgress.step("ledger");
2627
- await step("摘账本失败", member.sessionId, () => deps.host.detach(member.sessionId, workspaceId));
2764
+ const { sessionId, dir, workspaceId } = member;
2765
+ await step("摘账本失败", sessionId, async () => {
2766
+ const current = await deps.host.workspaceOf(sessionId);
2767
+ if (current === void 0) return;
2768
+ if (workspaceId === void 0 || current !== workspaceId) throw new Error(`会话工作区已变更,请重试:${sessionId}`);
2769
+ writeProgress.step("ledger");
2770
+ detaching.push({
2771
+ sessionId,
2772
+ dir,
2773
+ workspaceId: current
2774
+ });
2775
+ await deps.host.detach(sessionId, current);
2776
+ });
2628
2777
  }
2629
2778
  for (const row of plan.trash) try {
2630
2779
  if (row.present) {
@@ -2671,6 +2820,14 @@ async function executeRemoval(deps, plan, options) {
2671
2820
  };
2672
2821
  } catch (error) {
2673
2822
  const rollbackFailures = [];
2823
+ for (const { sessionId, dir, workspaceId } of [...detaching].reverse()) {
2824
+ if (deleted.has(sessionId)) continue;
2825
+ try {
2826
+ if (await deps.fs.exists(dir)) await deps.host.attach(sessionId, workspaceId, "if-unassigned");
2827
+ } catch (rollbackError) {
2828
+ rollbackFailures.push(rollbackReason(`恢复工作区失败(${sessionId})`, rollbackError));
2829
+ }
2830
+ }
2674
2831
  for (const sessionId of [...unarchived].reverse()) {
2675
2832
  if (!archivedBefore.has(sessionId) || deleted.has(sessionId) || !onDisk.has(sessionId)) continue;
2676
2833
  try {
@@ -2755,7 +2912,7 @@ async function loadOrphanGroups(deps, trash, roots) {
2755
2912
  for (const group of groups) {
2756
2913
  const members = [];
2757
2914
  for (const member of group.members) {
2758
- const measured = await measureMemberDir(deps, member);
2915
+ const measured = await measureMemberDir(deps, member, "absent");
2759
2916
  members.push({
2760
2917
  sessionId: member.sessionId,
2761
2918
  projectDir: member.projectDir,
@@ -2808,8 +2965,8 @@ async function planOrphanGroup(deps, group) {
2808
2965
  }
2809
2966
  /**
2810
2967
  * 清一组的**执行**(只写):量目录、摘归档集与账本、删目录与成员通告的顺序和失败形状都住 `permanent-removal.ts`,
2811
- * 这里只把这一组的计划递上去。顺序与删除那一半**对偶**但不照抄:
2812
- * - 删除那一半不碰归档(ADR-0008);这里目录是**删掉**不是搬走 ⇒ 归档集**在写之前整批摘掉**:失败时目录还在可重试,
2968
+ * 这里只把这一组的计划递上去。顺序与移入回收站那一半**对偶**但不照抄:
2969
+ * - 移入回收站那一半不碰归档(ADR-0008);这里目录是**删掉**不是搬走 ⇒ 归档集**在写之前整批摘掉**:失败时目录还在可重试,
2813
2970
  * 不留"会话没了却还在归档集里挂着"的幽灵 id(`unarchive` 对未归档会话本就是幂等 no-op,无需那次 `wasArchived` 读)。
2814
2971
  * - 摘账本只在账本真记着它时做(`workspaceOf` 未命中 = 未分组,不是故障);独占图片的剩余引用源由附件域在批级扫。
2815
2972
  */
@@ -2822,7 +2979,7 @@ const CAPTURED_AGENT_HANDLES = Symbol.for("dsh-session-delete.captured-agent-han
2822
2979
  const CAPTURED_AGENT_WRAPPERS = Symbol.for("dsh-session-delete.captured-agent-wrappers");
2823
2980
  /** 在 `ctx.agents` 上包一层 `resume` / `create`,把返回的 agent handle 的 dispose 按会话 id 记下。
2824
2981
  * 服务缺席时走 `ctx.inject(['agents'])` **等服务挂上再装**——live profile 的激活顺序可能早于 `agents` 就绪;只在 apply 时 `get`
2825
- * 一次会让捕获静默缺席(真机症状:刚删除的会话恢复后旧 agent 拦住 prompt)。形状不符 / 属性不可写都只是**不捕获**,不影响激活。
2982
+ * 一次会让捕获静默缺席(真机症状:刚移入回收站的会话恢复后旧 agent 拦住 prompt)。形状不符 / 属性不可写都只是**不捕获**,不影响激活。
2826
2983
  *
2827
2984
  * **symbol 表**:句柄表挂在服务实例上;同一个 agents 服务上的第二次安装看见它就直接共用,不把 wrapper 套第二层。
2828
2985
  * **安装者拥有 wrapper**:包装记录先在闭包里留一份,同时挂到 symbol;第一次成功安装时经 `ctx.effect` 注册卸载恢复——
@@ -2923,7 +3080,7 @@ function captureAgentHandles(ctx) {
2923
3080
  try {
2924
3081
  await dispose();
2925
3082
  } finally {
2926
- handles.delete(sessionId);
3083
+ if (handles.get(sessionId) === dispose) handles.delete(sessionId);
2927
3084
  }
2928
3085
  } };
2929
3086
  }
@@ -2958,11 +3115,34 @@ function escapeProjectKey(cwd) {
2958
3115
  //#endregion
2959
3116
  //#region src/ports/host-port.ts
2960
3117
  /** live store 的最小方法面判据(同 `projectionCacheOf` 的手法:按方法面判,不按 constructor.name)。 */
3118
+ function liveSessionsProbe(ctx) {
3119
+ const candidate = ctx.get("sessions");
3120
+ if (candidate === void 0) return { reason: "sessions service is absent" };
3121
+ if (candidate === null) return { reason: "sessions service returned null" };
3122
+ const missing = [];
3123
+ if (typeof candidate.get !== "function") missing.push("get");
3124
+ if (typeof candidate.liveEntryFor !== "function") missing.push("liveEntryFor");
3125
+ if (missing.length > 0) return { reason: `sessions service shape mismatch (missing ${missing.join(" / ")})` };
3126
+ return { store: candidate };
3127
+ }
2961
3128
  function liveSessionsOf(ctx) {
2962
- const store = ctx.get("sessions");
2963
- if (store === void 0 || store === null) return void 0;
2964
- if (typeof store.get !== "function" || typeof store.liveEntryFor !== "function") return void 0;
2965
- return store;
3129
+ return liveSessionsProbe(ctx).store;
3130
+ }
3131
+ /** 在场诊断只写宿主日志:unknown / agent 收尾失败是排查用的观测,不是用户面上的新状态。 */
3132
+ function warnPresence(message, detail) {
3133
+ if (detail === void 0) {
3134
+ console.warn(`[dsh-session-delete] presence: ${message}`);
3135
+ return;
3136
+ }
3137
+ console.warn(`[dsh-session-delete] presence: ${message}:`, detail);
3138
+ }
3139
+ /** agent 收尾是**附属写**:它失败不改变 live store 是否已无这条会话这一事实;失败单独记录。 */
3140
+ async function disposeAgentBestEffort(handles, sessionId) {
3141
+ try {
3142
+ await handles.dispose(sessionId);
3143
+ } catch (error) {
3144
+ warnPresence(`agent handle dispose failed for "${sessionId}" (session presence unchanged)`, error);
3145
+ }
2966
3146
  }
2967
3147
  /**
2968
3148
  * 会话 header 的**公开**读面:live `sessions.get(id).header` 优先,否则 `sessionPersistence.stat(id).header`。未知会话回 `undefined`;
@@ -3118,10 +3298,12 @@ function createHostPort(ctx) {
3118
3298
  const host = ctx;
3119
3299
  const registry = host.workspaceRegistry;
3120
3300
  const agentHandles = captureAgentHandles(host);
3301
+ /** 会话当前挂在哪个工作区(`registry.list()` 的实体 `sessionIds`;同一个判据 `workspaceOf` 也读它)。 */
3302
+ const ownerOf = (sessionId) => registry.list().find((workspace) => workspace.sessionIds.includes(sessionId))?.id;
3121
3303
  return {
3122
3304
  /** 账本里记着这个会话的工作区:`registry.list()` 的实体 `sessionIds`(该 getter 已按 canonical cwd 过滤过)。 */
3123
3305
  async workspaceOf(sessionId) {
3124
- return registry.list().find((workspace) => workspace.sessionIds.includes(sessionId))?.id;
3306
+ return ownerOf(sessionId);
3125
3307
  },
3126
3308
  /** 账本里还有这个工作区吗:`registry.get(id)` 是同步 Map 查找,未知 id 回 `undefined` ⇒ 只做一次判别,不抛。 */
3127
3309
  async workspaceExists(workspaceId) {
@@ -3136,6 +3318,10 @@ function createHostPort(ctx) {
3136
3318
  if (header === void 0) return void 0;
3137
3319
  return projectDirOfCwd(header.cwd);
3138
3320
  },
3321
+ /** 宿主工作区显示顺序 → 项目目录名。`registry.list()` 的顺序就是宿主持久的显示顺序,照抄、不排序。 */
3322
+ async projectOrder() {
3323
+ return registry.list().map((workspace) => projectDirOfCwd(workspace.path));
3324
+ },
3139
3325
  /** 显示名走宿主投影缓存(与工作中同名):子会话取 `subagent` 投影的 label,其余取 `title` 行的**视图值**(整条未命中才回落 predecessor)。
3140
3326
  * header 来自公开的 live/持久化读面,尽力取,取不到返回空串。 */
3141
3327
  async titleOf(sessionId) {
@@ -3180,23 +3366,46 @@ function createHostPort(ctx) {
3180
3366
  * `SessionController` 会丢掉 `AgentHandle`,所以 `agent-handles.ts` 按会话 id 留住 handle,这里先 detach 再 dispose。
3181
3367
  * 捕获不到 handle(插件激活前已启动,或 `ctx.agents` 形状变化)时只能摘 session,这是已知限制,不拿归档兜底(ADR-0008)。
3182
3368
  *
3183
- * 三态:读不到 store / 形状不符 / detach 或 dispose 抛 ⇒ `unknown`(不通告);内存里本来没有 ⇒ `not-live`;摘成功 ⇒ `evicted`。任何一步都不抛。
3369
+ * 三态只由 **live store** 判:读不到 store / 形状不符 / `get` 或 `detach` 抛 / detach 后 store 仍有这条 ⇒ `unknown`(不通告);
3370
+ * 内存里本来没有 ⇒ `not-live`;摘成功且复读已无 ⇒ `evicted`。任何一步都不抛。
3371
+ *
3372
+ * agent handle 的 `dispose` 是**附属写**:它失败(典型是目录已搬走、写句柄 drain 找不到路径)不改变 live store 已经
3373
+ * 没有这条会话的事实;只记一条诊断,不把 `not-live`/`evicted` 折成 `unknown`。否则 memberGone 会跳过通告,冷会话那
3374
+ * 一行就留在客户端(见 ADR-0008 的在场三态与真机 issue #10)。
3184
3375
  */
3185
3376
  async evictLive(sessionId) {
3186
3377
  try {
3187
- const store = liveSessionsOf(host);
3188
- const session = store?.get(sessionId);
3189
- if (store === void 0) return "unknown";
3378
+ const probe = liveSessionsProbe(host);
3379
+ const store = probe.store;
3380
+ if (store === void 0) {
3381
+ warnPresence(`cannot read the live session store: ${probe.reason ?? "unknown reason"}`);
3382
+ return "unknown";
3383
+ }
3384
+ const session = store.get(sessionId);
3190
3385
  if (session === void 0 || session === null) {
3191
- await agentHandles.dispose(sessionId);
3386
+ await disposeAgentBestEffort(agentHandles, sessionId);
3387
+ const remaining = store.get(sessionId);
3388
+ if (remaining !== void 0 && remaining !== null) {
3389
+ warnPresence(`session "${sessionId}" reappeared after agent dispose`);
3390
+ return "unknown";
3391
+ }
3192
3392
  return "not-live";
3193
3393
  }
3194
3394
  const entry = store.liveEntryFor(session);
3195
- if (entry === void 0 || entry === null || typeof entry.detach !== "function") return "unknown";
3395
+ if (entry === void 0 || entry === null || typeof entry.detach !== "function") {
3396
+ warnPresence(`live entry for "${sessionId}" has no detach`);
3397
+ return "unknown";
3398
+ }
3196
3399
  entry.detach();
3197
- await agentHandles.dispose(sessionId);
3400
+ await disposeAgentBestEffort(agentHandles, sessionId);
3401
+ const remaining = store.get(sessionId);
3402
+ if (remaining !== void 0 && remaining !== null) {
3403
+ warnPresence(`session "${sessionId}" is still live after detach`);
3404
+ return "unknown";
3405
+ }
3198
3406
  return "evicted";
3199
- } catch {
3407
+ } catch (error) {
3408
+ warnPresence(`evictLive failed for "${sessionId}"`, error);
3200
3409
  return "unknown";
3201
3410
  }
3202
3411
  },
@@ -3240,9 +3449,10 @@ function createHostPort(ctx) {
3240
3449
  if (workspace === void 0) throw new Error(`${WORKSPACE_MISSING_MESSAGE} (detach): ${workspaceId}`);
3241
3450
  await workspace.detachSession(sessionId);
3242
3451
  },
3243
- /** 挂账本:实体方法 `attachSession`(顶层没有)。 */
3244
- async attach(sessionId, workspaceId) {
3452
+ /** 挂账本:实体方法 `attachSession`(顶层没有)。`if-unassigned` 只在失败回滚用(见接口注释)。 */
3453
+ async attach(sessionId, workspaceId, when) {
3245
3454
  const workspace = registry.get(workspaceId);
3455
+ if (when === "if-unassigned" && (workspace === void 0 || ownerOf(sessionId) !== void 0)) return;
3246
3456
  if (workspace === void 0) throw new Error(`${WORKSPACE_MISSING_MESSAGE} (attach): ${workspaceId}`);
3247
3457
  await workspace.attachSession(sessionId);
3248
3458
  },
@@ -3423,7 +3633,7 @@ function createHostPort(ctx) {
3423
3633
  //#endregion
3424
3634
  //#region src/verbs/restore-session.ts
3425
3635
  /**
3426
- * 恢复:把删除那次按原路退回,并按组走。预检整组(不写盘):回收站目录与原项目目录必须在,账本缺席不算硬失败(归「未分组」)。
3636
+ * 恢复:把移入回收站那次按原路退回,并按组走。预检整组(不写盘):回收站目录与原项目目录必须在,账本缺席不算硬失败(归「未分组」)。
3427
3637
  * 逐个恢复:文件先回来 → 挂账本 →(旧条目)取消归档 → 摘清册行;中途失败由 journal 回滚当前成员,已恢复的兄弟按相反顺序退回。
3428
3638
  * 通告归批量层(ADR-0002)。
3429
3639
  */
@@ -3452,13 +3662,13 @@ function restoreSession(deps) {
3452
3662
  return target;
3453
3663
  };
3454
3664
  }
3455
- /** 放回哪儿:用 entryId 里删除时写下的**已编码目录段**原地回放,不从 sessionId 现编——宿主换编码算法也不影响旧条目回家
3665
+ /** 放回哪儿:用 entryId 里移入回收站时写下的**已编码目录段**原地回放,不从 sessionId 现编——宿主换编码算法也不影响旧条目回家
3456
3666
  * (编码唯一实现住 `src/shared/session-path.ts`;本插件认的就是宿主编出来的那一段)。 */
3457
3667
  function restoreTargetDir(deps, entry) {
3458
3668
  return sessionDirOf(entry.projectDir, parseEntryId(entry.id).sessionDirName, deps.home);
3459
3669
  }
3460
3670
  /**
3461
- * 这一次恢复**到底挂不挂账本**:交出能挂的 `workspaceId`,挂不了就 `undefined`。两种缺席是同一件事:空串 = 删除时就没有账目;
3671
+ * 这一次恢复**到底挂不挂账本**:交出能挂的 `workspaceId`,挂不了就 `undefined`。两种缺席是同一件事:空串 = 移入回收站时就没有账目;
3462
3672
  * 非空但账本里已没它 = 宿主的「删除工作区」只删注册、保留目录与日志,那些会话本来就在「未分组」下。
3463
3673
  * 判据**只有这一处**(`memberRestore` 与 `GET /list` 共用),两处各问一遍就会有一天一个说、一个不挂。
3464
3674
  */
@@ -3466,7 +3676,7 @@ async function attachableWorkspaceId(host, entry) {
3466
3676
  if (entry.workspaceId === "") return void 0;
3467
3677
  return await host.workspaceExists(entry.workspaceId) ? entry.workspaceId : void 0;
3468
3678
  }
3469
- /** 这一条记着的工作区**是不是已经没了**(区别于删除时就没有账目的空串)——清单行据此决定说不说那句
3679
+ /** 这一条记着的工作区**是不是已经没了**(区别于移入回收站时就没有账目的空串)——清单行据此决定说不说那句
3470
3680
  * 「原工作区已不存在,恢复后归入未分组」。由 {@link attachableWorkspaceId} 派生,不另起判据(否则会一个说、一个不挂)。 */
3471
3681
  async function isWorkspaceMissing(host, entry) {
3472
3682
  return entry.workspaceId !== "" && await attachableWorkspaceId(host, entry) === void 0;
@@ -3489,9 +3699,9 @@ async function memberRestore(deps, presence, entry) {
3489
3699
  label: "放回会话目录失败",
3490
3700
  run: async () => {
3491
3701
  writeProgress.step("moving");
3492
- await deps.fs.rename(trashDir, sessionDir);
3702
+ await moveDirectoryWithRetry(deps.fs.rename, trashDir, sessionDir);
3493
3703
  },
3494
- undo: () => stepUndo("目录退回回收站失败", () => deps.fs.rename(sessionDir, trashDir))
3704
+ undo: () => stepUndo("目录退回回收站失败", () => moveDirectoryWithRetry(deps.fs.rename, sessionDir, trashDir))
3495
3705
  },
3496
3706
  ...workspaceId === void 0 ? [] : [{
3497
3707
  key: "workspace",
@@ -3546,6 +3756,8 @@ function createTrashScope(rows, execute) {
3546
3756
  const view = createShrinkingView(rows);
3547
3757
  return {
3548
3758
  claimAll: (ids) => view.claimAll(ids),
3759
+ claim: (id) => view.claim(id),
3760
+ originalGroup: (id) => view.originalGroup(id),
3549
3761
  runGroup: async (plan) => {
3550
3762
  const stats = await execute(plan);
3551
3763
  view.takeRows(plan.trash.map((row) => row.entry.id));
@@ -3576,12 +3788,19 @@ function assembleOutcome(outcome, action, id) {
3576
3788
  if (!isApplyOutcomeOf(outcome, action)) throw verbError("io", `信封装配不合形:${id}`);
3577
3789
  return outcome;
3578
3790
  }
3579
- function failure(id, action, error) {
3791
+ function failure(id, action, error, attachments) {
3792
+ const remote = toRemoteFailure(error);
3580
3793
  return assembleOutcome({
3581
3794
  id,
3582
3795
  action,
3583
3796
  ok: false,
3584
- error: toRemoteFailure(error)
3797
+ error: attachments === void 0 ? remote : {
3798
+ ...remote,
3799
+ details: {
3800
+ ...remote.details,
3801
+ [FAILURE_DETAILS_ATTACHMENTS_KEY]: attachments
3802
+ }
3803
+ }
3585
3804
  }, action, id);
3586
3805
  }
3587
3806
  /** 按动作收窄的成功支(判别联合要的是**字面量**)。 */
@@ -3832,70 +4051,67 @@ async function applyRestore(deps, ids) {
3832
4051
  }
3833
4052
  return entryReceipts("restore", wanted, slots);
3834
4053
  }
4054
+ /** 收口槽 → 合成层的裁决面;没落定按 failed 算(`receiptsOf` 的兜底同口径)。 */
4055
+ function verdictOf(slot) {
4056
+ if (slot === void 0) return "failed";
4057
+ if (slot.kind === "done") return "ok";
4058
+ return slot.kind === "carried" ? "carried" : "failed";
4059
+ }
3835
4060
  /**
3836
- * per-id 附件读数合成(批级尾 → 逐条回执的 `attachments` 格):`byGroup` 拆回 ok 支;无主(失败组来的)
3837
- * 对象读数并入**批内最后一个 ok 支**;skipped 逐组归因——候选日志 / 对象 stat 的读不出只落**自己组**的成功
3838
- * 回执(不串台),全批共享的两段(证明失败、执行期复核失败)落进过计划的组,没人进过计划时全挂
3839
- * (skipped 原文是 fail-closed 的用户可见落点,丢了就是红线回归);整批零 ok 支不产出附件读数
3840
- * (与全失败批一致);carried 幂等支不带 `attachments`(那一趟没有读数,缺席与 0 是两件事)。
3841
- * 对象单归属(计划期先到先得)+ 无主归并 ⇒ 批内各 id 的读数相加 = 尾 `run` 的合计,客户端「按批相加」的归并不动。
4061
+ * per-id 附件读数合成(批级尾 → 逐条信封的 `attachments` 格):`byGroup` 按**组归属**(计划期先到先得)
4062
+ * 拆回各条——ok 支挂进自己的成功回执,失败支挂进自己 `error.details` 的同一格。对象读数不冒领别的条的
4063
+ * 回执;执行级「谁删了哪组目录」的第二本账本层不加,组归属就是这本账。carried 幂等支不带 `attachments`
4064
+ * (那一趟没有读数,缺席与 0 是两件事)。skipped 逐组归因——候选日志 / 对象 stat 的读不出只落**自己组**
4065
+ * 的载体(不串台);全批共享的两段(证明失败、执行期复核失败)按三档落点——先落有对象要删的组,
4066
+ * 没有这种组时落有候选图的组(不误挂 `absent` / 无图组),连候选都没有才全挂
4067
+ * (skipped 原文是 fail-closed 的用户可见落点,丢了就是红线回归)。
4068
+ * ok 支没有读数也带零读数(与 carried 的缺席区分);失败支没有信号不带(缺席与 0 是两件事)。
4069
+ * 组归属不变 ⇒ 批内各 id 的读数(成功回执 + 失败 details)相加 = 尾 `run` 的合计,客户端「按批相加」的归并不动。
3842
4070
  */
3843
4071
  function synthesizeAttachmentReadings(batch, tail, runs) {
3844
4072
  const out = /* @__PURE__ */ new Map();
3845
- const okIds = [];
3846
- let lastOk;
3847
- for (const run of runs) {
3848
- if (!run.ok) continue;
3849
- okIds.push(run.id);
3850
- const own = tail.byGroupRun.get(run.id);
4073
+ const slotOf = (id) => {
4074
+ const found = out.get(id);
4075
+ if (found !== void 0) return found;
4076
+ const own = tail.byGroupRun.get(id);
3851
4077
  const slot = {
3852
4078
  removed: own?.removed ?? 0,
3853
4079
  freedBytes: own?.freedBytes ?? 0,
3854
4080
  failed: own?.failed ?? 0
3855
4081
  };
3856
- out.set(run.id, slot);
3857
- lastOk = slot;
3858
- }
3859
- if (lastOk !== void 0) {
3860
- const failedGroups = new Set(runs.filter((run) => !run.ok).map((run) => run.id));
3861
- for (const [groupId, reading] of tail.byGroupRun) {
3862
- if (!failedGroups.has(groupId)) continue;
3863
- lastOk.removed += reading.removed;
3864
- lastOk.freedBytes += reading.freedBytes;
3865
- lastOk.failed += reading.failed;
3866
- }
3867
- }
3868
- if (tail.run.skipped !== void 0) {
3869
- const withObjects = okIds.filter((id) => (batch.byGroup.get(id)?.size ?? 0) > 0);
3870
- const sharedTarget = new Set(withObjects.length > 0 ? withObjects : okIds);
3871
- for (const id of okIds) {
3872
- const slot = out.get(id);
3873
- if (slot === void 0) continue;
3874
- const parts = [];
3875
- const ownCandidates = batch.unreadableCandidatesByGroup.get(id) ?? 0;
3876
- if (ownCandidates > 0) parts.push(unreadableCandidatesReason(ownCandidates));
3877
- const ownObjects = batch.unreadableObjectsByGroup.get(id) ?? 0;
3878
- if (ownObjects > 0) parts.push(unreadableObjectsReason(ownObjects));
3879
- if (sharedTarget.has(id)) {
3880
- if (batch.sharedSkipped !== void 0) parts.push(batch.sharedSkipped);
3881
- if (tail.recheckSkipped !== void 0) parts.push(tail.recheckSkipped);
3882
- }
3883
- if (parts.length > 0) slot.skipped = parts.join(";");
4082
+ out.set(id, slot);
4083
+ return slot;
4084
+ };
4085
+ for (const run of runs) if (run.verdict === "ok" || run.verdict === "failed" && tail.byGroupRun.has(run.id)) slotOf(run.id);
4086
+ const withObjects = runs.filter((run) => run.verdict !== "carried" && (batch.byGroup.get(run.id)?.size ?? 0) > 0);
4087
+ const withCandidates = withObjects.length > 0 ? withObjects : runs.filter((run) => run.verdict !== "carried" && batch.candidateGroupIds.has(run.id));
4088
+ const sharedTarget = new Set((withCandidates.length > 0 ? withCandidates : runs.filter((run) => run.verdict !== "carried")).map((run) => run.id));
4089
+ for (const run of runs) {
4090
+ if (run.verdict === "carried") continue;
4091
+ const parts = [];
4092
+ const ownCandidates = batch.unreadableCandidatesByGroup.get(run.id) ?? 0;
4093
+ if (ownCandidates > 0) parts.push(unreadableCandidatesReason(ownCandidates));
4094
+ const ownObjects = batch.unreadableObjectsByGroup.get(run.id) ?? 0;
4095
+ if (ownObjects > 0) parts.push(unreadableObjectsReason(ownObjects));
4096
+ if (sharedTarget.has(run.id)) {
4097
+ if (batch.sharedSkipped !== void 0) parts.push(batch.sharedSkipped);
4098
+ if (tail.recheckSkipped !== void 0) parts.push(tail.recheckSkipped);
3884
4099
  }
4100
+ if (parts.length > 0) slotOf(run.id).skipped = parts.join(";");
3885
4101
  }
3886
4102
  return out;
3887
4103
  }
3888
- /** 逐条收口 → 信封(输入序):失败折错误对象、carried 回幂等零、成功支挂合成出来的附件读数。 */
4104
+ /** 逐条收口 → 信封(输入序):失败折错误对象并挂自己那组的附件读数,carried 回幂等零,成功支挂合成读数。 */
3889
4105
  function receiptsOf(action, ids, slots, readings) {
3890
4106
  return ids.map((id, index) => {
3891
4107
  const slot = slots.get(index);
3892
- if (slot === void 0) return failure(id, action, verbError("io", `批执行没有落定:${id}`));
3893
- if (slot.kind === "failed") return failure(id, action, slot.error);
4108
+ const attachments = readings.get(id);
4109
+ if (slot === void 0) return failure(id, action, verbError("io", `批执行没有落定:${id}`), attachments);
4110
+ if (slot.kind === "failed") return failure(id, action, slot.error, attachments);
3894
4111
  if (slot.kind === "carried") return success(id, action, {
3895
4112
  removed: 0,
3896
4113
  freedBytes: 0
3897
4114
  });
3898
- const attachments = readings.get(id);
3899
4115
  return success(id, action, {
3900
4116
  removed: slot.stats.removed,
3901
4117
  freedBytes: slot.stats.freedBytes,
@@ -3919,6 +4135,8 @@ async function applyPurge(deps, ids) {
3919
4135
  * (组内串行不动)→ 第二波串行补跑(实况为准)→ 批尾附件尾 → 合成 per-id 回执。 */
3920
4136
  async function runPurgeBatch(deps, scope, rows, wanted) {
3921
4137
  const claims = scope.claimAll(wanted);
4138
+ /** 整批只算一次「清册里的会话 id 集」:计划 / 挂起扫描都吃它,不再逐组重建(批量面的 n² 就在这里)。 */
4139
+ const manifestIds = manifestSessionIds(rows);
3922
4140
  const slots = /* @__PURE__ */ new Map();
3923
4141
  /** 槽位落定与条目 tick 的唯一闸:done 与「已处理条数」同义(含失败条),每处收口都走它。 */
3924
4142
  const closeSlot = (index, slot) => {
@@ -3939,7 +4157,7 @@ async function runPurgeBatch(deps, scope, rows, wanted) {
3939
4157
  prepared.push({
3940
4158
  index,
3941
4159
  id: claim.id,
3942
- plan: await planTrashRemoval(deps, rows, claim.group)
4160
+ plan: await planTrashRemoval(deps, rows, claim.group, manifestIds)
3943
4161
  });
3944
4162
  } catch (error) {
3945
4163
  closeSlot(index, {
@@ -3950,22 +4168,26 @@ async function runPurgeBatch(deps, scope, rows, wanted) {
3950
4168
  }
3951
4169
  const plannedDirs = new Set(prepared.flatMap((item) => item.plan.attachmentDirs));
3952
4170
  const carriedScan = [];
3953
- const seenGroups = /* @__PURE__ */ new Set();
3954
- const incompleteGroups = /* @__PURE__ */ new Set();
3955
- const groupKeyOf = (id) => groupOf(rows, id).map((row) => row.id).sort().join("\0");
4171
+ /** 同一原始组只扫一次:key = 组内行 id 排序;值 = 这次扫描是否读全。 */
4172
+ const scannedGroups = /* @__PURE__ */ new Map();
4173
+ /** 某一组的扫描读不出:这一组的所有挂起条第二波都失败关闭(不是整组号,逐条记)。 */
4174
+ const incompleteIds = /* @__PURE__ */ new Set();
3956
4175
  for (const claim of claims) {
3957
4176
  if (claim.verdict !== "carried") continue;
3958
- const group = groupOf(rows, claim.id);
3959
- const groupKey = groupKeyOf(claim.id);
3960
- if (seenGroups.has(groupKey)) continue;
4177
+ const group = scope.originalGroup(claim.id);
3961
4178
  if (group.every((row) => plannedDirs.has(trashDirOf(row.id, deps.home)))) continue;
3962
- seenGroups.add(groupKey);
3963
- const planned = await plannedAttachmentDirs(deps, rows, group);
3964
- carriedScan.push({
3965
- id: claim.id,
3966
- dirs: planned.dirs
3967
- });
3968
- if (!planned.complete) incompleteGroups.add(groupKey);
4179
+ const key = group.map((row) => row.id).sort().join("\0");
4180
+ let complete = scannedGroups.get(key);
4181
+ if (complete === void 0) {
4182
+ const planned = await plannedAttachmentDirs(deps, rows, group, manifestIds);
4183
+ carriedScan.push({
4184
+ id: claim.id,
4185
+ dirs: planned.dirs
4186
+ });
4187
+ complete = planned.complete;
4188
+ scannedGroups.set(key, complete);
4189
+ }
4190
+ if (!complete) incompleteIds.add(claim.id);
3969
4191
  }
3970
4192
  const batch = await planBatchImageAttachmentRemoval(deps, [...prepared.map((item) => ({
3971
4193
  id: item.id,
@@ -3987,8 +4209,8 @@ async function runPurgeBatch(deps, scope, rows, wanted) {
3987
4209
  await runWave(chainsOf(prepared, (item) => [...item.plan.attachmentDirs, ...item.plan.unarchive.map((sessionId) => `unarchive:${bareSessionId(sessionId)}`)]), (item) => settle(item.index, item.plan));
3988
4210
  for (const [index, claim] of claims.entries()) {
3989
4211
  if (claim.verdict !== "carried") continue;
3990
- const again = scope.claimAll([claim.id])[0];
3991
- if (again === void 0 || again.verdict === "carried") {
4212
+ const again = scope.claim(claim.id);
4213
+ if (again.verdict === "carried") {
3992
4214
  closeSlot(index, { kind: "carried" });
3993
4215
  continue;
3994
4216
  }
@@ -3999,7 +4221,7 @@ async function runPurgeBatch(deps, scope, rows, wanted) {
3999
4221
  });
4000
4222
  continue;
4001
4223
  }
4002
- if (incompleteGroups.has(groupKeyOf(claim.id))) {
4224
+ if (incompleteIds.has(claim.id)) {
4003
4225
  closeSlot(index, {
4004
4226
  kind: "failed",
4005
4227
  error: verbError("io", `批级附件扫描读不出这一组的盘上后代:${claim.id}`)
@@ -4007,7 +4229,7 @@ async function runPurgeBatch(deps, scope, rows, wanted) {
4007
4229
  continue;
4008
4230
  }
4009
4231
  try {
4010
- const plan = await planTrashRemoval(deps, rows, again.group);
4232
+ const plan = await planTrashRemoval(deps, rows, again.group, manifestIds);
4011
4233
  const unscanned = [...plan.trash.filter((row) => row.present).map((row) => row.dir), ...plan.members.map((member) => member.dir)].filter((dir) => !batch.presentDirs.has(dir));
4012
4234
  if (unscanned.length > 0) throw verbError("io", `第二波删除目录未进入批级附件扫描面:${unscanned[0]}`);
4013
4235
  await settle(index, plan);
@@ -4020,10 +4242,10 @@ async function runPurgeBatch(deps, scope, rows, wanted) {
4020
4242
  }
4021
4243
  return receiptsOf("purge", wanted, slots, synthesizeAttachmentReadings(batch, await executeAttachmentTail(deps, batch), wanted.map((id, index) => ({
4022
4244
  id,
4023
- ok: slots.get(index)?.kind === "done"
4245
+ verdict: verdictOf(slots.get(index))
4024
4246
  }))));
4025
4247
  }
4026
- /** 删除确认框那句「含 N 个子会话」:一次问完整批(`subagentMembersOf` 本来就是批量口)。
4248
+ /** 批量已选清单的子会话计数:一次问完整批(`subagentMembersOf` 本来就是批量口)。
4027
4249
  * 宿主口缺席按 0;真读失败则整次调用失败,浏览器半按"读不到"把整句不说。**父+子同批时逐条相加会
4028
4250
  * 重复计子根**(预裁决放开了「请求根可被父根发现」,ADR-0070 边界)——这是显示级读数、不是信封,
4029
4251
  * 且界面选择只发可见根行,不为此加去重层。 */
@@ -4033,7 +4255,7 @@ async function applyCount(deps, ids) {
4033
4255
  return wanted.map((id) => success(id, "count", read.available ? read.value[id]?.length ?? 0 : 0));
4034
4256
  }
4035
4257
  /**
4036
- * 解除归档(归档档的显式动作,不是删除/恢复的副作用,ADR-0008 不翻案):逐 id 调宿主 `unarchiveSession`
4258
+ * 解除归档(归档档的显式动作,不是移入回收站/恢复的副作用,ADR-0008 不翻案):逐 id 调宿主 `unarchiveSession`
4037
4259
  * (未归档是幂等 no-op);成功值固定 `1`——「这条 id 被处理成功」,不是实际状态变化数(宿主不为此多读一次 `isArchived`)。
4038
4260
  */
4039
4261
  async function applyUnarchive(deps, ids) {
@@ -4163,7 +4385,7 @@ async function runOrphanBatch(deps, groups, wanted) {
4163
4385
  }
4164
4386
  return receiptsOf("orphan-clean", wanted, slots, synthesizeAttachmentReadings(batch, await executeAttachmentTail(deps, batch), wanted.map((id, index) => ({
4165
4387
  id,
4166
- ok: slots.get(index)?.kind === "done"
4388
+ verdict: verdictOf(slots.get(index))
4167
4389
  }))));
4168
4390
  }
4169
4391
  /**
@@ -4338,6 +4560,21 @@ function displayNameOfLog(raw) {
4338
4560
  title
4339
4561
  };
4340
4562
  }
4563
+ //#endregion
4564
+ //#region src/trash/content-text.ts
4565
+ /**
4566
+ * 一条记录 `content[]` 里「正文文字」的**唯一抽取**:详情块与检索语料共用这一份,判据写两遍就是两份会漂移的抄本。
4567
+ *
4568
+ * 只认文本段:图片、文件、工具调用段都不是正文文字(附件另有自己的读数面)。过线 JSON 的数组元素可能是 `null`
4569
+ * (镜像说 `ContentPart`,运行时未必),所以取到的东西仍要判类型与 `text` 成员才用。
4570
+ *
4571
+ * 多段之间用换行连接再 `trim()`:宿主一条消息里的连续文本段本来就是一段话被切开,用换行连能保住段落边界,
4572
+ * 又不会像拼接那样把两句话粘成一个词。
4573
+ */
4574
+ function contentText(content) {
4575
+ if (!Array.isArray(content)) return "";
4576
+ return content.filter((part) => part?.type === "text" && typeof part.text === "string").map((part) => part.text).join("\n").trim();
4577
+ }
4341
4578
  /** 一次摘要要显示多少条孩子:`min(孩子总数, 条数闸)`;闸缺省取 {@link SUBAGENT_SUMMARY_LIMIT}。负数闸按 0 处理;调用方必须用这个数去切片。 */
4342
4579
  function displayedSubagentCount(count, limit) {
4343
4580
  return Math.max(0, Math.min(count, limit ?? 200));
@@ -4383,11 +4620,6 @@ const DEFAULT_LIMITS = {
4383
4620
  pageChars: PAGE_CHAR_LIMIT,
4384
4621
  subagents: 200
4385
4622
  };
4386
- /** 一条记录里那些 `content[]` 段的文字拼起来(`\n` 分隔;非 text 段一律不参与)。 */
4387
- function textOf(content) {
4388
- if (!Array.isArray(content)) return "";
4389
- return content.filter((part) => part?.type === "text" && typeof part.text === "string").map((part) => part.text).join("\n").trim();
4390
- }
4391
4623
  /** 一条记录的 `content[]` 里的附件块,映射成线上读数(形状只映射,不改判据——闸在 `attachmentsInContent` 里)。 */
4392
4624
  function attachmentWires(content) {
4393
4625
  return attachmentsInContent(content).map((ref) => ({
@@ -4649,7 +4881,7 @@ function createDetailFold(limits = DEFAULT_LIMITS, before) {
4649
4881
  case "user/message": {
4650
4882
  const source = data.source ?? {};
4651
4883
  const sourceKind = typeof source.kind === "string" ? source.kind : "";
4652
- const text = textOf(data.content);
4884
+ const text = contentText(data.content);
4653
4885
  const attachments = attachmentWires(data.content);
4654
4886
  if (sourceKind === "user") {
4655
4887
  const block = textBlock("user", time, text, attachments, limits.perBlockChars);
@@ -4728,17 +4960,17 @@ function createDetailFold(limits = DEFAULT_LIMITS, before) {
4728
4960
  const message = data.message ?? {};
4729
4961
  const callId = typeof message.toolCallId === "string" ? message.toolCallId : "";
4730
4962
  if (callId === "") return;
4731
- page.result(callId, textOf(message.content), message.isError === true, attachmentWires(message.content));
4963
+ page.result(callId, contentText(message.content), message.isError === true, attachmentWires(message.content));
4732
4964
  return;
4733
4965
  }
4734
4966
  case "system/message": {
4735
4967
  const message = data.message ?? {};
4736
- const block = textBlock("system", time, textOf(message.content), attachmentWires(message.content), limits.perBlockChars);
4968
+ const block = textBlock("system", time, contentText(message.content), attachmentWires(message.content), limits.perBlockChars);
4737
4969
  if (block !== void 0) page.add(block);
4738
4970
  return;
4739
4971
  }
4740
4972
  case "compaction/summary": {
4741
- const block = textBlock("compaction", time, textOf(data.summary), [], limits.perBlockChars);
4973
+ const block = textBlock("compaction", time, contentText(data.summary), [], limits.perBlockChars);
4742
4974
  if (block !== void 0) page.add(block);
4743
4975
  return;
4744
4976
  }
@@ -4948,6 +5180,746 @@ async function readArchiveSubagents(deps, sessionId, limits) {
4948
5180
  };
4949
5181
  }
4950
5182
  //#endregion
5183
+ //#region src/trash/search-corpus.ts
5184
+ /**
5185
+ * 检索语料的**抽取器**:把一条会话的日志记录流式折成「参与检索的消息」。
5186
+ *
5187
+ * 三个口径:
5188
+ * ① **只收用户与助手文字**。注入上下文、思考、工具调用 / 结果、系统消息、压缩摘要都不进——它们不是用户找会话时的记忆锚点,
5189
+ * 而且工具结果动辄几十 KB,收进来只会让扫描变慢、命中变噪声。判据与 `src/trash/detail.ts` 的建块规则同源,但这里**不建块**。
5190
+ * ② **流式、不落地**:调用方把每条记录喂进来,命中与否当场判定;这里从不保存整本消息数组。长日志靠调用方设的字符预算兜住
5191
+ * (压缩 32 MiB 的日志能解出几百 MB 文本,预算超了就整条判 `too-large`,不截断后假装搜全了)。
5192
+ * ③ **空正文不占序号**:序号是「第几条可检索消息」,预览按它寻址;把空消息也算进去会让序号与实际可搜内容错位。
5193
+ */
5194
+ /** 从 `assistant/message` 的 `message.content[]` 里取文字段:与详情共用同一份 `contentText`。 */
5195
+ function assistantText(data) {
5196
+ if (typeof data !== "object" || data === null) return "";
5197
+ const message = data.message;
5198
+ if (typeof message !== "object" || message === null) return "";
5199
+ return contentText(message.content);
5200
+ }
5201
+ /** `user/message` 里只有 `source.kind === 'user'` 才算用户原话;其余(注入、工具回填等)一律不是。 */
5202
+ function userText(data) {
5203
+ if (typeof data !== "object" || data === null) return "";
5204
+ const record = data;
5205
+ const source = record.source;
5206
+ if (typeof source !== "object" || source === null) return "";
5207
+ if (source.kind !== "user") return "";
5208
+ return contentText(record.content);
5209
+ }
5210
+ /**
5211
+ * 造一个抽取器。`onMessage` 返回 `false` 表示调用方「够了、不再收命中」(例如本页命中数已满)——
5212
+ * 它只停**收集**,不停**计账**:后续消息继续计字符,`finish()` 仍按整条会话报 `ok / too-large`。
5213
+ * 这样预算闸属于会话、分页属于传输,任何页都不会出现「先给了命中、后来又说没搜完」的半截结论。
5214
+ */
5215
+ function createMessageExtractor(onMessage, budget) {
5216
+ let count = 0;
5217
+ let chars = 0;
5218
+ let overflowed = false;
5219
+ let stopped = false;
5220
+ const emit = (role, time, text) => {
5221
+ if (overflowed || text === "") return;
5222
+ if (chars + text.length > budget.maxChars) {
5223
+ overflowed = true;
5224
+ return;
5225
+ }
5226
+ chars += text.length;
5227
+ if (stopped) return;
5228
+ const message = {
5229
+ index: count,
5230
+ role,
5231
+ time,
5232
+ text
5233
+ };
5234
+ count += 1;
5235
+ if (onMessage(message) === false) stopped = true;
5236
+ };
5237
+ return {
5238
+ feed(record) {
5239
+ if (overflowed) return;
5240
+ const time = typeof record.time === "number" ? record.time : 0;
5241
+ switch (record.type) {
5242
+ case "user/message":
5243
+ emit("user", time, userText(record.data));
5244
+ return;
5245
+ case "assistant/message":
5246
+ emit("assistant", time, assistantText(record.data));
5247
+ return;
5248
+ default: return;
5249
+ }
5250
+ },
5251
+ isExhausted() {
5252
+ return overflowed;
5253
+ },
5254
+ finish() {
5255
+ return overflowed ? {
5256
+ ok: false,
5257
+ kind: "too-large"
5258
+ } : {
5259
+ ok: true,
5260
+ count,
5261
+ chars
5262
+ };
5263
+ }
5264
+ };
5265
+ }
5266
+ //#endregion
5267
+ //#region src/trash/search-text.ts
5268
+ /**
5269
+ * 检索的**纯函数层**:查询归一、区间查找、开窗/摘要、游标编解码。零 I/O、不碰 deps——编排在 `src/verbs/search.ts`。
5270
+ *
5271
+ * 三条口径都不是口味:
5272
+ * ① **字面子串,不解析正则**:用户输入 `.*` 就该找那两个字面字符,不能变成模式(也不用正则去实现,省得转义漏一处就成漏洞)。
5273
+ * ② **不重叠**:`aaaa` 里找 `aa` 是两处,不是三处——重叠区段会让高亮切出互相吞并的片段,且「N 处」失去基数。
5274
+ * ③ **开窗按码点、高亮区间按 UTF-16 码元**:切窗不能切坏代理对(emoji),而 `ranges` 的坐标要在**切好的那一串**上重算,
5275
+ * 两套坐标混用就是高亮错位——所以这里从不搬运下标,只重算。
5276
+ */
5277
+ /** 检索范围唯一名单住 `shared/wire.ts`;纯函数层只投影,不另写一份字面量。 */
5278
+ /** 归一查询串:`trim` 后小写。空串(含全空白)回 `undefined`——那不是一次检索。 */
5279
+ function normalizeQuery(raw) {
5280
+ const normalized = raw.trim().toLowerCase();
5281
+ return normalized === "" ? void 0 : normalized;
5282
+ }
5283
+ /** 在 `text` 里找 `query` 的全部出现(大小写不敏感、字面、不重叠),按出现序。 */
5284
+ function findRanges(text, query) {
5285
+ const needle = query.toLowerCase();
5286
+ if (needle === "") return [];
5287
+ const haystack = text.toLowerCase();
5288
+ if (haystack.length === text.length) {
5289
+ const ranges = [];
5290
+ let from = 0;
5291
+ for (;;) {
5292
+ const at = haystack.indexOf(needle, from);
5293
+ if (at < 0) return ranges;
5294
+ ranges.push([at, at + needle.length]);
5295
+ from = at + needle.length;
5296
+ }
5297
+ }
5298
+ const unitStart = [];
5299
+ const unitEnd = [];
5300
+ const parts = [];
5301
+ let origPos = 0;
5302
+ for (const cp of text) {
5303
+ const nextOrig = origPos + cp.length;
5304
+ const lowered = cp.toLowerCase();
5305
+ parts.push(lowered);
5306
+ for (let i = 0; i < lowered.length; i += 1) {
5307
+ unitStart.push(origPos);
5308
+ unitEnd.push(nextOrig);
5309
+ }
5310
+ origPos = nextOrig;
5311
+ }
5312
+ const loweredText = text.toLowerCase();
5313
+ const mappedHaystack = loweredText.length === unitStart.length ? loweredText : parts.join("");
5314
+ const ranges = [];
5315
+ let from = 0;
5316
+ for (;;) {
5317
+ const at = mappedHaystack.indexOf(needle, from);
5318
+ if (at < 0) return ranges;
5319
+ const endAt = at + needle.length - 1;
5320
+ const startOffset = unitStart[at];
5321
+ const endOffset = unitEnd[endAt];
5322
+ const startsAtBoundary = at === 0 || startOffset !== unitStart[at - 1];
5323
+ const endsAtBoundary = endAt + 1 === mappedHaystack.length || unitStart[endAt + 1] !== unitStart[endAt];
5324
+ if (startsAtBoundary && endsAtBoundary && startOffset !== void 0 && endOffset !== void 0) {
5325
+ ranges.push([startOffset, endOffset]);
5326
+ from = at + needle.length;
5327
+ } else from = at + 1;
5328
+ }
5329
+ }
5330
+ function takeCodePointsFromStart(s, count) {
5331
+ if (count <= 0) return {
5332
+ text: "",
5333
+ truncated: s.length > 0
5334
+ };
5335
+ let end = 0;
5336
+ let taken = 0;
5337
+ for (const cp of s) {
5338
+ if (taken >= count) return {
5339
+ text: s.slice(0, end),
5340
+ truncated: true
5341
+ };
5342
+ end += cp.length;
5343
+ taken += 1;
5344
+ }
5345
+ return {
5346
+ text: s,
5347
+ truncated: false
5348
+ };
5349
+ }
5350
+ function takeCodePointsFromEnd(s, count) {
5351
+ if (count <= 0) return {
5352
+ text: "",
5353
+ truncated: s.length > 0
5354
+ };
5355
+ let rawStart = Math.max(0, s.length - count * 2 - 2);
5356
+ if (rawStart > 0 && s.charCodeAt(rawStart) >= 56320 && s.charCodeAt(rawStart) <= 57343) rawStart += 1;
5357
+ const tail = Array.from(s.slice(rawStart));
5358
+ if (tail.length <= count) return {
5359
+ text: s.slice(rawStart),
5360
+ truncated: rawStart > 0
5361
+ };
5362
+ return {
5363
+ text: tail.slice(-count).join(""),
5364
+ truncated: true
5365
+ };
5366
+ }
5367
+ /**
5368
+ * 码点窗口切片:以**第一处命中**为中心,前后各留 `before` / `after` 个码点;没有命中时退化成前 `before + after` 个码点。
5369
+ * 窗口按码点切(不破代理对),区间出窗之前由调用方在**新串**上重算。
5370
+ */
5371
+ function sliceAroundMatch(text, query, before, after) {
5372
+ const safeBefore = Math.max(0, before);
5373
+ const safeAfter = Math.max(0, after);
5374
+ const first = findRanges(text, query)[0];
5375
+ if (first === void 0) {
5376
+ const head = takeCodePointsFromStart(text, safeBefore + safeAfter);
5377
+ return {
5378
+ core: head.text,
5379
+ headTruncated: false,
5380
+ tailTruncated: head.truncated
5381
+ };
5382
+ }
5383
+ const prefix = takeCodePointsFromEnd(text.slice(0, first[0]), safeBefore);
5384
+ const match = text.slice(first[0], first[1]);
5385
+ const suffix = takeCodePointsFromStart(text.slice(first[1]), safeAfter);
5386
+ return {
5387
+ core: `${prefix.text}${match}${suffix.text}`,
5388
+ headTruncated: prefix.truncated,
5389
+ tailTruncated: suffix.truncated
5390
+ };
5391
+ }
5392
+ /** 以命为中心开窗,两端**不补省略号**(命中消息用:省略号会被误读成正文本身有截断标记)。 */
5393
+ function windowOf(text, query, before, after) {
5394
+ const { core, headTruncated, tailTruncated } = sliceAroundMatch(text, query, before, after);
5395
+ return {
5396
+ text: core,
5397
+ ranges: findRanges(core, query),
5398
+ truncated: headTruncated || tailTruncated
5399
+ };
5400
+ }
5401
+ /** 摘要:与 {@link windowOf} 同一刀,但两端被切时补 `…`;区间先在正文核心上算出再按前缀长度平移,不误高亮合成省略号。 */
5402
+ function snippetOf(text, query, before, after) {
5403
+ const { core, headTruncated, tailTruncated } = sliceAroundMatch(text, query, before, after);
5404
+ const coreRanges = findRanges(core, query);
5405
+ const head = headTruncated ? "…" : "";
5406
+ const tail = tailTruncated ? "…" : "";
5407
+ const offset = head.length;
5408
+ const ranges = offset === 0 ? coreRanges : coreRanges.map(([start, end]) => [start + offset, end + offset]);
5409
+ return {
5410
+ text: `${head}${core}${tail}`,
5411
+ ranges,
5412
+ truncated: headTruncated || tailTruncated
5413
+ };
5414
+ }
5415
+ /** 查询串的稳定短哈希(FNV-1a 32 位):游标只认同一次查询,防跨查询串页。 */
5416
+ function hashQuery(query) {
5417
+ let hash = 2166136261;
5418
+ for (let index = 0; index < query.length; index += 1) {
5419
+ hash ^= query.charCodeAt(index);
5420
+ hash = Math.imul(hash, 16777619) >>> 0;
5421
+ }
5422
+ return hash.toString(16).padStart(8, "0");
5423
+ }
5424
+ /** 游标 → 不透明串(base64url 的 JSON)。 */
5425
+ function encodeCursor(cursor) {
5426
+ return Buffer.from(JSON.stringify(cursor), "utf8").toString("base64url");
5427
+ }
5428
+ /** 不透明串 → 游标;畸形、版本不符、字段不合法一律 `undefined`,绝不抛(请求面据此回 400)。 */
5429
+ function decodeCursor(raw) {
5430
+ if (raw === "") return void 0;
5431
+ let parsed;
5432
+ try {
5433
+ parsed = JSON.parse(Buffer.from(raw, "base64url").toString("utf8"));
5434
+ } catch {
5435
+ return;
5436
+ }
5437
+ if (typeof parsed !== "object" || parsed === null) return void 0;
5438
+ const candidate = parsed;
5439
+ if (candidate.v !== 1) return void 0;
5440
+ const scope = SEARCH_SCOPES.find((candidateScope) => candidateScope === candidate.scope);
5441
+ if (scope === void 0) return void 0;
5442
+ if (typeof candidate.queryHash !== "string" || candidate.queryHash === "") return void 0;
5443
+ if (typeof candidate.rowId !== "string" || candidate.rowId === "") return void 0;
5444
+ const messageIndex = candidate.messageIndex;
5445
+ if (typeof messageIndex !== "number" || !Number.isInteger(messageIndex) || messageIndex < -1) return void 0;
5446
+ return {
5447
+ v: 1,
5448
+ scope,
5449
+ queryHash: candidate.queryHash,
5450
+ rowId: candidate.rowId,
5451
+ messageIndex
5452
+ };
5453
+ }
5454
+ /** 单条会话**解压后正文**的上限(UTF-16 码元,与 JS 字符串下标同一把尺):压缩比可以很高,字节闸兜不住解压后的量。 */
5455
+ const SEARCH_MAX_TEXT_CHARS = 8e6;
5456
+ /** 摘录开窗宽度(字符):标题短、正文长。 */
5457
+ const TITLE_SNIPPET = {
5458
+ before: 40,
5459
+ after: 60
5460
+ };
5461
+ const BODY_SNIPPET = {
5462
+ before: 60,
5463
+ after: 90
5464
+ };
5465
+ /** 一条标题命中:标题只读不扫日志,标题命中没有消息位置(判别式联合)。 */
5466
+ function titleHitOf(rowId, groupId, title, query) {
5467
+ if (findRanges(title, query).length === 0) return null;
5468
+ const snippet = snippetOf(title, query, TITLE_SNIPPET.before, TITLE_SNIPPET.after);
5469
+ return {
5470
+ rowId,
5471
+ groupId,
5472
+ kind: "title",
5473
+ snippet: snippet.text,
5474
+ ranges: snippet.ranges,
5475
+ isChild: rowId !== groupId
5476
+ };
5477
+ }
5478
+ function scanCellsOf(rows) {
5479
+ return visibleGroups(rows).flatMap(({ root, kids }) => [{
5480
+ row: root,
5481
+ groupId: root.id
5482
+ }, ...kids.map((kid) => ({
5483
+ row: kid,
5484
+ groupId: root.id
5485
+ }))]);
5486
+ }
5487
+ /**
5488
+ * 扫一条会话,把命中收进局部数组;`afterMessageIndex` 之前的消息跳过(续页用)。
5489
+ * 本条会话的命中数到 `limit` 就停收命中,但抽取器**继续计字符到会话结束**(或到预算溢出为止)——
5490
+ * 预算结论因此对整条会话成立,续页不会翻出「前页已命中、后页说太大」。
5491
+ */
5492
+ async function scanOne(deps, cell, query, afterMessageIndex, limit) {
5493
+ const dir = trashDirOf(cell.row.id, deps.home);
5494
+ let logName;
5495
+ try {
5496
+ logName = pickSessionLog(await deps.fs.listFiles(dir));
5497
+ } catch {
5498
+ return {
5499
+ ok: false,
5500
+ reason: "unreadable"
5501
+ };
5502
+ }
5503
+ if (logName === void 0) return {
5504
+ ok: false,
5505
+ reason: "unreadable"
5506
+ };
5507
+ const logPath = `${dir}/${logName}`;
5508
+ let size;
5509
+ try {
5510
+ size = (await deps.fs.statFile(logPath)).size;
5511
+ } catch {
5512
+ return {
5513
+ ok: false,
5514
+ reason: "unreadable"
5515
+ };
5516
+ }
5517
+ if (size > 33554432) return {
5518
+ ok: false,
5519
+ reason: "too-large"
5520
+ };
5521
+ const read = await readWholeSessionLog(deps.fs, logPath);
5522
+ if (!read.ok) return {
5523
+ ok: false,
5524
+ reason: read.kind === "too-large" ? "too-large" : "unreadable"
5525
+ };
5526
+ const hits = [];
5527
+ let lastHitIndex = -1;
5528
+ const extractor = createMessageExtractor((message) => {
5529
+ if (message.index <= afterMessageIndex) return;
5530
+ if (findRanges(message.text, query).length === 0) return;
5531
+ const snippet = snippetOf(message.text, query, BODY_SNIPPET.before, BODY_SNIPPET.after);
5532
+ lastHitIndex = message.index;
5533
+ hits.push({
5534
+ rowId: cell.row.id,
5535
+ groupId: cell.groupId,
5536
+ kind: "body",
5537
+ role: message.role,
5538
+ time: message.time,
5539
+ messageIndex: message.index,
5540
+ snippet: snippet.text,
5541
+ ranges: snippet.ranges,
5542
+ isChild: cell.row.id !== cell.groupId
5543
+ });
5544
+ if (hits.length >= limit) return false;
5545
+ }, { maxChars: SEARCH_MAX_TEXT_CHARS });
5546
+ try {
5547
+ walkSessionLog(read.raw, (record) => {
5548
+ extractor.feed(record);
5549
+ if (extractor.isExhausted()) return false;
5550
+ });
5551
+ } catch {
5552
+ return {
5553
+ ok: false,
5554
+ reason: "unreadable"
5555
+ };
5556
+ }
5557
+ if (!extractor.finish().ok) return {
5558
+ ok: false,
5559
+ reason: "too-large"
5560
+ };
5561
+ return {
5562
+ ok: true,
5563
+ lastHitIndex,
5564
+ hits
5565
+ };
5566
+ }
5567
+ /** 归档语料:归档集成员按语料原序。归档服务缺席 ⇒ `io`(不拿「搜到零条」冒充「没有」)。
5568
+ * 标题批量读只在首页需要(续页 `titleHits` 恒空);续页不白付一次全量标题读。
5569
+ *
5570
+ * 标题口径与归档清单行**同一份显示名**(`src/trash/session-rows.ts` 的 `projectRowFacts`):批量标题缺席
5571
+ * ⇒ 逐条回退 `titleOf`(旧宿主不是「这一条读不出」);子代理行 label 优先于日志标题。不拿空标题冒充
5572
+ * 「没有这条命中」——归档检索的标题区与正文区一样,读不出就是读不出。 */
5573
+ async function archiveCellsOf(deps, withTitles) {
5574
+ const archived = await deps.host.archivedSessionIds();
5575
+ const corpus = await deps.host.listSessions();
5576
+ if (!corpus.available) throw verbError("io", "归档语料不可见,检索无法进行");
5577
+ const archivedSet = new Set(archived);
5578
+ const identities = corpus.value.filter((identity) => archivedSet.has(identity.sessionId));
5579
+ if (!withTitles) return identities.map((identity) => ({
5580
+ sessionId: identity.sessionId,
5581
+ title: ""
5582
+ }));
5583
+ const titles = await deps.host.titleSnapshots(identities.map((identity) => identity.sessionId));
5584
+ if (!titles.available) return await mapLimit(identities, 8, async (identity) => ({
5585
+ sessionId: identity.sessionId,
5586
+ title: await deps.host.titleOf(identity.sessionId)
5587
+ }));
5588
+ return await mapLimit(identities, 8, async (identity) => {
5589
+ const logTitle = titles.value.get(identity.sessionId) ?? "";
5590
+ if (!identity.subagent) return {
5591
+ sessionId: identity.sessionId,
5592
+ title: logTitle
5593
+ };
5594
+ const label = await deps.host.labelOf(identity.sessionId);
5595
+ return {
5596
+ sessionId: identity.sessionId,
5597
+ title: label === "" ? logTitle : label
5598
+ };
5599
+ });
5600
+ }
5601
+ /** 一条归档会话的扫描:整本事件流喂同一个抽取器(回收站读日志文件、这里读宿主事件流,语料口径同一份)。 */
5602
+ async function scanArchiveOne(deps, cell, query, afterMessageIndex, limit) {
5603
+ let read;
5604
+ try {
5605
+ read = await deps.host.readSession(cell.sessionId);
5606
+ } catch {
5607
+ return {
5608
+ ok: false,
5609
+ reason: "unreadable"
5610
+ };
5611
+ }
5612
+ const hits = [];
5613
+ let lastHitIndex = -1;
5614
+ const extractor = createMessageExtractor((message) => {
5615
+ if (message.index <= afterMessageIndex) return;
5616
+ if (findRanges(message.text, query).length === 0) return;
5617
+ const snippet = snippetOf(message.text, query, BODY_SNIPPET.before, BODY_SNIPPET.after);
5618
+ lastHitIndex = message.index;
5619
+ hits.push({
5620
+ rowId: cell.sessionId,
5621
+ groupId: cell.sessionId,
5622
+ kind: "body",
5623
+ role: message.role,
5624
+ time: message.time,
5625
+ messageIndex: message.index,
5626
+ snippet: snippet.text,
5627
+ ranges: snippet.ranges,
5628
+ isChild: false
5629
+ });
5630
+ if (hits.length >= limit) return false;
5631
+ }, { maxChars: SEARCH_MAX_TEXT_CHARS });
5632
+ for (const event of read.events) {
5633
+ extractor.feed({
5634
+ type: event.type,
5635
+ time: event.time,
5636
+ data: event.data
5637
+ });
5638
+ if (extractor.isExhausted()) break;
5639
+ }
5640
+ if (!extractor.finish().ok) return {
5641
+ ok: false,
5642
+ reason: "too-large"
5643
+ };
5644
+ return {
5645
+ ok: true,
5646
+ lastHitIndex,
5647
+ hits
5648
+ };
5649
+ }
5650
+ function openSearch(request, scope) {
5651
+ const query = normalizeQuery(request.query);
5652
+ if (query === void 0) throw routeError("bad-request", 400, "检索词不能是空白");
5653
+ const queryHash = hashQuery(query);
5654
+ const cursor = request.cursor === void 0 ? void 0 : decodeCursor(request.cursor);
5655
+ if (request.cursor !== void 0 && cursor === void 0) throw routeError("bad-request", 400, "检索游标不认识(可能来自别的查询或已被改坏)");
5656
+ if (cursor !== void 0 && (cursor.scope !== scope || cursor.queryHash !== queryHash)) throw routeError("bad-request", 400, "检索游标不属于这一次查询");
5657
+ return {
5658
+ query,
5659
+ queryHash,
5660
+ cursor
5661
+ };
5662
+ }
5663
+ /** 一页检索:标题命中首页给全,正文命中按实体游标续扫;`cursor === null` 表示扫完。 */
5664
+ async function runPagedSearch(source, opened) {
5665
+ const { query, queryHash, cursor } = opened;
5666
+ const cells = await source.cells(cursor === void 0);
5667
+ const titleHits = cursor === void 0 ? source.titleHits(cells, query) : [];
5668
+ const bodyHits = [];
5669
+ const skipped = [];
5670
+ const startedAt = Date.now();
5671
+ const startIndex = cursor === void 0 ? 0 : cells.findIndex((cell) => source.idOf(cell) === cursor.rowId);
5672
+ let index = startIndex;
5673
+ let after = cursor === void 0 ? -1 : cursor.messageIndex;
5674
+ let scanned = 0;
5675
+ let nextCursor = null;
5676
+ if (cursor !== void 0 && index < 0) return {
5677
+ titleHits,
5678
+ bodyHits,
5679
+ cursor: null,
5680
+ scanned: 0,
5681
+ total: cells.length,
5682
+ skipped,
5683
+ incomplete: true
5684
+ };
5685
+ while (index < cells.length) {
5686
+ const cell = cells[index];
5687
+ if (cell === void 0) break;
5688
+ if (scanned >= source.pageSessions || Date.now() - startedAt >= 1500) {
5689
+ nextCursor = encodeCursor({
5690
+ v: 1,
5691
+ scope: source.scope,
5692
+ queryHash,
5693
+ rowId: source.idOf(cell),
5694
+ messageIndex: after
5695
+ });
5696
+ break;
5697
+ }
5698
+ const outcome = await source.scan(cell, after, 20 - bodyHits.length);
5699
+ if (outcome.ok) bodyHits.push(...outcome.hits);
5700
+ else skipped.push({
5701
+ rowId: source.idOf(cell),
5702
+ groupId: source.groupIdOf(cell),
5703
+ reason: outcome.reason
5704
+ });
5705
+ scanned += 1;
5706
+ if (outcome.ok && bodyHits.length >= 20) {
5707
+ nextCursor = encodeCursor({
5708
+ v: 1,
5709
+ scope: source.scope,
5710
+ queryHash,
5711
+ rowId: source.idOf(cell),
5712
+ messageIndex: outcome.lastHitIndex
5713
+ });
5714
+ break;
5715
+ }
5716
+ index += 1;
5717
+ after = -1;
5718
+ }
5719
+ return {
5720
+ titleHits,
5721
+ bodyHits,
5722
+ cursor: nextCursor,
5723
+ scanned: startIndex + scanned,
5724
+ total: cells.length,
5725
+ skipped
5726
+ };
5727
+ }
5728
+ /** 回收站档的一页检索(段名 `/search`):标题命中首页给全,正文命中按实体游标续扫。 */
5729
+ async function runSearch(deps, request, rows) {
5730
+ const opened = openSearch(request, "trash");
5731
+ const cells = scanCellsOf(rows);
5732
+ return await runPagedSearch({
5733
+ scope: "trash",
5734
+ pageSessions: 40,
5735
+ cells: () => Promise.resolve(cells),
5736
+ titleHits: (sourceCells, query) => sourceCells.flatMap((cell) => {
5737
+ if (cell.row.id !== cell.groupId) return [];
5738
+ const hit = titleHitOf(cell.row.id, cell.groupId, cell.row.title, query);
5739
+ return hit === null ? [] : [hit];
5740
+ }),
5741
+ scan: async (cell, after, limit) => await scanOne(deps, cell, opened.query, after, limit),
5742
+ idOf: (cell) => cell.row.id,
5743
+ groupIdOf: (cell) => cell.groupId
5744
+ }, opened);
5745
+ }
5746
+ /** 归档档的一页检索(段名 `/archive-search`):与回收站同一条分页协议,语料换成「归档集 ∩ 语料」。 */
5747
+ async function runArchiveSearch(deps, request) {
5748
+ const opened = openSearch(request, "archive");
5749
+ return await runPagedSearch({
5750
+ scope: "archive",
5751
+ pageSessions: 8,
5752
+ cells: async (withTitles) => await archiveCellsOf(deps, withTitles),
5753
+ titleHits: (sourceCells, query) => sourceCells.flatMap((cell) => {
5754
+ const hit = titleHitOf(cell.sessionId, cell.sessionId, cell.title, query);
5755
+ return hit === null ? [] : [hit];
5756
+ }),
5757
+ scan: async (cell, after, limit) => await scanArchiveOne(deps, cell, opened.query, after, limit),
5758
+ idOf: (cell) => cell.sessionId,
5759
+ groupIdOf: (cell) => cell.sessionId
5760
+ }, opened);
5761
+ }
5762
+ /** 预览三格窗口 + 命中序号的**唯一构造**:回收站与归档两档都走它(消息序列形状同一份)。 */
5763
+ function buildPreview(rowId, groupId, messages, query, messageIndex) {
5764
+ const hitMessages = messages.filter((message) => findRanges(message.text, query).length > 0);
5765
+ const hitIndex = hitMessages.findIndex((message) => message.index === messageIndex);
5766
+ if (hitIndex < 0) throw routeError("bad-request", 400, "这个位置不是这次查询的一处命中");
5767
+ const hit = messages[messageIndex];
5768
+ if (hit === void 0) throw routeError("bad-request", 400, "消息下标越界");
5769
+ const hitWindow = windowOf(hit.text, query, 300, 300);
5770
+ const messagesOut = [];
5771
+ const previous = messages[hit.index - 1];
5772
+ if (previous !== void 0) {
5773
+ const sliced = snippetOf(previous.text, "", 0, 200);
5774
+ messagesOut.push({
5775
+ messageIndex: previous.index,
5776
+ role: previous.role,
5777
+ time: previous.time,
5778
+ text: sliced.text,
5779
+ truncated: sliced.truncated,
5780
+ isHit: false,
5781
+ ranges: []
5782
+ });
5783
+ }
5784
+ messagesOut.push({
5785
+ messageIndex: hit.index,
5786
+ role: hit.role,
5787
+ time: hit.time,
5788
+ text: hitWindow.text,
5789
+ truncated: hitWindow.truncated,
5790
+ isHit: true,
5791
+ ranges: hitWindow.ranges
5792
+ });
5793
+ const next = messages[hit.index + 1];
5794
+ if (next !== void 0) {
5795
+ const sliced = snippetOf(next.text, "", 0, 200);
5796
+ messagesOut.push({
5797
+ messageIndex: next.index,
5798
+ role: next.role,
5799
+ time: next.time,
5800
+ text: sliced.text,
5801
+ truncated: sliced.truncated,
5802
+ isHit: false,
5803
+ ranges: []
5804
+ });
5805
+ }
5806
+ return {
5807
+ groupId,
5808
+ rowId,
5809
+ hitIndex,
5810
+ hitCount: hitMessages.length,
5811
+ previousHitMessageIndex: hitMessages[hitIndex - 1]?.index ?? null,
5812
+ nextHitMessageIndex: hitMessages[hitIndex + 1]?.index ?? null,
5813
+ messages: messagesOut
5814
+ };
5815
+ }
5816
+ /** 回收站档的命中预览(段名 `/search-preview`):寻址只认清册行(外部输入进不了文件系统)。 */
5817
+ async function runSearchPreview(deps, request, rows) {
5818
+ const query = normalizeQuery(request.query);
5819
+ if (query === void 0) throw routeError("bad-request", 400, "检索词不能是空白");
5820
+ const row = rows.find((candidate) => candidate.id === request.rowId);
5821
+ if (row === void 0) throw verbError("not-found", `回收站里没有这一条:${request.rowId}`);
5822
+ const groupId = rootIdOf(rows, row.id);
5823
+ const dir = trashDirOf(row.id, deps.home);
5824
+ let logName;
5825
+ try {
5826
+ logName = pickSessionLog(await deps.fs.listFiles(dir));
5827
+ } catch (error) {
5828
+ throw verbError("io", "读不出这条会话的日志", error);
5829
+ }
5830
+ if (logName === void 0) throw verbError("io", "读不出这条会话的日志");
5831
+ const logPath = `${dir}/${logName}`;
5832
+ let size;
5833
+ try {
5834
+ size = (await deps.fs.statFile(logPath)).size;
5835
+ } catch (error) {
5836
+ throw verbError("io", "读不出这条会话的日志", error);
5837
+ }
5838
+ if (size > 33554432) throw verbError("io", "这条会话的日志太大,取不出预览", "too-large");
5839
+ const read = await readWholeSessionLog(deps.fs, logPath);
5840
+ if (!read.ok) throw verbError("io", read.kind === "too-large" ? "这条会话的日志太大,取不出预览" : "读不出这条会话的日志", read.kind);
5841
+ const messages = [];
5842
+ const extractor = createMessageExtractor((message) => {
5843
+ messages.push(message);
5844
+ }, { maxChars: SEARCH_MAX_TEXT_CHARS });
5845
+ try {
5846
+ walkSessionLog(read.raw, (record) => {
5847
+ extractor.feed(record);
5848
+ if (extractor.isExhausted()) return false;
5849
+ });
5850
+ } catch (error) {
5851
+ throw verbError("io", "读不出这条会话的日志", error);
5852
+ }
5853
+ if (!extractor.finish().ok) throw verbError("io", "这条会话的正文超出检索上限,取不出预览");
5854
+ return buildPreview(row.id, groupId, messages, query, request.messageIndex);
5855
+ }
5856
+ /** 归档档的命中预览(段名 `/archive-search-preview`):只认归档集成员(与 `/archive-detail` 同一条寻址边界,ADR-0061)。 */
5857
+ async function runArchivePreview(deps, request) {
5858
+ const query = normalizeQuery(request.query);
5859
+ if (query === void 0) throw routeError("bad-request", 400, "检索词不能是空白");
5860
+ let archived;
5861
+ try {
5862
+ archived = await deps.host.isArchived(request.rowId);
5863
+ } catch (error) {
5864
+ throw verbError("io", "读归档状态失败,无法校验这条会话", error);
5865
+ }
5866
+ if (!archived) throw verbError("not-found", `归档里没有这一条:${request.rowId}`);
5867
+ let read;
5868
+ try {
5869
+ read = await deps.host.readSession(request.rowId);
5870
+ } catch (error) {
5871
+ throw verbError("io", `读归档日志失败:${error instanceof Error ? error.message : String(error)}`, error);
5872
+ }
5873
+ const messages = [];
5874
+ const extractor = createMessageExtractor((message) => {
5875
+ messages.push(message);
5876
+ }, { maxChars: SEARCH_MAX_TEXT_CHARS });
5877
+ for (const event of read.events) {
5878
+ extractor.feed({
5879
+ type: event.type,
5880
+ time: event.time,
5881
+ data: event.data
5882
+ });
5883
+ if (extractor.isExhausted()) break;
5884
+ }
5885
+ if (!extractor.finish().ok) throw verbError("io", "这条会话的正文超出检索上限,取不出预览");
5886
+ return buildPreview(request.rowId, request.rowId, messages, query, request.messageIndex);
5887
+ }
5888
+ //#endregion
5889
+ //#region src/api/search.ts
5890
+ /**
5891
+ * 检索两段的**请求面**:段名选语料(`/search` = 回收站、`/archive-search` = 归档),请求体只带查询串与游标;
5892
+ * 预览两段带寻址键与消息下标。字段是否存在 / 类型对不对由路由表的通用解析手先过,这里只做**语义**校验——
5893
+ * 查询串归一后还非不非空、有没有超过上限、游标形状是否可解码(游标与段名的 scope 匹配在动词层校验)。
5894
+ *
5895
+ * 语料不可见 / 归档读面失败这类**操作结果**不在这里,归动词抛 `io`。
5896
+ */
5897
+ /** 归一后的查询串:空串与超长都算请求不对(静默改写成别的查询比报错更坏);上限与检索框共用 `shared/wire.ts`。 */
5898
+ function queryOf(raw) {
5899
+ const query = normalizeQuery(raw);
5900
+ if (query === void 0) throw routeError("bad-request", 400, "检索词不能是空白");
5901
+ if (Array.from(query).length > 100) throw routeError("bad-request", 400, `检索词最多 100 个字符`);
5902
+ return query;
5903
+ }
5904
+ /** 检索两段的请求体解析:形状已由通用解析手保证,这里只查语义。 */
5905
+ function searchBodyOf(fields) {
5906
+ const query = queryOf(fields[PARAMS.query]);
5907
+ const cursor = fields[PARAMS.cursor];
5908
+ if (cursor !== void 0 && decodeCursor(cursor) === void 0) throw routeError("bad-request", 400, "检索游标不认识(可能来自别的查询或已被改坏)");
5909
+ return {
5910
+ query,
5911
+ cursor
5912
+ };
5913
+ }
5914
+ /** 预览两段的请求体解析:`rowId` 非空与 `messageIndex` 非负整数由字段组保证。 */
5915
+ function searchPreviewBodyOf(fields) {
5916
+ return {
5917
+ query: queryOf(fields[PARAMS.query]),
5918
+ rowId: fields[PARAMS.rowId],
5919
+ messageIndex: fields[PARAMS.messageIndex]
5920
+ };
5921
+ }
5922
+ //#endregion
4951
5923
  //#region src/ports/attachments-port.ts
4952
5924
  /** 服务在 `available()` 之后消失/形状变了:调用方可以退回直接 fs,而不是把这次读取判成 io。 */
4953
5925
  var AttachmentsUnavailableError = class extends Error {
@@ -5198,6 +6170,16 @@ async function reportAttachmentOrphans(deps) {
5198
6170
  };
5199
6171
  }
5200
6172
  //#endregion
6173
+ //#region src/api/project-ranks.ts
6174
+ async function projectRankTableOf(host) {
6175
+ const order = await host.projectOrder();
6176
+ const ranks = /* @__PURE__ */ new Map();
6177
+ order.forEach((projectDir, index) => {
6178
+ if (!ranks.has(projectDir)) ranks.set(projectDir, index);
6179
+ });
6180
+ return ranks;
6181
+ }
6182
+ //#endregion
5201
6183
  //#region src/api/trash-rows.ts
5202
6184
  /** 清册行 → 线上行:清册字段走 `entryWire`(多一个必填字段会编译错),这里只补 `/list` 只读数。 */
5203
6185
  function toWire(row, readouts) {
@@ -5208,7 +6190,8 @@ function toWire(row, readouts) {
5208
6190
  ...readouts.subagentBytes === void 0 ? {} : { subagentBytes: readouts.subagentBytes },
5209
6191
  ...readouts.strandedSubagents === void 0 ? {} : { strandedSubagents: readouts.strandedSubagents },
5210
6192
  ...readouts.strandedBytes === void 0 ? {} : { strandedBytes: readouts.strandedBytes },
5211
- ...readouts.workspaceMissing === void 0 ? {} : { workspaceMissing: readouts.workspaceMissing }
6193
+ ...readouts.workspaceMissing === void 0 ? {} : { workspaceMissing: readouts.workspaceMissing },
6194
+ ...readouts.projectRank === void 0 ? {} : { projectRank: readouts.projectRank }
5212
6195
  };
5213
6196
  }
5214
6197
  /** 装配成「一行 = 一组」:孩子折进父行,父行不在时孩子自己占一行(否则看不见也清不掉)。
@@ -5216,20 +6199,29 @@ function toWire(row, readouts) {
5216
6199
  * 组释放量与盘上剩余只由 `planVisibleTrash` 一处算,不碰 `isLive`。 */
5217
6200
  async function assembleTrashRows(deps, rows) {
5218
6201
  const groups = visibleGroups(rows);
5219
- const [planned, missingByRowId] = await Promise.all([planVisibleTrash(deps, rows, groups), Promise.all(groups.map(async ({ root }) => [root.id, await isWorkspaceMissing(deps.host, root)]))]);
5220
- const gone = new Map(missingByRowId);
5221
- return planned.map(({ root, kids, releaseBytes, subagentBytes, strandedCount, strandedBytes }) => toWire(root, {
5222
- releaseBytes,
5223
- ...kids.length === 0 ? {} : {
5224
- subagentCount: kids.length,
5225
- subagentBytes
5226
- },
5227
- ...strandedCount === 0 ? {} : {
5228
- strandedSubagents: strandedCount,
5229
- strandedBytes
5230
- },
5231
- ...gone.get(root.id) === true ? { workspaceMissing: true } : {}
5232
- }));
6202
+ const workspaces = new Map(groups.map(({ root }) => [root.workspaceId, root]));
6203
+ const [planned, missingByWorkspace, ranks] = await Promise.all([
6204
+ planVisibleTrash(deps, rows, groups),
6205
+ Promise.all(Array.from(workspaces, async ([workspaceId, row]) => [workspaceId, await isWorkspaceMissing(deps.host, row)])),
6206
+ projectRankTableOf(deps.host)
6207
+ ]);
6208
+ const gone = new Map(missingByWorkspace);
6209
+ return planned.map(({ root, kids, releaseBytes, subagentBytes, strandedCount, strandedBytes }) => {
6210
+ const projectRank = ranks.get(root.projectDir);
6211
+ return toWire(root, {
6212
+ releaseBytes,
6213
+ ...projectRank === void 0 ? {} : { projectRank },
6214
+ ...kids.length === 0 ? {} : {
6215
+ subagentCount: kids.length,
6216
+ subagentBytes
6217
+ },
6218
+ ...strandedCount === 0 ? {} : {
6219
+ strandedSubagents: strandedCount,
6220
+ strandedBytes
6221
+ },
6222
+ ...gone.get(root.workspaceId) === true ? { workspaceMissing: true } : {}
6223
+ });
6224
+ });
5233
6225
  }
5234
6226
  //#endregion
5235
6227
  //#region src/api/archive-rows.ts
@@ -5245,11 +6237,14 @@ async function assembleArchiveRows(deps) {
5245
6237
  wantsLabel: identity.subagent
5246
6238
  })), { sizeFailure: "throw" });
5247
6239
  const { totalBytes, missingSizeCount } = sizeTotals(facts);
6240
+ /** 与回收站同一张顺序表:项目不在账本里 ⇒ 这一格不落键(不是 0)。 */
6241
+ const ranks = await projectRankTableOf(deps.host);
5248
6242
  return {
5249
6243
  available: true,
5250
6244
  rows: facts.flatMap((fact, index) => {
5251
6245
  const identity = identities[index];
5252
6246
  if (identity === void 0) return [];
6247
+ const projectRank = ranks.get(identity.projectDir);
5253
6248
  return [{
5254
6249
  sessionId: identity.sessionId,
5255
6250
  projectDir: identity.projectDir,
@@ -5258,6 +6253,7 @@ async function assembleArchiveRows(deps) {
5258
6253
  ...fact.updatedAt === void 0 ? {} : { updatedAt: fact.updatedAt },
5259
6254
  ...fact.updatedAtSource === void 0 ? {} : { updatedAtSource: fact.updatedAtSource },
5260
6255
  ...fact.sizeBytes === void 0 ? {} : { sizeBytes: fact.sizeBytes },
6256
+ ...projectRank === void 0 ? {} : { projectRank },
5261
6257
  subagent: identity.subagent
5262
6258
  }];
5263
6259
  }),
@@ -5277,7 +6273,9 @@ const BODY_KIND = {
5277
6273
  config: "json",
5278
6274
  entry: "json",
5279
6275
  apply: "json",
5280
- sessionId: "json"
6276
+ sessionId: "json",
6277
+ search: "json",
6278
+ searchPreview: "json"
5281
6279
  };
5282
6280
  /** 读的是 wire 那一格(`ROUTES.x.body`):无字段与查询串段不读,带 JSON 字段的段读一次。 */
5283
6281
  function bodyOf(route) {
@@ -5309,7 +6307,8 @@ const APPLY_ACTION_TABLE = {
5309
6307
  "orphan-clean": APPLY_ACTION_INDEX["orphan-clean"].purity,
5310
6308
  unarchive: APPLY_ACTION_INDEX.unarchive.purity
5311
6309
  };
5312
- const APPLY_ACTIONS = Object.keys(APPLY_ACTION_TABLE);
6310
+ /** 本表自认的动作序(与 `shared/apply-actions.ts` 的规范序等值,由 `apply-actions-matrix.test` 双向钉住;不另起同名导出)。 */
6311
+ const ROUTE_APPLY_ACTIONS = Object.keys(APPLY_ACTION_TABLE);
5313
6312
  /** `/apply` 的动作:全仓唯一识别器,纯度函数与字段闸都从这里过。不抛:不认得一律回 `undefined`,
5314
6313
  * 抛不抛、抛哪句话归通用解析手({@link parseBody})。 */
5315
6314
  function actionValueOf(value) {
@@ -5326,7 +6325,7 @@ function parseBody(body, group) {
5326
6325
  for (const [field, kind] of Object.entries(group)) fields[field] = readField(body, field, kind);
5327
6326
  return fields;
5328
6327
  }
5329
- /** 描述里的一个字段读成它的值:五种种类各一句 400 原文,原文只住这一处。 */
6328
+ /** 描述里的一个字段读成它的值:六种种类各一句 400 原文,原文只住这一处。 */
5330
6329
  function readField(body, field, kind) {
5331
6330
  const value = body?.[field];
5332
6331
  switch (kind) {
@@ -5341,9 +6340,12 @@ function readField(body, field, kind) {
5341
6340
  if (value === void 0) return void 0;
5342
6341
  if (typeof value !== "number" || !Number.isInteger(value) || value < 0) throw routeError("bad-request", 400, `请求体字段 ${field} 需是非负整数`);
5343
6342
  return value;
6343
+ case "requiredNumber":
6344
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0) throw routeError("bad-request", 400, `请求体字段 ${field} 需是非负整数`);
6345
+ return value;
5344
6346
  case "action": {
5345
6347
  const action = actionValueOf(value);
5346
- if (action === void 0) throw routeError("bad-request", 400, `批量动作不认识:需是 ${APPLY_ACTIONS.join(" / ")} 之一`);
6348
+ if (action === void 0) throw routeError("bad-request", 400, `批量动作不认识:需是 ${ROUTE_APPLY_ACTIONS.join(" / ")} 之一`);
5347
6349
  return action;
5348
6350
  }
5349
6351
  case "idArray":
@@ -5438,6 +6440,34 @@ const ROUTE_TABLE = createRouteTable({
5438
6440
  response: "json",
5439
6441
  run: async (deps, _body, read) => await runEmptyBatch(deps, await read.rows())
5440
6442
  }),
6443
+ search: defineRoute("search", {
6444
+ slice: "core",
6445
+ purity: "pure",
6446
+ read: "raw",
6447
+ response: "json",
6448
+ run: async (deps, body, read) => runSearch(deps, searchBodyOf(parseBody(body, BODY_GROUPS.search)), await read.rows())
6449
+ }),
6450
+ archiveSearch: defineRoute("archiveSearch", {
6451
+ slice: "core",
6452
+ purity: "pure",
6453
+ read: "none",
6454
+ response: "json",
6455
+ run: async (deps, body) => runArchiveSearch(deps, searchBodyOf(parseBody(body, BODY_GROUPS.search)))
6456
+ }),
6457
+ searchPreview: defineRoute("searchPreview", {
6458
+ slice: "core",
6459
+ purity: "pure",
6460
+ read: "raw",
6461
+ response: "json",
6462
+ run: async (deps, body, read) => runSearchPreview(deps, searchPreviewBodyOf(parseBody(body, BODY_GROUPS.searchPreview)), await read.rows())
6463
+ }),
6464
+ archiveSearchPreview: defineRoute("archiveSearchPreview", {
6465
+ slice: "core",
6466
+ purity: "pure",
6467
+ read: "none",
6468
+ response: "json",
6469
+ run: async (deps, body) => runArchivePreview(deps, searchPreviewBodyOf(parseBody(body, BODY_GROUPS.searchPreview)))
6470
+ }),
5441
6471
  progress: defineRoute("progress", {
5442
6472
  slice: "core",
5443
6473
  purity: "pure",
@@ -5752,7 +6782,7 @@ function registerConnectionRoutes(service, dispatch) {
5752
6782
  * ① 平台自己的 helper `dshHomePath(...segments)` 逐字就是 `join(resolveDshHome(), ...segments)`,同样不传 `configured`;
5753
6783
  * ② `ctx.profileContext` 按 launcher 原文只装「profile 位置 / 启动 bundle 名 / 调用覆盖 / 遥测开关」,里面没有数据根;
5754
6784
  * ③ 宿主自己的服务也不是「问出来」的——它们各自声明 `Config.dshHome`,由装配那一行的人填。
5755
- * 后果:显式配置过的 profile 上我们算出的根与宿主不一致 ⇒ 文件探测落空 ⇒ 删除/恢复**响亮拒绝、零副作用**;不会动到别的树
6785
+ * 后果:显式配置过的 profile 上我们算出的根与宿主不一致 ⇒ 文件探测落空 ⇒ 移入回收站/恢复**响亮拒绝、零副作用**;不会动到别的树
5756
6786
  * (sessions 与回收站同源 ⇒ 同卷)。`homeDir` 只用于测试注入假主目录。
5757
6787
  */
5758
6788
  function resolveHome(env = process.env, homeDir = homedir()) {