dsh-mop 0.2.0 → 0.2.1
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/client.js +191 -126
- package/lib/artifacts.mjs +15 -3
- package/lib/clean.mjs +132 -115
- package/lib/errors.mjs +14 -0
- package/lib/guard.mjs +7 -2
- package/lib/routes.mjs +3 -2
- package/lib/session-shell.mjs +9 -11
- package/lib/store.mjs +90 -30
- package/package.json +1 -1
package/lib/artifacts.mjs
CHANGED
|
@@ -4,6 +4,20 @@ import { reject } from './errors.mjs';
|
|
|
4
4
|
|
|
5
5
|
export const isSystemMetadata = (name) => ['.DS_Store', 'Thumbs.db', 'desktop.ini'].includes(name);
|
|
6
6
|
|
|
7
|
+
// 会话目录内容词表:扫描器(store)、purge 校验器(clean)与残壳删除器
|
|
8
|
+
// (session-shell)共用同一份定义;任何一处私有拷贝都会让三者对同一目录
|
|
9
|
+
// 的分类互相矛盾。
|
|
10
|
+
export const SESSION_DIR_RE = /^session-[0-9a-zA-Z-]+$/;
|
|
11
|
+
export const SESSION_LOG_RE = /^session(?:\.v\d+)?\.jsonl(?:\.zstd)?$/;
|
|
12
|
+
export const EVENT_ONLY_LOG_NAMES = ['session.v4.jsonl', 'session.v4.jsonl.zstd'];
|
|
13
|
+
export const SESSION_LOCK = 'session.lock';
|
|
14
|
+
|
|
15
|
+
/** bigint lstat 身份守卫:校验与删除之间的 TOCTOU 窗口内文件不得被替换。 */
|
|
16
|
+
export function assertFileIdentity(current, previous) {
|
|
17
|
+
if (!current.isFile() || current.isSymbolicLink() || current.dev !== previous.dev || current.ino !== previous.ino
|
|
18
|
+
|| current.size !== previous.size || current.mtimeNs !== previous.mtimeNs) reject('session_changed');
|
|
19
|
+
}
|
|
20
|
+
|
|
7
21
|
export async function removeEmptyProject(project, root) {
|
|
8
22
|
project = resolve(project);
|
|
9
23
|
root = resolve(root);
|
|
@@ -21,9 +35,7 @@ export async function removeEmptyProject(project, root) {
|
|
|
21
35
|
entries.push({ path, info });
|
|
22
36
|
}
|
|
23
37
|
for (const { path, info } of entries) {
|
|
24
|
-
|
|
25
|
-
if (!current.isFile() || current.isSymbolicLink() || current.dev !== info.dev || current.ino !== info.ino
|
|
26
|
-
|| current.size !== info.size || current.mtimeNs !== info.mtimeNs) reject('session_changed');
|
|
38
|
+
assertFileIdentity(await lstat(path, { bigint: true }), info);
|
|
27
39
|
}
|
|
28
40
|
for (const { path } of entries) await unlink(path);
|
|
29
41
|
await rmdir(project);
|
package/lib/clean.mjs
CHANGED
|
@@ -1,15 +1,17 @@
|
|
|
1
1
|
/** dsh-mop · 永久删除:日志目录、投影缓存、工作区注册一并清除,不留自有数据。
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
2
|
+
* 已归档且无进行中工作的会话当场删除(信任条件全部来自官方信号:agent
|
|
3
|
+
* idle、activity 瀑布、schedule 引用)。仍在内存注册表中的条目用官方
|
|
4
|
+
* api-session/removed 通知前端撤行;条目本身无公开释放 API,在残留页
|
|
5
|
+
* 如实记账(纯内存派生),重启后自动消散。 */
|
|
5
6
|
import { lstat, readdir, unlink } from 'node:fs/promises';
|
|
6
7
|
import { basename, dirname, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
7
8
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
8
|
-
import { assertSessionDirSafe } from './guard.mjs';
|
|
9
|
+
import { assertSessionDir, assertSessionDirSafe } from './guard.mjs';
|
|
9
10
|
import { removeSessionShell } from './session-shell.mjs';
|
|
10
|
-
import { cleanError, reject } from './errors.mjs';
|
|
11
|
-
import { buildOverview, isEventOnlyLog,
|
|
12
|
-
|
|
11
|
+
import { cleanError, failureShape, reject } from './errors.mjs';
|
|
12
|
+
import { buildOverview, isEventOnlyLog, isResidentSession, isArchivedSession, markPurgedResident,
|
|
13
|
+
sessionsRoot, projcacheDir, projcacheTable, workspaceTable, hiddenSessionIds, registrationRecord } from './store.mjs';
|
|
14
|
+
import { isSystemMetadata, removeEmptyProject, SESSION_LOCK, SESSION_LOG_RE } from './artifacts.mjs';
|
|
13
15
|
|
|
14
16
|
/** Server-derived keys identify the only paths and registry entries eligible for selection. */
|
|
15
17
|
export function listResidue(overview) {
|
|
@@ -40,22 +42,39 @@ export function listResidue(overview) {
|
|
|
40
42
|
label: basename(item.path) || item.path,
|
|
41
43
|
sizeBytes: item.sizeBytes, mtimeMs: item.mtimeMs,
|
|
42
44
|
})),
|
|
45
|
+
...(overview.residue.memoryResidents ?? []).map((item) => ({
|
|
46
|
+
key: `memory:${item.id}`, kind: 'memory-resident', id: item.id, label: item.title || item.id,
|
|
47
|
+
sizeBytes: null, mtimeMs: null,
|
|
48
|
+
})),
|
|
43
49
|
];
|
|
44
50
|
}
|
|
45
51
|
|
|
46
|
-
const LOG = /^session(?:\.v\d+)?\.jsonl(?:\.zstd)?$/;
|
|
47
52
|
const purging = new Set();
|
|
48
53
|
const unarchiveOwner = new AsyncLocalStorage();
|
|
49
54
|
export function isPurgingSession(id) { return purging.has(id); }
|
|
50
55
|
export function isExternalUnarchive(id) { return purging.has(id) && unarchiveOwner.getStore() !== id; }
|
|
51
56
|
|
|
52
|
-
/**
|
|
53
|
-
|
|
57
|
+
/** 与 index.js 两个钩子(否决外部 unarchive / session created)联动的删除
|
|
58
|
+
* 窗口锁;purge 与残留清理两个流程共用同一获取/释放协议。 */
|
|
59
|
+
async function withPurging(id, run) {
|
|
60
|
+
if (purging.has(id)) reject('purge_busy');
|
|
61
|
+
purging.add(id);
|
|
62
|
+
try { return await run(); } finally { purging.delete(id); }
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** 缓存删除与注册 detach 是同一个清理单元:官方缓存表拥有文件与内存两份
|
|
66
|
+
* 视图,直接 unlink 会让两者不一致直到重启。 */
|
|
67
|
+
async function clearRegistrations(cache, targets, id) {
|
|
68
|
+
await cache.delete(id);
|
|
69
|
+
for (const workspace of targets) await workspace.detachSession(id);
|
|
70
|
+
}
|
|
54
71
|
|
|
55
72
|
const isTaskTarget = (task, id) => (task.target?.kind === 'session' || task.target?.kind === 'new_once') && task.target.sessionId === id;
|
|
56
73
|
|
|
57
|
-
|
|
58
|
-
|
|
74
|
+
/** 信任条件全部来自官方信号。`purge` 语境下,指向常驻会话的暂停任务也算
|
|
75
|
+
* 引用:文件删除后条目仍在内存,恢复的任务可能唤醒已删除的会话。 */
|
|
76
|
+
async function checkCurrent(ctx, id, { purge = false } = {}) {
|
|
77
|
+
if (!isArchivedSession(ctx, id)) reject('session_not_archived');
|
|
59
78
|
const agent = ctx.get('agents')?.get(id);
|
|
60
79
|
if (agent && agent.status !== 'idle') reject('session_resident');
|
|
61
80
|
let activity;
|
|
@@ -68,24 +87,22 @@ async function checkCurrent(ctx, id) {
|
|
|
68
87
|
let tasks;
|
|
69
88
|
try { tasks = await schedule.catalog(); } catch { reject('reference_check_failed'); }
|
|
70
89
|
if (!Array.isArray(tasks)) reject('reference_check_failed');
|
|
71
|
-
if (tasks.some((task) =>
|
|
90
|
+
if (tasks.some((task) => isTaskTarget(task, id)
|
|
91
|
+
&& (!['paused', 'ended'].includes(task.status)
|
|
92
|
+
|| (purge && task.status === 'paused' && isResidentSession(ctx, id))))) reject('schedule_reference');
|
|
72
93
|
}
|
|
73
94
|
}
|
|
74
95
|
|
|
75
96
|
async function workspaceTargets(ctx, id) {
|
|
76
97
|
const workspaces = await ctx.workspaceRegistry.list();
|
|
77
|
-
|
|
78
|
-
if (!table) reject('workspace_unavailable');
|
|
98
|
+
if (!workspaceTable(ctx)) reject('workspace_unavailable');
|
|
79
99
|
const targets = [];
|
|
80
100
|
for (const workspace of workspaces) {
|
|
81
|
-
const record =
|
|
82
|
-
if (!record || !Array.isArray(record.sessionIds)) reject('workspace_unavailable');
|
|
101
|
+
const record = registrationRecord(ctx, workspace);
|
|
83
102
|
if (!record.sessionIds.includes(id)) continue;
|
|
84
103
|
// detachSession prunes every hidden candidate, not only the chosen ID.
|
|
85
|
-
const
|
|
86
|
-
const hidden = record.sessionIds.filter((other) => other !== id && !visible.has(other));
|
|
104
|
+
const hidden = hiddenSessionIds(workspace, record).filter((other) => other !== id);
|
|
87
105
|
if (hidden.length) throw Object.assign(cleanError('workspace_filtered'), { blockedIds: hidden });
|
|
88
|
-
if (typeof workspace.detachSession !== 'function') reject('workspace_unavailable');
|
|
89
106
|
targets.push(workspace);
|
|
90
107
|
}
|
|
91
108
|
return targets;
|
|
@@ -96,24 +113,23 @@ async function logFiles(snapshot, id) {
|
|
|
96
113
|
if (snapshot.formatStatus !== 'current') reject('historical_format');
|
|
97
114
|
const selected = resolve(snapshot.location.path);
|
|
98
115
|
const dir = dirname(selected);
|
|
99
|
-
|
|
100
|
-
await assertCanonicalSessionPath(sessionsRoot(), dir);
|
|
116
|
+
await assertSessionDir(dir, id);
|
|
101
117
|
const names = await readdir(dir);
|
|
102
118
|
const files = [];
|
|
103
119
|
for (const name of names) {
|
|
104
|
-
if (name ===
|
|
120
|
+
if (name === SESSION_LOCK || isSystemMetadata(name)) {
|
|
105
121
|
const lock = await lstat(resolve(dir, name));
|
|
106
122
|
if (!lock.isFile() || lock.isSymbolicLink()) reject('unsafe_path');
|
|
107
123
|
continue;
|
|
108
124
|
}
|
|
109
|
-
if (!
|
|
125
|
+
if (!SESSION_LOG_RE.test(name)) reject('unknown_artifact');
|
|
110
126
|
const path = resolve(dir, name);
|
|
111
127
|
const stat = await lstat(path);
|
|
112
128
|
if (!stat.isFile() || stat.isSymbolicLink()) reject('unsafe_path');
|
|
113
129
|
files.push(path);
|
|
114
130
|
}
|
|
115
131
|
if (!files.includes(selected)) reject('unsafe_path');
|
|
116
|
-
return files.
|
|
132
|
+
return [...files.filter((file) => file !== selected), selected];
|
|
117
133
|
}
|
|
118
134
|
|
|
119
135
|
/** Delete verified JSONL generations of non-resident archived sessions. */
|
|
@@ -122,77 +138,83 @@ export async function purgeSessions(ctx, overview, sessionIds) {
|
|
|
122
138
|
const deleted = [], failed = [];
|
|
123
139
|
for (const id of new Set(sessionIds)) {
|
|
124
140
|
const session = byId.get(id);
|
|
125
|
-
|
|
141
|
+
// 变更一旦开始(删日志或清缓存/注册),之后的失败都是「部分已清理」
|
|
142
|
+
// 而非「未生效」;用独立错误码表达中间态,重试可收敛。
|
|
143
|
+
let mutated = false;
|
|
126
144
|
try {
|
|
127
145
|
if (!session) reject('session_not_found');
|
|
128
146
|
if (!session.archived) reject('session_not_archived');
|
|
129
147
|
if (session.protected) reject('protected_workspace');
|
|
130
148
|
if (session.purgeBlock === 'reference_check_failed') reject(session.purgeBlock);
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
149
|
+
await withPurging(id, async () => {
|
|
150
|
+
await checkCurrent(ctx, id, { purge: true });
|
|
151
|
+
const snapshot = await ctx.sessionPersistence.stat(id);
|
|
152
|
+
// overview 时磁盘上还有日志、此刻 persistence 却无快照:状态已漂移,
|
|
153
|
+
// 且下面那次残留扫描的结果也会随之作废。
|
|
154
|
+
if (!snapshot && session.sessionDir) reject('session_changed');
|
|
155
|
+
let files = [];
|
|
156
|
+
const remaining = snapshot ? [] : (await buildOverview(ctx, { protectWorkspaces: [] })).residue.shellDirs
|
|
157
|
+
.filter((item) => item.sessionId === id);
|
|
158
|
+
const shells = snapshot?.location?.path ? [{ sessionDir: dirname(snapshot.location.path), shellType: 'lock' }] : remaining;
|
|
159
|
+
if (snapshot) {
|
|
160
|
+
files = await logFiles(snapshot, id);
|
|
161
|
+
if (snapshot.header?.origin === 'subagent' && snapshot.header.parentSession) {
|
|
162
|
+
const parent = await ctx.sessionPersistence.stat(snapshot.header.parentSession);
|
|
163
|
+
if (parent?.formatStatus === 'migration-required') reject('historical_parent');
|
|
164
|
+
}
|
|
165
|
+
} else {
|
|
166
|
+
// An interrupted purge leaves only the lock file. A directory with
|
|
167
|
+
// other unrecognized artifacts is not proof that the log is gone.
|
|
168
|
+
for (const shell of shells) {
|
|
169
|
+
assertSessionDirSafe(shell.sessionDir, id);
|
|
170
|
+
if (!['empty', 'lock', 'log'].includes(shell.shellType)) reject('unknown_artifact');
|
|
171
|
+
}
|
|
145
172
|
}
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
//
|
|
150
|
-
//
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
173
|
+
let targets = await workspaceTargets(ctx, id);
|
|
174
|
+
const cache = projcacheTable(ctx);
|
|
175
|
+
if (!cache) reject('cache_unavailable');
|
|
176
|
+
// Resident entries are no longer a refusal: checkCurrent's official
|
|
177
|
+
// signals (idle agent, empty activity, no task reference) already
|
|
178
|
+
// describe what can safely be deleted; the in-memory entry itself is
|
|
179
|
+
// handled after the removal below.
|
|
180
|
+
await checkCurrent(ctx, id, { purge: true });
|
|
181
|
+
if (snapshot) {
|
|
182
|
+
const current = await ctx.sessionPersistence.stat(id);
|
|
183
|
+
if (!current || current.revision !== snapshot.revision || current.location?.path !== snapshot.location.path) reject('session_changed');
|
|
184
|
+
files = await logFiles(current, id);
|
|
154
185
|
}
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
}
|
|
186
|
-
// Once the log and registrations are gone, the registry's own
|
|
187
|
-
// unarchive hook may run to retire the otherwise orphaned archive ID.
|
|
188
|
-
await unarchiveOwner.run(id, () => ctx.workspaceRegistry.unarchiveSession(id));
|
|
189
|
-
deleted.push(id);
|
|
186
|
+
const cleanAssociated = async () => {
|
|
187
|
+
mutated = true;
|
|
188
|
+
await clearRegistrations(cache, targets, id);
|
|
189
|
+
};
|
|
190
|
+
if (snapshot || shells.length === 0) {
|
|
191
|
+
for (const file of files) { await unlink(file); mutated = true; }
|
|
192
|
+
await cleanAssociated();
|
|
193
|
+
}
|
|
194
|
+
for (const [index, shell] of shells.entries()) {
|
|
195
|
+
await removeSessionShell(shell.sessionDir, id, {
|
|
196
|
+
mode: shell.shellType === 'log' ? 'event-only' : 'metadata',
|
|
197
|
+
recheck: async () => {
|
|
198
|
+
await checkCurrent(ctx, id, { purge: true });
|
|
199
|
+
if (await ctx.sessionPersistence.stat(id)) reject('session_changed');
|
|
200
|
+
if (shell.shellType === 'log' && !await isEventOnlyLog(ctx, id, shell.sessionDir)) reject('session_changed');
|
|
201
|
+
targets = await workspaceTargets(ctx, id);
|
|
202
|
+
},
|
|
203
|
+
cleanup: !snapshot && index === 0 ? cleanAssociated : undefined,
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
// Once the log and registrations are gone, the registry's own
|
|
207
|
+
// unarchive hook may run to retire the otherwise orphaned archive ID.
|
|
208
|
+
await unarchiveOwner.run(id, () => ctx.workspaceRegistry.unarchiveSession(id));
|
|
209
|
+
if (isResidentSession(ctx, id)) markPurgedResident(id);
|
|
210
|
+
// The shipped removal notification on the forwarded allowlist: clients
|
|
211
|
+
// drop the row immediately; failure is display-only and logged.
|
|
212
|
+
try { ctx.emit('api-session/removed', id); }
|
|
213
|
+
catch (error) { ctx.logger?.warn?.(`dsh-mop: cannot announce removal of "${id}"`, error); }
|
|
214
|
+
deleted.push(id);
|
|
215
|
+
});
|
|
190
216
|
} catch (error) {
|
|
191
|
-
failed.push({ id, title: session?.title,
|
|
192
|
-
...(error?.blockedIds ? { blockedCount: error.blockedIds.length } : {}),
|
|
193
|
-
...(!error?.cleanCode ? { message: String(error?.message ?? error) } : {}) });
|
|
194
|
-
} finally {
|
|
195
|
-
if (claimed) purging.delete(id);
|
|
217
|
+
failed.push({ id, title: session?.title, ...failureShape(error, { mutated, fallback: 'purge_failed' }) });
|
|
196
218
|
}
|
|
197
219
|
}
|
|
198
220
|
return { deleted, failed };
|
|
@@ -208,29 +230,29 @@ export async function cleanResidue(ctx, overview, selectedKeys, confirmedTasks =
|
|
|
208
230
|
const completedRegistrations = new Set();
|
|
209
231
|
for (const key of selection) {
|
|
210
232
|
const item = candidates.get(key);
|
|
233
|
+
// 同 purgeSessions:cleanup 夹层一旦执行(缓存+注册已清),失败报
|
|
234
|
+
// cleanup_partial 而非笼统的 session_changed。
|
|
235
|
+
let mutated = false;
|
|
211
236
|
try {
|
|
212
237
|
if (!item) reject('residue_changed');
|
|
213
238
|
if (item.kind === 'ghost-registry') {
|
|
214
239
|
if (!completedRegistrations.has(key)) {
|
|
215
240
|
const workspace = (await ctx.workspaceRegistry.list()).find((entry) => entry.id === item.workspaceId);
|
|
216
|
-
|
|
217
|
-
|
|
241
|
+
if (!workspace) reject('workspace_unavailable');
|
|
242
|
+
const record = registrationRecord(ctx, workspace);
|
|
218
243
|
if (!record.sessionIds.includes(item.id)) reject('residue_changed');
|
|
219
|
-
const
|
|
220
|
-
const hidden = record.sessionIds.filter((id) => !visible.has(id));
|
|
221
|
-
const affected = new Set([item.id, ...hidden]);
|
|
244
|
+
const affected = new Set([item.id, ...hiddenSessionIds(workspace, record)]);
|
|
222
245
|
const blockedIds = [...affected].filter((id) => {
|
|
223
246
|
const affectedKey = `ghost:${item.workspaceId}:${id}`;
|
|
224
247
|
return !selection.has(affectedKey) || !candidates.has(affectedKey);
|
|
225
248
|
});
|
|
226
249
|
if (blockedIds.length) throw Object.assign(cleanError('workspace_filtered'), { blockedIds });
|
|
227
250
|
for (const id of affected) {
|
|
228
|
-
if (isResidentSession(ctx, id)
|
|
229
|
-
|| (ctx.workspaceRegistry.archivedSessionIds ?? []).includes(id)
|
|
251
|
+
if (isResidentSession(ctx, id) || isArchivedSession(ctx, id)
|
|
230
252
|
|| await ctx.sessionPersistence.stat(id)) reject('session_changed');
|
|
231
253
|
}
|
|
232
254
|
await workspace.detachSession(item.id);
|
|
233
|
-
const remaining =
|
|
255
|
+
const remaining = workspaceTable(ctx)?.get(item.workspaceId)?.sessionIds;
|
|
234
256
|
if (!Array.isArray(remaining) || [...affected].some((id) => remaining.includes(id))) reject('residue_changed');
|
|
235
257
|
for (const id of affected) completedRegistrations.add(`ghost:${item.workspaceId}:${id}`);
|
|
236
258
|
}
|
|
@@ -247,7 +269,7 @@ export async function cleanResidue(ctx, overview, selectedKeys, confirmedTasks =
|
|
|
247
269
|
if (!Array.isArray(listed)) reject('reference_check_failed');
|
|
248
270
|
if (listed.some((entry) => (entry?.header?.id ?? entry?.id) === item.targetSessionId)
|
|
249
271
|
|| isResidentSession(ctx, item.targetSessionId)
|
|
250
|
-
|| (ctx
|
|
272
|
+
|| isArchivedSession(ctx, item.targetSessionId)
|
|
251
273
|
|| await ctx.sessionPersistence.stat(item.targetSessionId)) reject('session_changed');
|
|
252
274
|
let result;
|
|
253
275
|
try { result = await schedule.edit({ id: item.id, action: 'delete', expectedUpdatedAt: item.updatedAt }); }
|
|
@@ -260,15 +282,13 @@ export async function cleanResidue(ctx, overview, selectedKeys, confirmedTasks =
|
|
|
260
282
|
if (!rel || isAbsolute(rel) || rel === '..' || rel.startsWith(`..${sep}`)) reject('unsafe_path');
|
|
261
283
|
// The official cache owns an in-memory table as well as the file. A
|
|
262
284
|
// direct unlink leaves those two views inconsistent until restart.
|
|
263
|
-
const
|
|
264
|
-
if (!
|
|
265
|
-
if (!await
|
|
285
|
+
const cache = projcacheTable(ctx);
|
|
286
|
+
if (!cache) reject('cache_unavailable');
|
|
287
|
+
if (!await cache.delete(item.id)) reject('residue_changed');
|
|
266
288
|
} else if (item.kind === 'shell-dir' && ['empty', 'lock', 'log', 'unknown'].includes(item.shellType)) {
|
|
267
289
|
const target = key.slice('shell:'.length);
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
try {
|
|
271
|
-
if ((ctx.workspaceRegistry.archivedSessionIds ?? []).includes(item.id)) await checkCurrent(ctx, item.id);
|
|
290
|
+
await withPurging(item.id, async () => {
|
|
291
|
+
if (isArchivedSession(ctx, item.id)) await checkCurrent(ctx, item.id);
|
|
272
292
|
// A shell whose session is still mounted in this instance is not
|
|
273
293
|
// removable without a DSH restart (no public release API).
|
|
274
294
|
if (isResidentSession(ctx, item.id)) reject('session_resident');
|
|
@@ -277,8 +297,8 @@ export async function cleanResidue(ctx, overview, selectedKeys, confirmedTasks =
|
|
|
277
297
|
const eventOnly = await isEventOnlyLog(ctx, item.id, target).catch(() => false);
|
|
278
298
|
const mode = eventOnly ? 'event-only' : item.shellType === 'unknown' ? 'unknown' : 'metadata';
|
|
279
299
|
let targets = await workspaceTargets(ctx, item.id);
|
|
280
|
-
const cache = ctx
|
|
281
|
-
if (!cache
|
|
300
|
+
const cache = projcacheTable(ctx);
|
|
301
|
+
if (!cache) reject('cache_unavailable');
|
|
282
302
|
await removeSessionShell(target, item.id, {
|
|
283
303
|
mode,
|
|
284
304
|
recheck: async () => {
|
|
@@ -287,29 +307,26 @@ export async function cleanResidue(ctx, overview, selectedKeys, confirmedTasks =
|
|
|
287
307
|
if (mode === 'event-only' && !await isEventOnlyLog(ctx, item.id, target)) reject('session_changed');
|
|
288
308
|
// A shell and its cache/registrations are one cleanup, whether
|
|
289
309
|
// it originated from an interrupted purge or outside the plugin.
|
|
290
|
-
if ((ctx
|
|
310
|
+
if (isArchivedSession(ctx, item.id)) {
|
|
291
311
|
await checkCurrent(ctx, item.id);
|
|
292
312
|
}
|
|
293
313
|
targets = await workspaceTargets(ctx, item.id);
|
|
294
314
|
},
|
|
295
315
|
cleanup: async () => {
|
|
296
|
-
|
|
297
|
-
|
|
316
|
+
mutated = true;
|
|
317
|
+
await clearRegistrations(cache, targets, item.id);
|
|
298
318
|
},
|
|
299
319
|
});
|
|
300
|
-
if ((ctx
|
|
320
|
+
if (isArchivedSession(ctx, item.id)) {
|
|
301
321
|
await unarchiveOwner.run(item.id, () => ctx.workspaceRegistry.unarchiveSession(item.id));
|
|
302
322
|
}
|
|
303
|
-
}
|
|
323
|
+
});
|
|
304
324
|
} else if (item.kind === 'empty-project') {
|
|
305
325
|
await removeEmptyProject(item.id, sessionsRoot());
|
|
306
326
|
} else reject('residue_unavailable');
|
|
307
327
|
done.push({ key, kind: item.kind, id: item.id });
|
|
308
328
|
} catch (error) {
|
|
309
|
-
failed.push({ key, kind: item?.kind, id: item?.id,
|
|
310
|
-
...(error?.blockedIds ? { blockedCount: error.blockedIds.length } : {}),
|
|
311
|
-
...(!error?.cleanCode ? { message: String(error?.message ?? error) } : {}),
|
|
312
|
-
...(error?.cleanCode === 'schedule_delete_failed' && error.cause ? { detail: String(error.cause?.message ?? error.cause) } : {}) });
|
|
329
|
+
failed.push({ key, kind: item?.kind, id: item?.id, ...failureShape(error, { mutated, fallback: 'residue_failed' }) });
|
|
313
330
|
}
|
|
314
331
|
}
|
|
315
332
|
return { done, failed };
|
package/lib/errors.mjs
CHANGED
|
@@ -4,3 +4,17 @@ export function cleanError(code, cause) {
|
|
|
4
4
|
}
|
|
5
5
|
|
|
6
6
|
export function reject(code, cause) { throw cleanError(code, cause); }
|
|
7
|
+
|
|
8
|
+
/** Uniform failure projection shared by purge, residue cleanup and the routes:
|
|
9
|
+
* once a mutation started the code becomes cleanup_partial; the raw message is
|
|
10
|
+
* kept only when no stable code matched; blocked count / wrapped cause ride
|
|
11
|
+
* along when present. */
|
|
12
|
+
export function failureShape(error, { mutated = false, fallback } = {}) {
|
|
13
|
+
const code = mutated ? 'cleanup_partial' : error?.cleanCode || fallback;
|
|
14
|
+
return {
|
|
15
|
+
...(code !== undefined ? { code } : {}),
|
|
16
|
+
...(error?.blockedIds ? { blockedCount: error.blockedIds.length } : {}),
|
|
17
|
+
...(!error?.cleanCode ? { message: String(error?.message ?? error) } : {}),
|
|
18
|
+
...(error?.cleanCode === 'schedule_delete_failed' && error.cause ? { detail: String(error.cause?.message ?? error.cause) } : {}),
|
|
19
|
+
};
|
|
20
|
+
}
|
package/lib/guard.mjs
CHANGED
|
@@ -2,10 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
import { basename, resolve, sep } from 'node:path';
|
|
4
4
|
import { dshHome } from './home.mjs';
|
|
5
|
+
import { SESSION_DIR_RE, assertCanonicalSessionPath } from './artifacts.mjs';
|
|
5
6
|
import { reject } from './errors.mjs';
|
|
6
7
|
|
|
7
|
-
const SESSION_DIR_RE = /^session-[0-9a-zA-Z-]+$/;
|
|
8
|
-
|
|
9
8
|
/** rm 会话目录前的断言:位于 sessions 根内、目录名 === 会话 id。 */
|
|
10
9
|
export function assertSessionDirSafe(sessionDir, sessionId) {
|
|
11
10
|
const root = resolve(dshHome('sessions'));
|
|
@@ -18,3 +17,9 @@ export function assertSessionDirSafe(sessionDir, sessionId) {
|
|
|
18
17
|
reject('unsafe_path');
|
|
19
18
|
}
|
|
20
19
|
}
|
|
20
|
+
|
|
21
|
+
/** 删除会话目录前的成对断言(safe + canonical),供 logFiles 与残壳删除共用。 */
|
|
22
|
+
export async function assertSessionDir(sessionDir, sessionId) {
|
|
23
|
+
assertSessionDirSafe(sessionDir, sessionId);
|
|
24
|
+
await assertCanonicalSessionPath(dshHome('sessions'), sessionDir);
|
|
25
|
+
}
|
package/lib/routes.mjs
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
*/
|
|
7
7
|
import { buildOverview } from './store.mjs';
|
|
8
8
|
import { purgeSessions, cleanResidue, listResidue } from './clean.mjs';
|
|
9
|
+
import { failureShape } from './errors.mjs';
|
|
9
10
|
|
|
10
11
|
const PREFIX = '/api/dsh-mop';
|
|
11
12
|
|
|
@@ -97,7 +98,7 @@ export function registerRoutes(ctx, config) {
|
|
|
97
98
|
if (error?.name === 'WorkspaceActiveSessionError' && Array.isArray(error.activity)) {
|
|
98
99
|
failed.push({ id, title: session.title, code: 'session_active', activity: error.activity });
|
|
99
100
|
} else {
|
|
100
|
-
failed.push({ id, ...(error
|
|
101
|
+
failed.push({ id, ...failureShape(error) });
|
|
101
102
|
}
|
|
102
103
|
}
|
|
103
104
|
}
|
|
@@ -121,7 +122,7 @@ export function registerRoutes(ctx, config) {
|
|
|
121
122
|
await ctx.workspaceRegistry.unarchiveSession(id);
|
|
122
123
|
done.push(id);
|
|
123
124
|
} catch (error) {
|
|
124
|
-
failed.push({ id, ...(error
|
|
125
|
+
failed.push({ id, ...failureShape(error) });
|
|
125
126
|
}
|
|
126
127
|
}
|
|
127
128
|
return json({ done, failed });
|
package/lib/session-shell.mjs
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
import { lstat, readdir, rmdir, unlink } from 'node:fs/promises';
|
|
2
2
|
import { dirname, join, resolve } from 'node:path';
|
|
3
3
|
import { dshHome } from './home.mjs';
|
|
4
|
-
import {
|
|
5
|
-
import { assertCanonicalSessionPath, isSystemMetadata, removeEmptyProject
|
|
4
|
+
import { assertSessionDir } from './guard.mjs';
|
|
5
|
+
import { assertCanonicalSessionPath, assertFileIdentity, isSystemMetadata, removeEmptyProject,
|
|
6
|
+
SESSION_LOG_RE, EVENT_ONLY_LOG_NAMES, SESSION_LOCK } from './artifacts.mjs';
|
|
6
7
|
import { reject } from './errors.mjs';
|
|
7
8
|
|
|
8
9
|
/** Validate and remove a session directory and its recognized files. */
|
|
9
10
|
export async function removeSessionShell(sessionDir, id, { recheck, mode = 'metadata', cleanup = async () => {} }) {
|
|
10
11
|
const target = resolve(sessionDir);
|
|
11
|
-
|
|
12
|
-
await assertCanonicalSessionPath(dshHome('sessions'), target);
|
|
12
|
+
await assertSessionDir(target, id);
|
|
13
13
|
const names = await readdir(target);
|
|
14
|
-
const allowed = (name) => name ===
|
|
15
|
-
|| (mode === 'event-only' &&
|
|
16
|
-
|| (mode === 'unknown' &&
|
|
14
|
+
const allowed = (name) => name === SESSION_LOCK || isSystemMetadata(name)
|
|
15
|
+
|| (mode === 'event-only' && EVENT_ONLY_LOG_NAMES.includes(name))
|
|
16
|
+
|| (mode === 'unknown' && !SESSION_LOG_RE.test(name));
|
|
17
17
|
if (names.some((name) => !allowed(name))) reject('unknown_artifact');
|
|
18
|
-
const files = [...names.filter((name) => name !==
|
|
18
|
+
const files = [...names.filter((name) => name !== SESSION_LOCK), ...names.filter((name) => name === SESSION_LOCK)];
|
|
19
19
|
const identities = new Map();
|
|
20
20
|
for (const name of files) {
|
|
21
21
|
const file = await lstat(join(target, name), { bigint: true });
|
|
@@ -29,9 +29,7 @@ export async function removeSessionShell(sessionDir, id, { recheck, mode = 'meta
|
|
|
29
29
|
const entries = await readdir(target);
|
|
30
30
|
if (entries.length !== expected.size || entries.some((name) => !expected.has(name))) reject('session_changed');
|
|
31
31
|
for (const [name, previous] of identities) {
|
|
32
|
-
|
|
33
|
-
if (!file.isFile() || file.isSymbolicLink() || file.dev !== previous.dev || file.ino !== previous.ino
|
|
34
|
-
|| file.size !== previous.size || file.mtimeNs !== previous.mtimeNs) reject('session_changed');
|
|
32
|
+
assertFileIdentity(await lstat(join(target, name), { bigint: true }), previous);
|
|
35
33
|
}
|
|
36
34
|
};
|
|
37
35
|
await verify();
|