dsh-remote 1.4.1 → 1.6.0

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/lib/web-attach.js CHANGED
@@ -90,6 +90,22 @@ const DEAD_MARKER = '__DSH_REMOTE_DIED__'
90
90
  export const TAIL_MARKER = '__DSH_TAIL__'
91
91
  /** Marker carrying the remote PID so the session can stop its own process. */
92
92
  export const PID_MARKER = '__DSH_PID__='
93
+ /**
94
+ * Stop-report markers: the stop command prints at most one of these so close()
95
+ * can tell the route what the kill actually PROVED. Reporting only the REQUEST
96
+ * used to turn three no-kill shapes into `stoppedRemote: true` — the same
97
+ * dishonest-reporting class fixed for recursive remove (#271/#272):
98
+ * · FAILED — the signal was delivered but the PID still exists afterwards;
99
+ * · REFUSED — the argv no longer looks like our dsh, so nothing was signalled
100
+ * (the never-kill-a-stranger guard, now visible instead of silent);
101
+ * · UNVERIFIED — the remote has no /proc (e.g. macOS), so neither the
102
+ * identity check nor the post-kill probe can run at all.
103
+ * No marker means the PID was observed gone — the only shape a stop may be
104
+ * reported from as verified.
105
+ */
106
+ export const STOP_FAILED_MARKER = '__DSH_REMOTE_STOP_FAILED__'
107
+ export const STOP_REFUSED_MARKER = '__DSH_REMOTE_STOP_REFUSED__'
108
+ export const STOP_UNVERIFIED_MARKER = '__DSH_REMOTE_STOP_UNVERIFIED__'
93
109
 
94
110
  /**
95
111
  * Budget for the issue #125 discovery step. Asking "is one already running?"
@@ -247,20 +263,83 @@ export function explainLaunchFailure(output) {
247
263
  * exists and still looks like a `dsh` process, so a recycled PID belonging to an
248
264
  * unrelated program is not killed.
249
265
  *
266
+ * Beyond the kill, the command now REPORTS what it achieved, because "we asked
267
+ * for a stop" is not "the process is gone" (#271/#272 honest-reporting line).
268
+ * After the signal it probes `/proc/$P` — briefly retried, since a SIGTERM
269
+ * needs a scheduler turn before /proc shows the death — and echoes FAILED when
270
+ * the process survived; the refusal branch of the argv guard echoes REFUSED;
271
+ * and a remote without /proc at all (macOS), where the kill is never attempted,
272
+ * echoes UNVERIFIED instead of silence. The cleanup stays unconditional and
273
+ * the whole command still exits 0, so teardown cannot fail the caller — only
274
+ * what it PRINTS changed.
275
+ *
250
276
  * @param {number} pid - the PID reported by the launch.
251
277
  * @param {string} [logPath] - this session's log file, removed after the kill so
252
278
  * repeated attaches do not accumulate files in the remote home.
253
- * @returns {string} a POSIX shell command (always exits 0, never throws).
279
+ * @returns {string} a single-line POSIX shell command (always exits 0, never
280
+ * throws; prints a stop marker when the kill could not be proven).
254
281
  */
255
282
  export function buildStopCommand(pid, logPath = '') {
256
283
  const p = Number(pid) || 0
257
284
  const cleanup = logPath ? `; rm -f "$HOME/${logPath}" 2>/dev/null` : ''
258
285
  if (p < 1) return `true${cleanup}`
259
286
  return `P=${p}`
260
- + `; if [ -d "/proc/$P" ]; then`
287
+ + `; if [ -d /proc ] && [ -d "/proc/$P" ]; then`
261
288
  + ` C=$(tr '\\0' ' ' < "/proc/$P/cmdline" 2>/dev/null);`
262
- + ` case "$C" in *dsh*) kill -- -"$P" 2>/dev/null || kill "$P" 2>/dev/null;; esac;`
263
- + ` fi${cleanup}; true`
289
+ + ` case "$C" in *dsh*)`
290
+ + ` kill -- -"$P" 2>/dev/null || kill "$P" 2>/dev/null;`
291
+ + ` i=0; while [ -d "/proc/$P" ] && [ "$i" -lt 3 ]; do sleep 1; i=$((i+1)); done;`
292
+ + ` [ -d "/proc/$P" ] && echo ${STOP_FAILED_MARKER};;`
293
+ + ` *) echo ${STOP_REFUSED_MARKER};; esac;`
294
+ + ` elif [ ! -d /proc ]; then echo ${STOP_UNVERIFIED_MARKER}; fi${cleanup}; true`
295
+ }
296
+
297
+ /**
298
+ * Classify what the stop command PROVED about the remote process.
299
+ *
300
+ * @param {object|string} output - the exec result (or a bare stdout string).
301
+ * @returns {'verified'|'failed'|'refused'|'unverified'} 'verified' is a
302
+ * positive observation — the command ran to completion (exit 0) and the
303
+ * post-kill probe found the PID gone. A result that never really ran
304
+ * (non-zero or signalled exit, a bare string with no exit status, nothing at
305
+ * all) is 'unverified': it proves nothing either way, and claiming a stop
306
+ * from it is exactly the old defect.
307
+ */
308
+ export function parseStopOutcome(output) {
309
+ const text = typeof output === 'string' ? output : String((output && output.stdout) || '')
310
+ if (text.includes(STOP_FAILED_MARKER)) return 'failed'
311
+ if (text.includes(STOP_REFUSED_MARKER)) return 'refused'
312
+ if (text.includes(STOP_UNVERIFIED_MARKER)) return 'unverified'
313
+ if (output && typeof output === 'object' && output.code === 0) return 'verified'
314
+ return 'unverified'
315
+ }
316
+
317
+ /**
318
+ * What the route may honestly claim about a stop, given close()'s outcome.
319
+ *
320
+ * Continues the #271/#272 honest-reporting line (recursive remove reports
321
+ * incompleteness instead of success): `stoppedRemote` is a fact the stop
322
+ * command verified, never a restatement of the request. The one legacy shape
323
+ * kept on purpose is the /proc-less remote (e.g. macOS), where the kill can be
324
+ * neither attempted nor disproved — there the old `true` survives so the wire
325
+ * shape stays compatible, but it is labelled unverified instead of silently
326
+ * passing as a verified stop.
327
+ *
328
+ * @param {'verified'|'unverified'|'failed'|'refused'|'error'|null} stopOutcome
329
+ * what close() proved ('error': the stop command could not run at all).
330
+ * @returns {{stoppedRemote: boolean, note: string}} the response fields; the
331
+ * note is '' exactly when the claim needs no qualification, so the wire
332
+ * shape is unchanged for a verified stop.
333
+ */
334
+ export function stopRemoteReport(stopOutcome) {
335
+ if (stopOutcome === 'verified') return { stoppedRemote: true, note: '' }
336
+ if (stopOutcome === 'unverified') {
337
+ return { stoppedRemote: true, note: 'remote stop unverified: the remote has no /proc, so the outcome is unknown' }
338
+ }
339
+ if (stopOutcome === 'failed') return { stoppedRemote: false, note: 'remote stop failed: the process is still running' }
340
+ if (stopOutcome === 'refused') return { stoppedRemote: false, note: 'remote stop refused: the pid no longer looks like our dsh' }
341
+ if (stopOutcome === 'error') return { stoppedRemote: false, note: 'remote stop failed: the stop command could not run' }
342
+ return { stoppedRemote: false, note: 'remote stop not confirmed: close() reported no stop outcome' }
264
343
  }
265
344
 
266
345
  /**
@@ -294,9 +373,11 @@ export class WebAttach {
294
373
  this.localPortMax = opts.localPortMax ?? 50
295
374
  /** Whether the pool's lifecycle hooks are ours to install. */
296
375
  this.trackPool = opts.trackPool !== false
297
- /** Issue #125 discovery budgets (injectable so tests need not wait 8s). */
376
+ /** Issue #204: discover budgets (injectable so tests need not wait 8s). */
298
377
  this.discoverTimeoutMs = opts.discoverTimeoutMs ?? DISCOVER_TIMEOUT_MS
299
378
  this.probeTimeoutMs = opts.probeTimeoutMs ?? PROBE_TIMEOUT_MS
379
+ /** Issue #204: the reconnect backoff base (tests inject single-digit ms). */
380
+ this.reconnectBaseDelayMs = opts.reconnectBaseDelayMs ?? 1000
300
381
  /** @type {import('node:net').Server|null} */ this.server = null
301
382
  /** @type {Set<import('node:net').Socket>} */ this.sockets = new Set()
302
383
  /** @type {object|null} */ this.client = null
@@ -333,6 +414,10 @@ export class WebAttach {
333
414
  this.omittedNoOpen = false
334
415
  /** True while a reconnect-triggered re-resolve is in flight. */
335
416
  this._resolving = false
417
+ /** Issue #204: the reconnect-backoff loop's pending timer (null = idle). */
418
+ this._reconnectTimer = null
419
+ /** Issue #204: the current backoff delay (0 = fresh / reset). */
420
+ this._reconnectDelayMs = 0
336
421
  /** True once the borrowed connection has been lost (drives recovery). */
337
422
  this.connectionLost = false
338
423
  /** undefined = "not asked yet"; false = the remote process is provably gone. */
@@ -683,6 +768,9 @@ export class WebAttach {
683
768
  */
684
769
  _attach(client) {
685
770
  if (!client) return
771
+ // A client is (back) in hand: the issue #204 reconnect loop has done its
772
+ // job (or was never needed) — stop it and reset the backoff.
773
+ this._stopReconnectLoop()
686
774
  if (this.attachedClient && this.attachedClient !== client && this.onClientClose) {
687
775
  // A different client replaced the one we borrowed (pool reconnect). Stop
688
776
  // listening to the old one; its own 'close' has either fired already or
@@ -703,6 +791,40 @@ export class WebAttach {
703
791
  this.client = null
704
792
  this.connectionLost = true
705
793
  this.lastError = String(reason || 'ssh connection closed')
794
+ // Issue #204: without a driver the recovery machinery below never ran —
795
+ // the pool only reconnects when someone CALLS it, so an idle attach stayed
796
+ // a permanent dead end (listener up, every connection RST-ed) until the
797
+ // user manually disconnected.
798
+ this._scheduleReconnect()
799
+ }
800
+
801
+ /**
802
+ * Issue #204: dial the pool with a growing backoff until a client comes
803
+ * back. `pool.connect` memoizes an in-flight dial, so this loop and any
804
+ * other pool activity share one connection attempt; when one succeeds the
805
+ * pool fires onReady, whose hook re-attaches the client and kicks the
806
+ * (existing) re-resolve/restart of the remote `dsh web`. The loop stops on
807
+ * success, on close(), or when the pool goes away.
808
+ */
809
+ _scheduleReconnect() {
810
+ if (this.closed || !this.trackPool || !this.pool || typeof this.pool.connect !== 'function') return
811
+ if (this._reconnectTimer) return
812
+ const attempt = async () => {
813
+ this._reconnectTimer = null
814
+ if (this.closed || !this.pool || this.client) return
815
+ try { await this.pool.connect() } catch { /* link still down — back off and retry */ }
816
+ if (this.closed || !this.pool) return
817
+ if (this.client) { this._reconnectDelayMs = 0; return }
818
+ this._reconnectDelayMs = Math.min(this._reconnectDelayMs * 2 || this.reconnectBaseDelayMs, 30000)
819
+ this._reconnectTimer = setTimeout(attempt, this._reconnectDelayMs)
820
+ }
821
+ this._reconnectTimer = setTimeout(attempt, 0)
822
+ }
823
+
824
+ /** Stop the issue #204 reconnect loop (success, teardown, or pool change). */
825
+ _stopReconnectLoop() {
826
+ if (this._reconnectTimer) { clearTimeout(this._reconnectTimer); this._reconnectTimer = null }
827
+ this._reconnectDelayMs = 0
706
828
  }
707
829
 
708
830
  /**
@@ -982,25 +1104,44 @@ export class WebAttach {
982
1104
  // the whole host process (issue #54: every page refresh after the pooled
983
1105
  // connection dropped took the session, the browser and the remote orphan
984
1106
  // down with it). A dead tunnel is a UI state, not a reason to exit.
1107
+ //
1108
+ // That guard covers the window BEFORE ssh2 is called. The window AFTER it
1109
+ // ends at the same fatal destination, and the issue #54 fix did not cover
1110
+ // it: a LIVE forwardOut answers on a later turn (a real round-trip to the
1111
+ // remote sshd), and the socket used to get its 'error' listener only INSIDE
1112
+ // that callback. A client that reset in between (tab closed mid-request,
1113
+ // TCP RST) emitted 'error' with no listener, which Node raises from
1114
+ // TCP.onconnection as an uncaught exception — the same host-killing stack
1115
+ // as the throw above, from a connection that was perfectly healthy. So the
1116
+ // socket is tracked and wired the moment it is accepted, before ssh2 is
1117
+ // touched, and `kill` is idempotent so the callback's later channel wiring
1118
+ // can neither double-register nor resurrect a pair that already died.
1119
+ this.sockets.add(socket)
1120
+ let dead = false
1121
+ let channel = null
1122
+ const kill = () => {
1123
+ dead = true
1124
+ try { socket.destroy() } catch { /* already gone */ }
1125
+ try { if (channel) channel.close() } catch { /* already closed */ }
1126
+ this.sockets.delete(socket)
1127
+ }
1128
+ socket.on('error', kill)
1129
+ socket.on('close', kill)
985
1130
  try {
986
- this.client.forwardOut('127.0.0.1', 0, '127.0.0.1', this.remotePort, (err, channel) => {
987
- if (err) { try { socket.destroy() } catch { /* already gone */ } return }
988
- this.sockets.add(socket)
989
- socket.pipe(channel)
990
- channel.pipe(socket)
991
- const kill = () => {
992
- try { socket.destroy() } catch { /* already gone */ }
993
- try { channel.close() } catch { /* already closed */ }
994
- this.sockets.delete(socket)
995
- }
996
- socket.on('error', kill)
997
- channel.on('error', kill)
998
- socket.on('close', kill)
999
- channel.on('close', kill)
1131
+ this.client.forwardOut('127.0.0.1', 0, '127.0.0.1', this.remotePort, (err, ch) => {
1132
+ // The round-trip can land after the client already reset: close the
1133
+ // fresh channel rather than pipe it into a destroyed socket, or every
1134
+ // mid-window reset leaks one remote channel.
1135
+ channel = ch || null
1136
+ if (err || dead) { kill(); return }
1137
+ socket.pipe(ch)
1138
+ ch.pipe(socket)
1139
+ ch.on('error', kill)
1140
+ ch.on('close', kill)
1000
1141
  })
1001
1142
  } catch (err) {
1002
1143
  this._clientLost(String((err && err.message) || err))
1003
- try { socket.destroy() } catch { /* already gone */ }
1144
+ kill()
1004
1145
  }
1005
1146
  }
1006
1147
 
@@ -1046,13 +1187,26 @@ export class WebAttach {
1046
1187
  * user may be using that DSH elsewhere, and silently killing a process we did
1047
1188
  * not start is worse than a leftover one. `stopRemote` opts in.
1048
1189
  *
1190
+ * `stopRemote` used to be reported as a REQUEST: the caller answered
1191
+ * `stoppedRemote: true` from the flag alone, while the command always exited
1192
+ * 0, refused to signal non-dsh argvs, was skipped entirely on remotes without
1193
+ * /proc, and an exec failure was swallowed — every shape read as success. The
1194
+ * stop command now prints markers for what it PROVED, and this method returns
1195
+ * the classification so the caller can claim only that (#271/#272
1196
+ * honest-reporting line).
1197
+ *
1049
1198
  * @param {object} [opts] - close options.
1050
1199
  * @param {boolean} [opts.stopRemote] - also terminate the remote process.
1051
1200
  * @param {(cmd: string) => Promise<unknown>} [opts.exec] - remote exec.
1201
+ * @returns {Promise<{stopOutcome: 'verified'|'unverified'|'failed'|'refused'|'error'|null}>}
1202
+ * what the stop could prove; null when nothing was attempted (no
1203
+ * `stopRemote`, no exec, or no PID of ours to signal).
1052
1204
  */
1053
1205
  async close({ stopRemote = false, exec } = {}) {
1054
1206
  // Stop following the pool BEFORE any await: a reconnect landing mid-teardown
1055
- // must not re-arm the tunnel this call is in the middle of closing.
1207
+ // must not re-arm the tunnel this call is in the middle of closing. The
1208
+ // reconnect loop (issue #204) dies with the same stroke.
1209
+ this._stopReconnectLoop()
1056
1210
  this._detachPool()
1057
1211
  if (this.attachedClient && this.onClientClose) {
1058
1212
  try { this.attachedClient.removeListener('close', this.onClientClose) } catch { /* already gone */ }
@@ -1069,13 +1223,21 @@ export class WebAttach {
1069
1223
  if (server) await new Promise((resolve) => server.close(() => resolve()))
1070
1224
  // Only a process we started has a recorded PID; an attach to the user's own
1071
1225
  // running instance must never signal anything.
1226
+ let stopOutcome = null
1072
1227
  if (stopRemote && exec && this.remotePid) {
1073
- await Promise.resolve(execPosix(exec, buildStopCommand(this.remotePid, this.logPath))).catch(() => {})
1228
+ try {
1229
+ stopOutcome = parseStopOutcome(await execPosix(exec, buildStopCommand(this.remotePid, this.logPath)))
1230
+ } catch {
1231
+ // The transport failed, so the stop is UNPROVEN. The old
1232
+ // .catch(() => {}) swallowed exactly this shape into a silent success.
1233
+ stopOutcome = 'error'
1234
+ }
1074
1235
  }
1075
1236
  this.client = null
1076
1237
  // The recorded PID and log path are FACTS about this session (the UI shows
1077
1238
  // them, and `stopRemote` addresses them), so they survive; `closed` is what
1078
1239
  // stops recovery work from being re-armed after teardown.
1079
1240
  this.closed = true
1241
+ return { stopOutcome }
1080
1242
  }
1081
1243
  }
@@ -9,15 +9,15 @@
9
9
  // 2. Session logs live at `$DSH_HOME/sessions/<project-key(cwd)>/<encoded id>`
10
10
  // (the layout of `@deepseek-ai/dsh-session-persistence-jsonl`). The key and
11
11
  // segment encoders below mirror that package's `projectKey()` /
12
- // `encodeSegment()` so this module can find the directories DSH itself
13
- // writes. They are pure and covered by tests; if DSH ever changes the
14
- // layout, those tests name the drift instead of silently deleting nothing.
12
+ // `encodeSegment()`. A project key is a lossy index. The stored cwd
13
+ // must resolve to the physical mirror or a directory within it.
15
14
  //
16
15
  // Deletion is intentionally synchronous: the caller runs it from a maintenance
17
16
  // action (not a hot path), and it must finish before the UI reports success.
18
17
 
19
18
  import { existsSync, readdirSync, readFileSync, realpathSync, rmdirSync, rmSync, statSync } from 'node:fs'
20
19
  import path from 'node:path'
20
+ import { readStoredSessionCwd } from './binding.js'
21
21
 
22
22
  /** Name of the per-mirror binding file (`ensureMirror()` writes it). */
23
23
  export const MIRROR_META_FILE = '.dsh-remote-meta.json'
@@ -100,7 +100,27 @@ export function projectKey(cwd) {
100
100
  export function isUnder(root, target) {
101
101
  if (!root || !target) return false
102
102
  const rel = path.relative(path.resolve(String(root)), path.resolve(String(target)))
103
- return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel)
103
+ return rel !== '' && rel !== '..' && !rel.startsWith('..' + path.sep) && !path.isAbsolute(rel)
104
+ }
105
+
106
+ function realDirectory(dir) {
107
+ if (typeof dir !== 'string' || !path.isAbsolute(dir)) return ''
108
+ try {
109
+ const real = realpathSync(dir)
110
+ return statSync(real, { throwIfNoEntry: false })?.isDirectory() ? real : ''
111
+ } catch {
112
+ return ''
113
+ }
114
+ }
115
+
116
+ function containsCwd(mirror, cwd) {
117
+ return Boolean(cwd) && (path.relative(mirror, cwd) === '' || isUnder(mirror, cwd))
118
+ }
119
+
120
+ /** Whether a cwd is the physical mirror itself or a directory within it. */
121
+ export function isWorkspaceSessionCwd(mirror, cwd) {
122
+ const realMirror = realDirectory(mirror)
123
+ return Boolean(realMirror) && containsCwd(realMirror, realDirectory(cwd))
104
124
  }
105
125
 
106
126
  /** Parse a mirror's `.dsh-remote-meta.json`; undefined when absent/unusable.
@@ -232,50 +252,52 @@ export function sessionsDirFor(sessionsRoot, cwd) {
232
252
  return path.join(String(sessionsRoot), projectKey(String(cwd)))
233
253
  }
234
254
 
235
- /** Session directories DSH keeps for one project cwd.
236
- *
237
- * @param {object} input
238
- * @param {string} input.sessionsRoot - `$DSH_HOME/sessions`.
239
- * @param {string} input.cwd - the mirror directory recorded as the session cwd.
240
- * @returns {Array<{id: string, name: string, dir: string, modifiedAt: number}>}
241
- */
242
- export function listSessionDirs({ sessionsRoot, cwd, cwds = [] } = {}) {
243
- const out = []
244
- if (!sessionsRoot || !cwd || !existsSync(sessionsRoot)) return out
245
- // DSH stores the cwd as the session header saw it. When `$DSH_HOME` itself
246
- // is behind a symlink, realpath() and the header path differ, so accept both
247
- // spellings (the caller passes the alias it was given) and dedupe by dir.
248
- const candidates = []
249
- for (const candidate of [cwd, ...(Array.isArray(cwds) ? cwds : [])]) {
250
- const value = String(candidate || '')
251
- if (!value) continue
252
- try {
253
- const dir = sessionsDirFor(sessionsRoot, value)
254
- if (!candidates.includes(dir)) candidates.push(dir)
255
- } catch { /* unencodable candidate */ }
255
+ function directoriesUnder(dir) {
256
+ try {
257
+ return readdirSync(dir, { withFileTypes: true })
258
+ .filter((entry) => entry.isDirectory())
259
+ .map((entry) => entry.name)
260
+ } catch {
261
+ return []
256
262
  }
257
- const seen = new Set()
258
- for (const projectDir of candidates) {
259
- if (!existsSync(projectDir)) continue
260
- let children = []
261
- try {
262
- children = readdirSync(projectDir, { withFileTypes: true })
263
- } catch {
264
- continue
265
- }
266
- for (const child of children) {
267
- if (!child.isDirectory()) continue
268
- const dir = path.join(projectDir, child.name)
269
- if (seen.has(dir)) continue
270
- seen.add(dir)
263
+ }
264
+
265
+ function storedSessionRealCwd(dir, id) {
266
+ if (realDirectory(dir) !== dir) return ''
267
+ return realDirectory(readStoredSessionCwd(dir, id))
268
+ }
269
+
270
+ /** Gather history for the requested mirrors in one pass over the session store. */
271
+ export function listWorkspaceSessionDirs({ sessionsRoot, cwds = [] } = {}) {
272
+ const groups = new Map(cwds.map((cwd) => [cwd, []]))
273
+ const mirrors = [...groups].flatMap(([cwd, sessions]) => {
274
+ const real = realDirectory(cwd)
275
+ return real ? [{ real, sessions }] : []
276
+ })
277
+ const root = realDirectory(sessionsRoot)
278
+ if (!root || !mirrors.length) return groups
279
+
280
+ // Descendant sessions have their own buckets. A cwd can also be written
281
+ // through an alias, so verify each candidate using its log header.
282
+ for (const project of directoriesUnder(root)) {
283
+ const projectDir = path.join(root, project)
284
+ for (const name of directoriesUnder(projectDir)) {
285
+ const dir = path.join(projectDir, name)
286
+ const id = decodeSegment(name)
287
+ const realCwd = storedSessionRealCwd(dir, id)
288
+ const owners = mirrors.filter(({ real }) => containsCwd(real, realCwd))
289
+ if (!owners.length) continue
271
290
  let modifiedAt = 0
272
- try {
273
- modifiedAt = statSync(dir).mtimeMs || 0
274
- } catch { /* keep 0 */ }
275
- out.push({ id: decodeSegment(child.name), name: child.name, dir, modifiedAt })
291
+ try { modifiedAt = statSync(dir).mtimeMs || 0 } catch { /* keep 0 */ }
292
+ for (const { sessions } of owners) sessions.push({ id, name, dir, modifiedAt })
276
293
  }
277
294
  }
278
- return out
295
+ return groups
296
+ }
297
+
298
+ /** Session directories whose recorded cwd belongs to the given mirror. */
299
+ export function listSessionDirs({ sessionsRoot, cwd } = {}) {
300
+ return listWorkspaceSessionDirs({ sessionsRoot, cwds: [cwd] }).get(cwd)
279
301
  }
280
302
 
281
303
  /** Delete one mirror tree, refusing anything that is not a validated mirror.
@@ -291,7 +313,7 @@ export function deleteMirrorTree({ mirrorRoot, localMirror } = {}) {
291
313
  return true
292
314
  }
293
315
 
294
- /** Delete every session directory of one project cwd.
316
+ /** Delete the verified session directories of one mirror.
295
317
  *
296
318
  * `isLive(sessionId, dir)` is consulted per session; live ones are skipped and
297
319
  * reported so the caller can tell the person to stop them first. With
@@ -299,38 +321,41 @@ export function deleteMirrorTree({ mirrorRoot, localMirror } = {}) {
299
321
  *
300
322
  * @param {object} input
301
323
  * @param {string} input.sessionsRoot - `$DSH_HOME/sessions`.
302
- * @param {string} input.cwd - project cwd (the local mirror).
324
+ * @param {string} input.cwd - the local mirror directory.
303
325
  * @param {(id: string, dir: string) => boolean|Promise<boolean>} [input.isLive]
304
326
  * @param {boolean} [input.force]
305
327
  * @returns {Promise<{removed: string[], skippedLive: string[]}>}
306
328
  */
307
- export async function deleteSessionsFor({ sessionsRoot, cwd, cwds = [], isLive, force = false } = {}) {
329
+ export async function deleteSessionsFor({ sessionsRoot, cwd, isLive, force = false } = {}) {
308
330
  const removed = []
309
331
  const skippedLive = []
310
- for (const session of listSessionDirs({ sessionsRoot, cwd, cwds })) {
311
- let live = false
332
+ const emptiedProjects = new Set()
333
+ const mirror = realDirectory(cwd)
334
+ if (!mirror) return { removed, skippedLive }
335
+ for (const session of listSessionDirs({ sessionsRoot, cwd: mirror })) {
336
+ const ownsSession = () => containsCwd(mirror, storedSessionRealCwd(session.dir, session.id))
337
+ if (!ownsSession()) continue
312
338
  if (!force && typeof isLive === 'function') {
339
+ let live = false
313
340
  try {
314
341
  live = await isLive(session.id, session.dir) === true
315
- } catch {
316
- live = false
342
+ } catch { /* the liveness probe is best-effort */ }
343
+ if (live) {
344
+ skippedLive.push(session.id)
345
+ continue
317
346
  }
318
- }
319
- if (live) {
320
- skippedLive.push(session.id)
321
- continue
347
+ // The session directory or header may have changed during the probe.
348
+ if (!ownsSession()) continue
322
349
  }
323
350
  try {
324
351
  rmSync(session.dir, { recursive: true, force: true })
325
352
  removed.push(session.id)
353
+ emptiedProjects.add(path.dirname(session.dir))
326
354
  } catch { /* unreadable dir: leave it and let the caller report fewer removals */ }
327
355
  }
328
- // Leave no empty history group behind when the last session is gone; a
329
- // non-empty dir (live session, unreadable sibling) makes rmdir a no-op.
330
- for (const candidate of [cwd, ...(Array.isArray(cwds) ? cwds : [])]) {
331
- if (!candidate) continue
356
+ for (const project of emptiedProjects) {
332
357
  try {
333
- rmdirSync(sessionsDirFor(sessionsRoot, candidate))
358
+ if (realDirectory(project) === project) rmdirSync(project)
334
359
  } catch { /* still holds something */ }
335
360
  }
336
361
  return { removed, skippedLive }