dsh-manage-session 0.1.0-alpha.0 → 0.2.3
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/CHANGELOG.ja.md +159 -0
- package/CHANGELOG.ko.md +160 -0
- package/CHANGELOG.md +232 -0
- package/INSTALL.ja.md +2 -2
- package/INSTALL.ko.md +2 -2
- package/INSTALL.md +4 -4
- package/INSTALL.zh.md +4 -4
- package/README.en.md +63 -63
- package/README.ja.md +63 -63
- package/README.ko.md +61 -61
- package/README.md +96 -75
- package/dsh.plugin.json +22 -22
- package/lib/client.js +560 -120
- package/lib/index.d.ts +333 -78
- package/lib/index.js +694 -97
- package/package.json +121 -104
- package/screenshots.json +3 -3
- package/src/client/card.tsx +153 -106
- package/src/client/health-panel.tsx +397 -205
- package/src/client/history-panel.tsx +150 -35
- package/src/client/host-api.ts +177 -135
- package/src/client/index.ts +234 -198
- package/src/client/locales.ts +203 -153
- package/src/client/panel.tsx +118 -106
- package/src/config.ts +1 -1
- package/src/host/health/cache.ts +97 -0
- package/src/host/health/decode.ts +307 -307
- package/src/host/health/gates.ts +331 -312
- package/src/host/health/repair.ts +217 -126
- package/src/host/health/scan.ts +156 -114
- package/src/host/history/archive-source.ts +103 -42
- package/src/host/history/archive.ts +54 -5
- package/src/host/history/purge.ts +323 -0
- package/src/index.ts +504 -417
package/lib/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import z from "@deepseek-ai/schemastery";
|
|
2
2
|
import { homedir } from "node:os";
|
|
3
|
-
import { dirname, join } from "node:path";
|
|
4
|
-
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { basename, dirname, join, relative, resolve, sep } from "node:path";
|
|
4
|
+
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
5
5
|
import zlib from "node:zlib";
|
|
6
6
|
//#region src/config.ts
|
|
7
7
|
/** 缺省值。 */
|
|
@@ -20,9 +20,12 @@ const STEWARD_API_PREFIX = "/session-steward/api";
|
|
|
20
20
|
* 官方归档集合(archive set)的读取与清理 —— 自 dsh-session-search-toggle
|
|
21
21
|
* `src/host/archive-source.ts` **逐字迁入**(只依赖 node:fs/os/path),行为与迁移前等价。
|
|
22
22
|
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
* `
|
|
23
|
+
* 读取顺序:**优先直接读规范存储文件**(workspace domain 把 `archivedSessionIds`
|
|
24
|
+
* 落在 `global` 段:storage-json 即 `~/.dsh/storages/workspace.json`),
|
|
25
|
+
* 文件缺失时才回退到进程内 `workspaceRegistry` 服务。
|
|
26
|
+
* 之所以不再让 registry 优先:prune 只能改文件,列表若以 registry 为准,
|
|
27
|
+
* 清理成功后面板不会发生任何变化。registry 仍被读取,但只用作诊断面
|
|
28
|
+
* (`registryIds`:指出「已出文件、仍在内存里生效」的悬挂项)。
|
|
26
29
|
* 每次读取独立决定来源;失败降级为「空归档集合」并通过 diagnostics 面暴露。
|
|
27
30
|
*
|
|
28
31
|
* 写入(清理):官方后端没有 unarchive 端点,因此按 storage-json 自身的协议直接编辑
|
|
@@ -39,40 +42,108 @@ function readStorageFile(path) {
|
|
|
39
42
|
if (!Array.isArray(ids)) throw new Error(`storage hub "${path}" holds no global.archivedSessionIds array`);
|
|
40
43
|
return ids.filter((id) => typeof id === "string");
|
|
41
44
|
}
|
|
45
|
+
/** 尽力读取宿主内存里的归档集合;不可用时返回 undefined。 */
|
|
46
|
+
function readRegistryIds(registry) {
|
|
47
|
+
if (registry === void 0) return void 0;
|
|
48
|
+
try {
|
|
49
|
+
const ids = registry.archivedSessionIds;
|
|
50
|
+
return Array.isArray(ids) ? ids : void 0;
|
|
51
|
+
} catch {
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
42
55
|
/**
|
|
43
56
|
* 解析一次官方归档集合。
|
|
57
|
+
*
|
|
58
|
+
* **存储文件优先**:prune 唯一能改的就是这份文件,列表必须与「能被改的那份」
|
|
59
|
+
* 同源,否则清理成功后面板看起来毫无变化 —— 宿主 registry 是进程启动时的快照,
|
|
60
|
+
* 直接编辑文件不会回写它,于是「文件在瘦身、列表纹丝不动」。
|
|
61
|
+
* registry 退居为文件缺失时的兜底,同时作为诊断面(`registryIds`)返回。
|
|
44
62
|
* @param registry - 惰性 workspaceRegistry 面(可能缺失或抛错)。
|
|
45
63
|
* @param searchPaths - 可选候选路径覆盖(DSH_HOME 非默认值或测试注入时使用)。
|
|
46
|
-
* @returns 归档 ids
|
|
64
|
+
* @returns 归档 ids、服务它的来源,以及宿主内存里的同一集合。
|
|
47
65
|
*/
|
|
48
66
|
function readArchiveSet(registry, searchPaths) {
|
|
49
|
-
|
|
50
|
-
const ids = registry.archivedSessionIds;
|
|
51
|
-
if (Array.isArray(ids)) return {
|
|
52
|
-
ids,
|
|
53
|
-
source: "registry"
|
|
54
|
-
};
|
|
55
|
-
} catch {}
|
|
67
|
+
const registryIds = readRegistryIds(registry);
|
|
56
68
|
for (const path of searchPaths ?? storageFileCandidates()) {
|
|
57
69
|
if (!existsSync(path)) continue;
|
|
58
70
|
try {
|
|
59
71
|
return {
|
|
60
72
|
ids: readStorageFile(path),
|
|
61
|
-
source: "storage-file"
|
|
73
|
+
source: "storage-file",
|
|
74
|
+
...registryIds === void 0 ? {} : { registryIds }
|
|
62
75
|
};
|
|
63
76
|
} catch {}
|
|
64
77
|
}
|
|
78
|
+
if (registryIds !== void 0) return {
|
|
79
|
+
ids: registryIds,
|
|
80
|
+
source: "registry",
|
|
81
|
+
registryIds
|
|
82
|
+
};
|
|
65
83
|
return {
|
|
66
84
|
ids: [],
|
|
67
85
|
source: "none"
|
|
68
86
|
};
|
|
69
87
|
}
|
|
70
88
|
/**
|
|
71
|
-
*
|
|
89
|
+
* **本插件写 workspace.json 的唯一入口。**
|
|
72
90
|
*
|
|
73
|
-
*
|
|
74
|
-
*
|
|
75
|
-
*
|
|
91
|
+
* 任何「改归档集合 / 改工作区成员表」都必须走这里 —— 出现第二个写文件的实现,
|
|
92
|
+
* 就会重现「读的人和写的人不是同一份数据」那类问题。
|
|
93
|
+
*
|
|
94
|
+
* 协议与 storage-json 自身一致:读 → `edit(document)` 就地改 → 备份 → 同目录临时写入
|
|
95
|
+
* → 原子改名。`edit` 返回 `false` 表示无需写入(此时**不产生备份**)。
|
|
96
|
+
* @param path - 规范存储文件路径。
|
|
97
|
+
* @param edit - 就地修改文档;返回是否真的改了。
|
|
98
|
+
* @param log - 可选日志出口。
|
|
99
|
+
* @returns 编辑结果;失败时给出原因而非抛错。
|
|
100
|
+
*/
|
|
101
|
+
function editWorkspaceDocument(path, edit, log) {
|
|
102
|
+
if (!existsSync(path)) return {
|
|
103
|
+
ok: false,
|
|
104
|
+
reason: `存储文件不存在:${path}`
|
|
105
|
+
};
|
|
106
|
+
let document;
|
|
107
|
+
try {
|
|
108
|
+
document = JSON.parse(readFileSync(path, "utf8"));
|
|
109
|
+
} catch (err) {
|
|
110
|
+
return {
|
|
111
|
+
ok: false,
|
|
112
|
+
reason: `无法解析 "${path}":${String(err instanceof Error ? err.message : err)}`
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
let changed;
|
|
116
|
+
try {
|
|
117
|
+
changed = edit(document);
|
|
118
|
+
} catch (err) {
|
|
119
|
+
return {
|
|
120
|
+
ok: false,
|
|
121
|
+
reason: `编辑 "${path}" 失败:${String(err instanceof Error ? err.message : err)}`
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
if (!changed) return {
|
|
125
|
+
ok: true,
|
|
126
|
+
changed: false,
|
|
127
|
+
file: path
|
|
128
|
+
};
|
|
129
|
+
const backup = `${path}.bak-${Date.now()}`;
|
|
130
|
+
copyFileSync(path, backup);
|
|
131
|
+
const tmp = `${path}.prune-tmp`;
|
|
132
|
+
writeFileSync(tmp, `${JSON.stringify(document, null, 2)}
|
|
133
|
+
`, "utf8");
|
|
134
|
+
renameSync(tmp, path);
|
|
135
|
+
log?.(`workspace.json edited; backup=${backup}`);
|
|
136
|
+
return {
|
|
137
|
+
ok: true,
|
|
138
|
+
changed: true,
|
|
139
|
+
file: path
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* 从存储中枢的 `global.archivedSessionIds` 中移除会话 id(= 取消归档状态)。
|
|
144
|
+
*
|
|
145
|
+
* 官方后端没有 unarchive 端点,因此直接编辑规范文件;运行中的宿主把集合留在内存里、
|
|
146
|
+
* 只在启动时重载 —— 调用方必须提示需要重启 DSH。
|
|
76
147
|
* @param ids - 要从归档数组中移除的会话 id。
|
|
77
148
|
* @param log - 可选日志出口。
|
|
78
149
|
* @param searchPaths - 可选候选路径覆盖(测试注入用)。
|
|
@@ -80,48 +151,324 @@ function readArchiveSet(registry, searchPaths) {
|
|
|
80
151
|
*/
|
|
81
152
|
function pruneArchiveFile(ids, log, searchPaths) {
|
|
82
153
|
const wanted = new Set(ids);
|
|
154
|
+
let lastReason = "workspace storage file not found (searched ~/.dsh/storages/workspace.json)";
|
|
83
155
|
for (const path of searchPaths ?? storageFileCandidates()) {
|
|
84
|
-
|
|
85
|
-
let
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
156
|
+
let removed = 0;
|
|
157
|
+
let remaining = 0;
|
|
158
|
+
const outcome = editWorkspaceDocument(path, (document) => {
|
|
159
|
+
const global = document.global;
|
|
160
|
+
const current = global?.archivedSessionIds;
|
|
161
|
+
if (!Array.isArray(current)) throw new Error(`storage hub "${path}" holds no global.archivedSessionIds array`);
|
|
162
|
+
const kept = current.filter((id) => typeof id === "string" && !wanted.has(id));
|
|
163
|
+
removed = current.length - kept.length;
|
|
164
|
+
remaining = kept.length;
|
|
165
|
+
if (removed === 0) return false;
|
|
166
|
+
document.global = {
|
|
167
|
+
...global,
|
|
168
|
+
archivedSessionIds: kept
|
|
169
|
+
};
|
|
170
|
+
return true;
|
|
171
|
+
}, log);
|
|
172
|
+
if (!outcome.ok) {
|
|
173
|
+
lastReason = outcome.reason;
|
|
95
174
|
continue;
|
|
96
175
|
}
|
|
97
|
-
|
|
98
|
-
const removed = current.length - kept.length;
|
|
99
|
-
if (removed === 0) return {
|
|
100
|
-
removed: 0,
|
|
101
|
-
remaining: current.length,
|
|
102
|
-
file: path
|
|
103
|
-
};
|
|
104
|
-
const backup = `${path}.bak-${Date.now()}`;
|
|
105
|
-
copyFileSync(path, backup);
|
|
106
|
-
const next = {
|
|
107
|
-
...document,
|
|
108
|
-
global: {
|
|
109
|
-
...document.global,
|
|
110
|
-
archivedSessionIds: kept
|
|
111
|
-
}
|
|
112
|
-
};
|
|
113
|
-
const tmp = `${path}.prune-tmp`;
|
|
114
|
-
writeFileSync(tmp, `${JSON.stringify(next, null, 2)}
|
|
115
|
-
`, "utf8");
|
|
116
|
-
renameSync(tmp, path);
|
|
117
|
-
log?.(`archive prune: removed ${removed} of ${current.length} ids; backup=${backup}`);
|
|
176
|
+
if (outcome.changed) log?.(`archive prune: removed ${removed} ids; remaining ${remaining}`);
|
|
118
177
|
return {
|
|
119
178
|
removed,
|
|
120
|
-
remaining
|
|
121
|
-
file:
|
|
179
|
+
remaining,
|
|
180
|
+
file: outcome.file
|
|
122
181
|
};
|
|
123
182
|
}
|
|
124
|
-
throw new Error(
|
|
183
|
+
throw new Error(lastReason);
|
|
184
|
+
}
|
|
185
|
+
//#endregion
|
|
186
|
+
//#region src/host/history/purge.ts
|
|
187
|
+
/**
|
|
188
|
+
* 归档文件清理(**真删除**)—— 会话管家唯一的破坏性操作。
|
|
189
|
+
*
|
|
190
|
+
* 与「取消归档状态」(`pruneArchiveFile`)是**两件事**,刻意分开:
|
|
191
|
+
*
|
|
192
|
+
* | | 取消归档状态 | 清理归档文件 |
|
|
193
|
+
* |---|---|---|
|
|
194
|
+
* | 改什么 | 只改 `global.archivedSessionIds` | 删磁盘实体 **+** 改两处 id |
|
|
195
|
+
* | 会话 | 回到侧边栏 | 从世界上消失 |
|
|
196
|
+
* | 可逆 | 重启即生效 | 不可逆 |
|
|
197
|
+
*
|
|
198
|
+
* 「清理归档文件」必须**连带**执行「取消归档状态」:文件删了、id 还留在数组里,
|
|
199
|
+
* 就是一条僵尸归档 —— 侧边栏看不见它,一旦被取消归档又会冒出一个打不开的空会话。
|
|
200
|
+
*
|
|
201
|
+
* 一次清理动 4 处:
|
|
202
|
+
* 1. `~/.dsh/sessions/<工作区>/<会话id>/` —— 整个目录(可能含 `session.jsonl.zstd`
|
|
203
|
+
* 与旧格式 `session.v3.jsonl.zstd` 两份,所以必须整目录删,不能只删当前格式)
|
|
204
|
+
* 2. `~/.dsh/storages/session_projcache/sessions/<会话id>.json` —— 逐条投影缓存
|
|
205
|
+
* 3. `workspace.json` → `global.archivedSessionIds`
|
|
206
|
+
* 4. `workspace.json` → `tables.workspaces.*.sessionIds`
|
|
207
|
+
*
|
|
208
|
+
* 执行顺序是**先改文件、后删实体**:改文件是原子的且可整体中止(失败则一个字节都没删);
|
|
209
|
+
* 反过来先删实体再改文件,中途失败会留下僵尸 id。
|
|
210
|
+
*/
|
|
211
|
+
/** 转录根目录(`<dshHome>/sessions`)。 */
|
|
212
|
+
function sessionsRootFor(dshHome) {
|
|
213
|
+
return join(dshHome, "sessions");
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* 投影缓存(**逐条布局**)根目录。
|
|
217
|
+
*
|
|
218
|
+
* 注意另有一个 `<dshHome>/storages/session_projcache.json`(整份布局)——
|
|
219
|
+
* 那是布局迁移留下的**化石**,宿主早已不再写它,本插件也不碰它。
|
|
220
|
+
*/
|
|
221
|
+
function projCacheRootFor(dshHome) {
|
|
222
|
+
return join(dshHome, "storages", "session_projcache", "sessions");
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* 会话 id 的目录名归一化。
|
|
226
|
+
*
|
|
227
|
+
* 归档集合里一律是 `session-<uuid>`,但子会话的目录名是不带前缀的 `<uuid>`,
|
|
228
|
+
* 两者必须视为同一个会话,否则清理会「找不到文件」而静默什么都没删。
|
|
229
|
+
*/
|
|
230
|
+
function dirKey(name) {
|
|
231
|
+
return name.startsWith("session-") ? name.slice(8) : name;
|
|
232
|
+
}
|
|
233
|
+
/** 是不是目录(读不到就当不是)。 */
|
|
234
|
+
function isDir(path) {
|
|
235
|
+
try {
|
|
236
|
+
return statSync(path).isDirectory();
|
|
237
|
+
} catch {
|
|
238
|
+
return false;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* 扫一遍转录根,建立「会话 id → 目录」索引。
|
|
243
|
+
*
|
|
244
|
+
* 同一个 id 同时存在带前缀与不带前缀的目录时,**优先带 `session-` 前缀的那个**
|
|
245
|
+
* (归档集合里的 id 本身带前缀)。
|
|
246
|
+
* @param sessionsRoot - `<dshHome>/sessions`。
|
|
247
|
+
* @returns 归一化 id → 目录绝对路径。
|
|
248
|
+
*/
|
|
249
|
+
function indexSessionDirs(sessionsRoot) {
|
|
250
|
+
const map = /* @__PURE__ */ new Map();
|
|
251
|
+
if (!existsSync(sessionsRoot)) return map;
|
|
252
|
+
for (const workspace of readdirSync(sessionsRoot)) {
|
|
253
|
+
const wsDir = join(sessionsRoot, workspace);
|
|
254
|
+
if (!isDir(wsDir)) continue;
|
|
255
|
+
for (const name of readdirSync(wsDir)) {
|
|
256
|
+
const entry = join(wsDir, name);
|
|
257
|
+
if (!isDir(entry)) continue;
|
|
258
|
+
const key = dirKey(name);
|
|
259
|
+
const existing = map.get(key);
|
|
260
|
+
const prefer = name.startsWith("session-") && existing !== void 0 && !basename(existing).startsWith("session-");
|
|
261
|
+
if (existing === void 0 || prefer) map.set(key, entry);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
return map;
|
|
265
|
+
}
|
|
266
|
+
/** 递归求目录占用字节数(读不到的条目跳过,不抛错)。 */
|
|
267
|
+
function dirSize(dir) {
|
|
268
|
+
let total = 0;
|
|
269
|
+
let entries;
|
|
270
|
+
try {
|
|
271
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
272
|
+
} catch {
|
|
273
|
+
return 0;
|
|
274
|
+
}
|
|
275
|
+
for (const entry of entries) {
|
|
276
|
+
const path = join(dir, entry.name);
|
|
277
|
+
if (entry.isDirectory()) total += dirSize(path);
|
|
278
|
+
else try {
|
|
279
|
+
total += statSync(path).size;
|
|
280
|
+
} catch {}
|
|
281
|
+
}
|
|
282
|
+
return total;
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* 解析一批会话在磁盘上的实体与占用(**只读,不删任何东西**)。
|
|
286
|
+
*
|
|
287
|
+
* 列表按行显示体积就走这里 —— 体积差异极大(实测单条缓存可达 23 MB、单条转录可达
|
|
288
|
+
* 6 MB,也有 0 字节的),报一个总量对用户没有意义。
|
|
289
|
+
* @param ids - 会话 id(带不带 `session-` 前缀都接受)。
|
|
290
|
+
* @param dshHome - DSH 主目录。
|
|
291
|
+
* @returns 会话 id → 实体位置与占用。
|
|
292
|
+
*/
|
|
293
|
+
function locateSessionUsage(ids, dshHome) {
|
|
294
|
+
const dirs = indexSessionDirs(sessionsRootFor(dshHome));
|
|
295
|
+
const cacheRoot = projCacheRootFor(dshHome);
|
|
296
|
+
const out = /* @__PURE__ */ new Map();
|
|
297
|
+
for (const sessionId of ids) {
|
|
298
|
+
const key = dirKey(sessionId);
|
|
299
|
+
const usage = {
|
|
300
|
+
sessionId,
|
|
301
|
+
bytes: 0,
|
|
302
|
+
cacheBytes: 0
|
|
303
|
+
};
|
|
304
|
+
const dir = dirs.get(key);
|
|
305
|
+
if (dir !== void 0) {
|
|
306
|
+
usage.dir = dir;
|
|
307
|
+
usage.bytes = dirSize(dir);
|
|
308
|
+
}
|
|
309
|
+
for (const name of [`${sessionId}.json`, `${key}.json`]) {
|
|
310
|
+
const candidate = join(cacheRoot, name);
|
|
311
|
+
if (existsSync(candidate)) {
|
|
312
|
+
usage.cacheFile = candidate;
|
|
313
|
+
try {
|
|
314
|
+
usage.cacheBytes = statSync(candidate).size;
|
|
315
|
+
} catch {}
|
|
316
|
+
break;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
out.set(sessionId, usage);
|
|
320
|
+
}
|
|
321
|
+
return out;
|
|
322
|
+
}
|
|
323
|
+
/**
|
|
324
|
+
* 断言目标是 `root` 的**直接子项**(层级也校验)。
|
|
325
|
+
*
|
|
326
|
+
* 破坏性操作不能只靠「路径拼对了」—— 拼错一层就是删掉整个 sessions 根。
|
|
327
|
+
* @param root - 允许的父目录。
|
|
328
|
+
* @param target - 待删目标。
|
|
329
|
+
* @param depth - 相对 root 的期望层数。
|
|
330
|
+
* @returns 是否安全。
|
|
331
|
+
*/
|
|
332
|
+
function isSafeChild(root, target, depth) {
|
|
333
|
+
const rel = relative(resolve(root), resolve(target));
|
|
334
|
+
if (rel === "" || rel.startsWith("..") || resolve(root, rel) !== resolve(target)) return false;
|
|
335
|
+
return rel.split(sep).filter((part) => part !== "").length === depth;
|
|
336
|
+
}
|
|
337
|
+
/** 单次清理的最大 id 数(与 prune 一致)。 */
|
|
338
|
+
const MAX_PURGE_IDS = 5e3;
|
|
339
|
+
/**
|
|
340
|
+
* `session-history-purge`:**真删除**归档会话的磁盘实体,并连带取消其归档状态。
|
|
341
|
+
* @param payload - `{ sessionIds: string[] }`。
|
|
342
|
+
* @param log - 可选日志出口。
|
|
343
|
+
* @param options - `dshHome` 必填;`searchPaths` 可选覆盖。
|
|
344
|
+
* @returns 清理条数、释放字节数与逐条失败。
|
|
345
|
+
*/
|
|
346
|
+
function purgeHistory(payload, log, options) {
|
|
347
|
+
const dshHome = options?.dshHome;
|
|
348
|
+
if (dshHome === void 0 || dshHome === "") return {
|
|
349
|
+
ok: false,
|
|
350
|
+
error: "缺少 dshHome:破坏性清理拒绝在未知路径上执行"
|
|
351
|
+
};
|
|
352
|
+
const record = payload;
|
|
353
|
+
if (!Array.isArray(record?.sessionIds) || record.sessionIds.length === 0) return {
|
|
354
|
+
ok: false,
|
|
355
|
+
error: "缺少 sessionIds 数组"
|
|
356
|
+
};
|
|
357
|
+
const ids = [...new Set(record.sessionIds.filter((id) => typeof id === "string" && id !== ""))];
|
|
358
|
+
if (ids.length === 0) return {
|
|
359
|
+
ok: false,
|
|
360
|
+
error: "sessionIds 无有效值"
|
|
361
|
+
};
|
|
362
|
+
if (ids.length > 5e3) return {
|
|
363
|
+
ok: false,
|
|
364
|
+
error: `单次最多清理 ${MAX_PURGE_IDS} 个`
|
|
365
|
+
};
|
|
366
|
+
const wanted = new Set(ids);
|
|
367
|
+
const usage = locateSessionUsage(ids, dshHome);
|
|
368
|
+
const candidates = options?.searchPaths ?? [join(dshHome, "storages", "workspace.json")];
|
|
369
|
+
let edited = false;
|
|
370
|
+
let lastReason = `workspace 存储文件不存在(已试:${candidates.join("、")})`;
|
|
371
|
+
for (const path of candidates) {
|
|
372
|
+
const outcome = editWorkspaceDocument(path, (document) => {
|
|
373
|
+
let changed = false;
|
|
374
|
+
const global = document.global;
|
|
375
|
+
if (Array.isArray(global?.archivedSessionIds)) {
|
|
376
|
+
const kept = global.archivedSessionIds.filter((id) => typeof id !== "string" || !wanted.has(id));
|
|
377
|
+
if (kept.length !== global.archivedSessionIds.length) {
|
|
378
|
+
document.global = {
|
|
379
|
+
...global,
|
|
380
|
+
archivedSessionIds: kept
|
|
381
|
+
};
|
|
382
|
+
changed = true;
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
const tables = document.tables;
|
|
386
|
+
if (tables?.workspaces !== void 0) for (const [workspaceId, workspace] of Object.entries(tables.workspaces)) {
|
|
387
|
+
if (!Array.isArray(workspace?.sessionIds)) continue;
|
|
388
|
+
const kept = workspace.sessionIds.filter((id) => typeof id !== "string" || !wanted.has(id));
|
|
389
|
+
if (kept.length !== workspace.sessionIds.length) {
|
|
390
|
+
tables.workspaces[workspaceId] = {
|
|
391
|
+
...workspace,
|
|
392
|
+
sessionIds: kept
|
|
393
|
+
};
|
|
394
|
+
changed = true;
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
return changed;
|
|
398
|
+
}, log);
|
|
399
|
+
if (!outcome.ok) {
|
|
400
|
+
lastReason = outcome.reason;
|
|
401
|
+
continue;
|
|
402
|
+
}
|
|
403
|
+
edited = true;
|
|
404
|
+
break;
|
|
405
|
+
}
|
|
406
|
+
if (!edited) return {
|
|
407
|
+
ok: false,
|
|
408
|
+
error: lastReason
|
|
409
|
+
};
|
|
410
|
+
const sessionsRoot = sessionsRootFor(dshHome);
|
|
411
|
+
const cacheRoot = projCacheRootFor(dshHome);
|
|
412
|
+
const failures = [];
|
|
413
|
+
let purged = 0;
|
|
414
|
+
let freedBytes = 0;
|
|
415
|
+
for (const sessionId of ids) {
|
|
416
|
+
const entry = usage.get(sessionId);
|
|
417
|
+
let missing = 0;
|
|
418
|
+
let entryFreed = 0;
|
|
419
|
+
if (entry?.dir !== void 0) {
|
|
420
|
+
if (!isSafeChild(sessionsRoot, entry.dir, 2)) {
|
|
421
|
+
failures.push({
|
|
422
|
+
sessionId,
|
|
423
|
+
reason: `拒绝删除越界路径:${entry.dir}`
|
|
424
|
+
});
|
|
425
|
+
continue;
|
|
426
|
+
}
|
|
427
|
+
try {
|
|
428
|
+
rmSync(entry.dir, {
|
|
429
|
+
recursive: true,
|
|
430
|
+
force: true
|
|
431
|
+
});
|
|
432
|
+
entryFreed += entry.bytes;
|
|
433
|
+
} catch (err) {
|
|
434
|
+
failures.push({
|
|
435
|
+
sessionId,
|
|
436
|
+
reason: `删除转录目录失败:${String(err instanceof Error ? err.message : err)}`
|
|
437
|
+
});
|
|
438
|
+
continue;
|
|
439
|
+
}
|
|
440
|
+
} else missing++;
|
|
441
|
+
if (entry?.cacheFile !== void 0) {
|
|
442
|
+
if (!isSafeChild(cacheRoot, entry.cacheFile, 1)) {
|
|
443
|
+
failures.push({
|
|
444
|
+
sessionId,
|
|
445
|
+
reason: `拒绝删除越界缓存:${entry.cacheFile}`
|
|
446
|
+
});
|
|
447
|
+
continue;
|
|
448
|
+
}
|
|
449
|
+
try {
|
|
450
|
+
entryFreed += entry.cacheBytes;
|
|
451
|
+
rmSync(entry.cacheFile, { force: true });
|
|
452
|
+
} catch (err) {
|
|
453
|
+
failures.push({
|
|
454
|
+
sessionId,
|
|
455
|
+
reason: `删除投影缓存失败:${String(err instanceof Error ? err.message : err)}`
|
|
456
|
+
});
|
|
457
|
+
continue;
|
|
458
|
+
}
|
|
459
|
+
} else missing++;
|
|
460
|
+
if (missing === 2) log?.(`purge: ${sessionId} had no on-disk entity; only the archive state was cleared`);
|
|
461
|
+
purged++;
|
|
462
|
+
freedBytes += entryFreed;
|
|
463
|
+
}
|
|
464
|
+
log?.(`archive purge: cleared ${purged} of ${ids.length}; freed ${(freedBytes / 1048576).toFixed(1)}MB; failures ${failures.length}`);
|
|
465
|
+
return {
|
|
466
|
+
ok: true,
|
|
467
|
+
purged,
|
|
468
|
+
freedBytes,
|
|
469
|
+
requiresRestart: true,
|
|
470
|
+
...failures.length === 0 ? {} : { failures }
|
|
471
|
+
};
|
|
125
472
|
}
|
|
126
473
|
//#endregion
|
|
127
474
|
//#region src/host/history/archive.ts
|
|
@@ -131,9 +478,12 @@ function pruneArchiveFile(ids, log, searchPaths) {
|
|
|
131
478
|
* 与 dsh-session-search-toggle 的差异(**刻意且必须记入交付说明**):
|
|
132
479
|
* toggle 的 `list-archived` 从它自己的独立索引里列出归档行(`engine.listArchived()`),
|
|
133
480
|
* 而索引已随搜索索引包离开本包。因此本包改为从**官方归档集合**列出来源真值
|
|
134
|
-
* (`readArchiveSet
|
|
481
|
+
* (`readArchiveSet`:存储文件优先、registry 兜底),标题等元数据为尽力而为:
|
|
135
482
|
* 依次尝试 `sessionQuery.readTitleSnapshots` → 投影缓存记录里的 title。
|
|
136
|
-
*
|
|
483
|
+
* 列表与 prune **同源**(都认存储文件),否则清理成功后面板不会刷新;
|
|
484
|
+
* registry 与文件的差集作为 `pendingRestart` 返回,面板据此提示重启。
|
|
485
|
+
* 清理(prune)路径与迁移前**逐字等价**(备份 + 原子替换 + 需重启提示),
|
|
486
|
+
* 另加一道写后校验:读回文件确认目标 id 确实消失。
|
|
137
487
|
*/
|
|
138
488
|
/** 投影缓存记录里可能存在的标题(同目录第二来源)。 */
|
|
139
489
|
function titleFromProjectionCache(sessionId) {
|
|
@@ -153,7 +503,7 @@ function titleFromProjectionCache(sessionId) {
|
|
|
153
503
|
* @param searchPaths - 可选存储文件候选路径(DSH_HOME 非默认值/测试注入)。
|
|
154
504
|
* @returns 归档行清单。
|
|
155
505
|
*/
|
|
156
|
-
async function listHistory(getRegistry, query, searchPaths) {
|
|
506
|
+
async function listHistory(getRegistry, query, searchPaths, dshHome) {
|
|
157
507
|
const read = readArchiveSet(getRegistry(), searchPaths);
|
|
158
508
|
if (read.source === "none") return {
|
|
159
509
|
ok: false,
|
|
@@ -172,18 +522,33 @@ async function listHistory(getRegistry, query, searchPaths) {
|
|
|
172
522
|
degraded = "sessionQuery 标题快照不可用,标题回退到投影缓存/空";
|
|
173
523
|
}
|
|
174
524
|
else if (ids.length > 0) degraded = "sessionQuery 不可用,标题回退到投影缓存/空";
|
|
525
|
+
const items = ids.map((sessionId) => {
|
|
526
|
+
return {
|
|
527
|
+
sessionId,
|
|
528
|
+
title: titles.get(sessionId) ?? titleFromProjectionCache(sessionId),
|
|
529
|
+
cwd: "",
|
|
530
|
+
updatedAt: 0,
|
|
531
|
+
bytes: 0,
|
|
532
|
+
cacheBytes: 0
|
|
533
|
+
};
|
|
534
|
+
});
|
|
535
|
+
if (dshHome !== void 0 && dshHome !== "" && items.length > 0) try {
|
|
536
|
+
const usage = locateSessionUsage(ids, dshHome);
|
|
537
|
+
for (const item of items) {
|
|
538
|
+
const entry = usage.get(item.sessionId);
|
|
539
|
+
if (entry === void 0) continue;
|
|
540
|
+
item.bytes = entry.bytes;
|
|
541
|
+
item.cacheBytes = entry.cacheBytes;
|
|
542
|
+
}
|
|
543
|
+
} catch {}
|
|
544
|
+
const fileIds = new Set(ids);
|
|
545
|
+
const pendingRestart = (read.registryIds ?? []).filter((id) => !fileIds.has(id)).length;
|
|
175
546
|
return {
|
|
176
547
|
ok: true,
|
|
177
|
-
items
|
|
178
|
-
return {
|
|
179
|
-
sessionId,
|
|
180
|
-
title: titles.get(sessionId) ?? titleFromProjectionCache(sessionId),
|
|
181
|
-
cwd: "",
|
|
182
|
-
updatedAt: 0
|
|
183
|
-
};
|
|
184
|
-
}),
|
|
548
|
+
items,
|
|
185
549
|
source: read.source,
|
|
186
|
-
...degraded === void 0 ? {} : { degraded }
|
|
550
|
+
...degraded === void 0 ? {} : { degraded },
|
|
551
|
+
...pendingRestart === 0 ? {} : { pendingRestart }
|
|
187
552
|
};
|
|
188
553
|
}
|
|
189
554
|
/** 按 DSH_HOME 解析存储文件候选(与 archive-source 的默认候选保持同一形状)。 */
|
|
@@ -224,6 +589,17 @@ function pruneHistory(payload, log, searchPaths) {
|
|
|
224
589
|
error: String(err instanceof Error ? err.message : err)
|
|
225
590
|
};
|
|
226
591
|
}
|
|
592
|
+
const after = readArchiveSet(void 0, searchPaths);
|
|
593
|
+
if (after.source !== "storage-file") return {
|
|
594
|
+
ok: false,
|
|
595
|
+
error: "写入后无法读回存储文件,无法确认清理结果"
|
|
596
|
+
};
|
|
597
|
+
const stillThere = new Set(after.ids);
|
|
598
|
+
const leftover = ids.filter((id) => stillThere.has(id));
|
|
599
|
+
if (leftover.length > 0) return {
|
|
600
|
+
ok: false,
|
|
601
|
+
error: `存储文件在写入后仍包含 ${leftover.length} 个目标 id,清理未生效`
|
|
602
|
+
};
|
|
227
603
|
log?.(`archive prune requested ${ids.length}, removed ${result.removed}, remaining ${result.remaining}`);
|
|
228
604
|
return {
|
|
229
605
|
ok: true,
|
|
@@ -344,6 +720,75 @@ function createAttributor(index) {
|
|
|
344
720
|
};
|
|
345
721
|
}
|
|
346
722
|
//#endregion
|
|
723
|
+
//#region src/host/health/cache.ts
|
|
724
|
+
/** 进程内体检缓存:分批扫描过程中累积,走完一遍语料才成型。 */
|
|
725
|
+
var HealthCache = class {
|
|
726
|
+
ready;
|
|
727
|
+
pending;
|
|
728
|
+
/** 读当前成型的缓存(未成型则 undefined)。 */
|
|
729
|
+
read() {
|
|
730
|
+
return this.ready;
|
|
731
|
+
}
|
|
732
|
+
/** 开始一轮分批扫描(客户端以 `offset: 0` 发起时调用)。 */
|
|
733
|
+
begin(total) {
|
|
734
|
+
this.pending = {
|
|
735
|
+
total: Math.max(0, Math.floor(total)),
|
|
736
|
+
findings: [],
|
|
737
|
+
visited: 0
|
|
738
|
+
};
|
|
739
|
+
}
|
|
740
|
+
/**
|
|
741
|
+
* 追加一批扫描结果。
|
|
742
|
+
*
|
|
743
|
+
* 只有累积的已访问数走满语料总数才成型;语言中途断掉(关面板、报错)不会留下
|
|
744
|
+
* 半份缓存冒充完整结果。
|
|
745
|
+
* @param findings - 本批的非 ok 报告。
|
|
746
|
+
* @param scanned - 本批**已访问**的会话数(不是命中数)。
|
|
747
|
+
* @param now - 时间源(测试可控)。
|
|
748
|
+
* @returns 本批追加后缓存是否刚好成型。
|
|
749
|
+
*/
|
|
750
|
+
append(findings, scanned, now = Date.now) {
|
|
751
|
+
const pending = this.pending;
|
|
752
|
+
if (pending === void 0) return false;
|
|
753
|
+
pending.findings.push(...findings);
|
|
754
|
+
pending.visited += Math.max(0, Math.floor(scanned));
|
|
755
|
+
if (pending.visited < pending.total) return false;
|
|
756
|
+
this.ready = {
|
|
757
|
+
findings: pending.findings,
|
|
758
|
+
total: pending.total,
|
|
759
|
+
generatedAt: now()
|
|
760
|
+
};
|
|
761
|
+
this.pending = void 0;
|
|
762
|
+
return true;
|
|
763
|
+
}
|
|
764
|
+
/**
|
|
765
|
+
* 单条就地回写(单会话体检 / 可逆处置后调用)。
|
|
766
|
+
*
|
|
767
|
+
* 这是缓存的**关键收益**:处置本就重算了 `after` 报告,把它写回即可,
|
|
768
|
+
* 不必为了刷新一行而重扫整个语料。
|
|
769
|
+
* @param report - 重算出的单会话报告。
|
|
770
|
+
* @returns 是否真的改动了缓存(无缓存时为 false)。
|
|
771
|
+
*/
|
|
772
|
+
patch(report) {
|
|
773
|
+
const ready = this.ready;
|
|
774
|
+
if (ready === void 0) return false;
|
|
775
|
+
const index = ready.findings.findIndex((entry) => entry.sessionId === report.sessionId);
|
|
776
|
+
if (report.level === "ok") {
|
|
777
|
+
if (index < 0) return false;
|
|
778
|
+
ready.findings.splice(index, 1);
|
|
779
|
+
return true;
|
|
780
|
+
}
|
|
781
|
+
if (index >= 0) ready.findings[index] = report;
|
|
782
|
+
else ready.findings.push(report);
|
|
783
|
+
return true;
|
|
784
|
+
}
|
|
785
|
+
/** 丢弃缓存与未完成的累积。 */
|
|
786
|
+
clear() {
|
|
787
|
+
this.ready = void 0;
|
|
788
|
+
this.pending = void 0;
|
|
789
|
+
}
|
|
790
|
+
};
|
|
791
|
+
//#endregion
|
|
347
792
|
//#region src/host/health/decode.ts
|
|
348
793
|
/**
|
|
349
794
|
* 会话日志读取链路(`log-integrity` gate 与 `lossless-json` gate 的共同底座)。
|
|
@@ -886,8 +1331,8 @@ function gateProjectionCache(facts) {
|
|
|
886
1331
|
};
|
|
887
1332
|
if (!facts.present) return {
|
|
888
1333
|
id: "projection-cache",
|
|
889
|
-
level: "
|
|
890
|
-
evidence: "
|
|
1334
|
+
level: "skipped",
|
|
1335
|
+
evidence: "投影缓存记录不存在,本门无从判定(宿主会在下次检查点重建;若长期不出现说明检查点写入被拒)",
|
|
891
1336
|
detail: { path: facts.path }
|
|
892
1337
|
};
|
|
893
1338
|
const lag = facts.lag ?? 0;
|
|
@@ -922,14 +1367,14 @@ function gateProjectionCache(facts) {
|
|
|
922
1367
|
function gateLosslessJson(projectionState, attribute) {
|
|
923
1368
|
if (projectionState === void 0) return {
|
|
924
1369
|
id: "lossless-json",
|
|
925
|
-
level: "
|
|
926
|
-
evidence: "拿不到热态投影状态(宿主未暴露 sessionProjections);冷态记录经 JSON
|
|
1370
|
+
level: "skipped",
|
|
1371
|
+
evidence: "拿不到热态投影状态(宿主未暴露 sessionProjections);冷态记录经 JSON 往返必然无损,本门无从判定"
|
|
927
1372
|
};
|
|
928
1373
|
const keys = Object.keys(projectionState);
|
|
929
1374
|
if (keys.length === 0) return {
|
|
930
1375
|
id: "lossless-json",
|
|
931
|
-
level: "
|
|
932
|
-
evidence: "
|
|
1376
|
+
level: "skipped",
|
|
1377
|
+
evidence: "热态投影状态为空,本门无从判定"
|
|
933
1378
|
};
|
|
934
1379
|
for (const key of keys) {
|
|
935
1380
|
const row = projectionState[key];
|
|
@@ -976,8 +1421,8 @@ function gateColdRead(facts) {
|
|
|
976
1421
|
};
|
|
977
1422
|
if (facts.lastTurnEnd === void 0) return {
|
|
978
1423
|
id: "cold-read",
|
|
979
|
-
level: "
|
|
980
|
-
evidence: "日志中没有 turn/end
|
|
1424
|
+
level: "skipped",
|
|
1425
|
+
evidence: "日志中没有 turn/end,本门无从确认是否存在可接续的已完成轮次",
|
|
981
1426
|
detail
|
|
982
1427
|
};
|
|
983
1428
|
if (facts.lastTurnEnd.reason !== "completed") return {
|
|
@@ -1028,6 +1473,19 @@ function buildSessionReport(context) {
|
|
|
1028
1473
|
*
|
|
1029
1474
|
* 红线:禁止改写会话日志、禁止改历史数据、禁止静默丢弃字段。
|
|
1030
1475
|
*/
|
|
1476
|
+
/**
|
|
1477
|
+
* 该门是否构成「可处置的异常」。
|
|
1478
|
+
*
|
|
1479
|
+
* 判定标准与 gates.ts 的 GateLevel 文档一致:
|
|
1480
|
+
* `warn` / `fail` = **观测到了**异常现象(有据)→ 可开处方;
|
|
1481
|
+
* `skipped` = 无从观测/无从判定(无据)→ 不开方。
|
|
1482
|
+
*
|
|
1483
|
+
* 早期版本用 `level !== 'ok'` 判断,把 `skipped` 也算成异常,导致对着
|
|
1484
|
+
* 「本门无从判定」的证据输出「投影缓存未对齐」,并建议隔离一条不存在的记录。
|
|
1485
|
+
*/
|
|
1486
|
+
function isActionable(level) {
|
|
1487
|
+
return level === "warn" || level === "fail";
|
|
1488
|
+
}
|
|
1031
1489
|
/** 投影缓存记录路径。 */
|
|
1032
1490
|
function projectionCachePath(sessionId, dshHome) {
|
|
1033
1491
|
return join(dshHome ?? join(homedir(), ".dsh"), "storages", "session_projcache", "sessions", `${sessionId}.json`);
|
|
@@ -1096,15 +1554,60 @@ function prescribe(report, dshHome) {
|
|
|
1096
1554
|
return lines;
|
|
1097
1555
|
}
|
|
1098
1556
|
const cache = gate("projection-cache");
|
|
1099
|
-
if (cache?.level
|
|
1100
|
-
lines.push(`#
|
|
1557
|
+
if (isActionable(cache?.level)) {
|
|
1558
|
+
lines.push(`# 投影缓存异常:${cache?.evidence ?? "未知"}`);
|
|
1101
1559
|
lines.push("# 1) 先隔离陈旧记录,再重启宿主让其重折叠");
|
|
1102
1560
|
lines.push(`# POST /session-steward/api/session-health-repair {"sessionId":"${report.sessionId}"}`);
|
|
1103
1561
|
}
|
|
1104
1562
|
if (gate("cold-read")?.level === "fail") lines.push("# 会话仍处于 open step:请等待宿主结算(不要硬改日志),必要时重启宿主后重新体检");
|
|
1105
|
-
if (lines.length === 0)
|
|
1563
|
+
if (lines.length === 0) {
|
|
1564
|
+
const unjudged = report.gates.filter((entry) => entry.level === "skipped");
|
|
1565
|
+
lines.push(unjudged.length === 0 ? "# 四门全绿:无需处置" : `# 无可处置项(${unjudged.length} 门无从判定,非异常):${unjudged.map((entry) => entry.id).join(" / ")}`);
|
|
1566
|
+
}
|
|
1106
1567
|
return lines;
|
|
1107
1568
|
}
|
|
1569
|
+
/**
|
|
1570
|
+
* 判定一次处置的结果,并给出人读说明。
|
|
1571
|
+
*
|
|
1572
|
+
* 存在的理由:处置**只**隔离投影缓存记录,而会话的异常可能来自别处
|
|
1573
|
+
* (最典型是 `cold-read` 的 open step——插件红线不改会话日志,这类异常
|
|
1574
|
+
* 本就不该由处置修复)。旧版 UI 只显示 `处置前/处置后` 两个档位,
|
|
1575
|
+
* 两者都是「异常」时用户无法判断是处置失败还是处置与病灶无关。
|
|
1576
|
+
*
|
|
1577
|
+
* @param input - 处置前后的报告与处置执行结果。
|
|
1578
|
+
*/
|
|
1579
|
+
function assessRepair(input) {
|
|
1580
|
+
const { before, after, repair } = input;
|
|
1581
|
+
const residual = after.gates.filter((entry) => entry.level === "warn" || entry.level === "fail").map((entry) => ({
|
|
1582
|
+
id: entry.id,
|
|
1583
|
+
level: entry.level
|
|
1584
|
+
}));
|
|
1585
|
+
const residualIds = residual.map((entry) => entry.id).join(" / ");
|
|
1586
|
+
if (before.level === "ok") return {
|
|
1587
|
+
verdict: "nothing-to-do",
|
|
1588
|
+
explanation: "四门全绿,无需处置",
|
|
1589
|
+
residual: []
|
|
1590
|
+
};
|
|
1591
|
+
if (repair.ok) return residual.length === 0 ? {
|
|
1592
|
+
verdict: "repaired",
|
|
1593
|
+
explanation: "处置生效:已隔离投影缓存记录,体检结果已恢复",
|
|
1594
|
+
residual: []
|
|
1595
|
+
} : {
|
|
1596
|
+
verdict: "repaired-with-residual",
|
|
1597
|
+
explanation: `已隔离投影缓存记录;但仍有与该缓存无关的异常:${residualIds}。这类异常来自会话日志或宿主运行态,本插件不改会话日志,请等待宿主结算后重新体检。`,
|
|
1598
|
+
residual
|
|
1599
|
+
};
|
|
1600
|
+
if (!isActionable(before.gates.find((entry) => entry.id === "projection-cache")?.level)) return {
|
|
1601
|
+
verdict: "not-applicable",
|
|
1602
|
+
explanation: residualIds === "" ? "当前异常无可逆处置项" : `当前异常无可逆处置项(投影缓存无可隔离记录);异常来自 ${residualIds},本插件不改会话日志,请等待宿主结算后重新体检。`,
|
|
1603
|
+
residual
|
|
1604
|
+
};
|
|
1605
|
+
return {
|
|
1606
|
+
verdict: "failed",
|
|
1607
|
+
explanation: `处置失败:${repair.error ?? "未知原因"}`,
|
|
1608
|
+
residual
|
|
1609
|
+
};
|
|
1610
|
+
}
|
|
1108
1611
|
//#endregion
|
|
1109
1612
|
//#region src/host/health/scan.ts
|
|
1110
1613
|
/**
|
|
@@ -1162,24 +1665,47 @@ function discoverSessions(dshHome, limit = 200) {
|
|
|
1162
1665
|
out.sort((left, right) => right.updatedAt - left.updatedAt);
|
|
1163
1666
|
return out.slice(0, Math.max(1, limit));
|
|
1164
1667
|
}
|
|
1668
|
+
/**
|
|
1669
|
+
* 语料总数:只做目录枚举,**不跑体检**。
|
|
1670
|
+
*
|
|
1671
|
+
* 用于判断缓存是否已过期——枚举很便宜,而重扫要解 zstd、跑四门。
|
|
1672
|
+
* 正因为两者代价差着量级,「对账」才不构成缓存失效策略本身。
|
|
1673
|
+
* @param dshHome - DSH home(缺省 ~/.dsh)。
|
|
1674
|
+
*/
|
|
1675
|
+
function countCorpus(dshHome) {
|
|
1676
|
+
return discoverSessions(dshHome, DISCOVERY_LIMIT).length;
|
|
1677
|
+
}
|
|
1165
1678
|
/** 定位一个会话的日志路径(跨工程目录查找)。 */
|
|
1166
1679
|
function findSessionLog(sessionId, dshHome) {
|
|
1167
1680
|
return discoverSessions(dshHome, 1e5).find((session) => session.sessionId === sessionId)?.logPath;
|
|
1168
1681
|
}
|
|
1682
|
+
/** 语料枚举上限(进度分母的来源;与 route 侧 MAX_SCAN_LIMIT 同量级)。 */
|
|
1683
|
+
const DISCOVERY_LIMIT = 200;
|
|
1684
|
+
/** 未显式传 limit 时的单批会话数。 */
|
|
1685
|
+
const DEFAULT_BATCH_LIMIT = 50;
|
|
1169
1686
|
/**
|
|
1170
|
-
*
|
|
1171
|
-
*
|
|
1687
|
+
* 批量体检(支持分批)。
|
|
1688
|
+
*
|
|
1689
|
+
* 语料先整体列出(按 mtime 倒序,≤ DISCOVERY_LIMIT),再按 `[offset, offset+limit)`
|
|
1690
|
+
* 切片扫描。这样客户端可以用小批次连续调用、自己累计真实进度,而宿主保持无状态
|
|
1691
|
+
* ——不必把同步循环改成异步,也不必新增进度轮询端点。
|
|
1692
|
+
* @param options - dshHome / 批大小 / 批起点 / 是否只返回非 ok / 归属查询 / 热态状态提供者。
|
|
1172
1693
|
*/
|
|
1173
1694
|
function scanSessions(options) {
|
|
1174
|
-
const discovered = discoverSessions(options.dshHome,
|
|
1695
|
+
const discovered = discoverSessions(options.dshHome, DISCOVERY_LIMIT);
|
|
1175
1696
|
if (discovered.length === 0) return {
|
|
1176
1697
|
ok: false,
|
|
1177
1698
|
scanned: 0,
|
|
1699
|
+
total: 0,
|
|
1700
|
+
offset: 0,
|
|
1178
1701
|
findings: [],
|
|
1179
1702
|
error: "未发现任何会话日志(检查 DSH home 与 sessions 目录)"
|
|
1180
1703
|
};
|
|
1704
|
+
const offset = Math.max(0, Math.floor(options.offset ?? 0));
|
|
1705
|
+
const limit = Math.max(1, Math.floor(options.limit ?? DEFAULT_BATCH_LIMIT));
|
|
1706
|
+
const batch = discovered.slice(offset, offset + limit);
|
|
1181
1707
|
const findings = [];
|
|
1182
|
-
for (const session of
|
|
1708
|
+
for (const session of batch) {
|
|
1183
1709
|
const projectionState = options.projectionStateFor?.(session.sessionId);
|
|
1184
1710
|
const report = buildSessionReport({
|
|
1185
1711
|
sessionId: session.sessionId,
|
|
@@ -1194,7 +1720,9 @@ function scanSessions(options) {
|
|
|
1194
1720
|
}
|
|
1195
1721
|
return {
|
|
1196
1722
|
ok: true,
|
|
1197
|
-
scanned:
|
|
1723
|
+
scanned: batch.length,
|
|
1724
|
+
total: discovered.length,
|
|
1725
|
+
offset,
|
|
1198
1726
|
findings,
|
|
1199
1727
|
...options.onlyProblems === true ? { filtered: true } : {}
|
|
1200
1728
|
};
|
|
@@ -1304,8 +1832,17 @@ function asSessionId(value) {
|
|
|
1304
1832
|
}
|
|
1305
1833
|
/** 单会话体检的最大扫描上限。 */
|
|
1306
1834
|
const MAX_SCAN_LIMIT = 200;
|
|
1307
|
-
/**
|
|
1308
|
-
|
|
1835
|
+
/**
|
|
1836
|
+
* 支持的路由方法(按子域分组;用于对外声明与测试断言)。
|
|
1837
|
+
*
|
|
1838
|
+
* `session-history-prune` 与 `session-history-purge` 是**两件事**,不可合并:
|
|
1839
|
+
* prune = 取消归档状态(可逆,会话回到侧边栏);purge = 清理归档文件(不可逆,真删实体)。
|
|
1840
|
+
*/
|
|
1841
|
+
const HISTORY_METHODS = [
|
|
1842
|
+
"session-history-list",
|
|
1843
|
+
"session-history-prune",
|
|
1844
|
+
"session-history-purge"
|
|
1845
|
+
];
|
|
1309
1846
|
const HEALTH_METHODS = [
|
|
1310
1847
|
"session-health-status",
|
|
1311
1848
|
"session-health-scan",
|
|
@@ -1334,8 +1871,12 @@ async function handleMethod(method, payload, runtime) {
|
|
|
1334
1871
|
ok: false,
|
|
1335
1872
|
error: `子域已关闭(${HISTORY_METHODS.includes(method) ? "historyFiles" : "healthCheck"}=false):${method} 未注册`
|
|
1336
1873
|
};
|
|
1337
|
-
if (method === "session-history-list") return await listHistory(runtime.registry, void 0, storagePathsFor(runtime.dshHome));
|
|
1874
|
+
if (method === "session-history-list") return await listHistory(runtime.registry, void 0, storagePathsFor(runtime.dshHome), runtime.dshHome);
|
|
1338
1875
|
if (method === "session-history-prune") return pruneHistory(payload, runtime.log, storagePathsFor(runtime.dshHome));
|
|
1876
|
+
if (method === "session-history-purge") return purgeHistory(payload, runtime.log, {
|
|
1877
|
+
dshHome: runtime.dshHome,
|
|
1878
|
+
searchPaths: storagePathsFor(runtime.dshHome)
|
|
1879
|
+
});
|
|
1339
1880
|
if (method === "session-health-status") return {
|
|
1340
1881
|
ok: true,
|
|
1341
1882
|
namespace: STEWARD_SETTINGS_NAMESPACE,
|
|
@@ -1351,14 +1892,43 @@ async function handleMethod(method, payload, runtime) {
|
|
|
1351
1892
|
};
|
|
1352
1893
|
if (method === "session-health-scan") {
|
|
1353
1894
|
const request = payload ?? {};
|
|
1895
|
+
const onlyProblems = request.onlyProblems !== false;
|
|
1896
|
+
if (request.resume === true) {
|
|
1897
|
+
const cached = runtime.cache?.read();
|
|
1898
|
+
if (cached === void 0) return {
|
|
1899
|
+
ok: true,
|
|
1900
|
+
cached: false,
|
|
1901
|
+
scanned: 0,
|
|
1902
|
+
total: countCorpus(runtime.dshHome),
|
|
1903
|
+
offset: 0,
|
|
1904
|
+
findings: []
|
|
1905
|
+
};
|
|
1906
|
+
return {
|
|
1907
|
+
ok: true,
|
|
1908
|
+
cached: true,
|
|
1909
|
+
scanned: 0,
|
|
1910
|
+
total: cached.total,
|
|
1911
|
+
offset: 0,
|
|
1912
|
+
findings: cached.findings,
|
|
1913
|
+
generatedAt: cached.generatedAt,
|
|
1914
|
+
currentTotal: countCorpus(runtime.dshHome)
|
|
1915
|
+
};
|
|
1916
|
+
}
|
|
1354
1917
|
const limit = typeof request.limit === "number" && Number.isFinite(request.limit) ? Math.max(1, Math.min(MAX_SCAN_LIMIT, Math.floor(request.limit))) : 30;
|
|
1355
|
-
|
|
1918
|
+
const offset = typeof request.offset === "number" && Number.isFinite(request.offset) && request.offset > 0 ? Math.floor(request.offset) : 0;
|
|
1919
|
+
const result = scanSessions({
|
|
1356
1920
|
dshHome: runtime.dshHome,
|
|
1357
1921
|
limit,
|
|
1358
|
-
|
|
1922
|
+
offset,
|
|
1923
|
+
onlyProblems,
|
|
1359
1924
|
attribute: runtime.attribute,
|
|
1360
1925
|
projectionStateFor: runtime.projectionStateFor
|
|
1361
1926
|
});
|
|
1927
|
+
if (result.ok && onlyProblems) {
|
|
1928
|
+
if (offset === 0) runtime.cache?.begin(result.total);
|
|
1929
|
+
runtime.cache?.append(result.findings, result.scanned);
|
|
1930
|
+
}
|
|
1931
|
+
return result;
|
|
1362
1932
|
}
|
|
1363
1933
|
const sessionId = asSessionId((payload ?? {}).sessionId);
|
|
1364
1934
|
if (sessionId === void 0) return {
|
|
@@ -1380,6 +1950,7 @@ async function handleMethod(method, payload, runtime) {
|
|
|
1380
1950
|
});
|
|
1381
1951
|
if (method === "session-health-session") {
|
|
1382
1952
|
const report = reportFor();
|
|
1953
|
+
runtime.cache?.patch(report);
|
|
1383
1954
|
return {
|
|
1384
1955
|
ok: true,
|
|
1385
1956
|
report,
|
|
@@ -1387,23 +1958,48 @@ async function handleMethod(method, payload, runtime) {
|
|
|
1387
1958
|
};
|
|
1388
1959
|
}
|
|
1389
1960
|
const before = reportFor();
|
|
1390
|
-
if (before.level === "ok")
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1961
|
+
if (before.level === "ok") {
|
|
1962
|
+
runtime.cache?.patch(before);
|
|
1963
|
+
const clean = assessRepair({
|
|
1964
|
+
before,
|
|
1965
|
+
after: before,
|
|
1966
|
+
repair: {
|
|
1967
|
+
ok: false,
|
|
1968
|
+
action: "quarantine-projection-cache",
|
|
1969
|
+
sessionId,
|
|
1970
|
+
from: ""
|
|
1971
|
+
}
|
|
1972
|
+
});
|
|
1973
|
+
return {
|
|
1974
|
+
ok: true,
|
|
1975
|
+
changed: false,
|
|
1976
|
+
before,
|
|
1977
|
+
after: before,
|
|
1978
|
+
repair: null,
|
|
1979
|
+
verdict: clean.verdict,
|
|
1980
|
+
explanation: clean.explanation,
|
|
1981
|
+
residual: clean.residual,
|
|
1982
|
+
prescriptions: ["# 四门全绿:无需处置"]
|
|
1983
|
+
};
|
|
1984
|
+
}
|
|
1398
1985
|
const repair = quarantineProjectionCache(sessionId, runtime.dshHome);
|
|
1399
1986
|
const after = reportFor();
|
|
1400
|
-
|
|
1987
|
+
const assessment = assessRepair({
|
|
1988
|
+
before,
|
|
1989
|
+
after,
|
|
1990
|
+
repair
|
|
1991
|
+
});
|
|
1992
|
+
runtime.cache?.patch(after);
|
|
1993
|
+
runtime.log(`health repair ${sessionId}: verdict=${assessment.verdict} quarantine=${repair.ok ? "ok" : repair.error ?? "skipped"} before=${before.level} after=${after.level}`);
|
|
1401
1994
|
return {
|
|
1402
1995
|
ok: true,
|
|
1403
1996
|
changed: repair.ok,
|
|
1404
1997
|
repair,
|
|
1405
1998
|
before,
|
|
1406
1999
|
after,
|
|
2000
|
+
verdict: assessment.verdict,
|
|
2001
|
+
explanation: assessment.explanation,
|
|
2002
|
+
residual: assessment.residual,
|
|
1407
2003
|
prescriptions: prescribe(after, runtime.dshHome)
|
|
1408
2004
|
};
|
|
1409
2005
|
}
|
|
@@ -1465,7 +2061,8 @@ function apply(ctx) {
|
|
|
1465
2061
|
registry,
|
|
1466
2062
|
projectionStateFor,
|
|
1467
2063
|
attribute: attributor,
|
|
1468
|
-
log
|
|
2064
|
+
log,
|
|
2065
|
+
cache: new HealthCache()
|
|
1469
2066
|
};
|
|
1470
2067
|
if (current().enabled === false) {
|
|
1471
2068
|
log("enabled=false:不注册任何路由");
|
|
@@ -1511,4 +2108,4 @@ function apply(ctx) {
|
|
|
1511
2108
|
}), "dsh-manage-session: /session-steward/api route");
|
|
1512
2109
|
}
|
|
1513
2110
|
//#endregion
|
|
1514
|
-
export { DEFAULT_CONFIG, HEALTH_METHODS, HISTORY_METHODS, STEWARD_API_PREFIX, STEWARD_SETTINGS_NAMESPACE, apply, buildProjectionOwnerIndex, buildSessionReport, createAttributor, decodeSessionLogBytes, decodeSessionLogFile, discoverSessions, findSessionLog, firstLosslessViolation, gateColdRead, gateLogIntegrity, gateLosslessJson, gateProjectionCache, handleMethod, inject, isLossless, listHistory, methodEnabled, prescribe, pruneArchiveFile, pruneHistory, quarantineProjectionCache, readArchiveSet, readProjectionCache, readTailFacts, scanSessions, scanZstdFrames };
|
|
2111
|
+
export { DEFAULT_CONFIG, HEALTH_METHODS, HISTORY_METHODS, HealthCache, STEWARD_API_PREFIX, STEWARD_SETTINGS_NAMESPACE, apply, assessRepair, buildProjectionOwnerIndex, buildSessionReport, countCorpus, createAttributor, decodeSessionLogBytes, decodeSessionLogFile, dirSize, discoverSessions, editWorkspaceDocument, findSessionLog, firstLosslessViolation, gateColdRead, gateLogIntegrity, gateLosslessJson, gateProjectionCache, handleMethod, indexSessionDirs, inject, isLossless, isSafeChild, listHistory, locateSessionUsage, methodEnabled, prescribe, projCacheRootFor, pruneArchiveFile, pruneHistory, purgeHistory, quarantineProjectionCache, readArchiveSet, readProjectionCache, readTailFacts, scanSessions, scanZstdFrames, sessionsRootFor };
|