@240xu/dsh-message-ops 0.11.1 → 0.11.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +78 -27
- package/package.json +1 -2
- package/src/client.js +1083 -5
- package/src/index.js +231 -31
- package/src/ops-core.js +183 -23
- package/src/session-file.js +79 -13
- package/src/session-trash.js +432 -0
- package/test/branch-export-removed.test.js +0 -73
- package/test/client-p0-locks.test.js +0 -131
- package/test/client-perf-locks.test.js +0 -259
- package/test/composer-refill.test.js +0 -106
- package/test/derived-cache.test.js +0 -202
- package/test/dock-preview.test.js +0 -666
- package/test/fence.test.js +0 -181
- package/test/injected-regex.test.js +0 -62
- package/test/legacy-format.test.js +0 -120
- package/test/ops-core.test.js +0 -358
- package/test/redo-contract.test.js +0 -55
- package/test/revert-commit.test.js +0 -98
- package/test/revert-contract.test.js +0 -130
- package/test/session-file.test.js +0 -86
- package/test/step-restore.test.js +0 -112
- package/test/surface-visibility.test.js +0 -166
- package/test/transcript-visibility.test.js +0 -111
- package/test/undo-slash.test.js +0 -89
- package/test/user-revert-anchor.test.js +0 -103
- package/test/v4-stream-contract.test.js +0 -62
|
@@ -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
|
-
})
|
|
@@ -1,131 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 0.9.7 client.js 源码锁 —— 四个 P0 活 bug + 性能改动的红线。
|
|
3
|
-
*
|
|
4
|
-
* 为什么是「扫源码字符串」而不是跑代码:client.js 走 window.__ModuleLoader__
|
|
5
|
-
* + require('@deepseek-ai/...'),107→114 条既有测试里没有一条执行它
|
|
6
|
-
* (执行覆盖 = 0)。下面每条锁死一个**改得回去**的字面量。
|
|
7
|
-
*/
|
|
8
|
-
import test from 'node:test'
|
|
9
|
-
import assert from 'node:assert/strict'
|
|
10
|
-
import { readFileSync } from 'node:fs'
|
|
11
|
-
import { fileURLToPath } from 'node:url'
|
|
12
|
-
import { dirname, join } from 'node:path'
|
|
13
|
-
|
|
14
|
-
const src = readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'src', 'client.js'), 'utf8')
|
|
15
|
-
|
|
16
|
-
/** 从源码里截出 `const <name> = { … }` 的对象字面量并求值(引号内跳过花括号)。 */
|
|
17
|
-
function grabDict(name) {
|
|
18
|
-
const marker = `const ${name} = {`
|
|
19
|
-
const i = src.indexOf(marker)
|
|
20
|
-
assert.ok(i >= 0, `源码里找不到 ${name}`)
|
|
21
|
-
const start = src.indexOf('{', i)
|
|
22
|
-
let depth = 0
|
|
23
|
-
let quote = null
|
|
24
|
-
let esc = false
|
|
25
|
-
let j = start
|
|
26
|
-
for (; j < src.length; j++) {
|
|
27
|
-
const c = src[j]
|
|
28
|
-
if (quote) {
|
|
29
|
-
if (esc) { esc = false; continue }
|
|
30
|
-
if (c === '\\') { esc = true; continue }
|
|
31
|
-
if (c === quote) quote = null
|
|
32
|
-
continue
|
|
33
|
-
}
|
|
34
|
-
if (c === "'" || c === '"' || c === '`') { quote = c; continue }
|
|
35
|
-
if (c === '{') depth++
|
|
36
|
-
else if (c === '}') { depth--; if (depth === 0) { j++; break } }
|
|
37
|
-
}
|
|
38
|
-
assert.equal(depth, 0, `${name} 对象字面量没闭合`)
|
|
39
|
-
return new Function(`return (${src.slice(start, j)})`)()
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
// ═══════════════════════════════════════════════════════════════════════════
|
|
43
|
-
// P0-1 · okMsg 悬挂三元 → 对话框三个操作全部失败
|
|
44
|
-
// ═══════════════════════════════════════════════════════════════════════════
|
|
45
|
-
test('P0-1:对话框成功路径必须有 const okMsg 声明', () => {
|
|
46
|
-
// 只认**代码行**——注释里提到 `const okMsg =` 不算数
|
|
47
|
-
const m = src.match(/^\s*const okMsg = .*$/m)
|
|
48
|
-
assert.ok(m, 'ec862d6(0.9.0) 删掉声明后留下悬挂 `? :`')
|
|
49
|
-
const decl = m[0]
|
|
50
|
-
assert.ok(/done\.revert/.test(decl) && /done\.delete/.test(decl), 'okMsg 应在 revert/delete 里二选一')
|
|
51
|
-
assert.ok(!/done\.restore/.test(decl),
|
|
52
|
-
'对话框 mode 只有 revert|delete|branch(branch 在上游已 return),restore 分支不可达')
|
|
53
|
-
assert.ok(/setDoneMsg\(okMsg\)/.test(src), '成功态文案没接上')
|
|
54
|
-
assert.ok(/notifyDone\(okMsg\)/.test(src), 'toast 没接上')
|
|
55
|
-
})
|
|
56
|
-
|
|
57
|
-
test('P0-1:成功块里不再出现裸三元(失败时会把成功文案当错误抛出)', () => {
|
|
58
|
-
const i = src.indexOf('if (!res.ok || !data.ok) throw new Error(data.error || `HTTP ${res.status}`)')
|
|
59
|
-
assert.ok(i >= 0, '找不到对话框的成功判定')
|
|
60
|
-
const block = src.slice(i, src.indexOf('setDoneMsg(okMsg)', i))
|
|
61
|
-
assert.ok(!/^\s*\? t\(/m.test(block), '残留的悬挂 `? t(...)`')
|
|
62
|
-
assert.ok(!/:\s*t\('done\.revert'/.test(block), '残留的悬挂 `: t(...)`')
|
|
63
|
-
})
|
|
64
|
-
|
|
65
|
-
// ═══════════════════════════════════════════════════════════════════════════
|
|
66
|
-
// P0-2 · /redo 仍传裸 uuid 给 afterWrite
|
|
67
|
-
// ═══════════════════════════════════════════════════════════════════════════
|
|
68
|
-
test('P0-2:afterWrite 只能收带 session- 前缀的 rawSid', () => {
|
|
69
|
-
assert.ok(!/afterWrite\(sid,/.test(src), '/redo 仍传裸 uuid → openSession 抛 unknown session 被 catch 吞掉')
|
|
70
|
-
const redo = src.match(/var runRedo = \(\) => \{[\s\S]*?\n \}/)
|
|
71
|
-
assert.ok(redo, '找不到 runRedo')
|
|
72
|
-
assert.ok(/afterWrite\(rawSid,/.test(redo[0]), 'runRedo 必须把 rawSid 交给 afterWrite')
|
|
73
|
-
assert.ok(/const sid = bareSessionId\(rawSid\)/.test(redo[0]), 'POST /restore 仍要裸 uuid')
|
|
74
|
-
// afterWrite 本体的契约(与 composer-refill R4 互补)
|
|
75
|
-
const aw = src.match(/var afterWrite = \([\s\S]*?\n \}/)
|
|
76
|
-
assert.ok(aw && /openSession\(rawSid\)/.test(aw[0]))
|
|
77
|
-
assert.ok(!/openSession\(bare\)|openSession\(bareSessionId/.test(aw[0]))
|
|
78
|
-
})
|
|
79
|
-
|
|
80
|
-
// ═══════════════════════════════════════════════════════════════════════════
|
|
81
|
-
// P0-3 · opsPanel 渲染两次(两组同名 radio 互抢 name)
|
|
82
|
-
// ═══════════════════════════════════════════════════════════════════════════
|
|
83
|
-
test('P0-3:opsPanel 全文只出现 2 次(1 次定义 + 1 次渲染)', () => {
|
|
84
|
-
// 只数**代码行**:`const opsPanel = …` 与数组里单独成行的 `opsPanel,`
|
|
85
|
-
const code = src.split('\n').filter((l) => /^\s*(?:const\s+)?opsPanel\b/.test(l))
|
|
86
|
-
assert.equal(code.length, 2, `opsPanel 代码行 ${code.length} 行,应为 2:\n${code.join('\n')}`)
|
|
87
|
-
assert.equal(code.filter((l) => /^\s*const opsPanel = /.test(l)).length, 1, '定义只能有一处')
|
|
88
|
-
assert.equal(code.filter((l) => /^\s*opsPanel,\s*$/.test(l)).length, 1,
|
|
89
|
-
'渲染点只能留列表之前那一处(列表之后的旧位置是 P0)')
|
|
90
|
-
})
|
|
91
|
-
|
|
92
|
-
// ═══════════════════════════════════════════════════════════════════════════
|
|
93
|
-
// P0-4 · locale 字典不一致
|
|
94
|
-
// ═══════════════════════════════════════════════════════════════════════════
|
|
95
|
-
test('P0-4:zhDict / enDict 的 key 序列完全一致(含顺序)', () => {
|
|
96
|
-
const zh = grabDict('zhDict')
|
|
97
|
-
const en = grabDict('enDict')
|
|
98
|
-
assert.deepEqual(Object.keys(zh), Object.keys(en))
|
|
99
|
-
assert.equal(Object.keys(zh).length, Object.keys(en).length)
|
|
100
|
-
})
|
|
101
|
-
|
|
102
|
-
test('P0-4:undo/redo 等 10 个 key 两侧都有,且各写各的语言', () => {
|
|
103
|
-
const zh = grabDict('zhDict')
|
|
104
|
-
const en = grabDict('enDict')
|
|
105
|
-
const must = [
|
|
106
|
-
'undo.label', 'undo.desc', 'undo.done.undo', 'undo.done.redo',
|
|
107
|
-
'undo.none', 'undo.none.redo', 'redo.label', 'redo.desc',
|
|
108
|
-
'slot.revertUnmatched', 'dock.shadowedN',
|
|
109
|
-
]
|
|
110
|
-
const cjk = /[㐀-鿿]/
|
|
111
|
-
for (const k of must) {
|
|
112
|
-
assert.ok(k in zh, `zhDict 缺 ${k}`)
|
|
113
|
-
assert.ok(k in en, `enDict 缺 ${k}`)
|
|
114
|
-
assert.ok(cjk.test(zh[k]), `zhDict['${k}'] 不是中文:${zh[k]}`)
|
|
115
|
-
assert.ok(!cjk.test(en[k]), `enDict['${k}'] 是中文(英文用户会看到中文):${en[k]}`)
|
|
116
|
-
}
|
|
117
|
-
for (const [k, v] of Object.entries(zh)) assert.ok(cjk.test(v), `zhDict['${k}'] 不是中文`)
|
|
118
|
-
for (const [k, v] of Object.entries(en)) assert.ok(!cjk.test(v), `enDict['${k}'] 混进了中文:${v}`)
|
|
119
|
-
})
|
|
120
|
-
|
|
121
|
-
test('P0-4:占位符写法两侧一致({{text}} / ${seq} 都会被 __t 留成垃圾)', () => {
|
|
122
|
-
const zh = grabDict('zhDict')
|
|
123
|
-
const en = grabDict('enDict')
|
|
124
|
-
const names = (s) => (String(s).match(/\{[a-zA-Z]+\}/g) || []).sort()
|
|
125
|
-
const junk = (s) => /\{\{|\}\}|\$\{/.test(String(s))
|
|
126
|
-
for (const k of Object.keys(zh)) {
|
|
127
|
-
assert.ok(!junk(zh[k]), `zhDict['${k}'] 占位符异常:${zh[k]}`)
|
|
128
|
-
assert.ok(!junk(en[k]), `enDict['${k}'] 占位符异常:${en[k]}`)
|
|
129
|
-
assert.deepEqual(names(zh[k]), names(en[k]), `占位符集合不一致:${k}`)
|
|
130
|
-
}
|
|
131
|
-
})
|