@xrn1997/dsh-session-delete 0.12.0 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -3
- package/THIRD_PARTY_NOTICES.md +2 -2
- package/lib/client.js +7856 -5511
- package/lib/index.js +1147 -174
- package/lib/types/api/project-ranks.d.ts +3 -0
- package/lib/types/api/search.d.ts +7 -0
- package/lib/types/api/trash-rows.d.ts +1 -1
- package/lib/types/client/{batch-bar.d.ts → batch/batch-bar.d.ts} +2 -2
- package/lib/types/client/{batch-menu-item.d.ts → batch/batch-menu-item.d.ts} +1 -1
- package/lib/types/client/{batch-pick.d.ts → batch/batch-pick.d.ts} +1 -1
- package/lib/types/client/{batch-select.d.ts → batch/batch-select.d.ts} +2 -2
- package/lib/types/client/{delete-menu-item.d.ts → batch/delete-menu-item.d.ts} +1 -1
- package/lib/types/client/batch/index.d.ts +10 -0
- package/lib/types/client/{copy.d.ts → core/copy.d.ts} +41 -2
- package/lib/types/client/{receipt.d.ts → core/receipt.d.ts} +1 -1
- package/lib/types/client/{remote.d.ts → core/remote.d.ts} +23 -2
- package/lib/types/client/detail/block-render.d.ts +22 -0
- package/lib/types/client/{detail-blocks.d.ts → detail/detail-blocks.d.ts} +1 -1
- package/lib/types/client/detail/detail-style.d.ts +62 -0
- package/lib/types/client/detail/detail-text.d.ts +18 -0
- package/lib/types/client/detail/index.d.ts +17 -0
- package/lib/types/client/{markdown.d.ts → detail/markdown.d.ts} +2 -2
- package/lib/types/client/{prompt-rail.d.ts → detail/prompt-rail.d.ts} +2 -2
- package/lib/types/client/{session-detail.d.ts → detail/session-detail.d.ts} +20 -13
- package/lib/types/client/{subagent-section.d.ts → detail/subagent-section.d.ts} +2 -2
- package/lib/types/client/{use-archive-detail-reader.d.ts → detail/use-archive-detail-reader.d.ts} +2 -2
- package/lib/types/client/{use-detail-pager.d.ts → detail/use-detail-pager.d.ts} +1 -1
- package/lib/types/client/{use-detail-rail.d.ts → detail/use-detail-rail.d.ts} +3 -1
- package/lib/types/client/{use-detail-reader.d.ts → detail/use-detail-reader.d.ts} +3 -3
- package/lib/types/client/{use-prompt-rail.d.ts → detail/use-prompt-rail.d.ts} +1 -1
- package/lib/types/client/{use-trash-detail-reader.d.ts → detail/use-trash-detail-reader.d.ts} +2 -2
- package/lib/types/client/{context-menu-actions.d.ts → host/context-menu-actions.d.ts} +2 -2
- package/lib/types/client/host/guard.d.ts +16 -0
- package/lib/types/client/{host-archive-watch.d.ts → host/host-archive-watch.d.ts} +1 -1
- package/lib/types/client/host/index.d.ts +11 -0
- package/lib/types/client/panel/archive-detail.d.ts +22 -0
- package/lib/types/client/{archive-pane.d.ts → panel/archive-pane.d.ts} +28 -9
- package/lib/types/client/{detail-pane.d.ts → panel/detail-pane.d.ts} +3 -3
- package/lib/types/client/panel/index.d.ts +9 -0
- package/lib/types/client/panel/panel-tab.d.ts +61 -0
- package/lib/types/client/{session-list.d.ts → panel/session-list.d.ts} +4 -4
- package/lib/types/client/{trash-confirm.d.ts → panel/trash-confirm.d.ts} +2 -12
- package/lib/types/client/{trash-detail.d.ts → panel/trash-detail.d.ts} +10 -7
- package/lib/types/client/{trash-drop.d.ts → panel/trash-drop.d.ts} +1 -1
- package/lib/types/client/{trash-entry.d.ts → panel/trash-entry.d.ts} +2 -2
- package/lib/types/client/{trash-panel.d.ts → panel/trash-panel.d.ts} +1 -1
- package/lib/types/client/panel/trash-tab.d.ts +42 -0
- package/lib/types/client/{use-archive-panel-controller.d.ts → panel/use-archive-panel-controller.d.ts} +7 -5
- package/lib/types/client/{use-archive-query.d.ts → panel/use-archive-query.d.ts} +2 -2
- package/lib/types/client/{use-list-selection.d.ts → panel/use-list-selection.d.ts} +1 -1
- package/lib/types/client/{use-panel-child-view.d.ts → panel/use-panel-child-view.d.ts} +1 -1
- package/lib/types/client/{use-panel-tab.d.ts → panel/use-panel-tab.d.ts} +9 -12
- package/lib/types/client/{use-trash-panel-controller.d.ts → panel/use-trash-panel-controller.d.ts} +10 -4
- package/lib/types/client/{use-trash-query.d.ts → panel/use-trash-query.d.ts} +4 -4
- package/lib/types/client/panel/view-switches.d.ts +29 -0
- package/lib/types/client/scene.d.ts +8 -8
- package/lib/types/client/search/index.d.ts +12 -0
- package/lib/types/client/search/search-box.d.ts +24 -0
- package/lib/types/client/search/search-preview.d.ts +46 -0
- package/lib/types/client/search/search-results.d.ts +62 -0
- package/lib/types/client/search/search-text.d.ts +13 -0
- package/lib/types/client/search/use-search-view.d.ts +59 -0
- package/lib/types/client/search/use-search.d.ts +62 -0
- package/lib/types/client/{config-settings.d.ts → settings/config-settings.d.ts} +2 -2
- package/lib/types/client/settings/index.d.ts +8 -0
- package/lib/types/client/{maintenance-parts.d.ts → settings/maintenance-parts.d.ts} +1 -1
- package/lib/types/client/{maintenance-settings.d.ts → settings/maintenance-settings.d.ts} +1 -1
- package/lib/types/client/settings/orphan-confirm.d.ts +12 -0
- package/lib/types/client/{orphan-maintenance.d.ts → settings/orphan-maintenance.d.ts} +3 -3
- package/lib/types/client/{settings-cards.d.ts → settings/settings-cards.d.ts} +2 -2
- package/lib/types/client/{use-maintenance-section.d.ts → settings/use-maintenance-section.d.ts} +1 -1
- package/lib/types/client/{use-maintenance.d.ts → settings/use-maintenance.d.ts} +4 -4
- package/lib/types/client/{batch-selection-store.d.ts → state/batch-selection-store.d.ts} +11 -4
- package/lib/types/client/state/delete-action.d.ts +16 -0
- package/lib/types/client/{main-view.d.ts → state/main-view.d.ts} +1 -1
- package/lib/types/client/{trash-snapshot.d.ts → state/trash-snapshot.d.ts} +1 -1
- package/lib/types/client/{undo-notices.d.ts → state/undo-notices.d.ts} +9 -22
- package/lib/types/client/ui/Button.d.ts +2 -1
- package/lib/types/client/ui/ErrorBoundary.d.ts +4 -8
- package/lib/types/client/ui/Modal.d.ts +4 -3
- package/lib/types/client/ui/Toast.d.ts +13 -3
- package/lib/types/client/ui/Tooltip.d.ts +3 -2
- package/lib/types/client/ui/anchor-fit.d.ts +42 -0
- package/lib/types/client/ui/icons.d.ts +13 -2
- package/lib/types/client/ui/inert.d.ts +15 -0
- package/lib/types/client/{attachment-view.d.ts → widgets/attachment-view.d.ts} +3 -3
- package/lib/types/client/{confirm-dialog.d.ts → widgets/confirm-dialog.d.ts} +4 -0
- package/lib/types/client/{trash-view.d.ts → widgets/trash-view.d.ts} +8 -5
- package/lib/types/client/write/delete-action-host.d.ts +4 -0
- package/lib/types/client/write/index.d.ts +13 -0
- package/lib/types/client/{undo-toast.d.ts → write/undo-toast.d.ts} +2 -2
- package/lib/types/client/{use-write-progress.d.ts → write/use-write-progress.d.ts} +2 -2
- package/lib/types/client/{write-progress.d.ts → write/write-progress.d.ts} +1 -1
- package/lib/types/client/{write-seats.d.ts → write/write-seats.d.ts} +7 -15
- package/lib/types/ports/agent-handles.d.ts +2 -1
- package/lib/types/ports/host-port.d.ts +6 -1
- package/lib/types/shared/wire.d.ts +135 -3
- package/lib/types/trash/content-text.d.ts +10 -0
- package/lib/types/trash/groups.d.ts +18 -6
- package/lib/types/trash/search-corpus.d.ts +40 -0
- package/lib/types/trash/search-text.d.ts +43 -0
- package/lib/types/trash/shrinking-view.d.ts +6 -4
- package/lib/types/verbs/permanent-removal.d.ts +22 -6
- package/lib/types/verbs/search.d.ts +53 -0
- package/lib/types/verbs/trash-scope.d.ts +5 -1
- package/package.json +7 -7
- package/lib/types/client/archive-detail.d.ts +0 -19
- package/lib/types/client/delete-action.d.ts +0 -23
- package/lib/types/client/panel-tab.d.ts +0 -39
- package/lib/types/client/trash-tab.d.ts +0 -22
- package/lib/types/client/ui/Tag.d.ts +0 -16
- /package/lib/types/client/{api-base.d.ts → core/api-base.d.ts} +0 -0
- /package/lib/types/client/{context.d.ts → core/context.d.ts} +0 -0
- /package/lib/types/client/{detail-ledger.d.ts → core/detail-ledger.d.ts} +0 -0
- /package/lib/types/client/{plugin.d.ts → core/plugin.d.ts} +0 -0
- /package/lib/types/client/{use-gated-refresh.d.ts → core/use-gated-refresh.d.ts} +0 -0
- /package/lib/types/client/{use-prefetch.d.ts → core/use-prefetch.d.ts} +0 -0
- /package/lib/types/client/{store.d.ts → core/value-store.d.ts} +0 -0
- /package/lib/types/client/{use-detail-frame.d.ts → detail/use-detail-frame.d.ts} +0 -0
- /package/lib/types/client/{session-live.d.ts → host/session-live.d.ts} +0 -0
- /package/lib/types/client/{drop-machine.d.ts → panel/drop-machine.d.ts} +0 -0
- /package/lib/types/client/{trash-nav.d.ts → panel/trash-nav.d.ts} +0 -0
- /package/lib/types/client/{use-column-resize.d.ts → panel/use-column-resize.d.ts} +0 -0
- /package/lib/types/client/{use-panel-list-read.d.ts → panel/use-panel-list-read.d.ts} +0 -0
- /package/lib/types/client/{use-panel-selection.d.ts → panel/use-panel-selection.d.ts} +0 -0
- /package/lib/types/client/{use-panel-width.d.ts → panel/use-panel-width.d.ts} +0 -0
- /package/lib/types/client/{settings-view.d.ts → settings/settings-view.d.ts} +0 -0
- /package/lib/types/client/{archive-store.d.ts → state/archive-store.d.ts} +0 -0
- /package/lib/types/client/{host-rows.d.ts → state/host-rows.d.ts} +0 -0
- /package/lib/types/client/{pending-open.d.ts → state/pending-open.d.ts} +0 -0
- /package/lib/types/client/{trash-store.d.ts → state/trash-store.d.ts} +0 -0
- /package/lib/types/client/{notice.d.ts → widgets/notice.d.ts} +0 -0
- /package/lib/types/client/{busy-gate.d.ts → write/busy-gate.d.ts} +0 -0
package/lib/index.js
CHANGED
|
@@ -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,6 +303,17 @@ 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
|
};
|
|
274
319
|
/** 失败信封 `details` 里的附件读数格:批内失败条目也带走自己组的读数(ADR-0070 边界),键名与成功回执的
|
|
@@ -430,7 +475,9 @@ function createFsPort() {
|
|
|
430
475
|
if (!entry.isSymbolicLink()) continue;
|
|
431
476
|
try {
|
|
432
477
|
if ((await stat(join(p, entry.name))).isDirectory()) dirs.push(entry.name);
|
|
433
|
-
} catch {
|
|
478
|
+
} catch (error) {
|
|
479
|
+
if (!isAbsentPath(error)) throw error;
|
|
480
|
+
}
|
|
434
481
|
}
|
|
435
482
|
return dirs;
|
|
436
483
|
},
|
|
@@ -832,64 +879,6 @@ function trashDirOf(entryId, home) {
|
|
|
832
879
|
assertSingleSegment(entryId, "回收站条目 id");
|
|
833
880
|
return `${home}/${TRASH_DIR_NAME}/${entryId}`;
|
|
834
881
|
}
|
|
835
|
-
//#endregion
|
|
836
|
-
//#region src/trash/groups.ts
|
|
837
|
-
/** 这些孩子的父。 */
|
|
838
|
-
function kidsOf(rows, parentId) {
|
|
839
|
-
return rows.filter((row) => row.parentEntryId === parentId);
|
|
840
|
-
}
|
|
841
|
-
/**
|
|
842
|
-
* 清单露面的一行 = 组根,按清册原序。孩子折进根那一行(宿主的客户端本来就把 `origin:"subagent"` 的行整排藏了 ⇒ 单列会冒出一堆点不到的行)。
|
|
843
|
-
* 折不进去的那两种孩子(父行不在 / 父行自己也是孩子)**自己站出来占一行**——`visibleGroups` 与 `groupOf` 共用这条判据。
|
|
844
|
-
*/
|
|
845
|
-
function visibleGroups(rows) {
|
|
846
|
-
const byId = new Map(rows.map((row) => [row.id, row]));
|
|
847
|
-
const kidsByRoot = /* @__PURE__ */ new Map();
|
|
848
|
-
const folded = /* @__PURE__ */ new Set();
|
|
849
|
-
for (const row of rows) {
|
|
850
|
-
if (row.parentEntryId === void 0) continue;
|
|
851
|
-
const parent = byId.get(row.parentEntryId);
|
|
852
|
-
if (parent === void 0 || parent.parentEntryId !== void 0) continue;
|
|
853
|
-
folded.add(row.id);
|
|
854
|
-
const siblings = kidsByRoot.get(parent.id);
|
|
855
|
-
if (siblings === void 0) kidsByRoot.set(parent.id, [row]);
|
|
856
|
-
else siblings.push(row);
|
|
857
|
-
}
|
|
858
|
-
return rows.filter((row) => !folded.has(row.id)).map((root) => ({
|
|
859
|
-
root,
|
|
860
|
-
kids: kidsByRoot.get(root.id) ?? []
|
|
861
|
-
}));
|
|
862
|
-
}
|
|
863
|
-
/**
|
|
864
|
-
* 一条 id 所属的整组。三种形状,三个答案:**组根** ⇒ 它自己 + 它接住的孩子(UI 点的是父那一行,删除/恢复/彻底删除都按整组走);
|
|
865
|
-
* **孩子** ⇒ **只回它自己**(清单不单独列它,只有手工/降级路径会点到这里);**清册里没有这一条 id,但还有孩子指向它** ⇒ 那一批孩子;
|
|
866
|
-
* 都没有 ⇒ 空数组,调用方据此报 `trash-empty` / 判"已被同批前一条带走"。
|
|
867
|
-
*/
|
|
868
|
-
function groupOf(rows, id) {
|
|
869
|
-
const root = rows.find((row) => row.id === id);
|
|
870
|
-
if (root !== void 0) return root.parentEntryId === void 0 ? [root, ...kidsOf(rows, id)] : [root];
|
|
871
|
-
return kidsOf(rows, id);
|
|
872
|
-
}
|
|
873
|
-
/**
|
|
874
|
-
* 把一条 id 所属的**整组**从快照里摘掉,回一份新快照(组语义仍只读 `groupOf`)。「同批前一条已把这一组带走」的收缩就是它;
|
|
875
|
-
* 调用方各自持有那份可变视图,本函数不记账。
|
|
876
|
-
*/
|
|
877
|
-
function withoutGroup(rows, id) {
|
|
878
|
-
const gone = new Set(groupOf(rows, id).map((row) => row.id));
|
|
879
|
-
return rows.filter((row) => !gone.has(row.id));
|
|
880
|
-
}
|
|
881
|
-
/**
|
|
882
|
-
* 「这条是被**同批前一条**带走的,还是整批开始前就没有,还是仍在?」幂等语义只属于 `carried`:后来者本来就不在清册里(用户点了条幽灵 id、
|
|
883
|
-
* 或对账刚摘掉它)必须照样响亮报 `trash-empty`。**所以判据是快照的原始形状,不是当前形状**:原始快照里认得出而当前视图已空 ⇒ 同批带走的。
|
|
884
|
-
*/
|
|
885
|
-
function claimOf(original, current, id) {
|
|
886
|
-
if (groupOf(original, id).length === 0) return { verdict: "absent" };
|
|
887
|
-
const group = groupOf(current, id);
|
|
888
|
-
return group.length === 0 ? { verdict: "carried" } : {
|
|
889
|
-
verdict: "fresh",
|
|
890
|
-
group
|
|
891
|
-
};
|
|
892
|
-
}
|
|
893
882
|
/** 批量面:三个读面各读一次、零逐行读;大小读面抛错按策略折成整档缺席(null)或原样上抛。 */
|
|
894
883
|
async function readRowSurfaces(deps, ids, policy) {
|
|
895
884
|
return {
|
|
@@ -1817,39 +1806,119 @@ async function cleanOrphanImageAttachments(deps) {
|
|
|
1817
1806
|
};
|
|
1818
1807
|
}
|
|
1819
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
|
|
1820
1887
|
//#region src/trash/shrinking-view.ts
|
|
1821
1888
|
/**
|
|
1822
1889
|
* 开工时把整批的原始快照捕下来(三态判据的「整批开始前的样子」),当前视图从它出发、按组收缩。
|
|
1823
1890
|
* 调用纪律:`take` / `takeAll` 都在动作**成功之后**才调——清完才收缩,失败时视图不动、下一次重试还能看见这一组。
|
|
1824
|
-
*
|
|
1891
|
+
* 什么时候收缩、把实例放在哪里仍归调用方:本函数只记录哪些行仍在,不改清册。
|
|
1825
1892
|
*/
|
|
1826
1893
|
function createShrinkingView(rows) {
|
|
1827
|
-
const
|
|
1828
|
-
|
|
1894
|
+
const index = indexGroups(rows);
|
|
1895
|
+
const remaining = new Set(index.byId.keys());
|
|
1896
|
+
const present = (id) => remaining.has(id);
|
|
1829
1897
|
return {
|
|
1830
|
-
claim: (id) => claimOf(
|
|
1898
|
+
claim: (id) => claimOf(index, id, present),
|
|
1831
1899
|
claimAll: (ids) => {
|
|
1832
|
-
|
|
1900
|
+
const predicted = /* @__PURE__ */ new Set();
|
|
1901
|
+
const visible = (id) => present(id) && !predicted.has(id);
|
|
1833
1902
|
return ids.map((id) => {
|
|
1834
|
-
const claim = claimOf(
|
|
1835
|
-
if (claim.verdict === "fresh")
|
|
1903
|
+
const claim = claimOf(index, id, visible);
|
|
1904
|
+
if (claim.verdict === "fresh") for (const row of claim.group) predicted.add(row.id);
|
|
1836
1905
|
return {
|
|
1837
1906
|
id,
|
|
1838
1907
|
...claim
|
|
1839
1908
|
};
|
|
1840
1909
|
});
|
|
1841
1910
|
},
|
|
1911
|
+
originalGroup: (id) => groupOf(index, id),
|
|
1842
1912
|
take: (id) => {
|
|
1843
|
-
|
|
1913
|
+
for (const row of groupOf(index, id, present)) remaining.delete(row.id);
|
|
1844
1914
|
},
|
|
1845
1915
|
takeRows: (rowIds) => {
|
|
1846
|
-
const
|
|
1847
|
-
current = current.filter((row) => !gone.has(row.id));
|
|
1916
|
+
for (const id of rowIds) remaining.delete(id);
|
|
1848
1917
|
},
|
|
1849
1918
|
takeAll: () => {
|
|
1850
|
-
|
|
1919
|
+
remaining.clear();
|
|
1851
1920
|
},
|
|
1852
|
-
view: () =>
|
|
1921
|
+
view: () => rows.filter((row) => present(row.id))
|
|
1853
1922
|
};
|
|
1854
1923
|
}
|
|
1855
1924
|
//#endregion
|
|
@@ -2170,7 +2239,8 @@ function deleteSession(deps) {
|
|
|
2170
2239
|
const kids = read.available ? read.value[sessionId] ?? [] : [];
|
|
2171
2240
|
const parentProjectDir = await deps.host.projectDirOf(sessionId);
|
|
2172
2241
|
if (parentProjectDir === void 0) throw verbError("not-found", `宿主的持久化里没有这个会话:${sessionId}`);
|
|
2173
|
-
|
|
2242
|
+
const groupIds = [sessionId, ...kids.map((kid) => kid.sessionId)];
|
|
2243
|
+
await assertNoLive(deps.host, groupIds);
|
|
2174
2244
|
const parentDir = sessionDirForId(parentProjectDir, sessionId, deps.home);
|
|
2175
2245
|
if (!await deps.fs.exists(parentDir)) throw verbError("not-found", `会话目录不存在:${parentDir}`);
|
|
2176
2246
|
const parent = {
|
|
@@ -2189,7 +2259,8 @@ function deleteSession(deps) {
|
|
|
2189
2259
|
followers: members.slice(1),
|
|
2190
2260
|
move: async (member, rootResult) => {
|
|
2191
2261
|
const parentEntryId = rootResult?.id;
|
|
2192
|
-
const
|
|
2262
|
+
const recheckIds = rootResult === void 0 ? groupIds : [member.sessionId];
|
|
2263
|
+
const move = await memberMove(deps, presence, member, deletedAt, parentEntryId, recheckIds);
|
|
2193
2264
|
return {
|
|
2194
2265
|
journal: move.journal,
|
|
2195
2266
|
result: move.entry
|
|
@@ -2210,7 +2281,7 @@ function deleteSession(deps) {
|
|
|
2210
2281
|
* 每一步的反向动作都是"把这件写退回原样";清册行是最后一件写,失败时 journal 把目录搬回去、账本挂回去;
|
|
2211
2282
|
* 它的反向动作带闸:**回收站目录还没搬回来就不摘那一行**,留着行至少元数据还在。
|
|
2212
2283
|
*/
|
|
2213
|
-
async function memberMove(deps, presence, member, deletedAt, parentEntryId) {
|
|
2284
|
+
async function memberMove(deps, presence, member, deletedAt, parentEntryId, recheckIds) {
|
|
2214
2285
|
const { sessionId, projectDir } = member;
|
|
2215
2286
|
const workspaceId = await deps.host.workspaceOf(sessionId);
|
|
2216
2287
|
const sessionDirName = sessionDirSegmentOf(sessionId);
|
|
@@ -2239,6 +2310,7 @@ async function memberMove(deps, presence, member, deletedAt, parentEntryId) {
|
|
|
2239
2310
|
writeProgress.step("measuring");
|
|
2240
2311
|
entry.title = await deps.host.titleOf(sessionId);
|
|
2241
2312
|
entry.sizeBytes = await deps.fs.sizeOfDir(sessionDir);
|
|
2313
|
+
await assertNoLive(deps.host, recheckIds);
|
|
2242
2314
|
}
|
|
2243
2315
|
},
|
|
2244
2316
|
...workspaceId === void 0 ? [] : [{
|
|
@@ -2400,7 +2472,8 @@ async function dropDeletedSessionCache(deps, sessionId) {
|
|
|
2400
2472
|
/**
|
|
2401
2473
|
* 永久删除的测量、计划与执行:先记录目录/字节/账本归属,再按计划动盘。计划函数只读;活体准入在计划阶段、任何写之前完成,
|
|
2402
2474
|
* 执行器动第一笔写前再查一次(ADR-0027)。
|
|
2403
|
-
* 测量与补账本归属**分家**:`/list` 的只读计划只吃 `measureMembers`(零账本读);`workspaceOf`
|
|
2475
|
+
* 测量与补账本归属**分家**:`/list` 的只读计划只吃 `measureMembers`(零账本读);`workspaceOf` 只由 purge / orphan-clean
|
|
2476
|
+
* 的删除计划与执行器的归属复核付(`/list` 不吃)。
|
|
2404
2477
|
*
|
|
2405
2478
|
* **批级扫描 + 尾只带走真删掉的目录**:独占图片的候选与剩余引用扫描提到**批级**(`planBatchImageAttachmentRemoval`,
|
|
2406
2479
|
* 全批两趟读:计划一趟、复核一趟),逐组计划只吐本组被删目录(`attachmentDirs`);附件尾 `executeAttachmentTail`
|
|
@@ -2409,10 +2482,10 @@ async function dropDeletedSessionCache(deps, sessionId) {
|
|
|
2409
2482
|
* (活体准入复查 → 摘归档集 → 摘账本 → 删目录 → 摘清册行 → 通告离场 → 清缓存)顺序与回滚语义一格不动。
|
|
2410
2483
|
*/
|
|
2411
2484
|
/** `exists → sizeOfDir` 的唯一一条度量口径(成员目录与回收站目录共用):先问在不在,再量字节;缺席(ENOENT / ENOTDIR)才是不在,
|
|
2412
|
-
* 别的错误照旧响亮(ADR-0039
|
|
2413
|
-
*
|
|
2414
|
-
*
|
|
2415
|
-
async function probeDir(deps, dir) {
|
|
2485
|
+
* 别的错误照旧响亮(ADR-0039)。**递归里撞到的 ENOENT 不等于根目录没了**:子文件恰在这一拍消失时会报同一个码。
|
|
2486
|
+
* 写计划(`race: 'throw'`)要再确认根目录也不在——否则跳过删目录、照样摘清册行,留下「行没了、目录还在」的孤儿;
|
|
2487
|
+
* 读路径(`race: 'absent'`)没有删除动作,沿用 ADR-0027 的折叠:清单面板不因一次瞬态竞态整张读失败。 */
|
|
2488
|
+
async function probeDir(deps, dir, race) {
|
|
2416
2489
|
if (!await deps.fs.exists(dir)) return {
|
|
2417
2490
|
present: false,
|
|
2418
2491
|
bytes: 0
|
|
@@ -2423,17 +2496,18 @@ async function probeDir(deps, dir) {
|
|
|
2423
2496
|
bytes: await deps.fs.sizeOfDir(dir)
|
|
2424
2497
|
};
|
|
2425
2498
|
} catch (error) {
|
|
2426
|
-
if (isMissing(error)) return {
|
|
2499
|
+
if (isMissing(error) && (race === "absent" || !await deps.fs.exists(dir))) return {
|
|
2427
2500
|
present: false,
|
|
2428
2501
|
bytes: 0
|
|
2429
2502
|
};
|
|
2430
2503
|
throw error;
|
|
2431
2504
|
}
|
|
2432
2505
|
}
|
|
2433
|
-
/** 成员的盘上目录与字节(扫描、清单与 purge 共用一条口径);目录缺席回 `undefined`,不拿旧读数冒充盘上残留。
|
|
2434
|
-
|
|
2506
|
+
/** 成员的盘上目录与字节(扫描、清单与 purge 共用一条口径);目录缺席回 `undefined`,不拿旧读数冒充盘上残留。
|
|
2507
|
+
* `race` 决定递归 ENOENT 的处置(ADR-0078):读路径 `'absent'`,删除计划 `'throw'`。 */
|
|
2508
|
+
async function measureMemberDir(deps, member, race) {
|
|
2435
2509
|
const dir = sessionDirForId(member.projectDir, member.sessionId, deps.home);
|
|
2436
|
-
const probe = await probeDir(deps, dir);
|
|
2510
|
+
const probe = await probeDir(deps, dir, race);
|
|
2437
2511
|
return probe.present ? {
|
|
2438
2512
|
dir,
|
|
2439
2513
|
bytes: probe.bytes
|
|
@@ -2441,10 +2515,10 @@ async function measureMemberDir(deps, member) {
|
|
|
2441
2515
|
}
|
|
2442
2516
|
/** 只测量(目录 + 实测字节):`/list` 的只读计划只吃这一支,零账本读;目录不在的成员跳过。为什么不顺手问归属:
|
|
2443
2517
|
* `/list` 只用字节与条数,那一格立刻被丢弃——每开一次回收站为它付 N 次宿主调用,还把账本归属读拉进失败面。 */
|
|
2444
|
-
async function measureMembers(deps, members) {
|
|
2518
|
+
async function measureMembers(deps, members, race) {
|
|
2445
2519
|
const out = [];
|
|
2446
2520
|
for (const member of members) {
|
|
2447
|
-
const measured = await measureMemberDir(deps, member);
|
|
2521
|
+
const measured = await measureMemberDir(deps, member, race);
|
|
2448
2522
|
if (measured === void 0) continue;
|
|
2449
2523
|
out.push({
|
|
2450
2524
|
sessionId: member.sessionId,
|
|
@@ -2457,7 +2531,7 @@ async function measureMembers(deps, members) {
|
|
|
2457
2531
|
/** 把一组成员折成删除计划:`measureMembers` 之外**逐成员补账本归属**(`workspaceOf`)——executor 摘账本要用。 */
|
|
2458
2532
|
async function planMemberRemovals(deps, members) {
|
|
2459
2533
|
const plans = [];
|
|
2460
|
-
for (const measured of await measureMembers(deps, members)) {
|
|
2534
|
+
for (const measured of await measureMembers(deps, members, "throw")) {
|
|
2461
2535
|
const workspaceId = await deps.host.workspaceOf(measured.sessionId);
|
|
2462
2536
|
plans.push({
|
|
2463
2537
|
sessionId: measured.sessionId,
|
|
@@ -2468,10 +2542,10 @@ async function planMemberRemovals(deps, members) {
|
|
|
2468
2542
|
}
|
|
2469
2543
|
return plans;
|
|
2470
2544
|
}
|
|
2471
|
-
/** 量一条回收站行;目录不在回 `present: false` / 0
|
|
2472
|
-
async function measureTrashRow(deps, entry) {
|
|
2545
|
+
/** 量一条回收站行;目录不在回 `present: false` / 0 字节(目录不在不等于清册行不用摘)。`race` 同 {@link measureMemberDir}。 */
|
|
2546
|
+
async function measureTrashRow(deps, entry, race) {
|
|
2473
2547
|
const dir = trashDirOf(entry.id, deps.home);
|
|
2474
|
-
const probe = await probeDir(deps, dir);
|
|
2548
|
+
const probe = await probeDir(deps, dir, race);
|
|
2475
2549
|
return {
|
|
2476
2550
|
entry,
|
|
2477
2551
|
dir,
|
|
@@ -2479,6 +2553,10 @@ async function measureTrashRow(deps, entry) {
|
|
|
2479
2553
|
bytes: probe.bytes
|
|
2480
2554
|
};
|
|
2481
2555
|
}
|
|
2556
|
+
/** 一份清册快照里的会话 id 集(bare 归一)。批量面一次算好、多处复用,避免每个组重建一份 n 行的 Set。 */
|
|
2557
|
+
function manifestSessionIds(rows) {
|
|
2558
|
+
return new Set(rows.map((row) => bareSessionId(row.sessionId)));
|
|
2559
|
+
}
|
|
2482
2560
|
/**
|
|
2483
2561
|
* 盘上后代的选择判据(`/list` 与 purge 共用):`subagentMembersOf` 一次问全部父,再按 `bareSessionId` **排除全部清册 id**,
|
|
2484
2562
|
* 同一个 bare id 只认**遍历顺序里第一次**出现的那条(去重口径住 `firstByBare`)。语料看不见 ⇒ 每个根按空成员收(盘上残留留给 `GET /orphans`)。
|
|
@@ -2487,8 +2565,7 @@ async function measureTrashRow(deps, entry) {
|
|
|
2487
2565
|
* **单行读数与单行回执可能差一条**:同一个 bare id 挂在两个组根下时,全局去重只把它算给第一个根;单独 purge 那一组时它仍算进那一组
|
|
2488
2566
|
* ⇒ 那条的 `releaseBytes` 与 `freedBytes` 在共享后代上可以不等(全部可见行之和与 `/empty` 的回执仍相等)。数据有环或两代写法混杂才撞上。
|
|
2489
2567
|
*/
|
|
2490
|
-
async function selectStrandedMembers(host,
|
|
2491
|
-
const manifestIds = new Set(manifest.map((row) => bareSessionId(row.sessionId)));
|
|
2568
|
+
async function selectStrandedMembers(host, manifestIds, parentIds) {
|
|
2492
2569
|
const read = await host.subagentMembersOf(parentIds);
|
|
2493
2570
|
if (!read.available) return parentIds.map(() => []);
|
|
2494
2571
|
const flat = [];
|
|
@@ -2511,8 +2588,9 @@ async function selectStrandedMembers(host, manifest, parentIds) {
|
|
|
2511
2588
|
}
|
|
2512
2589
|
return out;
|
|
2513
2590
|
}
|
|
2514
|
-
/** `/list`
|
|
2515
|
-
* 会把上千个 `exists` / `sizeOfDir` 挂起抢同一个盘;它与逐行读数的旋钮分家(那边是宿主投影读,同一个数没有同一条理由)。
|
|
2591
|
+
/** `/list` 只读计划的盘上测量预算:`/list` 一次可能几百组、每组几百孩子,无界 `Promise.all`
|
|
2592
|
+
* 会把上千个 `exists` / `sizeOfDir` 挂起抢同一个盘;它与逐行读数的旋钮分家(那边是宿主投影读,同一个数没有同一条理由)。
|
|
2593
|
+
* 组与组内孩子排同一条队列,成员组随后另起一条(各 ≤8),不再叠出「8 组 × 8 孩子」。 */
|
|
2516
2594
|
const VISIBLE_MEASURE_CONCURRENCY = 8;
|
|
2517
2595
|
/**
|
|
2518
2596
|
* `/list` 的只读计划:一行 = 一组。释放量与 purge 同口径——回收站目录与成员目录**现测**,不用清册记的 `sizeBytes`(盘上早变了)。
|
|
@@ -2520,20 +2598,23 @@ const VISIBLE_MEASURE_CONCURRENCY = 8;
|
|
|
2520
2598
|
* 两级都有界(`VISIBLE_MEASURE_CONCURRENCY`);输出按 `groups` 原序(`mapLimit` 按 index 落位),首个失败原样抛。
|
|
2521
2599
|
*/
|
|
2522
2600
|
async function planVisibleTrash(deps, rows, groups) {
|
|
2523
|
-
const
|
|
2524
|
-
|
|
2525
|
-
|
|
2526
|
-
|
|
2527
|
-
|
|
2528
|
-
|
|
2529
|
-
const
|
|
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);
|
|
2530
2611
|
return {
|
|
2531
2612
|
root,
|
|
2532
2613
|
kids,
|
|
2533
|
-
trash
|
|
2614
|
+
trash,
|
|
2534
2615
|
members,
|
|
2535
|
-
releaseBytes:
|
|
2536
|
-
subagentBytes,
|
|
2616
|
+
releaseBytes: totalBytes(trash) + strandedBytes,
|
|
2617
|
+
subagentBytes: totalBytes(trash.slice(1)),
|
|
2537
2618
|
strandedBytes,
|
|
2538
2619
|
strandedCount: members.length
|
|
2539
2620
|
};
|
|
@@ -2552,11 +2633,11 @@ function totalBytes(items) {
|
|
|
2552
2633
|
* - 活体准入在量目录与任何写之前逐个查 targets 与**全部枚举到的**盘上后代;没有跳过它的开关(执行器首笔写前还会复查)。
|
|
2553
2634
|
* - `sessionQuery` 缺席 ⇒ members 为空、不抛(盘上残留留给 `GET /orphans` 兜底)。
|
|
2554
2635
|
*/
|
|
2555
|
-
async function planTrashRemoval(deps, rows, targets) {
|
|
2636
|
+
async function planTrashRemoval(deps, rows, targets, manifestIds = manifestSessionIds(rows)) {
|
|
2556
2637
|
writeProgress.step("measuring");
|
|
2557
|
-
const candidates = (await selectStrandedMembers(deps.host,
|
|
2638
|
+
const candidates = (await selectStrandedMembers(deps.host, manifestIds, targets.map((entry) => entry.sessionId))).flat();
|
|
2558
2639
|
await assertNoLive(deps.host, [...targets.map((entry) => entry.sessionId), ...candidates.map((member) => member.sessionId)]);
|
|
2559
|
-
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"));
|
|
2560
2641
|
const members = await planMemberRemovals(deps, candidates);
|
|
2561
2642
|
const attachmentDirs = [...trash.map((row) => row.dir), ...members.map((member) => member.dir)];
|
|
2562
2643
|
return {
|
|
@@ -2576,10 +2657,10 @@ async function planTrashRemoval(deps, rows, targets) {
|
|
|
2576
2657
|
* 盘上后代读不出时 `complete: false`、只交行目录:调用方要据此把该组的第二波补跑判失败(留着让人重试),
|
|
2577
2658
|
* 不能让它删掉一批没进过扫描面的目录——那才是孤儿附件的来源。
|
|
2578
2659
|
*/
|
|
2579
|
-
async function plannedAttachmentDirs(deps, rows, targets) {
|
|
2660
|
+
async function plannedAttachmentDirs(deps, rows, targets, manifestIds = manifestSessionIds(rows)) {
|
|
2580
2661
|
const dirs = targets.map((entry) => trashDirOf(entry.id, deps.home));
|
|
2581
2662
|
try {
|
|
2582
|
-
const members = await measureMembers(deps, (await selectStrandedMembers(deps.host,
|
|
2663
|
+
const members = await measureMembers(deps, (await selectStrandedMembers(deps.host, manifestIds, targets.map((entry) => entry.sessionId))).flat(), "throw");
|
|
2583
2664
|
return {
|
|
2584
2665
|
dirs: [...dirs, ...members.map((member) => member.dir)],
|
|
2585
2666
|
complete: true
|
|
@@ -2619,6 +2700,11 @@ async function planOrphanRemoval(deps, members) {
|
|
|
2619
2700
|
* 目录删掉就没有"退回去"这回事,中途失败**不回滚目录**;已删的由计数器如实交回。附件对象不在这条管线里——
|
|
2620
2701
|
* 归批级尾(`executeAttachmentTail`),见文件头注的口径。
|
|
2621
2702
|
*
|
|
2703
|
+
* **账本与工作区归属**(ADR-0077):摘账本前对每个计划成员复核一次 `workspaceOf`——执行时已无归属就跳过
|
|
2704
|
+
* (同批先手已摘 / 用户解绑 / 工作区已删,`detach` 本就是空转),有归属但与计划不一致则响亮失败等重试。
|
|
2705
|
+
* 失败出口按 detach 记录的反向顺序,对目录仍在的成员 `attach(..., 'if-unassigned')` 补回原工作区
|
|
2706
|
+
* (已删目录 / 用户已重新归组 / 工作区已删都跳过);回滚失败与归档回滚一样进 `details.rollbackFailures`。
|
|
2707
|
+
*
|
|
2622
2708
|
* **归档态回滚**:`unarchive` 排在所有删除之前,所以失败时目录还在、归档位却已摘。失败出口把**目录还在**的那些按删除前的读数
|
|
2623
2709
|
* 重新归档(预读 `isArchived`,不按 `wasArchived` 猜),目录不在的跳过——否则会造幽灵 id。回滚失败走 `details.rollbackFailures`(ADR-0040)。
|
|
2624
2710
|
*
|
|
@@ -2666,6 +2752,8 @@ async function executeRemoval(deps, plan, options) {
|
|
|
2666
2752
|
const onDisk = /* @__PURE__ */ new Set([...plan.trash.filter((row) => row.present).map((row) => row.entry.sessionId), ...plan.members.map((member) => member.sessionId)]);
|
|
2667
2753
|
/** 目录已经真删掉的 id:没有归档态可放回去,跳过——否则会在 registry 里留下幽灵 id。 */
|
|
2668
2754
|
const deleted = /* @__PURE__ */ new Set();
|
|
2755
|
+
/** 走到过 `detach` 这一步的成员(含失败那一条):失败时按它补回工作区归属。 */
|
|
2756
|
+
const detaching = [];
|
|
2669
2757
|
try {
|
|
2670
2758
|
for (const sessionId of plan.unarchive) {
|
|
2671
2759
|
unarchived.push(sessionId);
|
|
@@ -2673,10 +2761,19 @@ async function executeRemoval(deps, plan, options) {
|
|
|
2673
2761
|
await step("取消归档失败", sessionId, () => deps.host.unarchive(sessionId));
|
|
2674
2762
|
}
|
|
2675
2763
|
for (const member of plan.members) {
|
|
2676
|
-
const workspaceId = member
|
|
2677
|
-
|
|
2678
|
-
|
|
2679
|
-
|
|
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
|
+
});
|
|
2680
2777
|
}
|
|
2681
2778
|
for (const row of plan.trash) try {
|
|
2682
2779
|
if (row.present) {
|
|
@@ -2723,6 +2820,14 @@ async function executeRemoval(deps, plan, options) {
|
|
|
2723
2820
|
};
|
|
2724
2821
|
} catch (error) {
|
|
2725
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
|
+
}
|
|
2726
2831
|
for (const sessionId of [...unarchived].reverse()) {
|
|
2727
2832
|
if (!archivedBefore.has(sessionId) || deleted.has(sessionId) || !onDisk.has(sessionId)) continue;
|
|
2728
2833
|
try {
|
|
@@ -2807,7 +2912,7 @@ async function loadOrphanGroups(deps, trash, roots) {
|
|
|
2807
2912
|
for (const group of groups) {
|
|
2808
2913
|
const members = [];
|
|
2809
2914
|
for (const member of group.members) {
|
|
2810
|
-
const measured = await measureMemberDir(deps, member);
|
|
2915
|
+
const measured = await measureMemberDir(deps, member, "absent");
|
|
2811
2916
|
members.push({
|
|
2812
2917
|
sessionId: member.sessionId,
|
|
2813
2918
|
projectDir: member.projectDir,
|
|
@@ -2975,7 +3080,7 @@ function captureAgentHandles(ctx) {
|
|
|
2975
3080
|
try {
|
|
2976
3081
|
await dispose();
|
|
2977
3082
|
} finally {
|
|
2978
|
-
handles.delete(sessionId);
|
|
3083
|
+
if (handles.get(sessionId) === dispose) handles.delete(sessionId);
|
|
2979
3084
|
}
|
|
2980
3085
|
} };
|
|
2981
3086
|
}
|
|
@@ -3010,11 +3115,34 @@ function escapeProjectKey(cwd) {
|
|
|
3010
3115
|
//#endregion
|
|
3011
3116
|
//#region src/ports/host-port.ts
|
|
3012
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
|
+
}
|
|
3013
3128
|
function liveSessionsOf(ctx) {
|
|
3014
|
-
|
|
3015
|
-
|
|
3016
|
-
|
|
3017
|
-
|
|
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
|
+
}
|
|
3018
3146
|
}
|
|
3019
3147
|
/**
|
|
3020
3148
|
* 会话 header 的**公开**读面:live `sessions.get(id).header` 优先,否则 `sessionPersistence.stat(id).header`。未知会话回 `undefined`;
|
|
@@ -3170,10 +3298,12 @@ function createHostPort(ctx) {
|
|
|
3170
3298
|
const host = ctx;
|
|
3171
3299
|
const registry = host.workspaceRegistry;
|
|
3172
3300
|
const agentHandles = captureAgentHandles(host);
|
|
3301
|
+
/** 会话当前挂在哪个工作区(`registry.list()` 的实体 `sessionIds`;同一个判据 `workspaceOf` 也读它)。 */
|
|
3302
|
+
const ownerOf = (sessionId) => registry.list().find((workspace) => workspace.sessionIds.includes(sessionId))?.id;
|
|
3173
3303
|
return {
|
|
3174
3304
|
/** 账本里记着这个会话的工作区:`registry.list()` 的实体 `sessionIds`(该 getter 已按 canonical cwd 过滤过)。 */
|
|
3175
3305
|
async workspaceOf(sessionId) {
|
|
3176
|
-
return
|
|
3306
|
+
return ownerOf(sessionId);
|
|
3177
3307
|
},
|
|
3178
3308
|
/** 账本里还有这个工作区吗:`registry.get(id)` 是同步 Map 查找,未知 id 回 `undefined` ⇒ 只做一次判别,不抛。 */
|
|
3179
3309
|
async workspaceExists(workspaceId) {
|
|
@@ -3188,6 +3318,10 @@ function createHostPort(ctx) {
|
|
|
3188
3318
|
if (header === void 0) return void 0;
|
|
3189
3319
|
return projectDirOfCwd(header.cwd);
|
|
3190
3320
|
},
|
|
3321
|
+
/** 宿主工作区显示顺序 → 项目目录名。`registry.list()` 的顺序就是宿主持久的显示顺序,照抄、不排序。 */
|
|
3322
|
+
async projectOrder() {
|
|
3323
|
+
return registry.list().map((workspace) => projectDirOfCwd(workspace.path));
|
|
3324
|
+
},
|
|
3191
3325
|
/** 显示名走宿主投影缓存(与工作中同名):子会话取 `subagent` 投影的 label,其余取 `title` 行的**视图值**(整条未命中才回落 predecessor)。
|
|
3192
3326
|
* header 来自公开的 live/持久化读面,尽力取,取不到返回空串。 */
|
|
3193
3327
|
async titleOf(sessionId) {
|
|
@@ -3232,23 +3366,46 @@ function createHostPort(ctx) {
|
|
|
3232
3366
|
* `SessionController` 会丢掉 `AgentHandle`,所以 `agent-handles.ts` 按会话 id 留住 handle,这里先 detach 再 dispose。
|
|
3233
3367
|
* 捕获不到 handle(插件激活前已启动,或 `ctx.agents` 形状变化)时只能摘 session,这是已知限制,不拿归档兜底(ADR-0008)。
|
|
3234
3368
|
*
|
|
3235
|
-
*
|
|
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)。
|
|
3236
3375
|
*/
|
|
3237
3376
|
async evictLive(sessionId) {
|
|
3238
3377
|
try {
|
|
3239
|
-
const
|
|
3240
|
-
const
|
|
3241
|
-
if (store === void 0)
|
|
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);
|
|
3242
3385
|
if (session === void 0 || session === null) {
|
|
3243
|
-
await agentHandles
|
|
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
|
+
}
|
|
3244
3392
|
return "not-live";
|
|
3245
3393
|
}
|
|
3246
3394
|
const entry = store.liveEntryFor(session);
|
|
3247
|
-
if (entry === void 0 || entry === null || typeof entry.detach !== "function")
|
|
3395
|
+
if (entry === void 0 || entry === null || typeof entry.detach !== "function") {
|
|
3396
|
+
warnPresence(`live entry for "${sessionId}" has no detach`);
|
|
3397
|
+
return "unknown";
|
|
3398
|
+
}
|
|
3248
3399
|
entry.detach();
|
|
3249
|
-
await agentHandles
|
|
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
|
+
}
|
|
3250
3406
|
return "evicted";
|
|
3251
|
-
} catch {
|
|
3407
|
+
} catch (error) {
|
|
3408
|
+
warnPresence(`evictLive failed for "${sessionId}"`, error);
|
|
3252
3409
|
return "unknown";
|
|
3253
3410
|
}
|
|
3254
3411
|
},
|
|
@@ -3292,9 +3449,10 @@ function createHostPort(ctx) {
|
|
|
3292
3449
|
if (workspace === void 0) throw new Error(`${WORKSPACE_MISSING_MESSAGE} (detach): ${workspaceId}`);
|
|
3293
3450
|
await workspace.detachSession(sessionId);
|
|
3294
3451
|
},
|
|
3295
|
-
/** 挂账本:实体方法 `attachSession
|
|
3296
|
-
async attach(sessionId, workspaceId) {
|
|
3452
|
+
/** 挂账本:实体方法 `attachSession`(顶层没有)。`if-unassigned` 只在失败回滚用(见接口注释)。 */
|
|
3453
|
+
async attach(sessionId, workspaceId, when) {
|
|
3297
3454
|
const workspace = registry.get(workspaceId);
|
|
3455
|
+
if (when === "if-unassigned" && (workspace === void 0 || ownerOf(sessionId) !== void 0)) return;
|
|
3298
3456
|
if (workspace === void 0) throw new Error(`${WORKSPACE_MISSING_MESSAGE} (attach): ${workspaceId}`);
|
|
3299
3457
|
await workspace.attachSession(sessionId);
|
|
3300
3458
|
},
|
|
@@ -3598,6 +3756,8 @@ function createTrashScope(rows, execute) {
|
|
|
3598
3756
|
const view = createShrinkingView(rows);
|
|
3599
3757
|
return {
|
|
3600
3758
|
claimAll: (ids) => view.claimAll(ids),
|
|
3759
|
+
claim: (id) => view.claim(id),
|
|
3760
|
+
originalGroup: (id) => view.originalGroup(id),
|
|
3601
3761
|
runGroup: async (plan) => {
|
|
3602
3762
|
const stats = await execute(plan);
|
|
3603
3763
|
view.takeRows(plan.trash.map((row) => row.entry.id));
|
|
@@ -3975,6 +4135,8 @@ async function applyPurge(deps, ids) {
|
|
|
3975
4135
|
* (组内串行不动)→ 第二波串行补跑(实况为准)→ 批尾附件尾 → 合成 per-id 回执。 */
|
|
3976
4136
|
async function runPurgeBatch(deps, scope, rows, wanted) {
|
|
3977
4137
|
const claims = scope.claimAll(wanted);
|
|
4138
|
+
/** 整批只算一次「清册里的会话 id 集」:计划 / 挂起扫描都吃它,不再逐组重建(批量面的 n² 就在这里)。 */
|
|
4139
|
+
const manifestIds = manifestSessionIds(rows);
|
|
3978
4140
|
const slots = /* @__PURE__ */ new Map();
|
|
3979
4141
|
/** 槽位落定与条目 tick 的唯一闸:done 与「已处理条数」同义(含失败条),每处收口都走它。 */
|
|
3980
4142
|
const closeSlot = (index, slot) => {
|
|
@@ -3995,7 +4157,7 @@ async function runPurgeBatch(deps, scope, rows, wanted) {
|
|
|
3995
4157
|
prepared.push({
|
|
3996
4158
|
index,
|
|
3997
4159
|
id: claim.id,
|
|
3998
|
-
plan: await planTrashRemoval(deps, rows, claim.group)
|
|
4160
|
+
plan: await planTrashRemoval(deps, rows, claim.group, manifestIds)
|
|
3999
4161
|
});
|
|
4000
4162
|
} catch (error) {
|
|
4001
4163
|
closeSlot(index, {
|
|
@@ -4006,22 +4168,26 @@ async function runPurgeBatch(deps, scope, rows, wanted) {
|
|
|
4006
4168
|
}
|
|
4007
4169
|
const plannedDirs = new Set(prepared.flatMap((item) => item.plan.attachmentDirs));
|
|
4008
4170
|
const carriedScan = [];
|
|
4009
|
-
|
|
4010
|
-
const
|
|
4011
|
-
|
|
4171
|
+
/** 同一原始组只扫一次:key = 组内行 id 排序;值 = 这次扫描是否读全。 */
|
|
4172
|
+
const scannedGroups = /* @__PURE__ */ new Map();
|
|
4173
|
+
/** 某一组的扫描读不出:这一组的所有挂起条第二波都失败关闭(不是整组号,逐条记)。 */
|
|
4174
|
+
const incompleteIds = /* @__PURE__ */ new Set();
|
|
4012
4175
|
for (const claim of claims) {
|
|
4013
4176
|
if (claim.verdict !== "carried") continue;
|
|
4014
|
-
const group =
|
|
4015
|
-
const groupKey = groupKeyOf(claim.id);
|
|
4016
|
-
if (seenGroups.has(groupKey)) continue;
|
|
4177
|
+
const group = scope.originalGroup(claim.id);
|
|
4017
4178
|
if (group.every((row) => plannedDirs.has(trashDirOf(row.id, deps.home)))) continue;
|
|
4018
|
-
|
|
4019
|
-
|
|
4020
|
-
|
|
4021
|
-
|
|
4022
|
-
|
|
4023
|
-
|
|
4024
|
-
|
|
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);
|
|
4025
4191
|
}
|
|
4026
4192
|
const batch = await planBatchImageAttachmentRemoval(deps, [...prepared.map((item) => ({
|
|
4027
4193
|
id: item.id,
|
|
@@ -4043,8 +4209,8 @@ async function runPurgeBatch(deps, scope, rows, wanted) {
|
|
|
4043
4209
|
await runWave(chainsOf(prepared, (item) => [...item.plan.attachmentDirs, ...item.plan.unarchive.map((sessionId) => `unarchive:${bareSessionId(sessionId)}`)]), (item) => settle(item.index, item.plan));
|
|
4044
4210
|
for (const [index, claim] of claims.entries()) {
|
|
4045
4211
|
if (claim.verdict !== "carried") continue;
|
|
4046
|
-
const again = scope.
|
|
4047
|
-
if (again
|
|
4212
|
+
const again = scope.claim(claim.id);
|
|
4213
|
+
if (again.verdict === "carried") {
|
|
4048
4214
|
closeSlot(index, { kind: "carried" });
|
|
4049
4215
|
continue;
|
|
4050
4216
|
}
|
|
@@ -4055,7 +4221,7 @@ async function runPurgeBatch(deps, scope, rows, wanted) {
|
|
|
4055
4221
|
});
|
|
4056
4222
|
continue;
|
|
4057
4223
|
}
|
|
4058
|
-
if (
|
|
4224
|
+
if (incompleteIds.has(claim.id)) {
|
|
4059
4225
|
closeSlot(index, {
|
|
4060
4226
|
kind: "failed",
|
|
4061
4227
|
error: verbError("io", `批级附件扫描读不出这一组的盘上后代:${claim.id}`)
|
|
@@ -4063,7 +4229,7 @@ async function runPurgeBatch(deps, scope, rows, wanted) {
|
|
|
4063
4229
|
continue;
|
|
4064
4230
|
}
|
|
4065
4231
|
try {
|
|
4066
|
-
const plan = await planTrashRemoval(deps, rows, again.group);
|
|
4232
|
+
const plan = await planTrashRemoval(deps, rows, again.group, manifestIds);
|
|
4067
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));
|
|
4068
4234
|
if (unscanned.length > 0) throw verbError("io", `第二波删除目录未进入批级附件扫描面:${unscanned[0]}`);
|
|
4069
4235
|
await settle(index, plan);
|
|
@@ -4394,6 +4560,21 @@ function displayNameOfLog(raw) {
|
|
|
4394
4560
|
title
|
|
4395
4561
|
};
|
|
4396
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
|
+
}
|
|
4397
4578
|
/** 一次摘要要显示多少条孩子:`min(孩子总数, 条数闸)`;闸缺省取 {@link SUBAGENT_SUMMARY_LIMIT}。负数闸按 0 处理;调用方必须用这个数去切片。 */
|
|
4398
4579
|
function displayedSubagentCount(count, limit) {
|
|
4399
4580
|
return Math.max(0, Math.min(count, limit ?? 200));
|
|
@@ -4439,11 +4620,6 @@ const DEFAULT_LIMITS = {
|
|
|
4439
4620
|
pageChars: PAGE_CHAR_LIMIT,
|
|
4440
4621
|
subagents: 200
|
|
4441
4622
|
};
|
|
4442
|
-
/** 一条记录里那些 `content[]` 段的文字拼起来(`\n` 分隔;非 text 段一律不参与)。 */
|
|
4443
|
-
function textOf(content) {
|
|
4444
|
-
if (!Array.isArray(content)) return "";
|
|
4445
|
-
return content.filter((part) => part?.type === "text" && typeof part.text === "string").map((part) => part.text).join("\n").trim();
|
|
4446
|
-
}
|
|
4447
4623
|
/** 一条记录的 `content[]` 里的附件块,映射成线上读数(形状只映射,不改判据——闸在 `attachmentsInContent` 里)。 */
|
|
4448
4624
|
function attachmentWires(content) {
|
|
4449
4625
|
return attachmentsInContent(content).map((ref) => ({
|
|
@@ -4705,7 +4881,7 @@ function createDetailFold(limits = DEFAULT_LIMITS, before) {
|
|
|
4705
4881
|
case "user/message": {
|
|
4706
4882
|
const source = data.source ?? {};
|
|
4707
4883
|
const sourceKind = typeof source.kind === "string" ? source.kind : "";
|
|
4708
|
-
const text =
|
|
4884
|
+
const text = contentText(data.content);
|
|
4709
4885
|
const attachments = attachmentWires(data.content);
|
|
4710
4886
|
if (sourceKind === "user") {
|
|
4711
4887
|
const block = textBlock("user", time, text, attachments, limits.perBlockChars);
|
|
@@ -4784,17 +4960,17 @@ function createDetailFold(limits = DEFAULT_LIMITS, before) {
|
|
|
4784
4960
|
const message = data.message ?? {};
|
|
4785
4961
|
const callId = typeof message.toolCallId === "string" ? message.toolCallId : "";
|
|
4786
4962
|
if (callId === "") return;
|
|
4787
|
-
page.result(callId,
|
|
4963
|
+
page.result(callId, contentText(message.content), message.isError === true, attachmentWires(message.content));
|
|
4788
4964
|
return;
|
|
4789
4965
|
}
|
|
4790
4966
|
case "system/message": {
|
|
4791
4967
|
const message = data.message ?? {};
|
|
4792
|
-
const block = textBlock("system", time,
|
|
4968
|
+
const block = textBlock("system", time, contentText(message.content), attachmentWires(message.content), limits.perBlockChars);
|
|
4793
4969
|
if (block !== void 0) page.add(block);
|
|
4794
4970
|
return;
|
|
4795
4971
|
}
|
|
4796
4972
|
case "compaction/summary": {
|
|
4797
|
-
const block = textBlock("compaction", time,
|
|
4973
|
+
const block = textBlock("compaction", time, contentText(data.summary), [], limits.perBlockChars);
|
|
4798
4974
|
if (block !== void 0) page.add(block);
|
|
4799
4975
|
return;
|
|
4800
4976
|
}
|
|
@@ -5004,6 +5180,746 @@ async function readArchiveSubagents(deps, sessionId, limits) {
|
|
|
5004
5180
|
};
|
|
5005
5181
|
}
|
|
5006
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
|
|
5007
5923
|
//#region src/ports/attachments-port.ts
|
|
5008
5924
|
/** 服务在 `available()` 之后消失/形状变了:调用方可以退回直接 fs,而不是把这次读取判成 io。 */
|
|
5009
5925
|
var AttachmentsUnavailableError = class extends Error {
|
|
@@ -5254,6 +6170,16 @@ async function reportAttachmentOrphans(deps) {
|
|
|
5254
6170
|
};
|
|
5255
6171
|
}
|
|
5256
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
|
|
5257
6183
|
//#region src/api/trash-rows.ts
|
|
5258
6184
|
/** 清册行 → 线上行:清册字段走 `entryWire`(多一个必填字段会编译错),这里只补 `/list` 只读数。 */
|
|
5259
6185
|
function toWire(row, readouts) {
|
|
@@ -5264,7 +6190,8 @@ function toWire(row, readouts) {
|
|
|
5264
6190
|
...readouts.subagentBytes === void 0 ? {} : { subagentBytes: readouts.subagentBytes },
|
|
5265
6191
|
...readouts.strandedSubagents === void 0 ? {} : { strandedSubagents: readouts.strandedSubagents },
|
|
5266
6192
|
...readouts.strandedBytes === void 0 ? {} : { strandedBytes: readouts.strandedBytes },
|
|
5267
|
-
...readouts.workspaceMissing === void 0 ? {} : { workspaceMissing: readouts.workspaceMissing }
|
|
6193
|
+
...readouts.workspaceMissing === void 0 ? {} : { workspaceMissing: readouts.workspaceMissing },
|
|
6194
|
+
...readouts.projectRank === void 0 ? {} : { projectRank: readouts.projectRank }
|
|
5268
6195
|
};
|
|
5269
6196
|
}
|
|
5270
6197
|
/** 装配成「一行 = 一组」:孩子折进父行,父行不在时孩子自己占一行(否则看不见也清不掉)。
|
|
@@ -5272,20 +6199,29 @@ function toWire(row, readouts) {
|
|
|
5272
6199
|
* 组释放量与盘上剩余只由 `planVisibleTrash` 一处算,不碰 `isLive`。 */
|
|
5273
6200
|
async function assembleTrashRows(deps, rows) {
|
|
5274
6201
|
const groups = visibleGroups(rows);
|
|
5275
|
-
const
|
|
5276
|
-
const
|
|
5277
|
-
|
|
5278
|
-
|
|
5279
|
-
|
|
5280
|
-
|
|
5281
|
-
|
|
5282
|
-
|
|
5283
|
-
|
|
5284
|
-
|
|
5285
|
-
|
|
5286
|
-
|
|
5287
|
-
|
|
5288
|
-
|
|
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
|
+
});
|
|
5289
6225
|
}
|
|
5290
6226
|
//#endregion
|
|
5291
6227
|
//#region src/api/archive-rows.ts
|
|
@@ -5301,11 +6237,14 @@ async function assembleArchiveRows(deps) {
|
|
|
5301
6237
|
wantsLabel: identity.subagent
|
|
5302
6238
|
})), { sizeFailure: "throw" });
|
|
5303
6239
|
const { totalBytes, missingSizeCount } = sizeTotals(facts);
|
|
6240
|
+
/** 与回收站同一张顺序表:项目不在账本里 ⇒ 这一格不落键(不是 0)。 */
|
|
6241
|
+
const ranks = await projectRankTableOf(deps.host);
|
|
5304
6242
|
return {
|
|
5305
6243
|
available: true,
|
|
5306
6244
|
rows: facts.flatMap((fact, index) => {
|
|
5307
6245
|
const identity = identities[index];
|
|
5308
6246
|
if (identity === void 0) return [];
|
|
6247
|
+
const projectRank = ranks.get(identity.projectDir);
|
|
5309
6248
|
return [{
|
|
5310
6249
|
sessionId: identity.sessionId,
|
|
5311
6250
|
projectDir: identity.projectDir,
|
|
@@ -5314,6 +6253,7 @@ async function assembleArchiveRows(deps) {
|
|
|
5314
6253
|
...fact.updatedAt === void 0 ? {} : { updatedAt: fact.updatedAt },
|
|
5315
6254
|
...fact.updatedAtSource === void 0 ? {} : { updatedAtSource: fact.updatedAtSource },
|
|
5316
6255
|
...fact.sizeBytes === void 0 ? {} : { sizeBytes: fact.sizeBytes },
|
|
6256
|
+
...projectRank === void 0 ? {} : { projectRank },
|
|
5317
6257
|
subagent: identity.subagent
|
|
5318
6258
|
}];
|
|
5319
6259
|
}),
|
|
@@ -5333,7 +6273,9 @@ const BODY_KIND = {
|
|
|
5333
6273
|
config: "json",
|
|
5334
6274
|
entry: "json",
|
|
5335
6275
|
apply: "json",
|
|
5336
|
-
sessionId: "json"
|
|
6276
|
+
sessionId: "json",
|
|
6277
|
+
search: "json",
|
|
6278
|
+
searchPreview: "json"
|
|
5337
6279
|
};
|
|
5338
6280
|
/** 读的是 wire 那一格(`ROUTES.x.body`):无字段与查询串段不读,带 JSON 字段的段读一次。 */
|
|
5339
6281
|
function bodyOf(route) {
|
|
@@ -5383,7 +6325,7 @@ function parseBody(body, group) {
|
|
|
5383
6325
|
for (const [field, kind] of Object.entries(group)) fields[field] = readField(body, field, kind);
|
|
5384
6326
|
return fields;
|
|
5385
6327
|
}
|
|
5386
|
-
/**
|
|
6328
|
+
/** 描述里的一个字段读成它的值:六种种类各一句 400 原文,原文只住这一处。 */
|
|
5387
6329
|
function readField(body, field, kind) {
|
|
5388
6330
|
const value = body?.[field];
|
|
5389
6331
|
switch (kind) {
|
|
@@ -5398,6 +6340,9 @@ function readField(body, field, kind) {
|
|
|
5398
6340
|
if (value === void 0) return void 0;
|
|
5399
6341
|
if (typeof value !== "number" || !Number.isInteger(value) || value < 0) throw routeError("bad-request", 400, `请求体字段 ${field} 需是非负整数`);
|
|
5400
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;
|
|
5401
6346
|
case "action": {
|
|
5402
6347
|
const action = actionValueOf(value);
|
|
5403
6348
|
if (action === void 0) throw routeError("bad-request", 400, `批量动作不认识:需是 ${ROUTE_APPLY_ACTIONS.join(" / ")} 之一`);
|
|
@@ -5495,6 +6440,34 @@ const ROUTE_TABLE = createRouteTable({
|
|
|
5495
6440
|
response: "json",
|
|
5496
6441
|
run: async (deps, _body, read) => await runEmptyBatch(deps, await read.rows())
|
|
5497
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
|
+
}),
|
|
5498
6471
|
progress: defineRoute("progress", {
|
|
5499
6472
|
slice: "core",
|
|
5500
6473
|
purity: "pure",
|