@kangyishuai/dsh-session-delete 0.5.0 → 0.6.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 +33 -25
- package/README.zh-CN.md +25 -17
- package/lib/agent-tool.js +39 -3
- package/lib/audit.js +1 -1
- package/lib/client.js +1061 -153
- package/lib/operations.js +496 -147
- package/lib/recovery.js +477 -0
- package/lib/refs.js +217 -6
- package/lib/restore.js +187 -0
- package/lib/service.js +105 -0
- package/lib/trash.js +157 -14
- package/lib/workspace-state.js +63 -0
- package/locale/en.json +23 -2
- package/locale/zh.json +23 -2
- package/package.json +1 -1
package/lib/operations.js
CHANGED
|
@@ -1,19 +1,22 @@
|
|
|
1
1
|
// @ts-check
|
|
2
2
|
// 操作编排层:不依赖 typert,可在单元测试里用假 ctx 跑(真实宿主交互全部经 capability.js 探测)。
|
|
3
|
-
import { readdir,
|
|
3
|
+
import { readdir, stat } from "node:fs/promises";
|
|
4
4
|
import { createRequire } from "node:module";
|
|
5
5
|
import { join } from "node:path";
|
|
6
6
|
import { setTimeout as delayMs } from "node:timers/promises";
|
|
7
7
|
import { createAudit } from "./audit.js";
|
|
8
8
|
import { describeCapabilities, probeCapabilities } from "./capability.js";
|
|
9
|
-
import { beginOperation, finishOperation, listPending } from "./journal.js";
|
|
9
|
+
import { beginOperation, finishOperation, listPending, updateOperation } from "./journal.js";
|
|
10
10
|
import { directorySize, locateSession } from "./locate.js";
|
|
11
11
|
import { auditPath, requireSessionId, sessionsRoot, trashRoot } from "./paths.js";
|
|
12
12
|
import { buildPlan, digestOfWorkspace, planExecutable, summarizePlan } from "./plan.js";
|
|
13
13
|
import { readPreferences, writePreferences } from "./preferences.js";
|
|
14
14
|
import { listReceipts, writeReceipt } from "./receipts.js";
|
|
15
|
-
import {
|
|
15
|
+
import { createRecovery } from "./recovery.js";
|
|
16
|
+
import { buildRefs, removeAllRefs, restoreAllRefs, snapshotAllRefs } from "./refs.js";
|
|
17
|
+
import { describeRestoreSummary, restoreSummary, verifyRestored } from "./restore.js";
|
|
16
18
|
import { listEntries, moveIntoTrash, purgeEntry, readEntry, restoreEntry } from "./trash.js";
|
|
19
|
+
import { readWorkspaceState } from "./workspace-state.js";
|
|
17
20
|
|
|
18
21
|
const nodeRequire = createRequire(import.meta.url);
|
|
19
22
|
const pkg = nodeRequire("../package.json");
|
|
@@ -77,11 +80,93 @@ export function normalizeActivity(raw) {
|
|
|
77
80
|
* @param {{ ctx: any, dataRoot: string, logger: any }} options
|
|
78
81
|
*/
|
|
79
82
|
export function createOperations({ ctx, dataRoot, logger }) {
|
|
80
|
-
|
|
83
|
+
/**
|
|
84
|
+
* 能力探测**不能一次性固化**(USIM-U3-02 的根因):桌面组合里 `workspaceRegistry`
|
|
85
|
+
* 与 `agents` 比 `sessionPersistence` 晚挂载,插件启动对账在后者可用时就跑,
|
|
86
|
+
* 探到的 caps 里 workspace 是 undefined —— 之后每次删除都跳过归档闸门/停止/工作区
|
|
87
|
+
* 记账,每次恢复都把 `workspace-archive` 报成「unarchiveSession unavailable」。
|
|
88
|
+
*
|
|
89
|
+
* 所以 caps 与引用适配器都是**可刷新**的:每次进入操作前重探一次(只是几次属性读取),
|
|
90
|
+
* 服务集合或门禁结果一变就**原地**重建 refs(原地重建让 createRecovery 早先拿到的
|
|
91
|
+
* 数组引用也跟着更新,不需要把 refs 传遍每一层)。
|
|
92
|
+
*
|
|
93
|
+
* 原地重建的前提:`buildRefs()` 的条目**数量与顺序必须稳定**(同一次宿主组合下)。
|
|
94
|
+
* 若以后新增按能力条件增删引用的适配器,就不能再用 length=0/push,要改成 getRefs()。
|
|
95
|
+
*/
|
|
96
|
+
let caps = probeCapabilities(ctx);
|
|
97
|
+
const refs = buildRefs(caps, logger, { dataRoot });
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* 影响引用适配器行为的探针结果。服务换了身份或门禁结论翻转都要重建适配器。
|
|
101
|
+
* @param {import("./capability.js").Capabilities} value
|
|
102
|
+
* @returns {unknown[]}
|
|
103
|
+
*/
|
|
104
|
+
function hostSignature(value) {
|
|
105
|
+
return [
|
|
106
|
+
value.services.persistence,
|
|
107
|
+
value.services.sessions,
|
|
108
|
+
value.services.workspace,
|
|
109
|
+
value.services.storageDomain,
|
|
110
|
+
value.services.agents,
|
|
111
|
+
value.checks["workspace.archive"],
|
|
112
|
+
value.checks["workspace.unarchive"],
|
|
113
|
+
value.checks["workspace.pin"],
|
|
114
|
+
value.checks["workspace.unpin"],
|
|
115
|
+
value.checks["workspace.list"],
|
|
116
|
+
value.checks["storage.domain"],
|
|
117
|
+
value.checks["sessions.detach"],
|
|
118
|
+
value.checks["agents.detach"],
|
|
119
|
+
value.checks["event.session-stop"],
|
|
120
|
+
];
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* 重探宿主能力;有变化就重建引用适配器(原地)。返回最新的 caps。
|
|
125
|
+
* @returns {import("./capability.js").Capabilities}
|
|
126
|
+
*/
|
|
127
|
+
function refreshHost() {
|
|
128
|
+
const next = probeCapabilities(ctx);
|
|
129
|
+
const before = hostSignature(caps);
|
|
130
|
+
const after = hostSignature(next);
|
|
131
|
+
let changed = before.length !== after.length;
|
|
132
|
+
for (let index = 0; !changed && index < before.length; index += 1) {
|
|
133
|
+
if (before[index] !== after[index]) changed = true;
|
|
134
|
+
}
|
|
135
|
+
caps = next;
|
|
136
|
+
if (changed) {
|
|
137
|
+
const rebuilt = buildRefs(caps, logger, { dataRoot });
|
|
138
|
+
refs.length = 0;
|
|
139
|
+
refs.push(...rebuilt);
|
|
140
|
+
}
|
|
141
|
+
return caps;
|
|
142
|
+
}
|
|
143
|
+
|
|
81
144
|
const audit = createAudit(dataRoot);
|
|
82
|
-
const refs = buildRefs(caps, logger);
|
|
83
145
|
/** 当前进程里正在操作中的会话,防止双击/并发把同一个会话删两遍。 */
|
|
84
146
|
const inFlight = new Set();
|
|
147
|
+
/** 上一次启动对账的结论(内存里一份,磁盘上另有审计)。 @type {any} */
|
|
148
|
+
let lastRecovery = null;
|
|
149
|
+
/** @type {Promise<any> | null} */
|
|
150
|
+
let recoveryInFlight = null;
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* 写审计。失败只降级成 logger 告警,绝不静默——但也不让审计故障阻断删除。
|
|
154
|
+
* @param {any} entry
|
|
155
|
+
*/
|
|
156
|
+
async function note(entry) {
|
|
157
|
+
const result = await audit.append(entry);
|
|
158
|
+
if (!result.ok) logger.warn(`session-delete: audit append failed: ${result.error}`);
|
|
159
|
+
return result;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const recovery = createRecovery({
|
|
163
|
+
dataRoot,
|
|
164
|
+
refs,
|
|
165
|
+
logger,
|
|
166
|
+
audit,
|
|
167
|
+
reconcile: (/** @type {string} */ sessionId, /** @type {any} */ options) =>
|
|
168
|
+
reconcile(sessionId, options),
|
|
169
|
+
});
|
|
85
170
|
|
|
86
171
|
/**
|
|
87
172
|
* 收集一份完整事实并生成 Plan。
|
|
@@ -92,6 +177,7 @@ export function createOperations({ ctx, dataRoot, logger }) {
|
|
|
92
177
|
* @param {{ all?: unknown[] }} [options] all = 预加载的 persistence.list()(工作区批量复用)
|
|
93
178
|
*/
|
|
94
179
|
async function makePlan(sessionIdRaw, options = {}) {
|
|
180
|
+
refreshHost();
|
|
95
181
|
const sessionId = requireSessionId(sessionIdRaw);
|
|
96
182
|
/** @type {string[]} */
|
|
97
183
|
const notes = [];
|
|
@@ -222,26 +308,21 @@ export function createOperations({ ctx, dataRoot, logger }) {
|
|
|
222
308
|
}
|
|
223
309
|
|
|
224
310
|
/**
|
|
225
|
-
*
|
|
226
|
-
*
|
|
311
|
+
* 移走之后复查一次原路径;目录若被迟到的写入重建,就**真的**再移一次(AUD-SD-07)。
|
|
312
|
+
* 只查一次、不循环:活句柄若持续写盘,由「未完成的操作」与体检暴露,而不是互相对抗。
|
|
313
|
+
* @param {import("./plan.js").Plan} plan
|
|
227
314
|
* @param {string} originalPath
|
|
315
|
+
* @param {string} entryId 本次生成的回收站条目;它被 restore/purge 后守卫必须放手(B2)。
|
|
228
316
|
*/
|
|
229
|
-
function scheduleReviveCheck(
|
|
317
|
+
function scheduleReviveCheck(plan, originalPath, entryId) {
|
|
230
318
|
const timer = setTimeout(async () => {
|
|
231
319
|
try {
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
await audit.append({
|
|
238
|
-
action: "trash",
|
|
239
|
-
result: "ok",
|
|
240
|
-
sessionId,
|
|
241
|
-
operator: "system",
|
|
242
|
-
detail: "会话目录在移走后被重建,已记录(复活守卫)",
|
|
320
|
+
await recovery.reviveGuard({
|
|
321
|
+
sessionId: plan.sessionId,
|
|
322
|
+
originalPath,
|
|
323
|
+
entryId,
|
|
324
|
+
meta: { title: plan.title, cwd: plan.cwd },
|
|
243
325
|
});
|
|
244
|
-
logger.warn(`session-delete: session ${sessionId} was recreated after deletion`);
|
|
245
326
|
} catch (error) {
|
|
246
327
|
logger.warn(`session-delete: revive check failed: ${messageOf(error)}`);
|
|
247
328
|
}
|
|
@@ -255,9 +336,30 @@ export function createOperations({ ctx, dataRoot, logger }) {
|
|
|
255
336
|
* all?: unknown[] }} request all = 预加载的 persistence.list()(工作区批量复用)
|
|
256
337
|
*/
|
|
257
338
|
async function trash(sessionIdRaw, request = {}) {
|
|
258
|
-
|
|
339
|
+
refreshHost();
|
|
340
|
+
const operator = request.operator ?? "ui";
|
|
341
|
+
/** @type {Awaited<ReturnType<typeof makePlan>>} */
|
|
342
|
+
let loaded;
|
|
343
|
+
try {
|
|
344
|
+
loaded = await makePlan(sessionIdRaw, { all: request.all });
|
|
345
|
+
} catch (error) {
|
|
346
|
+
// AUD-SD-04:plan 阶段的拒绝(not-found / invalid-id)同样是拒绝,必须进审计,
|
|
347
|
+
// 否则「一次拒绝都没有记录过」的取证缺口会一直在。
|
|
348
|
+
const code = /** @type {any} */ (error)?.code;
|
|
349
|
+
if (code === "session/not-found" || code === "session-delete/invalid-id") {
|
|
350
|
+
await note({ action: "trash", result: "refused", operator, detail: `plan:${code}` });
|
|
351
|
+
}
|
|
352
|
+
throw error;
|
|
353
|
+
}
|
|
259
354
|
const { plan, location, header } = loaded;
|
|
260
355
|
if (request.digest && request.digest !== plan.digest) {
|
|
356
|
+
await note({
|
|
357
|
+
action: "trash",
|
|
358
|
+
result: "refused",
|
|
359
|
+
sessionId: plan.sessionId,
|
|
360
|
+
operator,
|
|
361
|
+
detail: "stale-plan:会话状态在确认期间发生变化",
|
|
362
|
+
});
|
|
261
363
|
throw failure(
|
|
262
364
|
"session-delete/stale-plan",
|
|
263
365
|
"会话状态在确认期间发生了变化,请重新查看影响面。",
|
|
@@ -268,11 +370,11 @@ export function createOperations({ ctx, dataRoot, logger }) {
|
|
|
268
370
|
);
|
|
269
371
|
}
|
|
270
372
|
if (!planExecutable(plan)) {
|
|
271
|
-
await
|
|
373
|
+
await note({
|
|
272
374
|
action: "trash",
|
|
273
375
|
result: "refused",
|
|
274
376
|
sessionId: plan.sessionId,
|
|
275
|
-
operator
|
|
377
|
+
operator,
|
|
276
378
|
detail: plan.blockers.map((b) => b.code).join(","),
|
|
277
379
|
});
|
|
278
380
|
throw failure("session-delete/blocked", plan.blockers[0].message, {
|
|
@@ -287,7 +389,7 @@ export function createOperations({ ctx, dataRoot, logger }) {
|
|
|
287
389
|
if (request.cascade === true && request.child !== true) {
|
|
288
390
|
for (const child of plan.children) {
|
|
289
391
|
try {
|
|
290
|
-
const result = await trash(child.id, { operator
|
|
392
|
+
const result = await trash(child.id, { operator, child: true });
|
|
291
393
|
cascaded.push({ id: child.id, ok: true, entryId: result.entryId });
|
|
292
394
|
} catch (error) {
|
|
293
395
|
cascaded.push({ id: child.id, ok: false, error: messageOf(error) });
|
|
@@ -303,37 +405,33 @@ export function createOperations({ ctx, dataRoot, logger }) {
|
|
|
303
405
|
const record = await beginOperation({
|
|
304
406
|
dataRoot,
|
|
305
407
|
action: "trash",
|
|
306
|
-
extra: { sessionId: plan.sessionId, digest: plan.digest, operator
|
|
408
|
+
extra: { sessionId: plan.sessionId, digest: plan.digest, operator },
|
|
307
409
|
});
|
|
308
410
|
|
|
309
411
|
let moved = false;
|
|
310
412
|
let entryId = "";
|
|
413
|
+
/** @type {{ id: string, label: string, status: string, detail?: string }[]} */
|
|
414
|
+
let removed = [];
|
|
311
415
|
try {
|
|
312
|
-
// 1.
|
|
416
|
+
// 1. 先记录引用状态,供恢复时还原 —— **必须早于归档**:
|
|
417
|
+
// 宿主归档会在同一次写里清掉 pin(docs/runtime/0.2.1-rc.5 §6),
|
|
418
|
+
// 归档后再读 storages/workspace.json 只能读到「未置顶」。
|
|
419
|
+
const snapshots = await snapshotAllRefs(refs, plan.sessionId, logger);
|
|
420
|
+
const pinned = snapshots["workspace-pin"]?.pinned;
|
|
421
|
+
|
|
422
|
+
// 2. 归档:归档集合就是 provider 的 agent/pre-step 闸门。
|
|
313
423
|
if (caps.checks["workspace.archive"]) {
|
|
314
424
|
await caps.services.workspace.archiveSession(plan.sessionId, { stopActivity: true });
|
|
315
425
|
}
|
|
316
|
-
//
|
|
426
|
+
// 3. 官方停止通道(跑着的轮次、子代理、后台任务、提醒)。
|
|
317
427
|
if (caps.checks["event.session-stop"]) {
|
|
318
428
|
await ctx.parallel("workspace/session-stop", { sessionId: plan.sessionId });
|
|
319
429
|
}
|
|
320
|
-
//
|
|
430
|
+
// 4. 落盘并等写入稳定。
|
|
321
431
|
const live = caps.services.sessions?.get?.(plan.sessionId);
|
|
322
432
|
if (live && caps.checks["sessions.flush"]) await caps.services.sessions.flush(live);
|
|
323
433
|
await delayMs(SETTLE_MS);
|
|
324
434
|
|
|
325
|
-
// 4. 记录引用状态,供恢复时还原。
|
|
326
|
-
/** @type {Record<string, any>} */
|
|
327
|
-
const snapshots = {};
|
|
328
|
-
for (const ref of refs) {
|
|
329
|
-
if (typeof ref.snapshot !== "function") continue;
|
|
330
|
-
try {
|
|
331
|
-
snapshots[ref.id] = await ref.snapshot(plan.sessionId);
|
|
332
|
-
} catch (error) {
|
|
333
|
-
logger.warn(`session-delete: snapshot ${ref.id} failed: ${messageOf(error)}`);
|
|
334
|
-
}
|
|
335
|
-
}
|
|
336
|
-
|
|
337
435
|
// 5. 移入回收站(原子 rename)。
|
|
338
436
|
const movedResult = await moveIntoTrash({
|
|
339
437
|
dataRoot,
|
|
@@ -348,48 +446,29 @@ export function createOperations({ ctx, dataRoot, logger }) {
|
|
|
348
446
|
live: plan.live,
|
|
349
447
|
children: plan.children,
|
|
350
448
|
workspaceIds: snapshots["workspace-slot"]?.workspaceIds ?? [],
|
|
351
|
-
pinned: null,
|
|
449
|
+
pinned: typeof pinned === "boolean" ? pinned : null,
|
|
352
450
|
},
|
|
353
451
|
});
|
|
354
452
|
moved = true;
|
|
355
453
|
entryId = movedResult.entryId;
|
|
454
|
+
// AUD-SD-01/03:把 entryId 记进 journal —— 崩溃后启动对账能精确知道是哪一条,
|
|
455
|
+
// 已移动但收尾失败的路径也能写出带 entryId 的 partial 回执。
|
|
456
|
+
await updateOperation(dataRoot, record.id, { entryId });
|
|
356
457
|
|
|
357
458
|
// 6. 摘掉所有还指向它的引用。
|
|
358
|
-
|
|
359
|
-
const removed = [];
|
|
360
|
-
for (const ref of refs) {
|
|
361
|
-
if (typeof ref.remove !== "function" || ref.tier === "unknown") {
|
|
362
|
-
removed.push({
|
|
363
|
-
id: ref.id,
|
|
364
|
-
label: ref.label,
|
|
365
|
-
status: "skipped",
|
|
366
|
-
detail: "当前宿主不提供该接口",
|
|
367
|
-
});
|
|
368
|
-
continue;
|
|
369
|
-
}
|
|
370
|
-
try {
|
|
371
|
-
await ref.remove(plan.sessionId, snapshots[ref.id] ?? {});
|
|
372
|
-
removed.push({ id: ref.id, label: ref.label, status: "ok" });
|
|
373
|
-
} catch (error) {
|
|
374
|
-
removed.push({
|
|
375
|
-
id: ref.id,
|
|
376
|
-
label: ref.label,
|
|
377
|
-
status: "failed",
|
|
378
|
-
detail: messageOf(error),
|
|
379
|
-
});
|
|
380
|
-
}
|
|
381
|
-
}
|
|
459
|
+
removed = await removeAllRefs(refs, plan.sessionId, snapshots);
|
|
382
460
|
|
|
383
461
|
// 7. 复活复查 + 对账回执。
|
|
384
|
-
|
|
462
|
+
// 把本次 entryId 交给守卫:它被 restore/purge 之后就不该再移(B2)。
|
|
463
|
+
scheduleReviveCheck(plan, location.path, entryId);
|
|
385
464
|
const checks = await reconcile(plan.sessionId, { skipDirCheck: true });
|
|
386
465
|
await finishOperation({ dataRoot, id: record.id, state: "done" });
|
|
387
|
-
await
|
|
466
|
+
await note({
|
|
388
467
|
action: "trash",
|
|
389
468
|
result: "ok",
|
|
390
469
|
sessionId: plan.sessionId,
|
|
391
470
|
entryId,
|
|
392
|
-
operator
|
|
471
|
+
operator,
|
|
393
472
|
detail: summarizePlan(plan),
|
|
394
473
|
});
|
|
395
474
|
const receiptId = await writeReceipt(dataRoot, {
|
|
@@ -423,21 +502,86 @@ export function createOperations({ ctx, dataRoot, logger }) {
|
|
|
423
502
|
try {
|
|
424
503
|
await caps.services.workspace?.unarchiveSession?.(plan.sessionId);
|
|
425
504
|
} catch {
|
|
426
|
-
//
|
|
505
|
+
// 尽力而为:回滚归档闸门失败不改变「会话没动过」的事实。
|
|
427
506
|
}
|
|
507
|
+
try {
|
|
508
|
+
await finishOperation({
|
|
509
|
+
dataRoot,
|
|
510
|
+
id: record.id,
|
|
511
|
+
state: "failed",
|
|
512
|
+
detail: messageOf(error),
|
|
513
|
+
});
|
|
514
|
+
} catch (journalError) {
|
|
515
|
+
logger.warn(`session-delete: finishOperation failed: ${messageOf(journalError)}`);
|
|
516
|
+
}
|
|
517
|
+
await note({
|
|
518
|
+
action: "trash",
|
|
519
|
+
result: "failed",
|
|
520
|
+
sessionId: plan.sessionId,
|
|
521
|
+
operator,
|
|
522
|
+
detail: messageOf(error),
|
|
523
|
+
});
|
|
524
|
+
throw failure("session-delete/failed", `删除失败:${messageOf(error)}`, {
|
|
525
|
+
partial: false,
|
|
526
|
+
entryId: null,
|
|
527
|
+
});
|
|
528
|
+
}
|
|
529
|
+
// AUD-SD-03:已移动但收尾失败。磁盘事实是「会话已在回收站」,所以:
|
|
530
|
+
// 审计写明「已进入回收站」,回执标 partial,错误码也单独区分——用户重试会拿到
|
|
531
|
+
// not-found,必须能在回执里看到到底哪一步没做完。
|
|
532
|
+
// 收尾本身也可能坏(例如 journal 目录不可写):每一步都单独兜住,
|
|
533
|
+
// 否则「二次异常」会把真正的 partial 结论和回执一起吞掉。
|
|
534
|
+
try {
|
|
535
|
+
await finishOperation({
|
|
536
|
+
dataRoot,
|
|
537
|
+
id: record.id,
|
|
538
|
+
state: "failed",
|
|
539
|
+
detail: `已移动但收尾失败:${messageOf(error)}`,
|
|
540
|
+
});
|
|
541
|
+
} catch (journalError) {
|
|
542
|
+
logger.warn(`session-delete: partial finishOperation failed: ${messageOf(journalError)}`);
|
|
543
|
+
}
|
|
544
|
+
const checks = await reconcile(plan.sessionId, { skipDirCheck: true }).catch(
|
|
545
|
+
(/** @type {unknown} */ reconcileError) => [
|
|
546
|
+
{
|
|
547
|
+
id: "reconcile",
|
|
548
|
+
label: "对账",
|
|
549
|
+
status: "skipped",
|
|
550
|
+
detail: `对账失败:${messageOf(reconcileError)}`,
|
|
551
|
+
},
|
|
552
|
+
],
|
|
553
|
+
);
|
|
554
|
+
/** @type {string | undefined} */
|
|
555
|
+
let receiptId;
|
|
556
|
+
try {
|
|
557
|
+
receiptId = await writeReceipt(dataRoot, {
|
|
558
|
+
action: "trash",
|
|
559
|
+
at: new Date().toISOString(),
|
|
560
|
+
sessionId: plan.sessionId,
|
|
561
|
+
entryId,
|
|
562
|
+
title: plan.title,
|
|
563
|
+
sizeBytes: plan.sizeBytes,
|
|
564
|
+
partial: true,
|
|
565
|
+
removed,
|
|
566
|
+
checks,
|
|
567
|
+
});
|
|
568
|
+
} catch (receiptError) {
|
|
569
|
+
logger.warn(`session-delete: partial receipt failed: ${messageOf(receiptError)}`);
|
|
428
570
|
}
|
|
429
|
-
|
|
430
|
-
await
|
|
571
|
+
const cleaned = removed.filter((item) => item.status === "ok").length;
|
|
572
|
+
await note({
|
|
431
573
|
action: "trash",
|
|
432
574
|
result: "failed",
|
|
433
575
|
sessionId: plan.sessionId,
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
throw failure("session-delete/failed", `删除失败:${messageOf(error)}`, {
|
|
438
|
-
partial: moved,
|
|
439
|
-
entryId: moved ? entryId : null,
|
|
576
|
+
entryId,
|
|
577
|
+
operator,
|
|
578
|
+
detail: `已移入回收站(${entryId}),引用清理 ${cleaned}/${removed.length} 项后收尾失败:${messageOf(error)}`,
|
|
440
579
|
});
|
|
580
|
+
throw failure(
|
|
581
|
+
"session-delete/partial",
|
|
582
|
+
`会话已移入回收站,但收尾未完成:${messageOf(error)}`,
|
|
583
|
+
{ partial: true, entryId, receiptId: receiptId ?? null, removed, checks },
|
|
584
|
+
);
|
|
441
585
|
} finally {
|
|
442
586
|
inFlight.delete(plan.sessionId);
|
|
443
587
|
}
|
|
@@ -445,10 +589,12 @@ export function createOperations({ ctx, dataRoot, logger }) {
|
|
|
445
589
|
|
|
446
590
|
/** @param {number} [limit] */
|
|
447
591
|
async function auditLog(limit = 100) {
|
|
592
|
+
refreshHost();
|
|
448
593
|
return { path: auditPath(dataRoot), entries: await audit.read(limit) };
|
|
449
594
|
}
|
|
450
595
|
|
|
451
596
|
async function list() {
|
|
597
|
+
refreshHost();
|
|
452
598
|
const listed = await listEntries(dataRoot);
|
|
453
599
|
const pending = await listPending(dataRoot);
|
|
454
600
|
return {
|
|
@@ -463,42 +609,79 @@ export function createOperations({ ctx, dataRoot, logger }) {
|
|
|
463
609
|
};
|
|
464
610
|
}
|
|
465
611
|
|
|
612
|
+
/**
|
|
613
|
+
* 恢复删除前的引用快照(只含有恢复动作的引用)。
|
|
614
|
+
* 条目 meta 在最终化时随条目一起删除,所以重检要用回执里留存的那一份。
|
|
615
|
+
* @param {import("./trash.js").TrashMeta} meta
|
|
616
|
+
* @returns {{ workspaceIds: string[], pinned: boolean | null }}
|
|
617
|
+
*/
|
|
618
|
+
function restoredSnapshotOf(meta) {
|
|
619
|
+
return {
|
|
620
|
+
workspaceIds: Array.isArray(meta.workspaceIds) ? meta.workspaceIds : [],
|
|
621
|
+
pinned: typeof meta.pinned === "boolean" ? meta.pinned : null,
|
|
622
|
+
};
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
/**
|
|
626
|
+
* 引用恢复 + 自动重试一次(USIM-U3-02)。
|
|
627
|
+
*
|
|
628
|
+
* 为什么重试:失败大多是「宿主刚挂上/写入还在路上」这类瞬时状态,重试一次很便宜;
|
|
629
|
+
* 重试仍然失败的才进回执与界面,并且带上**具体引用名 + 下一步动作**。
|
|
630
|
+
* @param {import("./refs.js").RefSnapshot} snapshot
|
|
631
|
+
* @param {string} sessionId
|
|
632
|
+
*/
|
|
633
|
+
async function restoreRefsWithRetry(snapshot, sessionId) {
|
|
634
|
+
refreshHost();
|
|
635
|
+
const first = await restoreAllRefs(refs, sessionId, snapshot);
|
|
636
|
+
const failed = first.filter((item) => item.status === "failed");
|
|
637
|
+
if (failed.length === 0) return first;
|
|
638
|
+
await delayMs(120);
|
|
639
|
+
refreshHost();
|
|
640
|
+
const retried = await restoreAllRefs(refs, sessionId, snapshot, {
|
|
641
|
+
onlyIds: failed.map((item) => item.id),
|
|
642
|
+
retried: true,
|
|
643
|
+
});
|
|
644
|
+
const byId = new Map(retried.map((item) => [item.id, item]));
|
|
645
|
+
return first.map((item) => byId.get(item.id) ?? item);
|
|
646
|
+
}
|
|
647
|
+
|
|
466
648
|
/**
|
|
467
649
|
* @param {string} entryId
|
|
468
650
|
* @param {{ operator?: string }} [request]
|
|
469
651
|
*/
|
|
470
652
|
async function restore(entryId, request = {}) {
|
|
653
|
+
refreshHost();
|
|
471
654
|
const meta = await readEntry(dataRoot, entryId);
|
|
655
|
+
const operator = request.operator ?? "ui";
|
|
472
656
|
const record = await beginOperation({
|
|
473
657
|
dataRoot,
|
|
474
658
|
action: "restore",
|
|
475
|
-
extra: { sessionId: meta.sessionId, entryId },
|
|
659
|
+
extra: { sessionId: meta.sessionId, entryId, operator },
|
|
476
660
|
});
|
|
477
661
|
try {
|
|
478
662
|
const restored = await restoreEntry({ dataRoot, entryId });
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
});
|
|
491
|
-
} catch (error) {
|
|
492
|
-
logger.warn(`session-delete: restore ${ref.id} failed: ${messageOf(error)}`);
|
|
493
|
-
}
|
|
494
|
-
}
|
|
663
|
+
// 引用恢复逐项记录:文件回来了只是「会话可用」,归属/置顶回来才算「恢复完整」。
|
|
664
|
+
// 单项失败不再静默 —— 进回执、进 checks、进界面(AUD-SD-02)。
|
|
665
|
+
const snapshot = restoredSnapshotOf(meta);
|
|
666
|
+
const refResults = await restoreRefsWithRetry(snapshot, meta.sessionId);
|
|
667
|
+
const checks = await verifyRestored({
|
|
668
|
+
refs,
|
|
669
|
+
sessionId: meta.sessionId,
|
|
670
|
+
restoredTo: restored.restoredTo,
|
|
671
|
+
meta,
|
|
672
|
+
});
|
|
673
|
+
const summary = restoreSummary(refResults, checks);
|
|
495
674
|
await finishOperation({ dataRoot, id: record.id, state: "done" });
|
|
496
|
-
await
|
|
675
|
+
await note({
|
|
497
676
|
action: "restore",
|
|
498
677
|
result: "ok",
|
|
499
678
|
sessionId: meta.sessionId,
|
|
500
679
|
entryId,
|
|
501
|
-
operator
|
|
680
|
+
operator,
|
|
681
|
+
title: meta.title ?? null,
|
|
682
|
+
// 审计要能回答「到底是哪一处没通过」(USIM-U3-05):计数不够,写清单。
|
|
683
|
+
detail: describeRestoreSummary(summary),
|
|
684
|
+
failures: summary.failures,
|
|
502
685
|
});
|
|
503
686
|
const receiptId = await writeReceipt(dataRoot, {
|
|
504
687
|
action: "restore",
|
|
@@ -507,27 +690,156 @@ export function createOperations({ ctx, dataRoot, logger }) {
|
|
|
507
690
|
entryId,
|
|
508
691
|
title: meta.title,
|
|
509
692
|
restoredTo: restored.restoredTo,
|
|
693
|
+
// 删除时它是否正在宿主里打开:界面据此提示「仍被标记为忙碌」的下一步。
|
|
694
|
+
wasLive: meta.live === true,
|
|
695
|
+
refs: refResults,
|
|
696
|
+
checks,
|
|
697
|
+
partial: summary.partial,
|
|
698
|
+
// 重检要用的删除前快照:条目已经没了,回执是唯一副本。
|
|
699
|
+
expected: snapshot,
|
|
700
|
+
failures: summary.failures,
|
|
510
701
|
});
|
|
511
|
-
return {
|
|
702
|
+
return {
|
|
703
|
+
ok: true,
|
|
704
|
+
sessionId: meta.sessionId,
|
|
705
|
+
title: meta.title ?? null,
|
|
706
|
+
restoredTo: restored.restoredTo,
|
|
707
|
+
wasLive: meta.live === true,
|
|
708
|
+
receiptId,
|
|
709
|
+
refs: refResults,
|
|
710
|
+
checks,
|
|
711
|
+
partial: summary.partial,
|
|
712
|
+
failedRefs: summary.failedRefs,
|
|
713
|
+
failedChecks: summary.failedChecks,
|
|
714
|
+
failures: summary.failures,
|
|
715
|
+
};
|
|
512
716
|
} catch (error) {
|
|
513
|
-
|
|
514
|
-
|
|
717
|
+
try {
|
|
718
|
+
await finishOperation({
|
|
719
|
+
dataRoot,
|
|
720
|
+
id: record.id,
|
|
721
|
+
state: "failed",
|
|
722
|
+
detail: messageOf(error),
|
|
723
|
+
});
|
|
724
|
+
} catch (journalError) {
|
|
725
|
+
logger.warn(`session-delete: finishOperation failed: ${messageOf(journalError)}`);
|
|
726
|
+
}
|
|
727
|
+
await note({
|
|
515
728
|
action: "restore",
|
|
516
729
|
result: "failed",
|
|
517
730
|
sessionId: meta.sessionId,
|
|
518
731
|
entryId,
|
|
519
|
-
operator
|
|
732
|
+
operator,
|
|
520
733
|
detail: messageOf(error),
|
|
521
734
|
});
|
|
522
735
|
throw failure("session-delete/restore-failed", `恢复失败:${messageOf(error)}`);
|
|
523
736
|
}
|
|
524
737
|
}
|
|
525
738
|
|
|
739
|
+
/**
|
|
740
|
+
* 重检一次已完成的恢复(USIM-U3-05 的「可操作」出口):用最近一条 restore 回执里
|
|
741
|
+
* 留存的 `expected` 快照重放引用恢复与校验。失败项仍然失败就照实返回,不伪造成功。
|
|
742
|
+
* @param {{ sessionId?: string, receiptId?: string }} [request]
|
|
743
|
+
*/
|
|
744
|
+
async function recheckRestore(request = {}) {
|
|
745
|
+
refreshHost();
|
|
746
|
+
const listed = await listReceipts(dataRoot, 200);
|
|
747
|
+
const candidates = listed.filter(
|
|
748
|
+
(item) => item?.action === "restore" || item?.action === "restore-recheck",
|
|
749
|
+
);
|
|
750
|
+
/** @type {any} */
|
|
751
|
+
let target = null;
|
|
752
|
+
if (typeof request.receiptId === "string" && request.receiptId.length > 0) {
|
|
753
|
+
target = candidates.find((item) => item.id === request.receiptId) ?? null;
|
|
754
|
+
} else if (typeof request.sessionId === "string" && request.sessionId.length > 0) {
|
|
755
|
+
target = candidates.find((item) => item.sessionId === request.sessionId) ?? null;
|
|
756
|
+
}
|
|
757
|
+
if (!target) {
|
|
758
|
+
throw failure(
|
|
759
|
+
"session-delete/not-found",
|
|
760
|
+
"没有找到这次恢复的回执,无法重检(回执可能已被清理)。",
|
|
761
|
+
);
|
|
762
|
+
}
|
|
763
|
+
const sessionId = requireSessionId(target.sessionId);
|
|
764
|
+
// B1(复审):旧版本写的 restore 回执没有 `expected` 快照。用空快照重放会让
|
|
765
|
+
// `workspace-slot` 以「原本不在任何工作区」返回 ok、校验也只给 skipped,
|
|
766
|
+
// 于是「重检通过」变成假绿(正是本批要消灭的「不伪造成功」)。宁可拒绝:
|
|
767
|
+
// 没有依据就不假装重检成功,让用户按回执里的提示手动处理。
|
|
768
|
+
if (!target.expected || typeof target.expected !== "object") {
|
|
769
|
+
throw failure(
|
|
770
|
+
"session-delete/receipt-legacy",
|
|
771
|
+
"这条回执是旧版本写的,没有留存恢复前的引用快照,不能自动重检;" +
|
|
772
|
+
"请按回执里的提示手动把会话挂回工作区(会话右键菜单「归属到项目…」)。",
|
|
773
|
+
);
|
|
774
|
+
}
|
|
775
|
+
// N13(复审):快照可能是很久以前留下的。会话目录已经不在时,重放
|
|
776
|
+
// attachSession/pinSession/unarchiveSession 只会对一个不可用的现场做写操作。
|
|
777
|
+
const restoredTo = typeof target.restoredTo === "string" ? target.restoredTo : "";
|
|
778
|
+
const dirOk = await stat(restoredTo)
|
|
779
|
+
.then((value) => value.isDirectory())
|
|
780
|
+
.catch(() => false);
|
|
781
|
+
if (!dirOk) {
|
|
782
|
+
throw failure(
|
|
783
|
+
"session-delete/receipt-stale",
|
|
784
|
+
`回执里记录的会话目录已不存在(${restoredTo || "未知路径"}),` +
|
|
785
|
+
"会话可能又被删除/移动过;请重新确认回收站状态,不要按旧快照重检。",
|
|
786
|
+
);
|
|
787
|
+
}
|
|
788
|
+
/** @type {{ workspaceIds: string[], pinned: boolean | null }} */
|
|
789
|
+
const expected = {
|
|
790
|
+
workspaceIds: Array.isArray(target.expected.workspaceIds)
|
|
791
|
+
? target.expected.workspaceIds.map(String)
|
|
792
|
+
: [],
|
|
793
|
+
pinned: typeof target.expected.pinned === "boolean" ? target.expected.pinned : null,
|
|
794
|
+
};
|
|
795
|
+
const refResults = await restoreRefsWithRetry(expected, sessionId);
|
|
796
|
+
const checks = await verifyRestored({
|
|
797
|
+
refs,
|
|
798
|
+
sessionId,
|
|
799
|
+
restoredTo: String(target.restoredTo ?? ""),
|
|
800
|
+
meta: expected,
|
|
801
|
+
});
|
|
802
|
+
const summary = restoreSummary(refResults, checks);
|
|
803
|
+
await note({
|
|
804
|
+
action: "restore-recheck",
|
|
805
|
+
result: "ok",
|
|
806
|
+
sessionId,
|
|
807
|
+
operator: "ui",
|
|
808
|
+
title: target.title ?? null,
|
|
809
|
+
detail: describeRestoreSummary(summary),
|
|
810
|
+
failures: summary.failures,
|
|
811
|
+
});
|
|
812
|
+
const receiptId = await writeReceipt(dataRoot, {
|
|
813
|
+
action: "restore-recheck",
|
|
814
|
+
at: new Date().toISOString(),
|
|
815
|
+
sessionId,
|
|
816
|
+
title: target.title ?? null,
|
|
817
|
+
restoredTo: target.restoredTo ?? null,
|
|
818
|
+
refs: refResults,
|
|
819
|
+
checks,
|
|
820
|
+
partial: summary.partial,
|
|
821
|
+
expected,
|
|
822
|
+
failures: summary.failures,
|
|
823
|
+
});
|
|
824
|
+
return {
|
|
825
|
+
ok: !summary.partial,
|
|
826
|
+
sessionId,
|
|
827
|
+
receiptId,
|
|
828
|
+
refs: refResults,
|
|
829
|
+
checks,
|
|
830
|
+
partial: summary.partial,
|
|
831
|
+
failedRefs: summary.failedRefs,
|
|
832
|
+
failedChecks: summary.failedChecks,
|
|
833
|
+
failures: summary.failures,
|
|
834
|
+
};
|
|
835
|
+
}
|
|
836
|
+
|
|
526
837
|
/**
|
|
527
838
|
* @param {string} entryId
|
|
528
839
|
* @param {{ operator?: string }} [request]
|
|
529
840
|
*/
|
|
530
841
|
async function purge(entryId, request = {}) {
|
|
842
|
+
refreshHost();
|
|
531
843
|
const meta = await readEntry(dataRoot, entryId);
|
|
532
844
|
const record = await beginOperation({
|
|
533
845
|
dataRoot,
|
|
@@ -537,7 +849,7 @@ export function createOperations({ ctx, dataRoot, logger }) {
|
|
|
537
849
|
try {
|
|
538
850
|
const result = await purgeEntry({ dataRoot, entryId });
|
|
539
851
|
await finishOperation({ dataRoot, id: record.id, state: "done" });
|
|
540
|
-
await
|
|
852
|
+
await note({
|
|
541
853
|
action: "purge",
|
|
542
854
|
result: "ok",
|
|
543
855
|
entryId,
|
|
@@ -554,8 +866,17 @@ export function createOperations({ ctx, dataRoot, logger }) {
|
|
|
554
866
|
});
|
|
555
867
|
return { ok: true, bytes: result.bytes, sessionId: meta.sessionId, receiptId };
|
|
556
868
|
} catch (error) {
|
|
557
|
-
|
|
558
|
-
|
|
869
|
+
try {
|
|
870
|
+
await finishOperation({
|
|
871
|
+
dataRoot,
|
|
872
|
+
id: record.id,
|
|
873
|
+
state: "failed",
|
|
874
|
+
detail: messageOf(error),
|
|
875
|
+
});
|
|
876
|
+
} catch (journalError) {
|
|
877
|
+
logger.warn(`session-delete: finishOperation failed: ${messageOf(journalError)}`);
|
|
878
|
+
}
|
|
879
|
+
await note({
|
|
559
880
|
action: "purge",
|
|
560
881
|
result: "failed",
|
|
561
882
|
entryId,
|
|
@@ -572,6 +893,7 @@ export function createOperations({ ctx, dataRoot, logger }) {
|
|
|
572
893
|
* @param {{ skipDirCheck?: boolean }} [options]
|
|
573
894
|
*/
|
|
574
895
|
async function reconcile(sessionIdRaw, options = {}) {
|
|
896
|
+
refreshHost();
|
|
575
897
|
const sessionId = requireSessionId(sessionIdRaw);
|
|
576
898
|
/** @type {{ id: string, label: string, status: "ok" | "failed" | "skipped", detail: string }[]} */
|
|
577
899
|
const checks = [];
|
|
@@ -608,46 +930,11 @@ export function createOperations({ ctx, dataRoot, logger }) {
|
|
|
608
930
|
return checks;
|
|
609
931
|
}
|
|
610
932
|
|
|
611
|
-
/**
|
|
612
|
-
* 读取 workspace 存储快照(只读)。这是文件级兜底:
|
|
613
|
-
* 归档/置顶集合没有公开的读接口,只能读 storages/workspace.json。
|
|
614
|
-
* @returns {Promise<{ ok: boolean, reason?: string, archivedIds: string[], pinnedIds: string[],
|
|
615
|
-
* workspaces: { id: string, sessionIds: string[] }[] }>}
|
|
616
|
-
*/
|
|
617
|
-
async function readWorkspaceState() {
|
|
618
|
-
const file = join(dataRoot, "storages", "workspace.json");
|
|
619
|
-
let parsed;
|
|
620
|
-
try {
|
|
621
|
-
parsed = JSON.parse(await readFile(file, "utf8"));
|
|
622
|
-
} catch (error) {
|
|
623
|
-
return {
|
|
624
|
-
ok: false,
|
|
625
|
-
reason: `无法读取 ${file}:${messageOf(error)}`,
|
|
626
|
-
archivedIds: [],
|
|
627
|
-
pinnedIds: [],
|
|
628
|
-
workspaces: [],
|
|
629
|
-
};
|
|
630
|
-
}
|
|
631
|
-
const global = parsed?.global ?? {};
|
|
632
|
-
const tables = parsed?.tables ?? {};
|
|
633
|
-
const workspaces = Object.entries(tables.workspaces ?? {}).map(([id, value]) => ({
|
|
634
|
-
id,
|
|
635
|
-
sessionIds: Array.isArray(value?.sessionIds) ? value.sessionIds.map(String) : [],
|
|
636
|
-
}));
|
|
637
|
-
return {
|
|
638
|
-
ok: true,
|
|
639
|
-
archivedIds: Array.isArray(global.archivedSessionIds)
|
|
640
|
-
? global.archivedSessionIds.map(String)
|
|
641
|
-
: [],
|
|
642
|
-
pinnedIds: Array.isArray(global.pinnedSessionIds) ? global.pinnedSessionIds.map(String) : [],
|
|
643
|
-
workspaces,
|
|
644
|
-
};
|
|
645
|
-
}
|
|
646
|
-
|
|
647
933
|
/**
|
|
648
934
|
* 全库体检:找出指向已不存在会话的登记条目。只读,不修改任何东西。
|
|
649
935
|
*/
|
|
650
936
|
async function scanHealth() {
|
|
937
|
+
refreshHost();
|
|
651
938
|
if (!caps.checks["persistence.list"]) {
|
|
652
939
|
return {
|
|
653
940
|
ok: false,
|
|
@@ -670,7 +957,7 @@ export function createOperations({ ctx, dataRoot, logger }) {
|
|
|
670
957
|
}
|
|
671
958
|
const known = new Set([...storedIds, ...liveIds]);
|
|
672
959
|
|
|
673
|
-
const state = await readWorkspaceState();
|
|
960
|
+
const state = await readWorkspaceState(dataRoot);
|
|
674
961
|
/** @type {{ id: string, label: string, severity: "warn" | "info", items: any[] }[]} */
|
|
675
962
|
const findings = [];
|
|
676
963
|
/** @type {{ archived: string[], pinned: string[], workspace: { workspaceId: string, sessionId: string }[] }} */
|
|
@@ -775,7 +1062,7 @@ export function createOperations({ ctx, dataRoot, logger }) {
|
|
|
775
1062
|
if (pending.length > 0) {
|
|
776
1063
|
findings.push({
|
|
777
1064
|
id: "pending-operation",
|
|
778
|
-
label: "
|
|
1065
|
+
label: "未完成的操作(重启后自动对账;仍未处理需人工核对)",
|
|
779
1066
|
severity: "info",
|
|
780
1067
|
items: pending.map((record) => record.id),
|
|
781
1068
|
});
|
|
@@ -808,13 +1095,14 @@ export function createOperations({ ctx, dataRoot, logger }) {
|
|
|
808
1095
|
* @param {{ classes?: string[], operator?: string }} [request]
|
|
809
1096
|
*/
|
|
810
1097
|
async function cleanHealth(request = {}) {
|
|
1098
|
+
refreshHost();
|
|
811
1099
|
const classes = Array.isArray(request.classes)
|
|
812
1100
|
? request.classes
|
|
813
1101
|
: ["archived", "pinned", "workspace"];
|
|
814
1102
|
const scan = await scanHealth();
|
|
815
1103
|
if (!scan.ok)
|
|
816
1104
|
throw failure("session-delete/health-unavailable", `无法体检:${scan.reason ?? "未知原因"}`);
|
|
817
|
-
const state = await readWorkspaceState();
|
|
1105
|
+
const state = await readWorkspaceState(dataRoot);
|
|
818
1106
|
const counts = { archived: 0, pinned: 0, workspace: 0 };
|
|
819
1107
|
/** @type {string[]} */
|
|
820
1108
|
const errors = [];
|
|
@@ -858,7 +1146,7 @@ export function createOperations({ ctx, dataRoot, logger }) {
|
|
|
858
1146
|
}
|
|
859
1147
|
}
|
|
860
1148
|
const total = counts.archived + counts.pinned + counts.workspace;
|
|
861
|
-
await
|
|
1149
|
+
await note({
|
|
862
1150
|
action: "health",
|
|
863
1151
|
result: errors.length > 0 ? "failed" : "ok",
|
|
864
1152
|
operator: request.operator ?? "ui",
|
|
@@ -893,6 +1181,7 @@ export function createOperations({ ctx, dataRoot, logger }) {
|
|
|
893
1181
|
}
|
|
894
1182
|
|
|
895
1183
|
async function health() {
|
|
1184
|
+
refreshHost();
|
|
896
1185
|
const pending = await listPending(dataRoot);
|
|
897
1186
|
return {
|
|
898
1187
|
plugin: pkg.name,
|
|
@@ -902,10 +1191,56 @@ export function createOperations({ ctx, dataRoot, logger }) {
|
|
|
902
1191
|
trashRoot: trashRoot(dataRoot),
|
|
903
1192
|
capabilities: describeCapabilities(caps),
|
|
904
1193
|
pending: pending.length,
|
|
1194
|
+
// 启动对账的结论(本轮进程内),磁盘上另有 recover 审计可查。
|
|
1195
|
+
lastRecovery,
|
|
905
1196
|
readOnly: caps.tier === "unknown",
|
|
906
1197
|
};
|
|
907
1198
|
}
|
|
908
1199
|
|
|
1200
|
+
/**
|
|
1201
|
+
* 启动对账(AUD-SD-01):扫 journal 的未完成记录,按落盘事实补做或回滚。
|
|
1202
|
+
* 幂等,可重复调用;并发调用共用同一次(宿主服务重建时 ctx.inject 会重复触发)。
|
|
1203
|
+
* @param {{ operator?: string }} [options]
|
|
1204
|
+
*/
|
|
1205
|
+
async function recoverPending(options = {}) {
|
|
1206
|
+
refreshHost();
|
|
1207
|
+
if (recoveryInFlight) return recoveryInFlight;
|
|
1208
|
+
const job = recovery
|
|
1209
|
+
.recoverPending({ operator: options.operator ?? "system" })
|
|
1210
|
+
.then((summary) => {
|
|
1211
|
+
lastRecovery = summary;
|
|
1212
|
+
if (summary.examined > 0) {
|
|
1213
|
+
logger.info(
|
|
1214
|
+
`session-delete: startup recovery examined ${summary.examined} record(s): ` +
|
|
1215
|
+
`${summary.completed} completed / ${summary.rolledBack} rolled back / ` +
|
|
1216
|
+
`${summary.unresolved} unresolved / ${summary.failed} failed`,
|
|
1217
|
+
);
|
|
1218
|
+
}
|
|
1219
|
+
return summary;
|
|
1220
|
+
})
|
|
1221
|
+
.finally(() => {
|
|
1222
|
+
recoveryInFlight = null;
|
|
1223
|
+
});
|
|
1224
|
+
recoveryInFlight = job;
|
|
1225
|
+
return job;
|
|
1226
|
+
}
|
|
1227
|
+
|
|
1228
|
+
/**
|
|
1229
|
+
* 记录一次「拒绝」(AUD-SD-04)。模型工具的 token/stale-plan 拒绝同样要留痕,
|
|
1230
|
+
* 否则审计里会出现「20 天 0 条 refused」这种取证缺口。
|
|
1231
|
+
* @param {{ sessionId?: string, code?: string, operator?: string, action?: string }} event
|
|
1232
|
+
*/
|
|
1233
|
+
async function recordRefusal(event = {}) {
|
|
1234
|
+
const result = await note({
|
|
1235
|
+
action: event.action ?? "trash",
|
|
1236
|
+
result: "refused",
|
|
1237
|
+
sessionId: typeof event.sessionId === "string" ? event.sessionId : undefined,
|
|
1238
|
+
operator: event.operator ?? "agent",
|
|
1239
|
+
detail: event.code ?? "refused",
|
|
1240
|
+
});
|
|
1241
|
+
return { ok: result.ok };
|
|
1242
|
+
}
|
|
1243
|
+
|
|
909
1244
|
/**
|
|
910
1245
|
* 批量恢复回收站条目。
|
|
911
1246
|
* @param {{ entryIds?: string[], operator?: string }} request
|
|
@@ -919,12 +1254,18 @@ export function createOperations({ ctx, dataRoot, logger }) {
|
|
|
919
1254
|
`一次最多 ${MAX_BATCH_IDS} 条(界面会自动分批)`,
|
|
920
1255
|
);
|
|
921
1256
|
}
|
|
922
|
-
/** @type {{ entryId: string, ok: boolean, sessionId?: string, error?: string }[]} */
|
|
1257
|
+
/** @type {{ entryId: string, ok: boolean, sessionId?: string, partial?: boolean, error?: string }[]} */
|
|
923
1258
|
const results = [];
|
|
924
1259
|
for (const entryId of ids) {
|
|
925
1260
|
try {
|
|
926
1261
|
const result = await restore(entryId, { operator: request.operator ?? "ui" });
|
|
927
|
-
|
|
1262
|
+
// partial 也要带出去:批量行要能说「其中 N 条引用没还原」。
|
|
1263
|
+
results.push({
|
|
1264
|
+
entryId,
|
|
1265
|
+
ok: true,
|
|
1266
|
+
sessionId: result.sessionId,
|
|
1267
|
+
partial: result.partial === true,
|
|
1268
|
+
});
|
|
928
1269
|
} catch (error) {
|
|
929
1270
|
results.push({ entryId, ok: false, error: messageOf(error) });
|
|
930
1271
|
}
|
|
@@ -989,7 +1330,7 @@ export function createOperations({ ctx, dataRoot, logger }) {
|
|
|
989
1330
|
}
|
|
990
1331
|
}
|
|
991
1332
|
// 文件兜底:老版本/headless 组合里没有 workspaceRegistry。
|
|
992
|
-
const state = await readWorkspaceState();
|
|
1333
|
+
const state = await readWorkspaceState(dataRoot);
|
|
993
1334
|
const fromFile = state.workspaces.find((row) => row.id === workspaceId);
|
|
994
1335
|
if (fromFile) {
|
|
995
1336
|
return { workspaceId, title: null, sessionIds: fromFile.sessionIds.map(String) };
|
|
@@ -1139,11 +1480,18 @@ export function createOperations({ ctx, dataRoot, logger }) {
|
|
|
1139
1480
|
|
|
1140
1481
|
/** @param {number} [limit] */
|
|
1141
1482
|
async function receipts(limit = 50) {
|
|
1483
|
+
refreshHost();
|
|
1142
1484
|
return { entries: await listReceipts(dataRoot, limit) };
|
|
1143
1485
|
}
|
|
1144
1486
|
|
|
1145
1487
|
return {
|
|
1146
|
-
caps
|
|
1488
|
+
get caps() {
|
|
1489
|
+
return refreshHost();
|
|
1490
|
+
},
|
|
1491
|
+
// 启动对账与复活守卫的实现(暴露出来是为了单测能直接驱动它,不是公开契约)。
|
|
1492
|
+
recovery,
|
|
1493
|
+
recoverPending,
|
|
1494
|
+
recordRefusal,
|
|
1147
1495
|
health,
|
|
1148
1496
|
restoreMany,
|
|
1149
1497
|
purgeMany,
|
|
@@ -1154,6 +1502,7 @@ export function createOperations({ ctx, dataRoot, logger }) {
|
|
|
1154
1502
|
trash,
|
|
1155
1503
|
list,
|
|
1156
1504
|
restore,
|
|
1505
|
+
recheckRestore,
|
|
1157
1506
|
purge,
|
|
1158
1507
|
reconcile,
|
|
1159
1508
|
auditLog,
|