@240xu/dsh-message-ops 0.11.1 → 0.11.2

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.
@@ -17,8 +17,6 @@ import os from "node:os";
17
17
  import { constants, zstdCompressSync, zstdDecompressSync } from "node:zlib";
18
18
 
19
19
  const ZSTD_MAGIC = 0xfd2fb528;
20
- /** 魔数的字节形态(Buffer.indexOf 用;小端 0xfd2fb528 → 28 b5 2f fd)。 */
21
- const ZSTD_MAGIC_BYTES = Buffer.from([0x28, 0xb5, 0x2f, 0xfd]);
22
20
 
23
21
  /** 带语义状态码的操作错误(单点:HTTP 直接映射 status,工具端转失败文本)。 */
24
22
  export class OpsError extends Error {
@@ -67,14 +65,52 @@ function compressFrame(input) {
67
65
  });
68
66
  }
69
67
 
68
+ /**
69
+ * 按 RFC 8878 计算一个 zstd 帧的精确结束偏移。
70
+ * 魔数可能出现在压缩载荷内,因此不能用 Buffer.indexOf 定帧界。
71
+ * @returns {{end:number}|{error:'truncated'|'malformed'}}
72
+ */
73
+ function zstdFrameEnd(buf, start) {
74
+ if (start + 4 > buf.length || buf.readUInt32LE(start) !== ZSTD_MAGIC) return { error: "malformed" };
75
+ let p = start + 4;
76
+ if (p >= buf.length) return { error: "truncated" };
77
+ const fhd = buf[p++];
78
+ if ((fhd & 0x18) !== 0) return { error: "malformed" };
79
+ const fcsFlag = fhd >> 6;
80
+ const singleSegment = (fhd >> 5) & 1;
81
+ const checksum = (fhd >> 2) & 1;
82
+ const dictFlag = fhd & 3;
83
+ if (!singleSegment) {
84
+ if (p >= buf.length) return { error: "truncated" };
85
+ p += 1;
86
+ }
87
+ const dictSize = [0, 1, 2, 4][dictFlag];
88
+ const fcsSize = fcsFlag === 0 ? (singleSegment ? 1 : 0) : [0, 2, 4, 8][fcsFlag];
89
+ p += dictSize + fcsSize;
90
+ if (p > buf.length) return { error: "truncated" };
91
+ for (;;) {
92
+ if (p + 3 > buf.length) return { error: "truncated" };
93
+ const bh = buf[p] | (buf[p + 1] << 8) | (buf[p + 2] << 16);
94
+ p += 3;
95
+ const last = bh & 1;
96
+ const type = (bh >> 1) & 3;
97
+ const size = bh >>> 3;
98
+ if (type === 3) return { error: "malformed" };
99
+ const payload = type === 1 ? 1 : size;
100
+ if (p + payload > buf.length) return { error: "truncated" };
101
+ p += payload;
102
+ if (last) break;
103
+ }
104
+ if (checksum) {
105
+ if (p + 4 > buf.length) return { error: "truncated" };
106
+ p += 4;
107
+ }
108
+ return { end: p };
109
+ }
110
+
70
111
  /**
71
112
  * 扫描串联 zstd 流的完整帧边界(不解压块)。
72
- *
73
- * 找「下一个魔数」用 Buffer.indexOf(原生 memchr 实现)而不是逐字节
74
- * readUInt32LE 循环 —— 10.8MB 日志的逐字节扫描实测 44~73ms 且全程同步
75
- * 阻塞事件循环(单次卡顿 146ms 的主要来源);indexOf 同样从 offset+4
76
- * 起找、同样要求 4 字节完整落在缓冲区内,语义与原循环**逐位等价**
77
- * (命中区间 [offset+4, buf.length-4],找不到则 end=buf.length)。
113
+ * 帧界按结构计算,任何非帧字节或畸形帧都 fail-closed。
78
114
  * @returns {{frames: {start:number,end:number}[], tornStart?: number}}
79
115
  */
80
116
  export function scanZstdFrames(buf) {
@@ -86,11 +122,16 @@ export function scanZstdFrames(buf) {
86
122
  if (buf.readUInt32LE(offset) !== ZSTD_MAGIC) {
87
123
  throw new Error(`corrupt zstd session log: invalid frame magic at byte ${offset}`);
88
124
  }
89
- let end = buf.length;
90
- const found = buf.indexOf(ZSTD_MAGIC_BYTES, offset + 4);
91
- if (found !== -1) end = found;
92
- frames.push({ start, end });
93
- offset = end;
125
+ const parsed = zstdFrameEnd(buf, offset);
126
+ if (parsed.error === "truncated") {
127
+ frames.push({ start, end: buf.length });
128
+ return { frames, tornStart: start };
129
+ }
130
+ if (parsed.error) {
131
+ throw new Error(`corrupt zstd session log: malformed frame at byte ${offset}`);
132
+ }
133
+ frames.push({ start, end: parsed.end });
134
+ offset = parsed.end;
94
135
  }
95
136
  return { frames };
96
137
  }
@@ -135,6 +176,25 @@ export function readSessionFile(file) {
135
176
  return { header, events };
136
177
  }
137
178
 
179
+ /** Read only the first zstd frame (header); a damaged body cannot block titles. */
180
+ export function readSessionHeader(file) {
181
+ const buf = fs.readFileSync(file);
182
+ if (buf.length < 4 || buf.readUInt32LE(0) !== ZSTD_MAGIC) {
183
+ throw new Error(`session log ${file}: no zstd header frame`);
184
+ }
185
+ const parsed = zstdFrameEnd(buf, 0);
186
+ if (parsed.error) throw new Error(`session log ${file}: ${parsed.error} header frame`);
187
+ const text = zstdDecompressSync(buf.subarray(0, parsed.end)).toString("utf8");
188
+ for (const line of text.split("\n")) {
189
+ const t = line.trim();
190
+ if (!t) continue;
191
+ let json;
192
+ try { json = JSON.parse(t); } catch { continue; }
193
+ if (json && typeof json === "object" && json.type === "session") return json;
194
+ }
195
+ throw new Error(`session log ${file}: no {type:"session"} header line in the first frame`);
196
+ }
197
+
138
198
  /** 物化整份日志:header 帧(恰一行)+ 单一事件帧(全部事件行)。 */
139
199
  export function encodeSessionFile(header, events) {
140
200
  const headerText = JSON.stringify(header) + "\n";
@@ -224,6 +284,11 @@ export function turnBounds(events) {
224
284
  }
225
285
 
226
286
  export function listMessages(events) {
287
+ const syntheticTurns = new Set();
288
+ for (const e of events) {
289
+ if (e && e.type === "turn/start" && e.data && e.data.reason === "message-ops"
290
+ && Number.isSafeInteger(e.data.turn)) syntheticTurns.add(e.data.turn);
291
+ }
227
292
  const messages = [];
228
293
  for (const e of events) {
229
294
  if (!e || typeof e.seq !== "number") continue;
@@ -252,6 +317,7 @@ export function listMessages(events) {
252
317
  ? e.data.restoresSeq : null,
253
318
  time: e.time ?? null,
254
319
  turn: (e.data && e.data.turn) ?? null,
320
+ syntheticTurn: syntheticTurns.has(e.data && e.data.turn) || undefined,
255
321
  // 0.9.1:assistant 节点的宿主 node-key 是 `14:assistant-step<turn>:<step>`,
256
322
  // 没有 step 就无法把渲染行映射回日志 seq → 回滚时助手回答藏不掉。
257
323
  step: (e.data && e.data.step) ?? null,
@@ -0,0 +1,432 @@
1
+ /**
2
+ * Reversible session deletion for dsh-message-ops.
3
+ *
4
+ * A delete is a move, never an unlink:
5
+ * ~/.dsh/sessions/<slug>/<id>/ -> ~/.dsh/trash/session-ops/<trashId>/data/<slug>/<id>/
6
+ * The projection-cache row and workspace/archive/pin membership are copied into
7
+ * manifest.json, then removed from the live storage domains. Restore puts both
8
+ * the directory and the metadata back. Purge is the only destructive operation.
9
+ *
10
+ * This module deliberately has no dependency on the HTTP layer so the contract
11
+ * can be tested with a temporary DSH_HOME and an in-memory storageDomain.
12
+ */
13
+ import fs from "node:fs";
14
+ import os from "node:os";
15
+ import path from "node:path";
16
+ import { randomUUID } from "node:crypto";
17
+ import { OpsError, isSessionId, sessionIdVariants, sessionsRoot, readSessionHeader } from "./session-file.js";
18
+
19
+ export const TRASH_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
20
+ const TRASH_ID_RE = /^\d{10,}-[0-9a-f]{8}$/;
21
+
22
+ function dshHome() {
23
+ return process.env.DSH_HOME || path.join(os.homedir(), ".dsh");
24
+ }
25
+
26
+ export function trashRoot() {
27
+ return path.join(dshHome(), "trash", "session-ops");
28
+ }
29
+
30
+ function cloneJson(value) {
31
+ try { return JSON.parse(JSON.stringify(value)); } catch { return null; }
32
+ }
33
+
34
+ function findAllSessionDirs(sessionId) {
35
+ const root = sessionsRoot();
36
+ const variants = sessionIdVariants(sessionId);
37
+ let slugs = [];
38
+ try { slugs = fs.readdirSync(root, { withFileTypes: true }); } catch { return []; }
39
+ const found = [];
40
+ for (const slug of slugs) {
41
+ if (!slug.isDirectory()) continue;
42
+ for (const variant of variants) {
43
+ const dir = path.join(root, slug.name, variant);
44
+ try {
45
+ if (fs.statSync(dir).isDirectory() && !found.some((x) => x.dir === dir)) {
46
+ found.push({ dir, slug: slug.name, name: variant });
47
+ }
48
+ } catch { /* keep scanning */ }
49
+ }
50
+ }
51
+ return found;
52
+ }
53
+
54
+ function storageDomain(ctx) {
55
+ try { return ctx && typeof ctx.get === "function" ? ctx.get("storageDomain") : undefined; } catch { return undefined; }
56
+ }
57
+
58
+ function projectionTable(ctx) {
59
+ const sd = storageDomain(ctx);
60
+ const domain = sd && typeof sd.get === "function" ? sd.get("session_projcache") : undefined;
61
+ if (!domain || typeof domain.table !== "function") return null;
62
+ try { return domain.table("sessions"); } catch { return null; }
63
+ }
64
+
65
+ function workspaceDomain(ctx) {
66
+ const sd = storageDomain(ctx);
67
+ const domain = sd && typeof sd.get === "function" ? sd.get("workspace") : undefined;
68
+ return domain && typeof domain.table === "function" ? domain : null;
69
+ }
70
+
71
+ function titleOfRow(row) {
72
+ const title = row && row.rows && row.rows.title;
73
+ if (title && typeof title.val === "string" && title.val.trim()) return title.val.trim();
74
+ return null;
75
+ }
76
+
77
+ function headerTitle(dir) {
78
+ try {
79
+ const header = readSessionHeader(path.join(dir, fs.readdirSync(dir).find((f) => /^session(\.v[34])?\.jsonl\.zstd$/.test(f)) || ""));
80
+ for (const key of ["title", "name", "displayTitle"]) {
81
+ if (header && typeof header[key] === "string" && header[key].trim()) return header[key].trim();
82
+ }
83
+ if (header && header.session && typeof header.session.title === "string" && header.session.title.trim()) {
84
+ return header.session.title.trim();
85
+ }
86
+ } catch { /* header unreadable: caller decides */ }
87
+ return null;
88
+ }
89
+
90
+ /** Resolve the confirmation text shown by the delete dialog. Prefers the
91
+ * projection-cache title; falls back to the log header; untitled sessions
92
+ * confirm by their stable session id. */
93
+ export function resolveSessionTitle(ctx, sessionId) {
94
+ if (!isSessionId(sessionId)) return null;
95
+ const meta = readMetadata(ctx, sessionId);
96
+ const title = titleOfRow(meta.projRow);
97
+ if (title) return title;
98
+ const dirs = findAllSessionDirs(sessionId);
99
+ if (dirs.length === 1) {
100
+ const fromHeader = headerTitle(dirs[0].dir);
101
+ if (fromHeader) return fromHeader;
102
+ }
103
+ return sessionId;
104
+ }
105
+
106
+ function readMetadata(ctx, sessionId) {
107
+ const variants = sessionIdVariants(sessionId);
108
+ const projRows = [];
109
+ const table = projectionTable(ctx);
110
+ if (table && typeof table.get === "function") {
111
+ for (const variant of variants) {
112
+ let row;
113
+ try { row = table.get(variant); } catch { row = undefined; }
114
+ if (row !== undefined) {
115
+ const copy = cloneJson(row);
116
+ if (copy) projRows.push({ key: variant, row: copy });
117
+ }
118
+ }
119
+ }
120
+
121
+ const workspaceIds = [];
122
+ const archived = [];
123
+ const pinned = [];
124
+ const ws = workspaceDomain(ctx);
125
+ if (ws) {
126
+ if (typeof ws.table === "function") {
127
+ try {
128
+ for (const [wid, rec] of ws.table("workspaces").entries()) {
129
+ if (rec && Array.isArray(rec.sessionIds) && rec.sessionIds.some((x) => variants.includes(x))) {
130
+ workspaceIds.push(wid);
131
+ }
132
+ }
133
+ } catch { /* unit absent */ }
134
+ }
135
+ try {
136
+ const state = ws.global && typeof ws.global.get === "function" ? ws.global.get() : null;
137
+ if (state && Array.isArray(state.archivedSessionIds) && state.archivedSessionIds.some((x) => variants.includes(x))) archived.push(sessionId);
138
+ if (state && Array.isArray(state.pinnedSessionIds) && state.pinnedSessionIds.some((x) => variants.includes(x))) pinned.push(sessionId);
139
+ } catch { /* no global slot */ }
140
+ }
141
+
142
+ return {
143
+ projRows,
144
+ projRow: projRows.length ? projRows[0].row : null,
145
+ workspaceIds,
146
+ archived: archived.length > 0,
147
+ pinned: pinned.length > 0,
148
+ };
149
+ }
150
+
151
+ async function stripMetadata(ctx, sessionId, meta) {
152
+ const variants = sessionIdVariants(sessionId);
153
+ const table = projectionTable(ctx);
154
+ if (table && typeof table.delete === "function") {
155
+ const keys = new Set((meta.projRows || []).map((x) => x.key));
156
+ for (const variant of variants) keys.add(variant);
157
+ for (const key of keys) {
158
+ try {
159
+ if (typeof table.get !== "function" || table.get(key) !== undefined) await table.delete(key);
160
+ } catch { /* domain closed: the manifest still has the row */ }
161
+ }
162
+ }
163
+
164
+ const ws = workspaceDomain(ctx);
165
+ if (ws && typeof ws.table === "function") {
166
+ try {
167
+ const workspaces = ws.table("workspaces");
168
+ for (const [wid, rec] of workspaces.entries()) {
169
+ if (!rec || !Array.isArray(rec.sessionIds)) continue;
170
+ const next = rec.sessionIds.filter((x) => !variants.includes(x));
171
+ if (next.length !== rec.sessionIds.length) await workspaces.put(wid, { ...rec, sessionIds: next });
172
+ }
173
+ } catch { /* unit absent */ }
174
+ }
175
+ if (ws && ws.global) {
176
+ try {
177
+ const state = ws.global.get();
178
+ if (state && (Array.isArray(state.archivedSessionIds) || Array.isArray(state.pinnedSessionIds))) {
179
+ const next = { ...state };
180
+ if (Array.isArray(next.archivedSessionIds)) next.archivedSessionIds = next.archivedSessionIds.filter((x) => !variants.includes(x));
181
+ if (Array.isArray(next.pinnedSessionIds)) next.pinnedSessionIds = next.pinnedSessionIds.filter((x) => !variants.includes(x));
182
+ await ws.global.set(next);
183
+ }
184
+ } catch { /* no global slot */ }
185
+ }
186
+ }
187
+
188
+ async function restoreMetadata(ctx, sessionId, meta) {
189
+ const table = projectionTable(ctx);
190
+ if (table && typeof table.put === "function") {
191
+ for (const item of meta.projRows || []) {
192
+ try { await table.put(item.key, item.row); } catch { /* domain closed */ }
193
+ }
194
+ }
195
+ const ws = workspaceDomain(ctx);
196
+ if (ws && typeof ws.table === "function") {
197
+ try {
198
+ const workspaces = ws.table("workspaces");
199
+ for (const wid of meta.workspaceIds || []) {
200
+ let rec = typeof workspaces.get === "function" ? workspaces.get(wid) : undefined;
201
+ if (!rec && typeof workspaces.entries === "function") {
202
+ for (const [key, value] of workspaces.entries()) {
203
+ if (key === wid) { rec = value; break; }
204
+ }
205
+ }
206
+ if (!rec || !Array.isArray(rec.sessionIds)) continue;
207
+ if (!rec.sessionIds.includes(sessionId)) {
208
+ await workspaces.put(wid, { ...rec, sessionIds: rec.sessionIds.concat([sessionId]) });
209
+ }
210
+ }
211
+ } catch { /* unit absent */ }
212
+ }
213
+ if (ws && ws.global) {
214
+ try {
215
+ const state = ws.global.get();
216
+ if (state) {
217
+ const next = { ...state };
218
+ if (meta.archived && Array.isArray(next.archivedSessionIds) && !next.archivedSessionIds.includes(sessionId)) {
219
+ next.archivedSessionIds = next.archivedSessionIds.concat([sessionId]);
220
+ }
221
+ if (meta.pinned && Array.isArray(next.pinnedSessionIds) && !next.pinnedSessionIds.includes(sessionId)) {
222
+ next.pinnedSessionIds = next.pinnedSessionIds.concat([sessionId]);
223
+ }
224
+ await ws.global.set(next);
225
+ }
226
+ } catch { /* no global slot */ }
227
+ }
228
+ }
229
+
230
+ function moveDir(src, dst) {
231
+ fs.mkdirSync(path.dirname(dst), { recursive: true });
232
+ try {
233
+ fs.renameSync(src, dst);
234
+ } catch (err) {
235
+ if (!err || err.code !== "EXDEV") throw err;
236
+ fs.cpSync(src, dst, { recursive: true, errorOnExist: true });
237
+ fs.rmSync(src, { recursive: true, force: true });
238
+ }
239
+ }
240
+
241
+ function writeManifest(dir, manifest) {
242
+ fs.mkdirSync(dir, { recursive: true });
243
+ const tmp = path.join(dir, "manifest.json.tmp");
244
+ fs.writeFileSync(tmp, JSON.stringify(manifest, null, 2));
245
+ fs.renameSync(tmp, path.join(dir, "manifest.json"));
246
+ }
247
+
248
+ function assertTrashId(trashId) {
249
+ if (typeof trashId !== "string" || !TRASH_ID_RE.test(trashId)) throw new OpsError("invalid trashId", 400);
250
+ }
251
+
252
+ function readManifest(trashId) {
253
+ assertTrashId(trashId);
254
+ const file = path.join(trashRoot(), trashId, "manifest.json");
255
+ let raw;
256
+ try { raw = fs.readFileSync(file, "utf8"); } catch { throw new OpsError("trash entry not found", 404); }
257
+ try { return JSON.parse(raw); } catch { throw new OpsError("corrupt trash manifest", 500); }
258
+ }
259
+
260
+ function agentRunning(ctx, sessionId) {
261
+ let agents;
262
+ try { agents = ctx && typeof ctx.get === "function" ? ctx.get("agents") : undefined; } catch { return false; }
263
+ if (!agents || typeof agents.get !== "function") return false;
264
+ for (const variant of sessionIdVariants(sessionId)) {
265
+ const agent = agents.get(variant);
266
+ if (agent && agent.status === "running") return true;
267
+ }
268
+ return false;
269
+ }
270
+
271
+ /**
272
+ * Move one session into the trash. Refuses running sessions and mismatched
273
+ * confirmation titles; the caller must pass the title shown in the UI.
274
+ */
275
+ export async function deleteSessionToTrash(ctx, sessionId, confirmTitle) {
276
+ if (!isSessionId(sessionId)) throw new OpsError("invalid sessionId", 400);
277
+ const dirs = findAllSessionDirs(sessionId);
278
+ if (dirs.length === 0) throw new OpsError("session not found", 404);
279
+ if (dirs.length > 1) throw new OpsError(`ambiguous session id: found ${dirs.length} directories`, 409);
280
+ if (agentRunning(ctx, sessionId)) throw new OpsError("session is running; stop it first", 409);
281
+
282
+ const meta = readMetadata(ctx, sessionId);
283
+ const title = titleOfRow(meta.projRow) || headerTitle(dirs[0].dir);
284
+ const expected = title || sessionId;
285
+ if (String(confirmTitle == null ? "" : confirmTitle).trim() !== expected) {
286
+ throw new OpsError(`title mismatch: type "${expected}" to delete`, 400);
287
+ }
288
+
289
+ const now = Date.now();
290
+ const trashId = `${now}-${randomUUID().slice(0, 8)}`;
291
+ const root = path.join(trashRoot(), trashId);
292
+ const rel = path.relative(sessionsRoot(), dirs[0].dir);
293
+ const dataRel = path.join("data", rel);
294
+ const manifest = {
295
+ version: 1,
296
+ trashId,
297
+ sessionId,
298
+ title: title || null,
299
+ state: "moving",
300
+ deletedAt: now,
301
+ expiresAt: now + TRASH_RETENTION_MS,
302
+ dirs: [{ rel, originalSlug: dirs[0].slug, originalName: dirs[0].name }],
303
+ ...meta,
304
+ };
305
+ writeManifest(root, manifest);
306
+
307
+ const source = dirs[0].dir;
308
+ const target = path.join(root, dataRel);
309
+ let moved = false;
310
+ try {
311
+ moveDir(source, target);
312
+ moved = true;
313
+ if (findAllSessionDirs(sessionId).length > 0) throw new OpsError("session directory still present after move", 500);
314
+ await stripMetadata(ctx, sessionId, meta);
315
+ manifest.state = "trashed";
316
+ writeManifest(root, manifest);
317
+ } catch (err) {
318
+ let dataBack = !moved && fs.existsSync(source) && !fs.existsSync(target);
319
+ let metadataBack = dataBack;
320
+ if (moved) {
321
+ try {
322
+ moveDir(target, source);
323
+ dataBack = true;
324
+ await restoreMetadata(ctx, sessionId, meta);
325
+ metadataBack = true;
326
+ } catch { /* leave the manifest for manual restore */ }
327
+ }
328
+ if (dataBack && metadataBack) {
329
+ try { fs.rmSync(root, { recursive: true, force: true }); } catch { /* best effort */ }
330
+ }
331
+ throw err;
332
+ }
333
+
334
+ return {
335
+ ok: true,
336
+ trashId,
337
+ sessionId,
338
+ title: title || null,
339
+ expiresAt: manifest.expiresAt,
340
+ workspaceIds: meta.workspaceIds,
341
+ archived: meta.archived,
342
+ pinned: meta.pinned,
343
+ };
344
+ }
345
+
346
+ export async function listTrash(ctx, { purgeExpired = false, now = Date.now() } = {}) {
347
+ let names = [];
348
+ try { names = fs.readdirSync(trashRoot(), { withFileTypes: true }); } catch { return []; }
349
+ const entries = [];
350
+ for (const name of names) {
351
+ if (!name.isDirectory() || !TRASH_ID_RE.test(name.name)) continue;
352
+ let manifest;
353
+ try { manifest = readManifest(name.name); } catch { continue; }
354
+ if (purgeExpired && typeof manifest.expiresAt === "number" && manifest.expiresAt <= now) {
355
+ try { fs.rmSync(path.join(trashRoot(), name.name), { recursive: true, force: true }); } catch { /* retry next time */ }
356
+ continue;
357
+ }
358
+ entries.push({
359
+ trashId: name.name,
360
+ sessionId: manifest.sessionId,
361
+ title: manifest.title || null,
362
+ state: manifest.state || "trashed",
363
+ deletedAt: manifest.deletedAt || null,
364
+ expiresAt: manifest.expiresAt || null,
365
+ workspaceIds: Array.isArray(manifest.workspaceIds) ? manifest.workspaceIds : [],
366
+ });
367
+ }
368
+ entries.sort((a, b) => (b.deletedAt || 0) - (a.deletedAt || 0));
369
+ return entries;
370
+ }
371
+
372
+ function restoreTarget(manifest) {
373
+ if (!manifest || !Array.isArray(manifest.dirs) || manifest.dirs.length !== 1) {
374
+ throw new OpsError("unsupported trash manifest", 500);
375
+ }
376
+ if (!isSessionId(manifest.sessionId)) {
377
+ throw new OpsError("invalid trash manifest sessionId", 500);
378
+ }
379
+ const raw = manifest.dirs[0].rel;
380
+ if (typeof raw !== "string" || raw.length === 0 || path.isAbsolute(raw)) {
381
+ throw new OpsError("invalid trash manifest rel", 500);
382
+ }
383
+ const parts = raw.split(/[\\/]+/);
384
+ if (parts.length !== 2 || parts.some((part) => !part || part === "." || part === "..")) {
385
+ throw new OpsError("invalid trash manifest rel", 500);
386
+ }
387
+ if (!sessionIdVariants(manifest.sessionId).includes(parts[1])) {
388
+ throw new OpsError("trash manifest rel does not match sessionId", 500);
389
+ }
390
+ const root = path.resolve(sessionsRoot());
391
+ const target = path.join(root, ...parts);
392
+ if (!target.startsWith(root + path.sep)) {
393
+ throw new OpsError("trash manifest rel escapes the sessions root", 500);
394
+ }
395
+ return { rel: path.join(...parts), target };
396
+ }
397
+
398
+ export async function restoreTrash(ctx, trashId) {
399
+ const manifest = readManifest(trashId);
400
+ const { rel, target } = restoreTarget(manifest);
401
+ if (fs.existsSync(target)) throw new OpsError("session directory already exists; refusing to overwrite", 409);
402
+
403
+ const root = path.join(trashRoot(), trashId);
404
+ const source = path.join(root, "data", rel);
405
+ let sourceStat;
406
+ try { sourceStat = fs.lstatSync(source); } catch { throw new OpsError("trash payload missing", 404); }
407
+ if (!sourceStat.isDirectory()) throw new OpsError("trash payload is not a directory", 500);
408
+
409
+ try {
410
+ moveDir(source, target);
411
+ if (!fs.existsSync(target)) throw new OpsError("restore move failed", 500);
412
+ await restoreMetadata(ctx, manifest.sessionId, manifest);
413
+ } catch (err) {
414
+ try {
415
+ if (fs.existsSync(target) && !fs.existsSync(source)) moveDir(target, source);
416
+ } catch { /* leave both for manual recovery */ }
417
+ throw err;
418
+ }
419
+
420
+ try { fs.rmSync(root, { recursive: true, force: true }); } catch { /* manifest cleanup is best effort */ }
421
+ return { ok: true, trashId, sessionId: manifest.sessionId, title: manifest.title || null };
422
+ }
423
+
424
+ export async function purgeTrash(ctx, trashId) {
425
+ assertTrashId(trashId);
426
+ const root = path.join(trashRoot(), trashId);
427
+ if (!fs.existsSync(root)) throw new OpsError("trash entry not found", 404);
428
+ fs.rmSync(root, { recursive: true, force: true });
429
+ return { ok: true, trashId };
430
+ }
431
+
432
+ export const _internals = { findAllSessionDirs, readMetadata, stripMetadata, restoreMetadata };
@@ -1,73 +0,0 @@
1
- /**
2
- * 0.9.0 结构性回归:与 dsh 官方重复的能力必须**不存在**于本插件。
3
- *
4
- * 背景(专家核查结论):
5
- * - 分支:官方有完整 `session/fork`(RPC typert.host.js:1512,atSeq 任意)
6
- * + SessionStore.fork() + UI 消息级按钮 + 埋点 branch_session_click。
7
- * 本插件的磁盘分支实现语义是**错的**:branch.js 删掉了 isSeeded(官方设 true)、
8
- * 不写 inheritedEventCount、不调 buildForkSeed 补 closers → 子会话 turn 边界可能悬空。
9
- * 官方 fork 失败通常意味着源会话在运行,正确做法是拒绝而非绕过引擎。
10
- * - 导出:官方 /api/session.export 已有;但用户决定**直接删掉我们的 Markdown 导出**,
11
- * 导出一律用官方(尽管两者格式不重叠:官方 ZIP 归档 vs 我们 Markdown)。
12
- *
13
- * 本测试锁死这两个能力不复活,并验证 branch 只走官方。
14
- */
15
- import test from 'node:test'
16
- import assert from 'node:assert/strict'
17
- import fs from 'node:fs'
18
- import path from 'node:path'
19
- import url from 'node:url'
20
-
21
- const ROOT = path.resolve(path.dirname(url.fileURLToPath(import.meta.url)), '..')
22
- const read = (p) => fs.readFileSync(path.join(ROOT, p), 'utf8')
23
-
24
- test('src/branch.js 已删除(磁盘分支不再存在)', () => {
25
- assert.equal(fs.existsSync(path.join(ROOT, 'src/branch.js')), false, 'src/branch.js 仍在 —— 磁盘分支实现未清除')
26
- })
27
-
28
- test('src/index.js 不再 import applyBranch', () => {
29
- const s = read('src/index.js')
30
- assert.ok(!/import\s*\{[^}]*applyBranch/.test(s), 'index.js 仍 import applyBranch')
31
- assert.ok(!s.includes('applyBranch('), 'index.js 仍有 applyBranch( 调用')
32
- })
33
-
34
- test('后端不再有 /api/message-ops/branch 路由', () => {
35
- const s = read('src/index.js')
36
- assert.ok(!s.includes('/api/message-ops/branch'), 'branch 路由仍在')
37
- })
38
-
39
- test('后端不再有 /api/message-ops/export 路由', () => {
40
- const s = read('src/index.js')
41
- assert.ok(!s.includes('/api/message-ops/export'), 'export 路由仍在')
42
- })
43
-
44
- test('客户端不再有磁盘分支回落(只走官方 sessions.fork)', () => {
45
- const s = read('src/client.js')
46
- assert.ok(!s.includes('diskBranch'), 'client.js 仍有 diskBranch 回落')
47
- assert.ok(!s.includes('/api/message-ops/branch'), 'client.js 仍调磁盘分支端点')
48
- assert.ok(s.includes('fork'), 'client.js 应保留官方 fork 调用')
49
- })
50
-
51
- test('客户端不再有 fork.disk 文案', () => {
52
- const s = read('src/client.js')
53
- assert.ok(!s.includes('fork.disk'), 'fork.disk locale 仍在')
54
- })
55
-
56
- test('ops-core 不再导出 exportMarkdown', async () => {
57
- const mod = await import('../src/ops-core.js')
58
- assert.equal(mod.exportMarkdown, undefined, 'exportMarkdown 仍被导出')
59
- })
60
-
61
- test('message_ops tool 的 enum 不含 export', () => {
62
- const s = read('src/index.js')
63
- const m = s.match(/enum:\s*\[([^\]]+)\]/g) ?? [];
64
- const enums = m.map((x) => x).join(' ');
65
- assert.ok(!/["']export["']/.test(enums), `tool enum 仍含 export: ${enums}`)
66
- })
67
-
68
- test('message_ops tool 仍保留核心三操作(revert/delete/restore)', () => {
69
- const s = read('src/index.js')
70
- for (const op of ['revert', 'delete', 'restore']) {
71
- assert.ok(s.includes(`"${op}"`), `tool enum 缺少 ${op}`)
72
- }
73
- })