dsh-mop 0.1.4 → 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/index.js CHANGED
@@ -1,17 +1,32 @@
1
- /** dsh-mop 宿主半边:清理遗留会话数据,经 connection.fetch 路由暴露给浏览器。 */
1
+ /**
2
+ * dsh-mop 宿主半边:清理遗留会话数据,经 connection.fetch 路由暴露给浏览器。
3
+ *
4
+ * 行级配置(protectWorkspaces)通过官方 Loader 的 Config 校验与编辑面
5
+ * (设置 → 插件 → dsh-mop 行 → 配置)读写。
6
+ * @module dsh-mop
7
+ */
8
+ import z from '@deepseek-ai/schemastery';
2
9
  import { registerRoutes } from './lib/routes.mjs';
3
10
  import { isPurgingSession, isExternalUnarchive } from './lib/clean.mjs';
4
11
  import { cleanError } from './lib/errors.mjs';
5
12
 
6
13
  export const inject = ['connection', 'sessionQuery', 'sessionPersistence', 'workspaceRegistry'];
7
14
 
15
+ /** 行配置 schema:受保护的工作区根路径列表(绝对路径)。 */
16
+ export const Config = z.object({
17
+ protectWorkspaces: z.array(z.string()).default([]),
18
+ });
19
+
8
20
  export function apply(ctx, rawConfig = {}) {
9
- const config = {
10
- protectWorkspaces: Array.isArray(rawConfig.protectWorkspaces)
11
- ? rawConfig.protectWorkspaces.filter((p) => typeof p === 'string' && p)
12
- : [],
13
- };
21
+ // Config 是唯一解析点:Loader 校验过的输入直接通过;未经校验的
22
+ // 畸形输入退回默认值,不让插件加载失败。
23
+ let config;
24
+ try { config = Config(rawConfig); } catch { config = Config({}); }
14
25
  // Coordinate same-host activation and unarchive with the deletion window.
26
+ // session/created 的同步 throw 是官方支持的否决路径(dsh-session 注释:
27
+ // "Synchronous throws intentionally propagate and veto publication");
28
+ // workspace/session-unarchiving 的 parallel 分发会把 rejection 聚合后
29
+ // 抛给调用方,同样阻断外部取消归档。
15
30
  if (typeof ctx.on === 'function') ctx.effect(() => {
16
31
  const stopUnarchive = ctx.on('workspace/session-unarchiving', ({ sessionId }) => {
17
32
  if (isExternalUnarchive(sessionId)) throw cleanError('purge_busy');
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
- const current = await lstat(path, { bigint: true });
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,13 +1,17 @@
1
- /** dsh-mop · 永久删除:日志目录、投影缓存、工作区注册一并清除,不留自有数据。 */
1
+ /** dsh-mop · 永久删除:日志目录、投影缓存、工作区注册一并清除,不留自有数据。
2
+ * 已归档且无进行中工作的会话当场删除(信任条件全部来自官方信号:agent
3
+ * idle、activity 瀑布、schedule 引用)。仍在内存注册表中的条目用官方
4
+ * api-session/removed 通知前端撤行;条目本身无公开释放 API,在残留页
5
+ * 如实记账(纯内存派生),重启后自动消散。 */
2
6
  import { lstat, readdir, unlink } from 'node:fs/promises';
3
7
  import { basename, dirname, isAbsolute, relative, resolve, sep } from 'node:path';
4
8
  import { AsyncLocalStorage } from 'node:async_hooks';
5
- import { assertSessionDirSafe } from './guard.mjs';
9
+ import { assertSessionDir, assertSessionDirSafe } from './guard.mjs';
6
10
  import { removeSessionShell } from './session-shell.mjs';
7
- import { cleanError, reject } from './errors.mjs';
8
- import { buildOverview, isEventOnlyLog, sessionsRoot, projcacheDir } from './store.mjs';
9
- import { releaseResidentSession } from './release-session.mjs';
10
- import { assertCanonicalSessionPath, isSystemMetadata, removeEmptyProject } from './artifacts.mjs';
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';
11
15
 
12
16
  /** Server-derived keys identify the only paths and registry entries eligible for selection. */
13
17
  export function listResidue(overview) {
@@ -38,19 +42,39 @@ export function listResidue(overview) {
38
42
  label: basename(item.path) || item.path,
39
43
  sizeBytes: item.sizeBytes, mtimeMs: item.mtimeMs,
40
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
+ })),
41
49
  ];
42
50
  }
43
51
 
44
- const LOG = /^session(?:\.v\d+)?\.jsonl(?:\.zstd)?$/;
45
52
  const purging = new Set();
46
53
  const unarchiveOwner = new AsyncLocalStorage();
47
54
  export function isPurgingSession(id) { return purging.has(id); }
48
55
  export function isExternalUnarchive(id) { return purging.has(id) && unarchiveOwner.getStore() !== id; }
49
56
 
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
+ }
71
+
50
72
  const isTaskTarget = (task, id) => (task.target?.kind === 'session' || task.target?.kind === 'new_once') && task.target.sessionId === id;
51
73
 
52
- async function checkCurrent(ctx, id) {
53
- if (!(ctx.workspaceRegistry.archivedSessionIds ?? []).includes(id)) reject('session_not_archived');
74
+ /** 信任条件全部来自官方信号。`purge` 语境下,指向常驻会话的暂停任务也算
75
+ * 引用:文件删除后条目仍在内存,恢复的任务可能唤醒已删除的会话。 */
76
+ async function checkCurrent(ctx, id, { purge = false } = {}) {
77
+ if (!isArchivedSession(ctx, id)) reject('session_not_archived');
54
78
  const agent = ctx.get('agents')?.get(id);
55
79
  if (agent && agent.status !== 'idle') reject('session_resident');
56
80
  let activity;
@@ -63,25 +87,22 @@ async function checkCurrent(ctx, id) {
63
87
  let tasks;
64
88
  try { tasks = await schedule.catalog(); } catch { reject('reference_check_failed'); }
65
89
  if (!Array.isArray(tasks)) reject('reference_check_failed');
66
- if (tasks.some((task) => !['paused', 'ended'].includes(task.status) && isTaskTarget(task, id))) reject('schedule_reference');
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');
67
93
  }
68
94
  }
69
95
 
70
96
  async function workspaceTargets(ctx, id) {
71
97
  const workspaces = await ctx.workspaceRegistry.list();
72
- const domain = ctx.get('storageDomain')?.get('workspace');
73
- const table = domain?.table('workspaces');
74
- if (!table || typeof table.get !== 'function') reject('workspace_unavailable');
98
+ if (!workspaceTable(ctx)) reject('workspace_unavailable');
75
99
  const targets = [];
76
100
  for (const workspace of workspaces) {
77
- const record = table.get(workspace.id);
78
- if (!record || !Array.isArray(record.sessionIds)) reject('workspace_unavailable');
101
+ const record = registrationRecord(ctx, workspace);
79
102
  if (!record.sessionIds.includes(id)) continue;
80
103
  // detachSession prunes every hidden candidate, not only the chosen ID.
81
- const visible = new Set(workspace.sessionIds ?? []);
82
- const hidden = record.sessionIds.filter((other) => other !== id && !visible.has(other));
104
+ const hidden = hiddenSessionIds(workspace, record).filter((other) => other !== id);
83
105
  if (hidden.length) throw Object.assign(cleanError('workspace_filtered'), { blockedIds: hidden });
84
- if (typeof workspace.detachSession !== 'function') reject('workspace_unavailable');
85
106
  targets.push(workspace);
86
107
  }
87
108
  return targets;
@@ -92,105 +113,108 @@ async function logFiles(snapshot, id) {
92
113
  if (snapshot.formatStatus !== 'current') reject('historical_format');
93
114
  const selected = resolve(snapshot.location.path);
94
115
  const dir = dirname(selected);
95
- assertSessionDirSafe(dir, id);
96
- await assertCanonicalSessionPath(sessionsRoot(), dir);
116
+ await assertSessionDir(dir, id);
97
117
  const names = await readdir(dir);
98
118
  const files = [];
99
119
  for (const name of names) {
100
- if (name === 'session.lock' || isSystemMetadata(name)) {
120
+ if (name === SESSION_LOCK || isSystemMetadata(name)) {
101
121
  const lock = await lstat(resolve(dir, name));
102
122
  if (!lock.isFile() || lock.isSymbolicLink()) reject('unsafe_path');
103
123
  continue;
104
124
  }
105
- if (!LOG.test(name)) reject('unknown_artifact');
125
+ if (!SESSION_LOG_RE.test(name)) reject('unknown_artifact');
106
126
  const path = resolve(dir, name);
107
127
  const stat = await lstat(path);
108
128
  if (!stat.isFile() || stat.isSymbolicLink()) reject('unsafe_path');
109
129
  files.push(path);
110
130
  }
111
131
  if (!files.includes(selected)) reject('unsafe_path');
112
- return files.sort((a, b) => (a === selected ? 1 : 0) - (b === selected ? 1 : 0));
132
+ return [...files.filter((file) => file !== selected), selected];
113
133
  }
114
134
 
115
- /** Delete verified JSONL generations after releasing the local resident session. */
135
+ /** Delete verified JSONL generations of non-resident archived sessions. */
116
136
  export async function purgeSessions(ctx, overview, sessionIds) {
117
137
  const byId = new Map(overview.sessions.map((session) => [session.id, session]));
118
138
  const deleted = [], failed = [];
119
139
  for (const id of new Set(sessionIds)) {
120
140
  const session = byId.get(id);
121
- let claimed = false;
141
+ // 变更一旦开始(删日志或清缓存/注册),之后的失败都是「部分已清理」
142
+ // 而非「未生效」;用独立错误码表达中间态,重试可收敛。
143
+ let mutated = false;
122
144
  try {
123
145
  if (!session) reject('session_not_found');
124
146
  if (!session.archived) reject('session_not_archived');
125
147
  if (session.protected) reject('protected_workspace');
126
148
  if (session.purgeBlock === 'reference_check_failed') reject(session.purgeBlock);
127
- if (purging.has(id)) reject('purge_busy');
128
- purging.add(id);
129
- claimed = true;
130
- await checkCurrent(ctx, id);
131
- await releaseResidentSession(ctx, id);
132
- await checkCurrent(ctx, id);
133
- const snapshot = await ctx.sessionPersistence.stat(id);
134
- let files = [];
135
- const remaining = snapshot ? [] : (await buildOverview(ctx, { protectWorkspaces: [] })).residue.shellDirs
136
- .filter((item) => item.sessionId === id);
137
- const shells = snapshot?.location?.path ? [{ sessionDir: dirname(snapshot.location.path), shellType: 'lock' }] : remaining;
138
- if (snapshot) {
139
- files = await logFiles(snapshot, id);
140
- if (snapshot.header?.origin === 'subagent' && snapshot.header.parentSession) {
141
- const parent = await ctx.sessionPersistence.stat(snapshot.header.parentSession);
142
- if (parent?.formatStatus === 'migration-required') reject('historical_parent');
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
+ }
143
172
  }
144
- } else if (session.sessionDir) {
145
- reject('session_changed');
146
- } else {
147
- // An interrupted purge leaves only the lock file. A directory with
148
- // other unrecognized artifacts is not proof that the log is gone.
149
- for (const shell of shells) {
150
- assertSessionDirSafe(shell.sessionDir, id);
151
- if (!['empty', 'lock', 'log'].includes(shell.shellType)) reject('unknown_artifact');
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);
152
185
  }
153
- }
154
- let targets = await workspaceTargets(ctx, id);
155
- const cache = ctx.get('storageDomain')?.get('session_projcache')?.table('sessions');
156
- if (!cache || typeof cache.delete !== 'function') reject('cache_unavailable');
157
- await checkCurrent(ctx, id);
158
- if (ctx.get('sessions')?.get(id) || ctx.get('agents')?.get(id)) reject('session_resident');
159
- if (snapshot) {
160
- const current = await ctx.sessionPersistence.stat(id);
161
- if (!current || current.revision !== snapshot.revision || current.location?.path !== snapshot.location.path) reject('session_changed');
162
- files = await logFiles(current, id);
163
- }
164
- const cleanAssociated = async () => {
165
- await cache.delete(id);
166
- for (const workspace of targets) await workspace.detachSession(id);
167
- };
168
- if (snapshot || shells.length === 0) {
169
- for (const file of files) await unlink(file);
170
- await cleanAssociated();
171
- }
172
- for (const [index, shell] of shells.entries()) {
173
- await removeSessionShell(shell.sessionDir, id, {
174
- mode: shell.shellType === 'log' ? 'event-only' : 'metadata',
175
- recheck: async () => {
176
- await checkCurrent(ctx, id);
177
- if (await ctx.sessionPersistence.stat(id)) reject('session_changed');
178
- if (shell.shellType === 'log' && !await isEventOnlyLog(ctx, id, shell.sessionDir)) reject('session_changed');
179
- targets = await workspaceTargets(ctx, id);
180
- },
181
- cleanup: !snapshot && index === 0 ? cleanAssociated : undefined,
182
- });
183
- }
184
- // Once the log and registrations are gone, the registry's own
185
- // unarchive hook may run to retire the otherwise orphaned archive ID.
186
- await unarchiveOwner.run(id, () => ctx.workspaceRegistry.unarchiveSession(id));
187
- 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
+ });
188
216
  } catch (error) {
189
- failed.push({ id, title: session?.title, code: error?.cleanCode || 'purge_failed',
190
- ...(error?.blockedIds ? { blockedCount: error.blockedIds.length } : {}),
191
- ...(!error?.cleanCode ? { message: String(error?.message ?? error) } : {}) });
192
- } finally {
193
- if (claimed) purging.delete(id);
217
+ failed.push({ id, title: session?.title, ...failureShape(error, { mutated, fallback: 'purge_failed' }) });
194
218
  }
195
219
  }
196
220
  return { deleted, failed };
@@ -206,30 +230,29 @@ export async function cleanResidue(ctx, overview, selectedKeys, confirmedTasks =
206
230
  const completedRegistrations = new Set();
207
231
  for (const key of selection) {
208
232
  const item = candidates.get(key);
233
+ // 同 purgeSessions:cleanup 夹层一旦执行(缓存+注册已清),失败报
234
+ // cleanup_partial 而非笼统的 session_changed。
235
+ let mutated = false;
209
236
  try {
210
237
  if (!item) reject('residue_changed');
211
238
  if (item.kind === 'ghost-registry') {
212
239
  if (!completedRegistrations.has(key)) {
213
240
  const workspace = (await ctx.workspaceRegistry.list()).find((entry) => entry.id === item.workspaceId);
214
- const table = ctx.get('storageDomain')?.get('workspace')?.table('workspaces');
215
- const record = table?.get(item.workspaceId);
216
- if (!workspace || typeof workspace.detachSession !== 'function' || !Array.isArray(record?.sessionIds)) reject('workspace_unavailable');
241
+ if (!workspace) reject('workspace_unavailable');
242
+ const record = registrationRecord(ctx, workspace);
217
243
  if (!record.sessionIds.includes(item.id)) reject('residue_changed');
218
- const visible = new Set(workspace.sessionIds ?? []);
219
- const hidden = record.sessionIds.filter((id) => !visible.has(id));
220
- const affected = new Set([item.id, ...hidden]);
244
+ const affected = new Set([item.id, ...hiddenSessionIds(workspace, record)]);
221
245
  const blockedIds = [...affected].filter((id) => {
222
246
  const affectedKey = `ghost:${item.workspaceId}:${id}`;
223
247
  return !selection.has(affectedKey) || !candidates.has(affectedKey);
224
248
  });
225
249
  if (blockedIds.length) throw Object.assign(cleanError('workspace_filtered'), { blockedIds });
226
250
  for (const id of affected) {
227
- if (ctx.get('sessions')?.get(id) || ctx.get('agents')?.get(id)
228
- || (ctx.workspaceRegistry.archivedSessionIds ?? []).includes(id)
251
+ if (isResidentSession(ctx, id) || isArchivedSession(ctx, id)
229
252
  || await ctx.sessionPersistence.stat(id)) reject('session_changed');
230
253
  }
231
254
  await workspace.detachSession(item.id);
232
- const remaining = table.get(item.workspaceId)?.sessionIds;
255
+ const remaining = workspaceTable(ctx)?.get(item.workspaceId)?.sessionIds;
233
256
  if (!Array.isArray(remaining) || [...affected].some((id) => remaining.includes(id))) reject('residue_changed');
234
257
  for (const id of affected) completedRegistrations.add(`ghost:${item.workspaceId}:${id}`);
235
258
  }
@@ -245,8 +268,8 @@ export async function cleanResidue(ctx, overview, selectedKeys, confirmedTasks =
245
268
  const listed = await ctx.sessionQuery.listSessions();
246
269
  if (!Array.isArray(listed)) reject('reference_check_failed');
247
270
  if (listed.some((entry) => (entry?.header?.id ?? entry?.id) === item.targetSessionId)
248
- || ctx.get('sessions')?.get(item.targetSessionId) || ctx.get('agents')?.get(item.targetSessionId)
249
- || (ctx.workspaceRegistry.archivedSessionIds ?? []).includes(item.targetSessionId)
271
+ || isResidentSession(ctx, item.targetSessionId)
272
+ || isArchivedSession(ctx, item.targetSessionId)
250
273
  || await ctx.sessionPersistence.stat(item.targetSessionId)) reject('session_changed');
251
274
  let result;
252
275
  try { result = await schedule.edit({ id: item.id, action: 'delete', expectedUpdatedAt: item.updatedAt }); }
@@ -259,54 +282,51 @@ export async function cleanResidue(ctx, overview, selectedKeys, confirmedTasks =
259
282
  if (!rel || isAbsolute(rel) || rel === '..' || rel.startsWith(`..${sep}`)) reject('unsafe_path');
260
283
  // The official cache owns an in-memory table as well as the file. A
261
284
  // direct unlink leaves those two views inconsistent until restart.
262
- const table = ctx.get('storageDomain')?.get('session_projcache')?.table('sessions');
263
- if (!table || typeof table.delete !== 'function') reject('cache_unavailable');
264
- if (!await table.delete(item.id)) reject('residue_changed');
285
+ const cache = projcacheTable(ctx);
286
+ if (!cache) reject('cache_unavailable');
287
+ if (!await cache.delete(item.id)) reject('residue_changed');
265
288
  } else if (item.kind === 'shell-dir' && ['empty', 'lock', 'log', 'unknown'].includes(item.shellType)) {
266
289
  const target = key.slice('shell:'.length);
267
- if (purging.has(item.id)) reject('purge_busy');
268
- purging.add(item.id);
269
- try {
270
- if ((ctx.workspaceRegistry.archivedSessionIds ?? []).includes(item.id)) await checkCurrent(ctx, item.id);
271
- await releaseResidentSession(ctx, item.id);
290
+ await withPurging(item.id, async () => {
291
+ if (isArchivedSession(ctx, item.id)) await checkCurrent(ctx, item.id);
292
+ // A shell whose session is still mounted in this instance is not
293
+ // removable without a DSH restart (no public release API).
294
+ if (isResidentSession(ctx, item.id)) reject('session_resident');
272
295
  // Disposing an older, partially deleted session may flush events and
273
296
  // recreate an event-only log before its writer closes.
274
297
  const eventOnly = await isEventOnlyLog(ctx, item.id, target).catch(() => false);
275
298
  const mode = eventOnly ? 'event-only' : item.shellType === 'unknown' ? 'unknown' : 'metadata';
276
299
  let targets = await workspaceTargets(ctx, item.id);
277
- const cache = ctx.get('storageDomain')?.get('session_projcache')?.table('sessions');
278
- if (!cache || typeof cache.delete !== 'function') reject('cache_unavailable');
300
+ const cache = projcacheTable(ctx);
301
+ if (!cache) reject('cache_unavailable');
279
302
  await removeSessionShell(target, item.id, {
280
303
  mode,
281
304
  recheck: async () => {
282
- if (ctx.get('sessions')?.get(item.id) || ctx.get('agents')?.get(item.id)
305
+ if (isResidentSession(ctx, item.id)
283
306
  || await ctx.sessionPersistence.stat(item.id)) reject('session_changed');
284
307
  if (mode === 'event-only' && !await isEventOnlyLog(ctx, item.id, target)) reject('session_changed');
285
308
  // A shell and its cache/registrations are one cleanup, whether
286
309
  // it originated from an interrupted purge or outside the plugin.
287
- if ((ctx.workspaceRegistry.archivedSessionIds ?? []).includes(item.id)) {
310
+ if (isArchivedSession(ctx, item.id)) {
288
311
  await checkCurrent(ctx, item.id);
289
312
  }
290
313
  targets = await workspaceTargets(ctx, item.id);
291
314
  },
292
315
  cleanup: async () => {
293
- await cache.delete(item.id);
294
- for (const workspace of targets) await workspace.detachSession(item.id);
316
+ mutated = true;
317
+ await clearRegistrations(cache, targets, item.id);
295
318
  },
296
319
  });
297
- if ((ctx.workspaceRegistry.archivedSessionIds ?? []).includes(item.id)) {
320
+ if (isArchivedSession(ctx, item.id)) {
298
321
  await unarchiveOwner.run(item.id, () => ctx.workspaceRegistry.unarchiveSession(item.id));
299
322
  }
300
- } finally { purging.delete(item.id); }
323
+ });
301
324
  } else if (item.kind === 'empty-project') {
302
325
  await removeEmptyProject(item.id, sessionsRoot());
303
326
  } else reject('residue_unavailable');
304
327
  done.push({ key, kind: item.kind, id: item.id });
305
328
  } catch (error) {
306
- failed.push({ key, kind: item?.kind, id: item?.id, code: error?.cleanCode || 'residue_failed',
307
- ...(error?.blockedIds ? { blockedCount: error.blockedIds.length } : {}),
308
- ...(!error?.cleanCode ? { message: String(error?.message ?? error) } : {}),
309
- ...(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' }) });
310
330
  }
311
331
  }
312
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
 
@@ -34,15 +35,27 @@ function sessionIdsOf(body) {
34
35
 
35
36
  /** 注册全部路由(每条路由的注销由 ctx.effect 承载)。 */
36
37
  export function registerRoutes(ctx, config) {
38
+ /** Route failures answer a stable code; the raw error goes to the Host log. */
39
+ const fail = (path, error) => {
40
+ ctx.logger.warn(`dsh-mop: route ${path} failed`, error);
41
+ return json({ error: `dsh-mop:${error?.cleanCode ?? 'internal'}` }, 500);
42
+ };
37
43
  const get = (path, handler) => ctx.effect(() => ctx.connection.fetch.register({
38
44
  path: `${PREFIX}.${path}`, methods: ['GET', 'HEAD'], requestBody: 'buffered',
39
- fetch: async (request) => (request.method === 'HEAD' ? new Response(null, { status: 200 }) : handler(request)),
45
+ fetch: async (request) => {
46
+ if (request.method === 'HEAD') return new Response(null, { status: 200 });
47
+ try { return await handler(request); }
48
+ catch (error) { return fail(path, error); }
49
+ },
40
50
  }), `dsh-mop: ${PREFIX}.${path}`);
41
51
  const post = (path, handler) => ctx.effect(() => ctx.connection.fetch.register({
42
52
  path: `${PREFIX}.${path}`, methods: ['POST'], requestBody: 'buffered',
43
53
  fetch: async (request) => {
44
- try { return await handler(await readJsonBody(request)); }
45
- catch (error) { return json({ error: String(error?.message ?? error) }, 500); }
54
+ let body;
55
+ try { body = await readJsonBody(request); }
56
+ catch { return json({ error: 'dsh-mop:bad_request' }, 400); }
57
+ try { return await handler(body); }
58
+ catch (error) { return fail(path, error); }
46
59
  },
47
60
  }), `dsh-mop: ${PREFIX}.${path}`);
48
61
 
@@ -50,7 +63,7 @@ export function registerRoutes(ctx, config) {
50
63
  const overview = await buildOverview(ctx, config);
51
64
  const pick = (s) => ({
52
65
  id: s.id, title: s.title,
53
- live: s.live,
66
+ live: s.live, blank: s.blank, updatedAt: s.updatedAt,
54
67
  archived: s.archived, protected: s.protected, purgeBlock: s.purgeBlock, scheduleTasks: s.scheduleTasks,
55
68
  cwd: s.cwd, workspacePath: s.workspacePath, workspaceTitle: s.workspaceTitle, workspaceCreatedAt: s.workspaceCreatedAt,
56
69
  sizeBytes: s.sizeBytes, mtimeMs: s.mtimeMs,
@@ -85,7 +98,7 @@ export function registerRoutes(ctx, config) {
85
98
  if (error?.name === 'WorkspaceActiveSessionError' && Array.isArray(error.activity)) {
86
99
  failed.push({ id, title: session.title, code: 'session_active', activity: error.activity });
87
100
  } else {
88
- failed.push({ id, ...(error?.cleanCode ? { code: error.cleanCode } : { message: String(error?.message ?? error) }) });
101
+ failed.push({ id, ...failureShape(error) });
89
102
  }
90
103
  }
91
104
  }
@@ -109,7 +122,7 @@ export function registerRoutes(ctx, config) {
109
122
  await ctx.workspaceRegistry.unarchiveSession(id);
110
123
  done.push(id);
111
124
  } catch (error) {
112
- failed.push({ id, ...(error?.cleanCode ? { code: error.cleanCode } : { message: String(error?.message ?? error) }) });
125
+ failed.push({ id, ...failureShape(error) });
113
126
  }
114
127
  }
115
128
  return json({ done, failed });
@@ -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 { assertSessionDirSafe } from './guard.mjs';
5
- import { assertCanonicalSessionPath, isSystemMetadata, removeEmptyProject } from './artifacts.mjs';
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
- assertSessionDirSafe(target, id);
12
- await assertCanonicalSessionPath(dshHome('sessions'), target);
12
+ await assertSessionDir(target, id);
13
13
  const names = await readdir(target);
14
- const allowed = (name) => name === 'session.lock' || isSystemMetadata(name)
15
- || (mode === 'event-only' && ['session.v4.jsonl', 'session.v4.jsonl.zstd'].includes(name))
16
- || (mode === 'unknown' && !/^session(?:\.v\d+)?\.jsonl(?:\.zstd)?$/.test(name));
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 !== 'session.lock'), ...names.filter((name) => name === 'session.lock')];
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
- const file = await lstat(join(target, name), { bigint: true });
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();