dsh-mop 0.0.0-stage → 0.1.4

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.pt.js ADDED
@@ -0,0 +1,39 @@
1
+ /** dsh-mop 的葡萄牙文界面文案。键名与 client.en.js 保持一致,缺的键会回退到英文。 */
2
+ window.__ModuleLoader__.load({
3
+ id: 'dsh-mop',
4
+ chunk: 'client.pt.js',
5
+ factory() {
6
+ return {
7
+ messages: {
8
+ 'tabs.residue': 'Resíduos',
9
+ 'selection.summary': '{n} selecionadas · {size}',
10
+ 'search.placeholder': 'Buscar {section}',
11
+ 'confirm.purge.description': 'Esta ação não pode ser desfeita',
12
+ 'archive.scheduleDeletion': 'As tarefas automáticas ativas destinadas a esta sessão e seu histórico de execução serão excluídos.',
13
+ 'error.notArchived': 'Somente sessões arquivadas podem ser excluídas.',
14
+ 'error.workspaceProtected': 'Espaço de trabalho protegido.',
15
+ 'protection.label': 'protegida',
16
+ 'reference.schedule': 'Associada a uma tarefa agendada.',
17
+ 'residue.registeredCache': 'Também há um registro de espaço de trabalho para esta sessão.',
18
+ 'residue.orphanCache': 'cache órfã',
19
+ 'residue.ghostRegistry': 'registro fantasma',
20
+ 'residue.sessionDirectory': 'diretório casca',
21
+ 'residue.emptyProject': 'diretório de projeto vazio',
22
+ 'confirm.tasks.description': 'As tarefas selecionadas e seu histórico salvo serão excluídos',
23
+ 'error.schedule_changed': 'A tarefa mudou; atualize e tente novamente',
24
+ 'error.session_resident': 'A sessão ainda tem atividades em andamento',
25
+ 'error.purge_busy': 'Limpeza da sessão em andamento; tente novamente mais tarde',
26
+ 'error.workspace_unavailable': 'Não foi possível verificar os registros do espaço de trabalho',
27
+ 'error.workspace_filtered': 'Outros registros ocultos impedem a remoção individual',
28
+ 'error.unsupported_storage': 'Não foi possível identificar a localização do log',
29
+ 'error.historical_format': 'Migre o log da sessão antes de excluí-lo',
30
+ 'error.historical_parent': 'Abra a sessão principal para concluir a migração',
31
+ 'error.unsafe_path': 'Não foi possível verificar o caminho do arquivo',
32
+ 'error.unknown_artifact': 'O diretório da sessão contém arquivos desconhecidos',
33
+ 'error.session_changed': 'O estado da sessão mudou; tente novamente',
34
+ 'error.cache_unavailable': 'O serviço de cache de projeção está indisponível',
35
+ 'error.residue_changed': 'O resíduo mudou; atualize e tente novamente',
36
+ },
37
+ };
38
+ },
39
+ });
package/client.ru.js ADDED
@@ -0,0 +1,39 @@
1
+ /** dsh-mop 的俄文界面文案。键名与 client.en.js 保持一致,缺的键会回退到英文。 */
2
+ window.__ModuleLoader__.load({
3
+ id: 'dsh-mop',
4
+ chunk: 'client.ru.js',
5
+ factory() {
6
+ return {
7
+ messages: {
8
+ 'tabs.residue': 'Остатки',
9
+ 'selection.summary': 'выбрано {n} · {size}',
10
+ 'search.placeholder': 'Поиск: {section}',
11
+ 'confirm.purge.description': 'Это действие нельзя отменить',
12
+ 'archive.scheduleDeletion': 'Активные автоматические задачи для этой сессии и их сохранённая история будут удалены.',
13
+ 'error.notArchived': 'Удалять можно только архивированные сессии.',
14
+ 'error.workspaceProtected': 'Рабочее пространство защищено.',
15
+ 'protection.label': 'защищена',
16
+ 'reference.schedule': 'Связана с запланированной задачей.',
17
+ 'residue.registeredCache': 'Для этого сеанса также существует запись рабочего пространства.',
18
+ 'residue.orphanCache': 'осиротевший кэш',
19
+ 'residue.ghostRegistry': 'запись-призрак',
20
+ 'residue.sessionDirectory': 'каталог-оболочка',
21
+ 'residue.emptyProject': 'пустой каталог проекта',
22
+ 'confirm.tasks.description': 'Выбранные задачи и сохранённая история будут удалены',
23
+ 'error.schedule_changed': 'Задача изменилась; обновите данные и повторите попытку',
24
+ 'error.session_resident': 'В сеансе ещё выполняются задачи',
25
+ 'error.purge_busy': 'Идёт очистка сеанса; повторите попытку позже',
26
+ 'error.workspace_unavailable': 'Не удалось проверить записи рабочего пространства',
27
+ 'error.workspace_filtered': 'Другие скрытые записи мешают удалить эту запись отдельно',
28
+ 'error.unsupported_storage': 'Не удалось определить расположение журнала сеанса',
29
+ 'error.historical_format': 'Перед удалением необходимо перенести журнал сеанса',
30
+ 'error.historical_parent': 'Сначала откройте родительский сеанс для переноса',
31
+ 'error.unsafe_path': 'Не удалось проверить путь к файлу',
32
+ 'error.unknown_artifact': 'Каталог сеанса содержит неизвестные файлы',
33
+ 'error.session_changed': 'Состояние сеанса изменилось; повторите попытку',
34
+ 'error.cache_unavailable': 'Служба кэша проекций недоступна',
35
+ 'error.residue_changed': 'Остаточные данные изменились; обновите и повторите попытку',
36
+ },
37
+ };
38
+ },
39
+ });
package/client.zh.js ADDED
@@ -0,0 +1,39 @@
1
+ /** dsh-mop 的中文界面文案。键名与 client.en.js 保持一致,缺的键会回退到英文。 */
2
+ window.__ModuleLoader__.load({
3
+ id: 'dsh-mop',
4
+ chunk: 'client.zh.js',
5
+ factory() {
6
+ return {
7
+ messages: {
8
+ 'tabs.residue': '残留',
9
+ 'selection.summary': '已选 {n} 个 · {size}',
10
+ 'search.placeholder': '搜索{section}',
11
+ 'confirm.purge.description': '删除后无法恢复',
12
+ 'archive.scheduleDeletion': '发往此会话的活动自动化任务及其已保存的运行记录将被删除。',
13
+ 'error.notArchived': '只能删除已归档的会话',
14
+ 'error.workspaceProtected': '工作区受保护',
15
+ 'protection.label': '受保护',
16
+ 'reference.schedule': '关联了计划任务',
17
+ 'residue.registeredCache': '还有工作区注册',
18
+ 'residue.orphanCache': '无对应会话的缓存',
19
+ 'residue.ghostRegistry': '无对应会话的注册',
20
+ 'residue.sessionDirectory': '未识别会话目录',
21
+ 'residue.emptyProject': '空会话目录',
22
+ 'confirm.tasks.description': '所选任务及其保存的运行记录将被删除',
23
+ 'error.schedule_changed': '任务已变化,请刷新后重试',
24
+ 'error.session_resident': '会话仍在使用中',
25
+ 'error.purge_busy': '会话正在清理,请稍后重试',
26
+ 'error.workspace_unavailable': '无法检查工作区注册',
27
+ 'error.workspace_filtered': '工作区含其他隐藏注册,无法单独移除',
28
+ 'error.unsupported_storage': '无法确认会话日志位置',
29
+ 'error.historical_format': '会话日志需要迁移后才能删除',
30
+ 'error.historical_parent': '请先打开父会话完成迁移',
31
+ 'error.unsafe_path': '无法确认文件路径',
32
+ 'error.unknown_artifact': '会话目录包含未识别文件',
33
+ 'error.session_changed': '会话状态已变化,请重试',
34
+ 'error.cache_unavailable': '投影缓存服务不可用',
35
+ 'error.residue_changed': '残留已变化,请刷新后重试',
36
+ },
37
+ };
38
+ },
39
+ });
@@ -0,0 +1,3 @@
1
+ - insert:
2
+ - id: dsh-mop
3
+ name: 'dsh-mop'
package/icon.svg ADDED
@@ -0,0 +1,5 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="none" stroke="#4d8fd6" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">
2
+ <path d="M13.5 2.5H2.5C1.94772 2.5 1.5 2.94772 1.5 3.5V4.5C1.5 5.05228 1.94772 5.5 2.5 5.5H13.5C14.0523 5.5 14.5 5.05228 14.5 4.5V3.5C14.5 2.94772 14.0523 2.5 13.5 2.5Z"/>
3
+ <path d="M2.5 5.5V13.5C2.5 13.7652 2.60536 14.0196 2.79289 14.2071C2.98043 14.3946 3.23478 14.5 3.5 14.5H12.5C12.7652 14.5 13.0196 14.3946 13.2071 14.2071C13.3946 14.0196 13.5 13.7652 13.5 13.5V5.5"/>
4
+ <path d="M6.5 9.5H9.5"/>
5
+ </svg>
package/index.js ADDED
@@ -0,0 +1,25 @@
1
+ /** dsh-mop 宿主半边:清理遗留会话数据,经 connection.fetch 路由暴露给浏览器。 */
2
+ import { registerRoutes } from './lib/routes.mjs';
3
+ import { isPurgingSession, isExternalUnarchive } from './lib/clean.mjs';
4
+ import { cleanError } from './lib/errors.mjs';
5
+
6
+ export const inject = ['connection', 'sessionQuery', 'sessionPersistence', 'workspaceRegistry'];
7
+
8
+ 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
+ };
14
+ // Coordinate same-host activation and unarchive with the deletion window.
15
+ if (typeof ctx.on === 'function') ctx.effect(() => {
16
+ const stopUnarchive = ctx.on('workspace/session-unarchiving', ({ sessionId }) => {
17
+ if (isExternalUnarchive(sessionId)) throw cleanError('purge_busy');
18
+ });
19
+ const stopCreate = ctx.on('session/created', (session) => {
20
+ if (isPurgingSession(session.id)) throw cleanError('purge_busy');
21
+ });
22
+ return () => { stopUnarchive(); stopCreate(); };
23
+ }, 'dsh-mop: purge coordination');
24
+ registerRoutes(ctx, config);
25
+ }
@@ -0,0 +1,47 @@
1
+ import { lstat, readdir, realpath, rmdir, unlink } from 'node:fs/promises';
2
+ import { basename, dirname, join, resolve } from 'node:path';
3
+ import { reject } from './errors.mjs';
4
+
5
+ export const isSystemMetadata = (name) => ['.DS_Store', 'Thumbs.db', 'desktop.ini'].includes(name);
6
+
7
+ export async function removeEmptyProject(project, root) {
8
+ project = resolve(project);
9
+ root = resolve(root);
10
+ if (dirname(project) !== root) reject('unsafe_path');
11
+ const [rootInfo, projectInfo] = await Promise.all([lstat(root), lstat(project)]);
12
+ if (!rootInfo.isDirectory() || rootInfo.isSymbolicLink() || !projectInfo.isDirectory() || projectInfo.isSymbolicLink()) reject('unsafe_path');
13
+ if (dirname(await realpath(project)) !== await realpath(root)) reject('unsafe_path');
14
+ const names = await readdir(project);
15
+ if (names.some((name) => !isSystemMetadata(name))) reject('session_changed');
16
+ const entries = [];
17
+ for (const name of names) {
18
+ const path = join(project, name);
19
+ const info = await lstat(path, { bigint: true });
20
+ if (!info.isFile() || info.isSymbolicLink()) reject('unsafe_path');
21
+ entries.push({ path, info });
22
+ }
23
+ 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');
27
+ }
28
+ for (const { path } of entries) await unlink(path);
29
+ await rmdir(project);
30
+ }
31
+
32
+ // Permit platform canonicalization of ancestors while rejecting links at the
33
+ // managed root and both levels beneath it.
34
+ export async function assertCanonicalSessionPath(root, dir) {
35
+ root = resolve(root);
36
+ dir = resolve(dir);
37
+ const project = dirname(dir);
38
+ for (const path of [root, project, dir]) {
39
+ const info = await lstat(path);
40
+ if (!info.isDirectory() || info.isSymbolicLink()) reject('unsafe_path');
41
+ }
42
+ const [realRoot, realProject, realDir] = await Promise.all([root, project, dir].map((path) => realpath(path)));
43
+ if (realProject !== await realpath(join(root, basename(project)))
44
+ || dirname(realProject) !== realRoot
45
+ || realDir !== await realpath(join(project, basename(dir)))
46
+ || dirname(realDir) !== realProject) reject('unsafe_path');
47
+ }
package/lib/clean.mjs ADDED
@@ -0,0 +1,313 @@
1
+ /** dsh-mop · 永久删除:日志目录、投影缓存、工作区注册一并清除,不留自有数据。 */
2
+ import { lstat, readdir, unlink } from 'node:fs/promises';
3
+ import { basename, dirname, isAbsolute, relative, resolve, sep } from 'node:path';
4
+ import { AsyncLocalStorage } from 'node:async_hooks';
5
+ import { assertSessionDirSafe } from './guard.mjs';
6
+ 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
+
12
+ /** Server-derived keys identify the only paths and registry entries eligible for selection. */
13
+ export function listResidue(overview) {
14
+ return [
15
+ ...(overview.residue.orphanTasks ?? []).map((item) => ({
16
+ key: `task:${item.id}`, kind: 'orphan-task', id: item.id, label: item.title,
17
+ targetSessionId: item.targetSessionId, updatedAt: item.updatedAt, status: item.status,
18
+ workspacePath: item.workspacePath, workspaceTitle: item.workspaceTitle, workspaceCreatedAt: item.workspaceCreatedAt,
19
+ sizeBytes: null, mtimeMs: item.mtimeMs,
20
+ })),
21
+ ...overview.residue.orphanCaches.map((item) => ({
22
+ key: `cache:${item.id}`, kind: 'orphan-cache', id: item.id, label: item.title || item.id,
23
+ workspacePath: item.workspacePath, workspaceTitle: item.workspaceTitle, workspaceCreatedAt: item.workspaceCreatedAt,
24
+ sizeBytes: item.sizeBytes, mtimeMs: item.mtimeMs,
25
+ })),
26
+ ...overview.residue.ghostRegistrations.map((item) => ({
27
+ key: `ghost:${item.workspaceId}:${item.id}`, kind: 'ghost-registry', id: item.id, workspaceId: item.workspaceId, label: item.id,
28
+ workspacePath: item.workspacePath, workspaceTitle: item.workspaceTitle, workspaceCreatedAt: item.workspaceCreatedAt,
29
+ sizeBytes: null, mtimeMs: null,
30
+ })),
31
+ ...overview.residue.shellDirs.map((item) => ({
32
+ key: `shell:${item.sessionDir}`, kind: 'shell-dir', id: item.sessionId, label: item.sessionId,
33
+ workspacePath: item.workspacePath, workspaceTitle: item.workspaceTitle, workspaceCreatedAt: item.workspaceCreatedAt,
34
+ sizeBytes: item.sizeBytes, mtimeMs: item.mtimeMs, shellType: item.shellType,
35
+ })),
36
+ ...overview.residue.emptyProjectDirs.map((item) => ({
37
+ key: `dir:${item.path}`, kind: 'empty-project', id: item.path,
38
+ label: basename(item.path) || item.path,
39
+ sizeBytes: item.sizeBytes, mtimeMs: item.mtimeMs,
40
+ })),
41
+ ];
42
+ }
43
+
44
+ const LOG = /^session(?:\.v\d+)?\.jsonl(?:\.zstd)?$/;
45
+ const purging = new Set();
46
+ const unarchiveOwner = new AsyncLocalStorage();
47
+ export function isPurgingSession(id) { return purging.has(id); }
48
+ export function isExternalUnarchive(id) { return purging.has(id) && unarchiveOwner.getStore() !== id; }
49
+
50
+ const isTaskTarget = (task, id) => (task.target?.kind === 'session' || task.target?.kind === 'new_once') && task.target.sessionId === id;
51
+
52
+ async function checkCurrent(ctx, id) {
53
+ if (!(ctx.workspaceRegistry.archivedSessionIds ?? []).includes(id)) reject('session_not_archived');
54
+ const agent = ctx.get('agents')?.get(id);
55
+ if (agent && agent.status !== 'idle') reject('session_resident');
56
+ let activity;
57
+ try { activity = await ctx.waterfall('workspace/session-activity', { sessionId: id }, () => Promise.resolve([])); }
58
+ catch { reject('reference_check_failed'); }
59
+ if (!Array.isArray(activity)) reject('reference_check_failed');
60
+ if (activity.length) reject('session_resident');
61
+ const schedule = ctx.get('schedule');
62
+ if (schedule) {
63
+ let tasks;
64
+ try { tasks = await schedule.catalog(); } catch { reject('reference_check_failed'); }
65
+ if (!Array.isArray(tasks)) reject('reference_check_failed');
66
+ if (tasks.some((task) => !['paused', 'ended'].includes(task.status) && isTaskTarget(task, id))) reject('schedule_reference');
67
+ }
68
+ }
69
+
70
+ async function workspaceTargets(ctx, id) {
71
+ 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');
75
+ const targets = [];
76
+ for (const workspace of workspaces) {
77
+ const record = table.get(workspace.id);
78
+ if (!record || !Array.isArray(record.sessionIds)) reject('workspace_unavailable');
79
+ if (!record.sessionIds.includes(id)) continue;
80
+ // 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));
83
+ if (hidden.length) throw Object.assign(cleanError('workspace_filtered'), { blockedIds: hidden });
84
+ if (typeof workspace.detachSession !== 'function') reject('workspace_unavailable');
85
+ targets.push(workspace);
86
+ }
87
+ return targets;
88
+ }
89
+
90
+ async function logFiles(snapshot, id) {
91
+ if (snapshot?.location?.kind !== 'jsonl' || typeof snapshot.location.path !== 'string') reject('unsupported_storage');
92
+ if (snapshot.formatStatus !== 'current') reject('historical_format');
93
+ const selected = resolve(snapshot.location.path);
94
+ const dir = dirname(selected);
95
+ assertSessionDirSafe(dir, id);
96
+ await assertCanonicalSessionPath(sessionsRoot(), dir);
97
+ const names = await readdir(dir);
98
+ const files = [];
99
+ for (const name of names) {
100
+ if (name === 'session.lock' || isSystemMetadata(name)) {
101
+ const lock = await lstat(resolve(dir, name));
102
+ if (!lock.isFile() || lock.isSymbolicLink()) reject('unsafe_path');
103
+ continue;
104
+ }
105
+ if (!LOG.test(name)) reject('unknown_artifact');
106
+ const path = resolve(dir, name);
107
+ const stat = await lstat(path);
108
+ if (!stat.isFile() || stat.isSymbolicLink()) reject('unsafe_path');
109
+ files.push(path);
110
+ }
111
+ if (!files.includes(selected)) reject('unsafe_path');
112
+ return files.sort((a, b) => (a === selected ? 1 : 0) - (b === selected ? 1 : 0));
113
+ }
114
+
115
+ /** Delete verified JSONL generations after releasing the local resident session. */
116
+ export async function purgeSessions(ctx, overview, sessionIds) {
117
+ const byId = new Map(overview.sessions.map((session) => [session.id, session]));
118
+ const deleted = [], failed = [];
119
+ for (const id of new Set(sessionIds)) {
120
+ const session = byId.get(id);
121
+ let claimed = false;
122
+ try {
123
+ if (!session) reject('session_not_found');
124
+ if (!session.archived) reject('session_not_archived');
125
+ if (session.protected) reject('protected_workspace');
126
+ 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');
143
+ }
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');
152
+ }
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);
188
+ } 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);
194
+ }
195
+ }
196
+ return { deleted, failed };
197
+ }
198
+
199
+ /** Revalidate selected entries against a fresh overview before any changes. */
200
+ export async function cleanResidue(ctx, overview, selectedKeys, confirmedTasks = {}) {
201
+ const done = [];
202
+ const failed = [];
203
+ const cacheRoot = resolve(projcacheDir());
204
+ const candidates = new Map(listResidue(overview).map((item) => [item.key, item]));
205
+ const selection = new Set(selectedKeys);
206
+ const completedRegistrations = new Set();
207
+ for (const key of selection) {
208
+ const item = candidates.get(key);
209
+ try {
210
+ if (!item) reject('residue_changed');
211
+ if (item.kind === 'ghost-registry') {
212
+ if (!completedRegistrations.has(key)) {
213
+ 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');
217
+ 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]);
221
+ const blockedIds = [...affected].filter((id) => {
222
+ const affectedKey = `ghost:${item.workspaceId}:${id}`;
223
+ return !selection.has(affectedKey) || !candidates.has(affectedKey);
224
+ });
225
+ if (blockedIds.length) throw Object.assign(cleanError('workspace_filtered'), { blockedIds });
226
+ for (const id of affected) {
227
+ if (ctx.get('sessions')?.get(id) || ctx.get('agents')?.get(id)
228
+ || (ctx.workspaceRegistry.archivedSessionIds ?? []).includes(id)
229
+ || await ctx.sessionPersistence.stat(id)) reject('session_changed');
230
+ }
231
+ await workspace.detachSession(item.id);
232
+ const remaining = table.get(item.workspaceId)?.sessionIds;
233
+ if (!Array.isArray(remaining) || [...affected].some((id) => remaining.includes(id))) reject('residue_changed');
234
+ for (const id of affected) completedRegistrations.add(`ghost:${item.workspaceId}:${id}`);
235
+ }
236
+ } else if (item.kind === 'orphan-task') {
237
+ const confirmed = Object.hasOwn(confirmedTasks, item.id) ? confirmedTasks[item.id] : undefined;
238
+ if (!confirmed || confirmed.targetSessionId !== item.targetSessionId || confirmed.updatedAt !== item.updatedAt) reject('schedule_changed');
239
+ const schedule = ctx.get('schedule');
240
+ if (typeof schedule?.view !== 'function' || typeof schedule?.edit !== 'function') reject('reference_check_failed');
241
+ const task = await schedule.view({ id: item.id });
242
+ if (!task || task.code === 'schedule_not_found') reject('residue_changed');
243
+ if (task.target?.kind !== 'session' || task.target.sessionId !== item.targetSessionId
244
+ || (task.updatedAt ?? null) !== item.updatedAt) reject('schedule_changed');
245
+ const listed = await ctx.sessionQuery.listSessions();
246
+ if (!Array.isArray(listed)) reject('reference_check_failed');
247
+ 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)
250
+ || await ctx.sessionPersistence.stat(item.targetSessionId)) reject('session_changed');
251
+ let result;
252
+ try { result = await schedule.edit({ id: item.id, action: 'delete', expectedUpdatedAt: item.updatedAt }); }
253
+ catch (error) { reject('schedule_delete_failed', error); }
254
+ if (result?.code === 'schedule_conflict') reject('schedule_changed');
255
+ if (!result?.deleted) reject('residue_changed');
256
+ } else if (item.kind === 'orphan-cache') {
257
+ const target = overview.cacheFiles.get(item.id);
258
+ const rel = target && relative(cacheRoot, resolve(target));
259
+ if (!rel || isAbsolute(rel) || rel === '..' || rel.startsWith(`..${sep}`)) reject('unsafe_path');
260
+ // The official cache owns an in-memory table as well as the file. A
261
+ // 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');
265
+ } else if (item.kind === 'shell-dir' && ['empty', 'lock', 'log', 'unknown'].includes(item.shellType)) {
266
+ 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);
272
+ // Disposing an older, partially deleted session may flush events and
273
+ // recreate an event-only log before its writer closes.
274
+ const eventOnly = await isEventOnlyLog(ctx, item.id, target).catch(() => false);
275
+ const mode = eventOnly ? 'event-only' : item.shellType === 'unknown' ? 'unknown' : 'metadata';
276
+ 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');
279
+ await removeSessionShell(target, item.id, {
280
+ mode,
281
+ recheck: async () => {
282
+ if (ctx.get('sessions')?.get(item.id) || ctx.get('agents')?.get(item.id)
283
+ || await ctx.sessionPersistence.stat(item.id)) reject('session_changed');
284
+ if (mode === 'event-only' && !await isEventOnlyLog(ctx, item.id, target)) reject('session_changed');
285
+ // A shell and its cache/registrations are one cleanup, whether
286
+ // it originated from an interrupted purge or outside the plugin.
287
+ if ((ctx.workspaceRegistry.archivedSessionIds ?? []).includes(item.id)) {
288
+ await checkCurrent(ctx, item.id);
289
+ }
290
+ targets = await workspaceTargets(ctx, item.id);
291
+ },
292
+ cleanup: async () => {
293
+ await cache.delete(item.id);
294
+ for (const workspace of targets) await workspace.detachSession(item.id);
295
+ },
296
+ });
297
+ if ((ctx.workspaceRegistry.archivedSessionIds ?? []).includes(item.id)) {
298
+ await unarchiveOwner.run(item.id, () => ctx.workspaceRegistry.unarchiveSession(item.id));
299
+ }
300
+ } finally { purging.delete(item.id); }
301
+ } else if (item.kind === 'empty-project') {
302
+ await removeEmptyProject(item.id, sessionsRoot());
303
+ } else reject('residue_unavailable');
304
+ done.push({ key, kind: item.kind, id: item.id });
305
+ } 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) } : {}) });
310
+ }
311
+ }
312
+ return { done, failed };
313
+ }
package/lib/errors.mjs ADDED
@@ -0,0 +1,6 @@
1
+ /** Stable error identity; presentation and translation belong to the client. */
2
+ export function cleanError(code, cause) {
3
+ return Object.assign(new Error(`dsh-mop:${code}`, cause === undefined ? undefined : { cause }), { cleanCode: code });
4
+ }
5
+
6
+ export function reject(code, cause) { throw cleanError(code, cause); }
package/lib/guard.mjs ADDED
@@ -0,0 +1,20 @@
1
+ /** dsh-mop · 路径防御。 */
2
+
3
+ import { basename, resolve, sep } from 'node:path';
4
+ import { dshHome } from './home.mjs';
5
+ import { reject } from './errors.mjs';
6
+
7
+ const SESSION_DIR_RE = /^session-[0-9a-zA-Z-]+$/;
8
+
9
+ /** rm 会话目录前的断言:位于 sessions 根内、目录名 === 会话 id。 */
10
+ export function assertSessionDirSafe(sessionDir, sessionId) {
11
+ const root = resolve(dshHome('sessions'));
12
+ const target = resolve(sessionDir);
13
+ if (target === root || !target.startsWith(root + sep)) {
14
+ reject('unsafe_path');
15
+ }
16
+ const base = basename(target);
17
+ if (base !== sessionId || !SESSION_DIR_RE.test(base)) {
18
+ reject('unsafe_path');
19
+ }
20
+ }
package/lib/home.mjs ADDED
@@ -0,0 +1,12 @@
1
+ /**
2
+ * dsh-mop · 路径
3
+ * 优先级与官方 dsh-home-paths 一致:$DSH_HOME → ~/.dsh。
4
+ */
5
+ import { homedir } from 'node:os';
6
+ import { join } from 'node:path';
7
+
8
+ export function dshHome(...segments) {
9
+ const env = process.env.DSH_HOME;
10
+ const base = env && env.trim() ? env.trim() : join(homedir(), '.dsh');
11
+ return join(base, ...segments);
12
+ }
@@ -0,0 +1,30 @@
1
+ import { reject } from './errors.mjs';
2
+
3
+ /**
4
+ * DSH rc.5 keeps the owning AgentHandle private. Its agent-loop installs an
5
+ * ordered Cordis effect that owns the same teardown. Match both the effect's
6
+ * label and the exact child scope identity before invoking its disposer.
7
+ */
8
+ export async function releaseResidentSession(ctx, id) {
9
+ const agent = ctx.get('agents')?.get(id);
10
+ const session = ctx.get('sessions')?.get(id);
11
+ if (!agent && !session) return;
12
+ if (!agent || agent.status !== 'idle' || (session && agent.session !== session)) reject('session_resident');
13
+
14
+ const rawDispose = agent.scope?.rawDispose;
15
+ const disposables = agent.loopCtx?.fiber?._disposables;
16
+ if (typeof rawDispose !== 'function' || !disposables || typeof disposables[Symbol.iterator] !== 'function') reject('session_resident');
17
+ const candidates = [];
18
+ for (const symbol of Object.getOwnPropertySymbols(rawDispose)) {
19
+ const scopeEffect = rawDispose[symbol];
20
+ if (!scopeEffect || typeof scopeEffect !== 'object') continue;
21
+ for (const dispose of disposables) {
22
+ const effect = dispose?.[symbol];
23
+ if (typeof dispose === 'function' && effect?.label === `agentLoop.scope(${id})`
24
+ && Array.isArray(effect.children) && effect.children.includes(scopeEffect)) candidates.push(dispose);
25
+ }
26
+ }
27
+ if (candidates.length !== 1 || ctx.get('agents')?.get(id) !== agent) reject('session_resident');
28
+ await candidates[0]();
29
+ if (ctx.get('agents')?.get(id) || ctx.get('sessions')?.get(id)) reject('session_resident');
30
+ }