@kangyishuai/dsh-session-delete 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +123 -2
- package/README.zh-CN.md +124 -0
- package/cordis.patch.yml +3 -0
- package/lib/audit.js +93 -0
- package/lib/capability.js +106 -0
- package/lib/client.js +1412 -0
- package/lib/index.js +7 -0
- package/lib/journal.js +136 -0
- package/lib/locate.js +129 -0
- package/lib/operations.js +848 -0
- package/lib/paths.js +148 -0
- package/lib/plan.js +185 -0
- package/lib/receipts.js +65 -0
- package/lib/refs.js +192 -0
- package/lib/service.js +202 -0
- package/lib/trash.js +250 -0
- package/locale/en.json +49 -0
- package/locale/zh.json +49 -0
- package/package.json +57 -3
|
@@ -0,0 +1,848 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// 操作编排层:不依赖 typert,可在单元测试里用假 ctx 跑(真实宿主交互全部经 capability.js 探测)。
|
|
3
|
+
import { readdir, readFile, stat } from "node:fs/promises";
|
|
4
|
+
import { createRequire } from "node:module";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { setTimeout as delayMs } from "node:timers/promises";
|
|
7
|
+
import { createAudit } from "./audit.js";
|
|
8
|
+
import { describeCapabilities, probeCapabilities } from "./capability.js";
|
|
9
|
+
import { beginOperation, finishOperation, listPending } from "./journal.js";
|
|
10
|
+
import { directorySize, locateSession } from "./locate.js";
|
|
11
|
+
import { auditPath, requireSessionId, sessionsRoot, trashRoot } from "./paths.js";
|
|
12
|
+
import { buildPlan, planExecutable, summarizePlan } from "./plan.js";
|
|
13
|
+
import { listReceipts, writeReceipt } from "./receipts.js";
|
|
14
|
+
import { buildRefs } from "./refs.js";
|
|
15
|
+
import { listEntries, moveIntoTrash, purgeEntry, readEntry, restoreEntry } from "./trash.js";
|
|
16
|
+
|
|
17
|
+
const nodeRequire = createRequire(import.meta.url);
|
|
18
|
+
const pkg = nodeRequire("../package.json");
|
|
19
|
+
|
|
20
|
+
/** 等宿主把 flush / 取消落盘写完再动文件。 */
|
|
21
|
+
const SETTLE_MS = 200;
|
|
22
|
+
/** 移走之后复查原路径的时间点;活句柄迟到写入会在这个窗口里重建目录。 */
|
|
23
|
+
const REVIVE_CHECK_MS = 1500;
|
|
24
|
+
|
|
25
|
+
/** @param {unknown} error @returns {string} */
|
|
26
|
+
function messageOf(error) {
|
|
27
|
+
return error instanceof Error ? error.message : String(error);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* @param {string} code
|
|
32
|
+
* @param {string} message
|
|
33
|
+
* @param {Record<string, unknown>} [details]
|
|
34
|
+
*/
|
|
35
|
+
function failure(code, message, details) {
|
|
36
|
+
return Object.assign(new Error(message), { code, details });
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* 把 host 的活动条目归一成 { kind, count, labels, ids }。
|
|
41
|
+
* @param {unknown[]} raw
|
|
42
|
+
* @returns {{ kind: string, count: number, labels: string[], ids: string[] }[]}
|
|
43
|
+
*/
|
|
44
|
+
export function normalizeActivity(raw) {
|
|
45
|
+
/** @type {Map<string, { kind: string, count: number, labels: string[], ids: string[] }>} */
|
|
46
|
+
const groups = new Map();
|
|
47
|
+
for (const entry of Array.isArray(raw) ? raw : []) {
|
|
48
|
+
const kind = String(/** @type {any} */ (entry)?.kind ?? "other");
|
|
49
|
+
const items = Array.isArray(/** @type {any} */ (entry)?.items)
|
|
50
|
+
? /** @type {any} */ (entry).items
|
|
51
|
+
: [];
|
|
52
|
+
const group = groups.get(kind) ?? { kind, count: 0, labels: [], ids: [] };
|
|
53
|
+
for (const item of items) {
|
|
54
|
+
group.count += 1;
|
|
55
|
+
const label =
|
|
56
|
+
typeof item?.label === "string" && item.label.length > 0
|
|
57
|
+
? item.label
|
|
58
|
+
: String(item?.id ?? "");
|
|
59
|
+
if (label) group.labels.push(label);
|
|
60
|
+
if (typeof item?.id === "string") group.ids.push(item.id);
|
|
61
|
+
}
|
|
62
|
+
groups.set(kind, group);
|
|
63
|
+
}
|
|
64
|
+
return [...groups.values()].filter((group) => group.count > 0);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* @param {{ ctx: any, dataRoot: string, logger: any }} options
|
|
69
|
+
*/
|
|
70
|
+
export function createOperations({ ctx, dataRoot, logger }) {
|
|
71
|
+
const caps = probeCapabilities(ctx);
|
|
72
|
+
const audit = createAudit(dataRoot);
|
|
73
|
+
const refs = buildRefs(caps, logger);
|
|
74
|
+
/** 当前进程里正在操作中的会话,防止双击/并发把同一个会话删两遍。 */
|
|
75
|
+
const inFlight = new Set();
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* 收集一份完整事实并生成 Plan。
|
|
79
|
+
* @param {unknown} sessionIdRaw
|
|
80
|
+
*/
|
|
81
|
+
async function makePlan(sessionIdRaw) {
|
|
82
|
+
const sessionId = requireSessionId(sessionIdRaw);
|
|
83
|
+
/** @type {string[]} */
|
|
84
|
+
const notes = [];
|
|
85
|
+
|
|
86
|
+
let stored;
|
|
87
|
+
try {
|
|
88
|
+
stored = await caps.services.persistence?.stat?.(sessionId);
|
|
89
|
+
} catch (error) {
|
|
90
|
+
notes.push("stat failed: " + messageOf(error));
|
|
91
|
+
}
|
|
92
|
+
const liveEntry = caps.services.sessions?.get?.(sessionId);
|
|
93
|
+
if (!stored && !liveEntry) {
|
|
94
|
+
throw failure("session/not-found", "no session named " + sessionId, { sessionId });
|
|
95
|
+
}
|
|
96
|
+
const header = stored?.header ?? liveEntry?.header ?? null;
|
|
97
|
+
|
|
98
|
+
/** @type {unknown[]} */
|
|
99
|
+
let rawActivity = [];
|
|
100
|
+
if (typeof ctx.waterfall === "function") {
|
|
101
|
+
try {
|
|
102
|
+
rawActivity = await ctx.waterfall("workspace/session-activity", { sessionId }, () => []);
|
|
103
|
+
} catch (error) {
|
|
104
|
+
notes.push("activity unavailable: " + messageOf(error));
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
const activity = normalizeActivity(rawActivity);
|
|
108
|
+
const subagents = activity.find((group) => group.kind === "subagent");
|
|
109
|
+
const children = (subagents?.ids ?? []).map((id, index) => ({
|
|
110
|
+
id,
|
|
111
|
+
title: subagents?.labels[index] ?? null,
|
|
112
|
+
}));
|
|
113
|
+
|
|
114
|
+
const located = await locateSession({
|
|
115
|
+
dataRoot,
|
|
116
|
+
sessionId,
|
|
117
|
+
header,
|
|
118
|
+
persistence: caps.services.persistence,
|
|
119
|
+
});
|
|
120
|
+
const location = located.location;
|
|
121
|
+
const ambiguous = located.ambiguous;
|
|
122
|
+
|
|
123
|
+
let sizeBytes = typeof stored?.sizeBytes === "number" ? stored.sizeBytes : null;
|
|
124
|
+
if (sizeBytes === null && location) {
|
|
125
|
+
sizeBytes = await directorySize(location.path).catch(() => null);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** @type {{ code: string, message: string }[]} */
|
|
129
|
+
const blockers = [];
|
|
130
|
+
if (caps.tier === "unknown") {
|
|
131
|
+
blockers.push({
|
|
132
|
+
code: "session-delete/unsupported-host",
|
|
133
|
+
message: "当前 DSH 版本缺少本插件依赖的核心接口,删除功能已禁用(只读模式)。",
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
if (!location) {
|
|
137
|
+
blockers.push(
|
|
138
|
+
ambiguous.length > 1
|
|
139
|
+
? {
|
|
140
|
+
code: "session-delete/ambiguous-location",
|
|
141
|
+
message: "同一会话在 " + ambiguous.length + " 个项目目录下都有副本,已拒绝操作。",
|
|
142
|
+
}
|
|
143
|
+
: {
|
|
144
|
+
code: "session-delete/location-unknown",
|
|
145
|
+
message: "找不到这个会话在磁盘上的位置(可能宿主换了目录布局)。",
|
|
146
|
+
},
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
if (liveEntry && !caps.checks["event.session-stop"]) {
|
|
150
|
+
blockers.push({
|
|
151
|
+
code: "session-delete/live-unsupported",
|
|
152
|
+
message: "会话正在运行,但当前宿主不支持安全停止,已拒绝删除。",
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const plan = buildPlan({
|
|
157
|
+
sessionId,
|
|
158
|
+
title: typeof header?.title === "string" ? header.title : null,
|
|
159
|
+
cwd: typeof header?.cwd === "string" ? header.cwd : null,
|
|
160
|
+
sizeBytes,
|
|
161
|
+
live: Boolean(liveEntry),
|
|
162
|
+
activity: activity.map(({ kind, count, labels }) => ({ kind, count, labels })),
|
|
163
|
+
children,
|
|
164
|
+
location,
|
|
165
|
+
trashPath: null,
|
|
166
|
+
removes: refs.map((ref) => ({ id: ref.id, label: ref.label, tier: ref.tier })),
|
|
167
|
+
blockers,
|
|
168
|
+
});
|
|
169
|
+
return { plan, stored, header, location, refs, notes };
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* 移走之后复查一次原路径;目录若被迟到写入重建,就再移一次并记审计。
|
|
174
|
+
* @param {string} sessionId
|
|
175
|
+
* @param {string} originalPath
|
|
176
|
+
*/
|
|
177
|
+
function scheduleReviveCheck(sessionId, originalPath) {
|
|
178
|
+
const timer = setTimeout(async () => {
|
|
179
|
+
try {
|
|
180
|
+
const { stat } = await import("node:fs/promises");
|
|
181
|
+
const exists = await stat(originalPath)
|
|
182
|
+
.then(() => true)
|
|
183
|
+
.catch(() => false);
|
|
184
|
+
if (!exists) return;
|
|
185
|
+
await audit.append({
|
|
186
|
+
action: "trash",
|
|
187
|
+
result: "ok",
|
|
188
|
+
sessionId,
|
|
189
|
+
operator: "system",
|
|
190
|
+
detail: "会话目录在移走后被重建,已记录(复活守卫)",
|
|
191
|
+
});
|
|
192
|
+
logger.warn("session-delete: session " + sessionId + " was recreated after deletion");
|
|
193
|
+
} catch (error) {
|
|
194
|
+
logger.warn("session-delete: revive check failed: " + messageOf(error));
|
|
195
|
+
}
|
|
196
|
+
}, REVIVE_CHECK_MS);
|
|
197
|
+
/** @type {any} */ (timer).unref?.();
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* @param {string} sessionIdRaw
|
|
202
|
+
* @param {{ digest?: string, title?: string | null, operator?: string }} request
|
|
203
|
+
*/
|
|
204
|
+
async function trash(sessionIdRaw, request = {}) {
|
|
205
|
+
const loaded = await makePlan(sessionIdRaw);
|
|
206
|
+
const { plan, location, header } = loaded;
|
|
207
|
+
if (request.digest && request.digest !== plan.digest) {
|
|
208
|
+
throw failure(
|
|
209
|
+
"session-delete/stale-plan",
|
|
210
|
+
"会话状态在确认期间发生了变化,请重新查看影响面。",
|
|
211
|
+
{
|
|
212
|
+
expected: plan.digest,
|
|
213
|
+
actual: request.digest,
|
|
214
|
+
},
|
|
215
|
+
);
|
|
216
|
+
}
|
|
217
|
+
if (!planExecutable(plan)) {
|
|
218
|
+
await audit.append({
|
|
219
|
+
action: "trash",
|
|
220
|
+
result: "refused",
|
|
221
|
+
sessionId: plan.sessionId,
|
|
222
|
+
operator: request.operator ?? "ui",
|
|
223
|
+
detail: plan.blockers.map((b) => b.code).join(","),
|
|
224
|
+
});
|
|
225
|
+
throw failure("session-delete/blocked", plan.blockers[0].message, {
|
|
226
|
+
blockers: plan.blockers,
|
|
227
|
+
plan,
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
if (!location) throw failure("session-delete/location-unknown", "没有可移动的会话目录");
|
|
231
|
+
if (inFlight.has(plan.sessionId)) {
|
|
232
|
+
throw failure("session-delete/busy", "这个会话正在被另一个删除操作处理。");
|
|
233
|
+
}
|
|
234
|
+
inFlight.add(plan.sessionId);
|
|
235
|
+
|
|
236
|
+
const record = await beginOperation({
|
|
237
|
+
dataRoot,
|
|
238
|
+
action: "trash",
|
|
239
|
+
extra: { sessionId: plan.sessionId, digest: plan.digest, operator: request.operator ?? "ui" },
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
let moved = false;
|
|
243
|
+
let entryId = "";
|
|
244
|
+
try {
|
|
245
|
+
// 1. 先归档:归档集合就是 provider 的 agent/pre-step 闸门。
|
|
246
|
+
if (caps.checks["workspace.archive"]) {
|
|
247
|
+
await caps.services.workspace.archiveSession(plan.sessionId, { stopActivity: true });
|
|
248
|
+
}
|
|
249
|
+
// 2. 官方停止通道(跑着的轮次、子代理、后台任务、提醒)。
|
|
250
|
+
if (caps.checks["event.session-stop"]) {
|
|
251
|
+
await ctx.parallel("workspace/session-stop", { sessionId: plan.sessionId });
|
|
252
|
+
}
|
|
253
|
+
// 3. 落盘并等写入稳定。
|
|
254
|
+
const live = caps.services.sessions?.get?.(plan.sessionId);
|
|
255
|
+
if (live && caps.checks["sessions.flush"]) await caps.services.sessions.flush(live);
|
|
256
|
+
await delayMs(SETTLE_MS);
|
|
257
|
+
|
|
258
|
+
// 4. 记录引用状态,供恢复时还原。
|
|
259
|
+
/** @type {Record<string, any>} */
|
|
260
|
+
const snapshots = {};
|
|
261
|
+
for (const ref of refs) {
|
|
262
|
+
if (typeof ref.snapshot !== "function") continue;
|
|
263
|
+
try {
|
|
264
|
+
snapshots[ref.id] = await ref.snapshot(plan.sessionId);
|
|
265
|
+
} catch (error) {
|
|
266
|
+
logger.warn("session-delete: snapshot " + ref.id + " failed: " + messageOf(error));
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// 5. 移入回收站(原子 rename)。
|
|
271
|
+
const movedResult = await moveIntoTrash({
|
|
272
|
+
dataRoot,
|
|
273
|
+
sessionId: plan.sessionId,
|
|
274
|
+
sourceDir: location.path,
|
|
275
|
+
meta: {
|
|
276
|
+
title:
|
|
277
|
+
plan.title ??
|
|
278
|
+
(typeof request.title === "string" && request.title.length > 0 ? request.title : null),
|
|
279
|
+
cwd: typeof header?.cwd === "string" ? header.cwd : null,
|
|
280
|
+
bytes: plan.sizeBytes ?? 0,
|
|
281
|
+
live: plan.live,
|
|
282
|
+
children: plan.children,
|
|
283
|
+
workspaceIds: snapshots["workspace-slot"]?.workspaceIds ?? [],
|
|
284
|
+
pinned: null,
|
|
285
|
+
},
|
|
286
|
+
});
|
|
287
|
+
moved = true;
|
|
288
|
+
entryId = movedResult.entryId;
|
|
289
|
+
|
|
290
|
+
// 6. 摘掉所有还指向它的引用。
|
|
291
|
+
/** @type {{ id: string, label: string, status: string, detail?: string }[]} */
|
|
292
|
+
const removed = [];
|
|
293
|
+
for (const ref of refs) {
|
|
294
|
+
if (typeof ref.remove !== "function" || ref.tier === "unknown") {
|
|
295
|
+
removed.push({
|
|
296
|
+
id: ref.id,
|
|
297
|
+
label: ref.label,
|
|
298
|
+
status: "skipped",
|
|
299
|
+
detail: "当前宿主不提供该接口",
|
|
300
|
+
});
|
|
301
|
+
continue;
|
|
302
|
+
}
|
|
303
|
+
try {
|
|
304
|
+
await ref.remove(plan.sessionId, snapshots[ref.id] ?? {});
|
|
305
|
+
removed.push({ id: ref.id, label: ref.label, status: "ok" });
|
|
306
|
+
} catch (error) {
|
|
307
|
+
removed.push({
|
|
308
|
+
id: ref.id,
|
|
309
|
+
label: ref.label,
|
|
310
|
+
status: "failed",
|
|
311
|
+
detail: messageOf(error),
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
// 7. 复活复查 + 对账回执。
|
|
317
|
+
scheduleReviveCheck(plan.sessionId, location.path);
|
|
318
|
+
const checks = await reconcile(plan.sessionId, { skipDirCheck: true });
|
|
319
|
+
await finishOperation({ dataRoot, id: record.id, state: "done" });
|
|
320
|
+
await audit.append({
|
|
321
|
+
action: "trash",
|
|
322
|
+
result: "ok",
|
|
323
|
+
sessionId: plan.sessionId,
|
|
324
|
+
entryId,
|
|
325
|
+
operator: request.operator ?? "ui",
|
|
326
|
+
detail: summarizePlan(plan),
|
|
327
|
+
});
|
|
328
|
+
const receiptId = await writeReceipt(dataRoot, {
|
|
329
|
+
action: "trash",
|
|
330
|
+
at: new Date().toISOString(),
|
|
331
|
+
sessionId: plan.sessionId,
|
|
332
|
+
entryId,
|
|
333
|
+
title: plan.title ?? (typeof request.title === "string" ? request.title : null),
|
|
334
|
+
sizeBytes: plan.sizeBytes,
|
|
335
|
+
digest: plan.digest,
|
|
336
|
+
live: plan.live,
|
|
337
|
+
children: plan.children,
|
|
338
|
+
removed,
|
|
339
|
+
checks,
|
|
340
|
+
});
|
|
341
|
+
return {
|
|
342
|
+
ok: true,
|
|
343
|
+
entryId,
|
|
344
|
+
receiptId,
|
|
345
|
+
sessionId: plan.sessionId,
|
|
346
|
+
digest: plan.digest,
|
|
347
|
+
title: plan.title ?? (typeof request.title === "string" ? request.title : null),
|
|
348
|
+
sizeBytes: plan.sizeBytes,
|
|
349
|
+
removed,
|
|
350
|
+
checks,
|
|
351
|
+
};
|
|
352
|
+
} catch (error) {
|
|
353
|
+
if (!moved) {
|
|
354
|
+
try {
|
|
355
|
+
await caps.services.workspace?.unarchiveSession?.(plan.sessionId);
|
|
356
|
+
} catch {
|
|
357
|
+
// 尽力而为。
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
await finishOperation({ dataRoot, id: record.id, state: "failed", detail: messageOf(error) });
|
|
361
|
+
await audit.append({
|
|
362
|
+
action: "trash",
|
|
363
|
+
result: "failed",
|
|
364
|
+
sessionId: plan.sessionId,
|
|
365
|
+
operator: request.operator ?? "ui",
|
|
366
|
+
detail: messageOf(error),
|
|
367
|
+
});
|
|
368
|
+
throw failure("session-delete/failed", "删除失败:" + messageOf(error), {
|
|
369
|
+
partial: moved,
|
|
370
|
+
entryId: moved ? entryId : null,
|
|
371
|
+
});
|
|
372
|
+
} finally {
|
|
373
|
+
inFlight.delete(plan.sessionId);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/** @param {number} [limit] */
|
|
378
|
+
async function auditLog(limit = 100) {
|
|
379
|
+
return { path: auditPath(dataRoot), entries: await audit.read(limit) };
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
async function list() {
|
|
383
|
+
const listed = await listEntries(dataRoot);
|
|
384
|
+
const pending = await listPending(dataRoot);
|
|
385
|
+
return {
|
|
386
|
+
trashRoot: trashRoot(dataRoot),
|
|
387
|
+
entries: listed.entries,
|
|
388
|
+
unknown: listed.unknown,
|
|
389
|
+
pending: pending.map((record) => ({
|
|
390
|
+
id: record.id,
|
|
391
|
+
action: record.action,
|
|
392
|
+
sessionId: record.sessionId,
|
|
393
|
+
})),
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/**
|
|
398
|
+
* @param {string} entryId
|
|
399
|
+
* @param {{ operator?: string }} [request]
|
|
400
|
+
*/
|
|
401
|
+
async function restore(entryId, request = {}) {
|
|
402
|
+
const meta = await readEntry(dataRoot, entryId);
|
|
403
|
+
const record = await beginOperation({
|
|
404
|
+
dataRoot,
|
|
405
|
+
action: "restore",
|
|
406
|
+
extra: { sessionId: meta.sessionId, entryId },
|
|
407
|
+
});
|
|
408
|
+
try {
|
|
409
|
+
const restored = await restoreEntry({ dataRoot, entryId });
|
|
410
|
+
try {
|
|
411
|
+
await caps.services.workspace?.unarchiveSession?.(meta.sessionId);
|
|
412
|
+
} catch {
|
|
413
|
+
// 恢复失败不阻断:文件已经回去了。
|
|
414
|
+
}
|
|
415
|
+
for (const ref of refs) {
|
|
416
|
+
if (typeof ref.restore !== "function") continue;
|
|
417
|
+
try {
|
|
418
|
+
await ref.restore(meta.sessionId, {
|
|
419
|
+
workspaceIds: meta.workspaceIds,
|
|
420
|
+
pinned: meta.pinned,
|
|
421
|
+
});
|
|
422
|
+
} catch (error) {
|
|
423
|
+
logger.warn("session-delete: restore " + ref.id + " failed: " + messageOf(error));
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
await finishOperation({ dataRoot, id: record.id, state: "done" });
|
|
427
|
+
await audit.append({
|
|
428
|
+
action: "restore",
|
|
429
|
+
result: "ok",
|
|
430
|
+
sessionId: meta.sessionId,
|
|
431
|
+
entryId,
|
|
432
|
+
operator: request.operator ?? "ui",
|
|
433
|
+
});
|
|
434
|
+
const receiptId = await writeReceipt(dataRoot, {
|
|
435
|
+
action: "restore",
|
|
436
|
+
at: new Date().toISOString(),
|
|
437
|
+
sessionId: meta.sessionId,
|
|
438
|
+
entryId,
|
|
439
|
+
title: meta.title,
|
|
440
|
+
restoredTo: restored.restoredTo,
|
|
441
|
+
});
|
|
442
|
+
return { ok: true, sessionId: meta.sessionId, restoredTo: restored.restoredTo, receiptId };
|
|
443
|
+
} catch (error) {
|
|
444
|
+
await finishOperation({ dataRoot, id: record.id, state: "failed", detail: messageOf(error) });
|
|
445
|
+
await audit.append({
|
|
446
|
+
action: "restore",
|
|
447
|
+
result: "failed",
|
|
448
|
+
sessionId: meta.sessionId,
|
|
449
|
+
entryId,
|
|
450
|
+
operator: request.operator ?? "ui",
|
|
451
|
+
detail: messageOf(error),
|
|
452
|
+
});
|
|
453
|
+
throw failure("session-delete/restore-failed", "恢复失败:" + messageOf(error));
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/**
|
|
458
|
+
* @param {string} entryId
|
|
459
|
+
* @param {{ operator?: string }} [request]
|
|
460
|
+
*/
|
|
461
|
+
async function purge(entryId, request = {}) {
|
|
462
|
+
const meta = await readEntry(dataRoot, entryId);
|
|
463
|
+
const record = await beginOperation({
|
|
464
|
+
dataRoot,
|
|
465
|
+
action: "purge",
|
|
466
|
+
extra: { entryId, sessionId: meta.sessionId },
|
|
467
|
+
});
|
|
468
|
+
try {
|
|
469
|
+
const result = await purgeEntry({ dataRoot, entryId });
|
|
470
|
+
await finishOperation({ dataRoot, id: record.id, state: "done" });
|
|
471
|
+
await audit.append({
|
|
472
|
+
action: "purge",
|
|
473
|
+
result: "ok",
|
|
474
|
+
entryId,
|
|
475
|
+
operator: request.operator ?? "ui",
|
|
476
|
+
detail: "释放约 " + result.bytes + " 字节",
|
|
477
|
+
});
|
|
478
|
+
const receiptId = await writeReceipt(dataRoot, {
|
|
479
|
+
action: "purge",
|
|
480
|
+
at: new Date().toISOString(),
|
|
481
|
+
sessionId: meta.sessionId,
|
|
482
|
+
entryId,
|
|
483
|
+
title: meta.title,
|
|
484
|
+
bytes: result.bytes,
|
|
485
|
+
});
|
|
486
|
+
return { ok: true, bytes: result.bytes, sessionId: meta.sessionId, receiptId };
|
|
487
|
+
} catch (error) {
|
|
488
|
+
await finishOperation({ dataRoot, id: record.id, state: "failed", detail: messageOf(error) });
|
|
489
|
+
await audit.append({
|
|
490
|
+
action: "purge",
|
|
491
|
+
result: "failed",
|
|
492
|
+
entryId,
|
|
493
|
+
operator: request.operator ?? "ui",
|
|
494
|
+
detail: messageOf(error),
|
|
495
|
+
});
|
|
496
|
+
throw failure("session-delete/purge-failed", "彻底删除失败:" + messageOf(error));
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/**
|
|
501
|
+
* 删除后对账:目录是否消失、每处引用是否还在。
|
|
502
|
+
* @param {string} sessionIdRaw
|
|
503
|
+
* @param {{ skipDirCheck?: boolean }} [options]
|
|
504
|
+
*/
|
|
505
|
+
async function reconcile(sessionIdRaw, options = {}) {
|
|
506
|
+
const sessionId = requireSessionId(sessionIdRaw);
|
|
507
|
+
/** @type {{ id: string, label: string, status: "ok" | "failed" | "skipped", detail: string }[]} */
|
|
508
|
+
const checks = [];
|
|
509
|
+
|
|
510
|
+
if (options.skipDirCheck) {
|
|
511
|
+
checks.push({ id: "session-dir", label: "会话目录", status: "ok", detail: "已移入回收站" });
|
|
512
|
+
} else {
|
|
513
|
+
const located = await locateSession({
|
|
514
|
+
dataRoot,
|
|
515
|
+
sessionId,
|
|
516
|
+
header: undefined,
|
|
517
|
+
persistence: caps.services.persistence,
|
|
518
|
+
});
|
|
519
|
+
checks.push(
|
|
520
|
+
located.location
|
|
521
|
+
? {
|
|
522
|
+
id: "session-dir",
|
|
523
|
+
label: "会话目录",
|
|
524
|
+
status: "failed",
|
|
525
|
+
detail: "目录仍存在:" + located.location.path,
|
|
526
|
+
}
|
|
527
|
+
: { id: "session-dir", label: "会话目录", status: "ok", detail: "会话目录已不存在" },
|
|
528
|
+
);
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
for (const ref of refs) {
|
|
532
|
+
if (typeof ref.inspect !== "function") continue;
|
|
533
|
+
try {
|
|
534
|
+
checks.push(await ref.inspect(sessionId));
|
|
535
|
+
} catch (error) {
|
|
536
|
+
checks.push({ id: ref.id, label: ref.label, status: "skipped", detail: messageOf(error) });
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
return checks;
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
/**
|
|
543
|
+
* 读取 workspace 存储快照(只读)。这是文件级兜底:
|
|
544
|
+
* 归档/置顶集合没有公开的读接口,只能读 storages/workspace.json。
|
|
545
|
+
* @returns {Promise<{ ok: boolean, reason?: string, archivedIds: string[], pinnedIds: string[],
|
|
546
|
+
* workspaces: { id: string, sessionIds: string[] }[] }>}
|
|
547
|
+
*/
|
|
548
|
+
async function readWorkspaceState() {
|
|
549
|
+
const file = join(dataRoot, "storages", "workspace.json");
|
|
550
|
+
let parsed;
|
|
551
|
+
try {
|
|
552
|
+
parsed = JSON.parse(await readFile(file, "utf8"));
|
|
553
|
+
} catch (error) {
|
|
554
|
+
return {
|
|
555
|
+
ok: false,
|
|
556
|
+
reason: "无法读取 " + file + ":" + messageOf(error),
|
|
557
|
+
archivedIds: [],
|
|
558
|
+
pinnedIds: [],
|
|
559
|
+
workspaces: [],
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
const global = parsed?.global ?? {};
|
|
563
|
+
const tables = parsed?.tables ?? {};
|
|
564
|
+
const workspaces = Object.entries(tables.workspaces ?? {}).map(([id, value]) => ({
|
|
565
|
+
id,
|
|
566
|
+
sessionIds: Array.isArray(value?.sessionIds) ? value.sessionIds.map(String) : [],
|
|
567
|
+
}));
|
|
568
|
+
return {
|
|
569
|
+
ok: true,
|
|
570
|
+
archivedIds: Array.isArray(global.archivedSessionIds)
|
|
571
|
+
? global.archivedSessionIds.map(String)
|
|
572
|
+
: [],
|
|
573
|
+
pinnedIds: Array.isArray(global.pinnedSessionIds) ? global.pinnedSessionIds.map(String) : [],
|
|
574
|
+
workspaces,
|
|
575
|
+
};
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/**
|
|
579
|
+
* 全库体检:找出指向已不存在会话的登记条目。只读,不修改任何东西。
|
|
580
|
+
*/
|
|
581
|
+
async function scanHealth() {
|
|
582
|
+
if (!caps.checks["persistence.list"]) {
|
|
583
|
+
return {
|
|
584
|
+
ok: false,
|
|
585
|
+
reason: "当前宿主没有 sessionPersistence.list,无法枚举已存会话。",
|
|
586
|
+
findings: [],
|
|
587
|
+
inventory: null,
|
|
588
|
+
};
|
|
589
|
+
}
|
|
590
|
+
const persisted = (await caps.services.persistence.list()) ?? [];
|
|
591
|
+
const storedIds = new Set(
|
|
592
|
+
persisted
|
|
593
|
+
.map((/** @type {any} */ entry) => String(entry?.id ?? entry?.header?.id ?? ""))
|
|
594
|
+
.filter(Boolean),
|
|
595
|
+
);
|
|
596
|
+
const liveIds = new Set();
|
|
597
|
+
try {
|
|
598
|
+
for (const id of caps.services.sessions?.store?.keys?.() ?? []) liveIds.add(String(id));
|
|
599
|
+
} catch {
|
|
600
|
+
/* store 不可枚举时忽略 */
|
|
601
|
+
}
|
|
602
|
+
const known = new Set([...storedIds, ...liveIds]);
|
|
603
|
+
|
|
604
|
+
const state = await readWorkspaceState();
|
|
605
|
+
/** @type {{ id: string, label: string, severity: "warn" | "info", items: any[] }[]} */
|
|
606
|
+
const findings = [];
|
|
607
|
+
/** @type {{ archived: string[], pinned: string[], workspace: { workspaceId: string, sessionId: string }[] }} */
|
|
608
|
+
const cleanable = { archived: [], pinned: [], workspace: [] };
|
|
609
|
+
|
|
610
|
+
if (state.ok) {
|
|
611
|
+
const archivedGhosts = state.archivedIds.filter((id) => !known.has(id));
|
|
612
|
+
const pinnedGhosts = state.pinnedIds.filter((id) => !known.has(id));
|
|
613
|
+
const workspaceGhosts = [];
|
|
614
|
+
for (const workspace of state.workspaces) {
|
|
615
|
+
for (const sessionId of workspace.sessionIds) {
|
|
616
|
+
if (!known.has(sessionId)) workspaceGhosts.push({ workspaceId: workspace.id, sessionId });
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
if (archivedGhosts.length > 0) {
|
|
620
|
+
findings.push({
|
|
621
|
+
id: "archived-ghost",
|
|
622
|
+
label: "归档集合里的失效条目",
|
|
623
|
+
severity: "warn",
|
|
624
|
+
items: archivedGhosts,
|
|
625
|
+
});
|
|
626
|
+
cleanable.archived = archivedGhosts;
|
|
627
|
+
}
|
|
628
|
+
if (pinnedGhosts.length > 0) {
|
|
629
|
+
findings.push({
|
|
630
|
+
id: "pinned-ghost",
|
|
631
|
+
label: "置顶集合里的失效条目",
|
|
632
|
+
severity: "warn",
|
|
633
|
+
items: pinnedGhosts,
|
|
634
|
+
});
|
|
635
|
+
cleanable.pinned = pinnedGhosts;
|
|
636
|
+
}
|
|
637
|
+
if (workspaceGhosts.length > 0) {
|
|
638
|
+
findings.push({
|
|
639
|
+
id: "workspace-ghost",
|
|
640
|
+
label: "工作区记账里的失效会话",
|
|
641
|
+
severity: "warn",
|
|
642
|
+
items: workspaceGhosts,
|
|
643
|
+
});
|
|
644
|
+
cleanable.workspace = workspaceGhosts;
|
|
645
|
+
}
|
|
646
|
+
} else {
|
|
647
|
+
findings.push({
|
|
648
|
+
id: "workspace-unreadable",
|
|
649
|
+
label: "无法读取 workspace 存储",
|
|
650
|
+
severity: "info",
|
|
651
|
+
items: [state.reason],
|
|
652
|
+
});
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
// 孤儿会话目录:磁盘上有、但持久层与 live 都不认识。仅报告,绝不自动删。
|
|
656
|
+
/** @type {string[]} */
|
|
657
|
+
const orphanDirs = [];
|
|
658
|
+
try {
|
|
659
|
+
const projects = await readdir(sessionsRoot(dataRoot), { withFileTypes: true });
|
|
660
|
+
for (const project of projects) {
|
|
661
|
+
if (!project.isDirectory()) continue;
|
|
662
|
+
const entries = await readdir(join(sessionsRoot(dataRoot), project.name), {
|
|
663
|
+
withFileTypes: true,
|
|
664
|
+
});
|
|
665
|
+
for (const entry of entries) {
|
|
666
|
+
if (!entry.isDirectory()) continue;
|
|
667
|
+
const looksLikeSession =
|
|
668
|
+
/^[A-Za-z0-9][A-Za-z0-9_$.-]{0,127}$/u.test(entry.name) || entry.name.includes("~");
|
|
669
|
+
if (looksLikeSession && !known.has(entry.name)) {
|
|
670
|
+
orphanDirs.push(join(project.name, entry.name));
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
} catch {
|
|
675
|
+
/* sessions 根不存在时忽略 */
|
|
676
|
+
}
|
|
677
|
+
if (orphanDirs.length > 0) {
|
|
678
|
+
findings.push({
|
|
679
|
+
id: "orphan-session-dir",
|
|
680
|
+
label: "磁盘上的孤儿会话目录(仅报告)",
|
|
681
|
+
severity: "info",
|
|
682
|
+
items: orphanDirs,
|
|
683
|
+
});
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
// 回收站一致性:有 meta 没 data
|
|
687
|
+
/** @type {string[]} */
|
|
688
|
+
const brokenTrash = [];
|
|
689
|
+
const listed = await listEntries(dataRoot);
|
|
690
|
+
for (const entry of listed.entries) {
|
|
691
|
+
const exists = await stat(join(trashRoot(dataRoot), entry.entryId, "data"))
|
|
692
|
+
.then((value) => value.isDirectory())
|
|
693
|
+
.catch(() => false);
|
|
694
|
+
if (!exists) brokenTrash.push(entry.entryId);
|
|
695
|
+
}
|
|
696
|
+
if (brokenTrash.length > 0 || listed.unknown.length > 0) {
|
|
697
|
+
findings.push({
|
|
698
|
+
id: "trash-inconsistent",
|
|
699
|
+
label: "回收站条目与实际数据不一致",
|
|
700
|
+
severity: "warn",
|
|
701
|
+
items: [...brokenTrash, ...listed.unknown],
|
|
702
|
+
});
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
const pending = await listPending(dataRoot);
|
|
706
|
+
if (pending.length > 0) {
|
|
707
|
+
findings.push({
|
|
708
|
+
id: "pending-operation",
|
|
709
|
+
label: "未完成的操作(重启后自愈)",
|
|
710
|
+
severity: "info",
|
|
711
|
+
items: pending.map((record) => record.id),
|
|
712
|
+
});
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
return {
|
|
716
|
+
ok: true,
|
|
717
|
+
generatedAt: new Date().toISOString(),
|
|
718
|
+
inventory: {
|
|
719
|
+
stored: storedIds.size,
|
|
720
|
+
live: liveIds.size,
|
|
721
|
+
archived: state.archivedIds.length,
|
|
722
|
+
pinned: state.pinnedIds.length,
|
|
723
|
+
workspaces: state.workspaces.length,
|
|
724
|
+
trash: listed.entries.length,
|
|
725
|
+
pending: pending.length,
|
|
726
|
+
},
|
|
727
|
+
findings,
|
|
728
|
+
cleanable: {
|
|
729
|
+
archived: cleanable.archived.length,
|
|
730
|
+
pinned: cleanable.pinned.length,
|
|
731
|
+
workspace: cleanable.workspace.length,
|
|
732
|
+
total: cleanable.archived.length + cleanable.pinned.length + cleanable.workspace.length,
|
|
733
|
+
},
|
|
734
|
+
};
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
/**
|
|
738
|
+
* 清理体检发现的失效引用(只动登记表,不碰会话文件)。
|
|
739
|
+
* @param {{ classes?: string[], operator?: string }} [request]
|
|
740
|
+
*/
|
|
741
|
+
async function cleanHealth(request = {}) {
|
|
742
|
+
const classes = Array.isArray(request.classes)
|
|
743
|
+
? request.classes
|
|
744
|
+
: ["archived", "pinned", "workspace"];
|
|
745
|
+
const scan = await scanHealth();
|
|
746
|
+
if (!scan.ok)
|
|
747
|
+
throw failure(
|
|
748
|
+
"session-delete/health-unavailable",
|
|
749
|
+
"无法体检:" + (scan.reason ?? "未知原因"),
|
|
750
|
+
);
|
|
751
|
+
const state = await readWorkspaceState();
|
|
752
|
+
const counts = { archived: 0, pinned: 0, workspace: 0 };
|
|
753
|
+
/** @type {string[]} */
|
|
754
|
+
const errors = [];
|
|
755
|
+
if (classes.includes("archived")) {
|
|
756
|
+
for (const id of state.archivedIds) {
|
|
757
|
+
if (scan.findings.find((f) => f.id === "archived-ghost")?.items.includes(id) !== true)
|
|
758
|
+
continue;
|
|
759
|
+
try {
|
|
760
|
+
await caps.services.workspace?.unarchiveSession?.(id);
|
|
761
|
+
counts.archived += 1;
|
|
762
|
+
} catch (error) {
|
|
763
|
+
errors.push("unarchive " + id + ": " + messageOf(error));
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
if (classes.includes("pinned")) {
|
|
768
|
+
for (const id of state.pinnedIds) {
|
|
769
|
+
if (scan.findings.find((f) => f.id === "pinned-ghost")?.items.includes(id) !== true)
|
|
770
|
+
continue;
|
|
771
|
+
try {
|
|
772
|
+
await caps.services.workspace?.unpinSession?.(id);
|
|
773
|
+
counts.pinned += 1;
|
|
774
|
+
} catch (error) {
|
|
775
|
+
errors.push("unpin " + id + ": " + messageOf(error));
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
if (classes.includes("workspace")) {
|
|
780
|
+
const ghost = scan.findings.find((f) => f.id === "workspace-ghost");
|
|
781
|
+
for (const item of ghost?.items ?? []) {
|
|
782
|
+
const workspace = (caps.services.workspace?.list?.() ?? []).find(
|
|
783
|
+
(/** @type {any} */ candidate) => String(candidate.id) === String(item.workspaceId),
|
|
784
|
+
);
|
|
785
|
+
if (!workspace || typeof workspace.detachSession !== "function") continue;
|
|
786
|
+
try {
|
|
787
|
+
await workspace.detachSession(item.sessionId);
|
|
788
|
+
counts.workspace += 1;
|
|
789
|
+
} catch (error) {
|
|
790
|
+
errors.push("detach " + item.sessionId + ": " + messageOf(error));
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
const total = counts.archived + counts.pinned + counts.workspace;
|
|
795
|
+
await audit.append({
|
|
796
|
+
action: "health",
|
|
797
|
+
result: errors.length > 0 ? "failed" : "ok",
|
|
798
|
+
operator: request.operator ?? "ui",
|
|
799
|
+
detail:
|
|
800
|
+
"清理失效引用 " +
|
|
801
|
+
total +
|
|
802
|
+
" 条" +
|
|
803
|
+
(errors.length > 0 ? ",失败 " + errors.length + " 条" : ""),
|
|
804
|
+
});
|
|
805
|
+
const receiptId = await writeReceipt(dataRoot, {
|
|
806
|
+
action: "health",
|
|
807
|
+
at: new Date().toISOString(),
|
|
808
|
+
cleaned: counts,
|
|
809
|
+
total,
|
|
810
|
+
errors,
|
|
811
|
+
});
|
|
812
|
+
return { ok: errors.length === 0, cleaned: counts, total, errors, receiptId };
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
async function health() {
|
|
816
|
+
const pending = await listPending(dataRoot);
|
|
817
|
+
return {
|
|
818
|
+
plugin: pkg.name,
|
|
819
|
+
version: pkg.version,
|
|
820
|
+
dataRoot,
|
|
821
|
+
sessionsRoot: sessionsRoot(dataRoot),
|
|
822
|
+
trashRoot: trashRoot(dataRoot),
|
|
823
|
+
capabilities: describeCapabilities(caps),
|
|
824
|
+
pending: pending.length,
|
|
825
|
+
readOnly: caps.tier === "unknown",
|
|
826
|
+
};
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
/** @param {number} [limit] */
|
|
830
|
+
async function receipts(limit = 50) {
|
|
831
|
+
return { entries: await listReceipts(dataRoot, limit) };
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
return {
|
|
835
|
+
caps,
|
|
836
|
+
health,
|
|
837
|
+
receipts,
|
|
838
|
+
scanHealth,
|
|
839
|
+
cleanHealth,
|
|
840
|
+
plan: /** @param {unknown} sessionId */ async (sessionId) => (await makePlan(sessionId)).plan,
|
|
841
|
+
trash,
|
|
842
|
+
list,
|
|
843
|
+
restore,
|
|
844
|
+
purge,
|
|
845
|
+
reconcile,
|
|
846
|
+
auditLog,
|
|
847
|
+
};
|
|
848
|
+
}
|