@hongyongli/dsh-session-delete 0.0.0-stage → 1.0.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 ADDED
@@ -0,0 +1,456 @@
1
+ // dsh-chameleon workbench-session-delete: delete-session capability (Host half).
2
+ //
3
+ // Deletes one session end-to-end on the host:
4
+ // POST /__chameleon/session/delete - HTTP endpoint for the client button
5
+ // workbench_session_delete - model tool for edit mode
6
+ //
7
+ // Deletion steps, kept consistent with the LIVE storage services so the
8
+ // in-memory state and the on-disk units stay in sync (no "resurrected"
9
+ // session after the next periodic flush):
10
+ // 1. refuse while a live agent owns the session (ctx.agents.get(id));
11
+ // 2. flush a live session so dispose-time teardown has no pending writes;
12
+ // 3. remove the persisted log dir ~/.dsh/sessions/<slug>/<id>/ for both id
13
+ // spellings (raw uuid and `session-` prefixed);
14
+ // 4. drop the projection-cache row (storageDomain 'session_projcache',
15
+ // table 'sessions');
16
+ // 5. only after the log is confirmed gone, remove the workspace accounting
17
+ // (domain 'workspace': sessionIds arrays + global.archivedSessionIds).
18
+ //
19
+ // The client reloads after a successful delete, so the fresh session list is
20
+ // re-fetched from the host (session-query reads the persisted dirs).
21
+ //
22
+ // ESM module format (cordis bundle rule): named exports apply/inject/name.
23
+ // All registrations belong to the plugin fiber (ctx.effect / disposers).
24
+ import fs from 'node:fs'
25
+ import path from 'node:path'
26
+ import os from 'node:os'
27
+ import { defineTool } from '@deepseek-ai/dsh-tools'
28
+
29
+ const name = 'dsh-session-delete'
30
+ // Only `tools` is a hard dependency; webServer is optional (see apply).
31
+ const inject = ['tools']
32
+
33
+ // A session id is used verbatim as ONE path segment under
34
+ // ~/.dsh/sessions/<workspace-slug>/, so the only thing that may be enforced is
35
+ // that it forms a single safe segment. The id's *shape* must never be the gate:
36
+ // local sessions are UUIDs (optionally `session-` prefixed), but the Agents
37
+ // Anywhere bridge mints ids such as `aa_2f10c18041dad707_sess__5Jp6t1EGVfDFA`,
38
+ // and other surfaces may mint their own spellings. Refusing those made every
39
+ // AA-created session undeletable ("invalid session id", HTTP 400) even though
40
+ // the sidebar had listed it and the dialog offered to delete it.
41
+ const SESSION_ID_MAX_LENGTH = 512
42
+
43
+ function isSafeSessionId(value) {
44
+ if (typeof value !== 'string') return false
45
+ const id = value.trim()
46
+ if (id === '' || id.length > SESSION_ID_MAX_LENGTH) return false
47
+ // `.` / `..` name the slug directory itself or its parent.
48
+ if (id === '.' || id === '..') return false
49
+ // Separators (both flavours) and control characters can never be one segment.
50
+ if (id.includes('/') || id.includes('\\')) return false
51
+ if (/[\u0000-\u001f\u007f]/.test(id)) return false
52
+ // Nothing on any surface mints an id without a letter or digit.
53
+ if (!/\p{L}|\p{N}/u.test(id)) return false
54
+ return true
55
+ }
56
+
57
+ class DeleteError extends Error {
58
+ constructor(message, status) {
59
+ super(message)
60
+ this.status = status
61
+ }
62
+ }
63
+
64
+ // --- path helpers ------------------------------------------------------------
65
+
66
+ function dshHome() {
67
+ return process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
68
+ }
69
+
70
+ function sessionsRoot() {
71
+ return path.join(dshHome(), 'sessions')
72
+ }
73
+
74
+ // Session ids may appear in two spellings in different stores: the raw id
75
+ // (`<uuid>`) and the prefixed form (`session-<uuid>`). The on-disk JSONL
76
+ // backend encodes the exact session id, while older/workspace/projcache rows
77
+ // can carry either spelling. Return every unique spelling we should clean up.
78
+ function sessionIdVariants(sessionId) {
79
+ const id = sessionId.trim()
80
+ const variants = new Set([id])
81
+ if (id.startsWith('session-')) {
82
+ const bare = id.slice('session-'.length)
83
+ // `session-` alone strips to '' and would name the workspace-slug directory
84
+ // itself — removing it would wipe every session of that workspace.
85
+ if (isSafeSessionId(bare)) variants.add(bare)
86
+ } else {
87
+ const prefixed = `session-${id}`
88
+ if (isSafeSessionId(prefixed)) variants.add(prefixed)
89
+ }
90
+ return [...variants]
91
+ }
92
+
93
+ // Locate ~/.dsh/sessions/<slug>/<sessionId>/ by scanning every slug dir, so
94
+ // the workspace-path encoding never has to be re-derived here. Returns every
95
+ // matching directory (both id spellings, if both exist).
96
+ function findSessionDirs(sessionId) {
97
+ const root = sessionsRoot()
98
+ const variants = sessionIdVariants(sessionId)
99
+ let entries = []
100
+ try {
101
+ entries = fs.readdirSync(root, { withFileTypes: true })
102
+ } catch {
103
+ return []
104
+ }
105
+ const found = []
106
+ for (const e of entries) {
107
+ if (!e.isDirectory()) continue
108
+ for (const variant of variants) {
109
+ const slugDir = path.join(root, e.name)
110
+ const candidate = path.join(slugDir, variant)
111
+ // Belt and braces behind isSafeSessionId: a variant that ever escaped the
112
+ // slug directory is skipped instead of being stat'ed or removed.
113
+ if (path.dirname(candidate) !== slugDir) continue
114
+ try {
115
+ if (fs.statSync(candidate).isDirectory() && !found.includes(candidate)) found.push(candidate)
116
+ } catch { /* keep scanning */ }
117
+ }
118
+ }
119
+ return found
120
+ }
121
+
122
+ // Remove every on-disk session directory for both id spellings.
123
+ function removeSessionDirs(sessionId) {
124
+ const dirs = findSessionDirs(sessionId)
125
+ for (const dir of dirs) {
126
+ fs.rmSync(dir, { recursive: true, force: true })
127
+ }
128
+ return dirs.length > 0
129
+ }
130
+
131
+ // --- live storage mutation (memory + disk stay consistent) -------------------
132
+
133
+ // Remove the session from the projection-cache domain and (optionally) the
134
+ // workspace accounting domain. Uses the opened domain facilities (the
135
+ // authoritative in-memory state) so the periodic flush can never re-publish a
136
+ // stale row. All id spellings are cleaned because projcache/workspace rows
137
+ // may use either the raw uuid or the `session-` prefixed form.
138
+ // Domain API: storageDomain.get(name) -> domain with .table(name) (KvTable:
139
+ // get/put/delete/entries) and .global (handle with get/set).
140
+ async function stripStorageDomains(ctx, sessionId, { workspace = true } = {}) {
141
+ const sd = ctx.get('storageDomain')
142
+ if (!sd) return { projRemoved: false, workspaceRemoved: false }
143
+ const variants = sessionIdVariants(sessionId)
144
+ let projRemoved = false
145
+ let workspaceRemoved = false
146
+
147
+ const proj = sd.get('session_projcache')
148
+ if (proj && typeof proj.table === 'function') {
149
+ try {
150
+ const sessions = proj.table('sessions')
151
+ for (const variant of variants) {
152
+ if (sessions.get(variant) !== undefined) {
153
+ await sessions.delete(variant)
154
+ projRemoved = true
155
+ }
156
+ }
157
+ } catch { /* unit closed or table absent: nothing to clean */ }
158
+ }
159
+
160
+ if (workspace) {
161
+ const ws = sd.get('workspace')
162
+ if (ws && typeof ws.table === 'function') {
163
+ try {
164
+ const workspaces = ws.table('workspaces')
165
+ for (const [wid, rec] of workspaces.entries()) {
166
+ if (rec && Array.isArray(rec.sessionIds) && variants.some((v) => rec.sessionIds.includes(v))) {
167
+ await workspaces.put(wid, {
168
+ ...rec,
169
+ sessionIds: rec.sessionIds.filter((x) => !variants.includes(x)),
170
+ })
171
+ workspaceRemoved = true
172
+ }
173
+ }
174
+ } catch { /* unit closed or table absent */ }
175
+ try {
176
+ const g = ws.global
177
+ if (g && typeof g.get === 'function' && typeof g.set === 'function') {
178
+ const state = g.get()
179
+ if (state && Array.isArray(state.archivedSessionIds) && variants.some((v) => state.archivedSessionIds.includes(v))) {
180
+ await g.set({ ...state, archivedSessionIds: state.archivedSessionIds.filter((x) => !variants.includes(x)) })
181
+ workspaceRemoved = true
182
+ }
183
+ }
184
+ } catch { /* no global slot or unit closed */ }
185
+ }
186
+ }
187
+
188
+ return { projRemoved, workspaceRemoved }
189
+ }
190
+
191
+ // --- core delete --------------------------------------------------------------
192
+
193
+ // Stop a live agent (cancel the active turn, wait for quiescence) before its
194
+ // session is deleted. Cancel causes surface in the log as a user-cancel; the
195
+ // wait is time-boxed so a stuck driver never blocks the deletion.
196
+ async function stopAgentIfRunning(ctx, sessionId) {
197
+ const agents = ctx.get('agents')
198
+ if (!agents || typeof agents.get !== 'function') return false
199
+ const agent = agents.get(sessionId)
200
+ if (!agent) return false
201
+ if (typeof agent.cancel === 'function') {
202
+ try { agent.cancel({ kind: 'user' }) } catch { /* agent may already be settling */ }
203
+ }
204
+ if (typeof agent.whenIdle === 'function') {
205
+ try {
206
+ await Promise.race([
207
+ agent.whenIdle(),
208
+ new Promise((resolve) => setTimeout(resolve, 15000)),
209
+ ])
210
+ } catch { /* ignore: proceed with deletion anyway */ }
211
+ }
212
+ return true
213
+ }
214
+
215
+ // Flush a live session before detaching it. The persistence layer flushes on
216
+ // session/disposed; flushing here first drains any pending writes while the
217
+ // session is still alive, so the later dispose has nothing to re-create after
218
+ // we delete the on-disk log.
219
+ async function flushSessionIfLive(ctx, sessionId) {
220
+ const sessions = ctx.get('sessions')
221
+ if (!sessions || typeof sessions.get !== 'function') return false
222
+ let flushed = false
223
+ for (const variant of sessionIdVariants(sessionId)) {
224
+ const session = sessions.get(variant)
225
+ if (!session) continue
226
+ if (typeof sessions.flush === 'function') {
227
+ try {
228
+ await sessions.flush(session)
229
+ flushed = true
230
+ } catch { /* ignore: deletion proceeds and removes the log anyway */ }
231
+ }
232
+ }
233
+ return flushed
234
+ }
235
+
236
+ // Remove the session from the in-memory store so host session lists stop
237
+ // returning it and no flush can re-materialize its files. The store has no
238
+ // public remove API; detachEntered is the store's own teardown path (deletes
239
+ // the entry and emits session/disposed). Try every id spelling defensively.
240
+ function detachLiveSession(ctx, sessionId) {
241
+ const sessions = ctx.get('sessions')
242
+ if (!sessions) return false
243
+ let detached = false
244
+ try {
245
+ const store = sessions.store
246
+ for (const variant of sessionIdVariants(sessionId)) {
247
+ const entry = store && typeof store.get === 'function' ? store.get(variant) : undefined
248
+ if (entry === undefined) continue
249
+ if (typeof sessions.detachEntered === 'function') {
250
+ sessions.detachEntered(entry)
251
+ detached = true
252
+ } else if (store && typeof store.delete === 'function') {
253
+ store.delete(variant)
254
+ if (sessions.attachments && entry.session && typeof sessions.attachments.delete === 'function') {
255
+ sessions.attachments.delete(entry.session)
256
+ }
257
+ detached = true
258
+ }
259
+ }
260
+ } catch { /* ignore */ }
261
+ return detached
262
+ }
263
+
264
+ async function deleteSessionCore(ctx, rawSessionId) {
265
+ const sessionId = String(rawSessionId || '').trim()
266
+ if (!isSafeSessionId(sessionId)) {
267
+ throw new DeleteError(`invalid session id: ${sessionId}`, 400)
268
+ }
269
+ const stopped = await stopAgentIfRunning(ctx, sessionId)
270
+ await flushSessionIfLive(ctx, sessionId)
271
+ const detached = detachLiveSession(ctx, sessionId)
272
+
273
+ // Remove every on-disk log directory first. If the filesystem refuses, fail
274
+ // before touching workspace accounting so a half-deleted session cannot fall
275
+ // out of its group into "Ungrouped".
276
+ const firstDirRemoved = removeSessionDirs(sessionId)
277
+
278
+ // Remove projection rows now (they are not the grouping authority), then
279
+ // sweep again: the dispose path may have been mid-flight and could have
280
+ // re-created a directory after the first removal.
281
+ const projStorage = await stripStorageDomains(ctx, sessionId, { workspace: false })
282
+ const secondDirRemoved = removeSessionDirs(sessionId)
283
+ await new Promise((resolve) => setImmediate(resolve))
284
+ const thirdDirRemoved = removeSessionDirs(sessionId)
285
+
286
+ const remainingDirs = findSessionDirs(sessionId)
287
+ if (remainingDirs.length > 0) {
288
+ throw new DeleteError(`session files could not be fully removed: ${remainingDirs.join(', ')}`, 500)
289
+ }
290
+
291
+ // Only after the log is confirmed gone do we detach the session from its
292
+ // workspace/archive accounting.
293
+ const workspaceStorage = await stripStorageDomains(ctx, sessionId, { workspace: true })
294
+ const dirRemoved = firstDirRemoved || secondDirRemoved || thirdDirRemoved
295
+ const projRemoved = projStorage.projRemoved || workspaceStorage.projRemoved
296
+ const workspaceRemoved = workspaceStorage.workspaceRemoved
297
+ if (!dirRemoved && !projRemoved && !workspaceRemoved) {
298
+ throw new DeleteError(`session not found: ${sessionId}`, 404)
299
+ }
300
+ return { stopped, detached, dirRemoved, projRemoved, workspaceRemoved }
301
+ }
302
+
303
+ // --- session list (for sidebar menu title -> id matching) ----------------------
304
+
305
+ // Lightweight {sessionId, title, running} list from the projection cache
306
+ // (authoritative titles) plus the live agent registry. The client sidebar
307
+ // menu item matches the row title against this list so it can open the
308
+ // delete dialog for the right session WITHOUT switching to it.
309
+ async function listSessions(ctx) {
310
+ const agents = ctx.get('agents')
311
+ const sd = ctx.get('storageDomain')
312
+ const out = []
313
+ if (!sd) return out
314
+ const proj = sd.get('session_projcache')
315
+ if (!proj || typeof proj.table !== 'function') return out
316
+ try {
317
+ const sessions = proj.table('sessions')
318
+ for (const [id, rec] of sessions.entries()) {
319
+ if (!rec || typeof rec !== 'object') continue
320
+ const rows = rec.rows && typeof rec.rows === 'object' ? rec.rows : {}
321
+ const titleRow = rows.title && rows.title.val
322
+ const identity = rec.identity && typeof rec.identity === 'object' ? rec.identity : {}
323
+ out.push({
324
+ sessionId: id,
325
+ title: typeof titleRow === 'string' ? titleRow : null,
326
+ createdAt: typeof identity.createdAt === 'number' ? identity.createdAt : null,
327
+ running: !!(agents && typeof agents.get === 'function' && agents.get(id)),
328
+ })
329
+ }
330
+ } catch { /* unit closed or table absent */ }
331
+ return out
332
+ }
333
+
334
+ // --- http helpers -------------------------------------------------------------
335
+
336
+ function sendJson(res, status, obj) {
337
+ const body = JSON.stringify(obj)
338
+ res.writeHead(status, {
339
+ 'content-type': 'application/json; charset=utf-8',
340
+ 'content-length': Buffer.byteLength(body),
341
+ })
342
+ res.end(body)
343
+ }
344
+
345
+ function readBody(req) {
346
+ return new Promise((resolve, reject) => {
347
+ let data = ''
348
+ req.on('data', (d) => {
349
+ data += d
350
+ if (data.length > 1e6) req.destroy()
351
+ })
352
+ req.on('end', () => resolve(data))
353
+ req.on('error', reject)
354
+ req.on('aborted', () => reject(new Error('aborted')))
355
+ })
356
+ }
357
+
358
+ // --- plugin -------------------------------------------------------------------
359
+ // webServer is OPTIONAL (a terminal-only profile has no web surface): the
360
+ // HTTP endpoint registers when the service exists or appears later
361
+ // (ctx.inject child), while the tool registers unconditionally — so the
362
+ // plugin never hangs waiting on a service a profile will never provide.
363
+
364
+ function apply(ctx) {
365
+ function registerHttp(host, targetCtx) {
366
+ targetCtx.effect(() => host.register({
367
+ kind: 'exact',
368
+ path: '/__chameleon/session/list',
369
+ handler: async (req, res) => {
370
+ if (req.method !== 'GET') {
371
+ sendJson(res, 405, { error: 'method not allowed' })
372
+ return
373
+ }
374
+ try {
375
+ sendJson(res, 200, { ok: true, sessions: await listSessions(ctx) })
376
+ } catch (e) {
377
+ sendJson(res, 500, { error: e.message })
378
+ }
379
+ },
380
+ }))
381
+
382
+ targetCtx.effect(() => host.register({
383
+ kind: 'exact',
384
+ path: '/__chameleon/session/delete',
385
+ handler: async (req, res) => {
386
+ if (req.method !== 'POST') {
387
+ sendJson(res, 405, { error: 'method not allowed' })
388
+ return
389
+ }
390
+ let args = {}
391
+ try {
392
+ const body = await readBody(req)
393
+ if (body) args = JSON.parse(body)
394
+ } catch {
395
+ sendJson(res, 400, { error: 'bad json body' })
396
+ return
397
+ }
398
+ const sessionId = String(args.sessionId || '').trim()
399
+ if (!sessionId) {
400
+ sendJson(res, 400, { error: 'sessionId required' })
401
+ return
402
+ }
403
+ try {
404
+ const result = await deleteSessionCore(ctx, sessionId)
405
+ sendJson(res, 200, { ok: true, removed: [sessionId], ...result })
406
+ } catch (e) {
407
+ const status = e instanceof DeleteError && e.status ? e.status : 500
408
+ sendJson(res, status, { error: e.message })
409
+ }
410
+ },
411
+ }))
412
+ }
413
+
414
+ const ws = ctx.get('webServer')
415
+ if (ws !== undefined) {
416
+ registerHttp(ws, ctx)
417
+ } else {
418
+ // Register the route once a web surface appears (never in terminal-only
419
+ // profiles); the child fiber is torn down with this plugin's context.
420
+ ctx.inject(['webServer'], (sub) => {
421
+ registerHttp(sub.webServer, sub)
422
+ })
423
+ }
424
+
425
+ ctx.tools.register(defineTool({
426
+ name: 'workbench_session_delete',
427
+ description: 'Permanently delete one session of this workbench: stops the agent if it is running (cancel + quiescence), then removes its persisted log, projection-cache row and workspace accounting. After deletion the client reloads; the edit-mode caller should verify with workbench_status or the session list.',
428
+ parameters: {
429
+ sessionId: {
430
+ type: 'string',
431
+ required: true,
432
+ description: 'The exact session id as listed by the session list: a local <uuid>, a session-<uuid>, or a bridge-minted id such as aa_<hex>_sess__<token>. Rejected only when it is not a single safe path segment.',
433
+ },
434
+ },
435
+ output: {
436
+ schema: { type: 'string' },
437
+ render(_args, value) { return [{ type: 'text', text: value }] },
438
+ },
439
+ async execute(args) {
440
+ const sessionId = String(args.sessionId || '').trim()
441
+ try {
442
+ const result = await deleteSessionCore(ctx, sessionId)
443
+ return [
444
+ `deleted: ${sessionId}`,
445
+ `log dir removed: ${result.dirRemoved}`,
446
+ `projection row removed: ${result.projRemoved}`,
447
+ `workspace accounting removed: ${result.workspaceRemoved}`,
448
+ ].join('\n')
449
+ } catch (e) {
450
+ return `delete failed: ${e.message}`
451
+ }
452
+ },
453
+ }))
454
+ }
455
+
456
+ export { apply, inject, name }
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Session Delete",
4
+ "description": "Adds a delete-session button in the conversation header and a delete item in the session-row menu, both guarded by a risk-consent dialog. The host removes the session log, its projection-cache row and the workspace accounting, stopping a running agent first."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "删除会话",
4
+ "description": "在会话标题栏加一个删除按钮、在会话行的「...」菜单里加一条删除项,两者都会先弹出风险确认对话框。host 端删除会话日志、投影缓存与会话所在工作区的记账;运行中的会话会先被停止。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "@hongyongli/dsh-session-delete",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.1",
4
+ "type": "module",
5
+ "description": "Delete sessions of a DeepSeek Harness profile from the UI: header danger button + session-row menu item with a risk-consent dialog; host endpoint + tool delete the log, projection cache and workspace accounting. Version-unbound fork of @pepsi-ai/dsh-plugin-session-delete.",
6
+ "license": "MIT",
7
+ "main": "index.js",
8
+ "exports": {
9
+ ".": "./index.js",
10
+ "./client": "./client.js",
11
+ "./locale/*.json": "./locale/*.json",
12
+ "./icon": "./icon.svg",
13
+ "./package.json": "./package.json"
14
+ },
15
+ "files": [
16
+ "index.js",
17
+ "client.js",
18
+ "cordis.patch.yml",
19
+ "locale/en.json",
20
+ "locale/zh.json",
21
+ "icon.svg",
22
+ "test/session-id.test.mjs",
23
+ "README.md"
24
+ ],
25
+ "keywords": [
26
+ "dsh-plugin",
27
+ "dsh-bundle",
28
+ "session",
29
+ "delete"
30
+ ],
31
+ "publishConfig": {
32
+ "access": "public"
33
+ },
34
+ "dsh": {
35
+ "bundle": {
36
+ "patch": "./cordis.patch.yml"
37
+ },
38
+ "client": {
39
+ "platform": "web",
40
+ "inject": [
41
+ "@deepseek-ai/dsh-client-runtime"
42
+ ]
43
+ }
44
+ },
45
+ "peerDependencies": {
46
+ "@deepseek-ai/dsh-tools": "*"
47
+ }
6
48
  }
@@ -0,0 +1,133 @@
1
+ // Unit tests for the real plugin source: index.js is copied with only its two
2
+ // imports stubbed, then the internals are re-exported so the predicates and the
3
+ // filesystem walk are exercised exactly as shipped (no re-implementation).
4
+ import fs from 'node:fs'
5
+ import os from 'node:os'
6
+ import path from 'node:path'
7
+ import assert from 'node:assert/strict'
8
+ import { pathToFileURL } from 'node:url'
9
+
10
+ const repo = path.resolve(import.meta.dirname, '..')
11
+ const work = '/tmp/sd-test'
12
+ const home = path.join(work, 'home')
13
+ fs.rmSync(work, { recursive: true, force: true })
14
+ fs.mkdirSync(home, { recursive: true })
15
+
16
+ // --- stub the module and expose internals ------------------------------------
17
+ let src = fs.readFileSync(path.join(repo, 'index.js'), 'utf8')
18
+ src = src.replace(
19
+ "import { defineTool } from '@deepseek-ai/dsh-tools'",
20
+ 'const defineTool = (options) => options',
21
+ )
22
+ assert.ok(src.includes('const defineTool'), 'defineTool import was not stubbed')
23
+ src += '\nexport { isSafeSessionId, sessionIdVariants, findSessionDirs, removeSessionDirs, deleteSessionCore }\n'
24
+ const stubPath = path.join(work, 'index.stub.mjs')
25
+ fs.writeFileSync(stubPath, src)
26
+
27
+ process.env.DSH_HOME = home
28
+ const mod = await import(pathToFileURL(stubPath).href)
29
+ const { isSafeSessionId, sessionIdVariants, findSessionDirs, removeSessionDirs, deleteSessionCore } = mod
30
+
31
+ // --- id predicate + variants --------------------------------------------------
32
+ const AA = 'aa_2f10c18041dad707_sess__5Jp6t1EGVfDFA'
33
+ const UUID = '3ca4756c-f653-4412-9c04-967fb1beb0c3'
34
+
35
+ const safe = [
36
+ [AA, true],
37
+ [UUID, true],
38
+ [`session-${UUID}`, true],
39
+ ['session-', true], // a safe *segment*; the variant logic must still not strip to ''
40
+ ['测试-会话1', true],
41
+ [' ' + UUID + ' ', true], // trimmed by the caller/predicate
42
+ ['', false],
43
+ [' ', false],
44
+ ['.', false],
45
+ ['..', false],
46
+ ['../../etc/passwd', false],
47
+ ['a/b', false],
48
+ ['a\\b', false],
49
+ ['x\u0000y', false],
50
+ ['x\ny', false],
51
+ ['---', false],
52
+ ['a'.repeat(513), false],
53
+ ]
54
+ for (const [value, expected] of safe) {
55
+ assert.equal(isSafeSessionId(value), expected, `isSafeSessionId(${JSON.stringify(value)})`)
56
+ }
57
+ console.log(`isSafeSessionId: ${safe.length} cases ok`)
58
+
59
+ const variantCases = [
60
+ [AA, [AA, `session-${AA}`]],
61
+ [UUID, [UUID, `session-${UUID}`]],
62
+ [`session-${UUID}`, [`session-${UUID}`, UUID]],
63
+ ['session-', ['session-']], // never '', which would name the slug dir itself
64
+ [' ' + AA + ' ', [AA, `session-${AA}`]],
65
+ ]
66
+ for (const [id, expected] of variantCases) {
67
+ assert.deepEqual(sessionIdVariants(id), expected, `sessionIdVariants(${JSON.stringify(id)})`)
68
+ }
69
+ console.log(`sessionIdVariants: ${variantCases.length} cases ok`)
70
+
71
+ // --- filesystem walk against a fake DSH_HOME ---------------------------------
72
+ const slug = path.join(home, 'sessions', '--tmp-workspace--')
73
+ const other = path.join(home, 'sessions', '--other--')
74
+ for (const dir of [slug, other]) fs.mkdirSync(dir, { recursive: true })
75
+ const aaDir = path.join(slug, AA)
76
+ const uuidDir = path.join(slug, UUID)
77
+ const prefixedDir = path.join(slug, `session-${UUID}`)
78
+ const otherAaDir = path.join(other, AA)
79
+ for (const dir of [aaDir, uuidDir, prefixedDir, otherAaDir]) {
80
+ fs.mkdirSync(dir)
81
+ fs.writeFileSync(path.join(dir, 'session.jsonl'), '{}\n')
82
+ }
83
+
84
+ assert.deepEqual(findSessionDirs(AA).sort(), [aaDir, otherAaDir].sort(), 'AA id finds every spelling')
85
+ assert.deepEqual(findSessionDirs(UUID).sort(), [uuidDir, prefixedDir].sort(), 'uuid finds both spellings')
86
+ assert.deepEqual(findSessionDirs(`session-${UUID}`).sort(), [prefixedDir, uuidDir].sort(), 'prefixed id finds both spellings')
87
+ console.log('findSessionDirs: AA id, uuid and session-<uuid> all resolve')
88
+
89
+ // The data-loss regression: 'session-' must never resolve to the slug directory.
90
+ assert.deepEqual(findSessionDirs('session-'), [], "'session-' must not resolve the slug dir")
91
+ assert.deepEqual(findSessionDirs('..'), [], "'..' must not resolve anything")
92
+ assert.equal(removeSessionDirs('session-'), false, "removeSessionDirs('session-') must remove nothing")
93
+ assert.ok(fs.existsSync(slug), 'slug directory must survive a session- delete attempt')
94
+ assert.ok(fs.existsSync(aaDir), 'AA session must survive a session- delete attempt')
95
+ console.log("guard: 'session-' / '..' resolve to nothing and remove nothing")
96
+
97
+ // removeSessionDirs really deletes only the targeted session (both spellings).
98
+ assert.equal(removeSessionDirs(UUID), true, 'uuid delete reports a removal')
99
+ assert.ok(!fs.existsSync(uuidDir) && !fs.existsSync(prefixedDir), 'both uuid spellings removed')
100
+ assert.ok(fs.existsSync(aaDir) && fs.existsSync(otherAaDir), 'other sessions untouched')
101
+ console.log('removeSessionDirs: only the targeted session is removed')
102
+
103
+ assert.equal(removeSessionDirs(AA), true, 'AA delete reports a removal')
104
+ assert.ok(!fs.existsSync(aaDir) && !fs.existsSync(otherAaDir), 'AA session removed in every slug')
105
+ assert.ok(fs.existsSync(slug) && fs.existsSync(other), 'slug dirs remain')
106
+ console.log('removeSessionDirs: an AA-created session is deletable')
107
+
108
+ // --- the shipped entry point, driven with a bare ctx --------------------------
109
+ // A profile with no agents/sessions/storage services and an empty sessions root:
110
+ // the call must get PAST the id gate for an AA id and stop at "not found".
111
+ process.env.DSH_HOME = path.join(work, 'empty-home')
112
+ fs.mkdirSync(path.join(process.env.DSH_HOME, 'sessions'), { recursive: true })
113
+ const bareCtx = { get: () => undefined }
114
+
115
+ const statusOf = async (id) => {
116
+ try {
117
+ await deleteSessionCore(bareCtx, id)
118
+ return 'resolved'
119
+ } catch (error) {
120
+ return error.status ?? `no status (${error.message})`
121
+ }
122
+ }
123
+
124
+ assert.equal(await statusOf(AA), 404, 'AA id must pass the gate and report not-found, not invalid-id')
125
+ assert.equal(await statusOf('aa_0000000000000000_sess__ZZZZZZZZZZZZZ'), 404, 'any AA-shaped id passes the gate')
126
+ assert.equal(await statusOf('not-a-uuid'), 404, 'a safe non-uuid id passes the gate')
127
+ assert.equal(await statusOf('../../etc/passwd'), 400, 'traversal stays rejected')
128
+ assert.equal(await statusOf('a/b'), 400, 'a separator stays rejected')
129
+ assert.equal(await statusOf('..'), 400, "'..' stays rejected")
130
+ assert.equal(await statusOf('session-'), 404, "'session-' is a safe segment and reaches not-found")
131
+ console.log("deleteSessionCore: AA/non-uuid ids reach not-found (404), unsafe ids stay 400 invalid")
132
+
133
+ console.log('\nALL PASS')