dsh-remote 1.5.0 → 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
  /**
@@ -1025,25 +1104,44 @@ export class WebAttach {
1025
1104
  // the whole host process (issue #54: every page refresh after the pooled
1026
1105
  // connection dropped took the session, the browser and the remote orphan
1027
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)
1028
1130
  try {
1029
- this.client.forwardOut('127.0.0.1', 0, '127.0.0.1', this.remotePort, (err, channel) => {
1030
- if (err) { try { socket.destroy() } catch { /* already gone */ } return }
1031
- this.sockets.add(socket)
1032
- socket.pipe(channel)
1033
- channel.pipe(socket)
1034
- const kill = () => {
1035
- try { socket.destroy() } catch { /* already gone */ }
1036
- try { channel.close() } catch { /* already closed */ }
1037
- this.sockets.delete(socket)
1038
- }
1039
- socket.on('error', kill)
1040
- channel.on('error', kill)
1041
- socket.on('close', kill)
1042
- 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)
1043
1141
  })
1044
1142
  } catch (err) {
1045
1143
  this._clientLost(String((err && err.message) || err))
1046
- try { socket.destroy() } catch { /* already gone */ }
1144
+ kill()
1047
1145
  }
1048
1146
  }
1049
1147
 
@@ -1089,9 +1187,20 @@ export class WebAttach {
1089
1187
  * user may be using that DSH elsewhere, and silently killing a process we did
1090
1188
  * not start is worse than a leftover one. `stopRemote` opts in.
1091
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
+ *
1092
1198
  * @param {object} [opts] - close options.
1093
1199
  * @param {boolean} [opts.stopRemote] - also terminate the remote process.
1094
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).
1095
1204
  */
1096
1205
  async close({ stopRemote = false, exec } = {}) {
1097
1206
  // Stop following the pool BEFORE any await: a reconnect landing mid-teardown
@@ -1114,13 +1223,21 @@ export class WebAttach {
1114
1223
  if (server) await new Promise((resolve) => server.close(() => resolve()))
1115
1224
  // Only a process we started has a recorded PID; an attach to the user's own
1116
1225
  // running instance must never signal anything.
1226
+ let stopOutcome = null
1117
1227
  if (stopRemote && exec && this.remotePid) {
1118
- 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
+ }
1119
1235
  }
1120
1236
  this.client = null
1121
1237
  // The recorded PID and log path are FACTS about this session (the UI shows
1122
1238
  // them, and `stopRemote` addresses them), so they survive; `closed` is what
1123
1239
  // stops recovery work from being re-armed after teardown.
1124
1240
  this.closed = true
1241
+ return { stopOutcome }
1125
1242
  }
1126
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 }
@@ -49,7 +49,7 @@
49
49
  import { listDirStructured } from './remote-fs.js'
50
50
  import { missingRemoteFile } from './remote-write.js'
51
51
  import {
52
- normalizeRemotePath, joinRemoteRel, remoteDirname, relPathUnder, resolveRemoteWorkspacePath,
52
+ normalizeRemotePath, joinRemoteRel, remoteDirname, relPathUnder, resolveRemoteWorkspacePath, shq,
53
53
  } from './paths.js'
54
54
 
55
55
  // Defaults mirror dsh-api-workspace-files' Config so behavior holds even when
@@ -80,6 +80,8 @@ const notDirectory = (path, kind) =>
80
80
  remoteError('workspace-file/not-directory', `"${path}" is a ${kind}`, { path, kind })
81
81
  const outsideWorkspace = (path) =>
82
82
  remoteError('workspace-file/outside-workspace', `"${path}" is outside the workspace`, { path })
83
+ const searchFailed = (message) =>
84
+ remoteError('workspace-file/search-failed', message, {})
83
85
 
84
86
  const NUL = String.fromCharCode(0)
85
87
  const isMissingError = (error) =>
@@ -405,10 +407,156 @@ const remoteImpl = {
405
407
  truncated: entries.length > caps.maxEntries,
406
408
  }
407
409
  },
410
+
411
+ /**
412
+ * Issue #228: the core `search` (added on the host after #194) lists files
413
+ * under the LOCAL MIRROR with ripgrep, so a remote file that has not been
414
+ * synced yet is invisible to the core workspace search. Serve the same
415
+ * query shape from the remote: enumerate with `rg --files` over the remote
416
+ * root, admit name/path matches exactly as the core does (case-insensitive
417
+ * substring; with `/` the query matches the relative path), infer ancestor
418
+ * directories, and answer { matches, truncated, incomplete } in the core's
419
+ * vocabulary. Paths in the result are workspace-relative, never remote
420
+ * absolutes.
421
+ */
422
+ async search(binding, [request, signal], service, deps) {
423
+ throwIfAborted(signal)
424
+ const query = String(request && request.query || '').trim()
425
+ if (!query) throw badRequest('query is required')
426
+ const excluded = Array.isArray(request && request.excludedPaths) ? request.excludedPaths.map(String) : []
427
+ const includeHidden = !!(request && request.includeHidden)
428
+ const respectGitignore = !request || request.respectGitignore !== false
429
+ const limits = (service && service.config && service.config.search) || {}
430
+ const maxResults = Number.isFinite(Number(limits.maxResults)) && Number(limits.maxResults) > 0 ? Number(limits.maxResults) : 200
431
+ const maxEntries = Number.isFinite(Number(limits.maxEntries)) && Number(limits.maxEntries) > 0 ? Number(limits.maxEntries) : 20000
432
+ const graceMs = Number.isFinite(Number(limits.graceMs)) && Number(limits.graceMs) > 0 ? Number(limits.graceMs) : 2000
433
+ const timeoutMs = Number.isFinite(Number(limits.timeoutMs)) && Number(limits.timeoutMs) > 0 ? Number(limits.timeoutMs) : 30000
434
+
435
+ // Confirm the workspace root itself (core: not-found / not-directory).
436
+ const pool = deps.poolForMachine(binding.machine)
437
+ const sftp = await pool.sftp()
438
+ const root = binding.remotePath
439
+ const rootEntry = await lstatEntry(sftp, root, root)
440
+ if (attrKind(rootEntry) === 'symlink') {
441
+ const resolved = await statEntry(sftp, root, root)
442
+ if (attrKind(resolved) !== 'directory') throw notDirectory(root, 'symlink')
443
+ } else if (attrKind(rootEntry) !== 'directory') throw notDirectory(root, attrKind(rootEntry))
444
+
445
+ // Enumerate with ripgrep when present (the core's own vocabulary); fall
446
+ // back to `find` on hosts without rg — the same file set, but native
447
+ // ignore rules only apply where rg exists, so the fallback reports itself
448
+ // incomplete whenever the caller asked for them.
449
+ const excludeGlobs = excluded.map((p) => `--glob=!${shq(p.includes('/') ? '/' + p : p)}`).join(' ')
450
+ const rgFlags = ['--files', '--sort=path', '--null', '--path-separator=/',
451
+ includeHidden ? '--hidden' : '',
452
+ respectGitignore ? '' : '--no-ignore',
453
+ excludeGlobs,
454
+ ].filter(Boolean).join(' ')
455
+ const rgScript = `cd ${shq(root)} && if command -v rg >/dev/null 2>&1; then rg ${rgFlags}; else printf 'DSH_REMOTE_SEARCH_FALLBACK\\n' >&2; find . -type f -print0; fi`
456
+
457
+ // The pool truncates buffered stdout at maxOutputChars (200k by default),
458
+ // and parsing that blob silently loses every record past the cut while
459
+ // still reporting incomplete=false. Consume the stream instead and stop one
460
+ // record past maxEntries, which also makes the entry cap honest.
461
+ const stop = new AbortController()
462
+ const combined = signal ? AbortSignal.any([signal, stop.signal]) : stop.signal
463
+ const records = []
464
+ let listed = 0
465
+ let capped = false
466
+ let streamed = false
467
+ let pending = ''
468
+ const admit = (record) => {
469
+ if (!record) return true
470
+ listed += 1
471
+ if (listed > maxEntries) { capped = true; stop.abort(); return false }
472
+ records.push(record)
473
+ return true
474
+ }
475
+ const consume = (chunk) => {
476
+ streamed = true
477
+ pending += String(chunk)
478
+ let end
479
+ while (!capped && (end = pending.indexOf('\u0000')) !== -1) {
480
+ const record = pending.slice(0, end)
481
+ pending = pending.slice(end + 1)
482
+ if (!admit(record)) return
483
+ }
484
+ }
485
+ let res
486
+ try {
487
+ res = await pool.exec(rgScript, {
488
+ timeoutMs: Math.min(timeoutMs, 600000),
489
+ signal: combined,
490
+ onData: (channel, chunk) => { if (channel === 'stdout') consume(chunk) },
491
+ })
492
+ } catch (error) {
493
+ // A backstop that rejects on abort is fine once the cap already fired.
494
+ if (!(capped && stop.signal.aborted)) throw error
495
+ res = { code: null, signal: 'ABORTED', stdout: '', stderr: '' }
496
+ }
497
+ if (!capped) {
498
+ if (res.signal === 'ABORTED') {
499
+ if (signal && signal.aborted) throwIfAborted(signal)
500
+ if (!stop.signal.aborted) throw searchFailed('workspace file search was aborted')
501
+ }
502
+ if (res.signal === 'TIMEOUT') throw searchFailed(`workspace file search timed out after ${timeoutMs}ms`)
503
+ if (streamed) {
504
+ if (pending) admit(pending)
505
+ } else {
506
+ // Older adapters (and the unit harness) hand back buffered stdout and
507
+ // never tap onData; accept the same two separators there.
508
+ for (const record of String(res.stdout || '').split(/\r?\n|\u0000/)) {
509
+ if (!admit(record)) break
510
+ }
511
+ }
512
+ if (res.code !== null && res.code !== 0 && res.code !== 1 && res.code !== 2) {
513
+ throw searchFailed(`workspace file search failed (exit ${res.code}): ${String(res.stderr || '').trim().slice(0, 200)}`)
514
+ }
515
+ }
516
+ const fallback = /DSH_REMOTE_SEARCH_FALLBACK/.test(String(res.stderr || ''))
517
+ const incomplete = capped || res.code === 2 || (fallback && respectGitignore)
518
+
519
+ const needle = query.toLowerCase()
520
+ const byPath = query.includes('/')
521
+ const entries = new Map()
522
+ const isHidden = (path) => path.split('/').some((part) => part.startsWith('.'))
523
+ const isExcluded = (path) => excluded.some((p) => path === p || path.startsWith(p + '/'))
524
+ for (const record of records) {
525
+ // rg and find both print paths relative to the root we cd into; other
526
+ // adapters may hand back absolute or './'-prefixed ones. The ancestor
527
+ // walk below must never see a leading slash (lastIndexOf('/', 0) would
528
+ // keep returning 0 and loop forever).
529
+ const cleaned = record.replace(/^\.\//, '').trim()
530
+ if (!cleaned) continue
531
+ const relative = cleaned.startsWith(root + '/') ? cleaned.slice(root.length + 1) : cleaned
532
+ if (!relative) continue
533
+ // rg applied --hidden/--glob itself; only the find fallback needs the
534
+ // local filter (it cannot express those flags portably).
535
+ if (fallback && ((!includeHidden && isHidden(relative)) || isExcluded(relative))) continue
536
+ entries.set(relative, { path: relative, type: 'file' })
537
+ let end = relative.lastIndexOf('/')
538
+ while (end > 0) {
539
+ entries.set(relative.slice(0, end), { path: relative.slice(0, end), type: 'directory' })
540
+ end = relative.lastIndexOf('/', end - 1)
541
+ }
542
+ }
543
+ const matches = [...entries.values()].filter((entry) => {
544
+ const candidate = byPath ? entry.path : entry.path.slice(entry.path.lastIndexOf('/') + 1)
545
+ return candidate.toLowerCase().includes(needle)
546
+ }).sort((a, b) => {
547
+ const da = a.path.split('/').length, db = b.path.split('/').length
548
+ return da !== db ? da - db : (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)
549
+ })
550
+ return {
551
+ matches: matches.slice(0, maxResults),
552
+ truncated: matches.length > maxResults,
553
+ incomplete,
554
+ }
555
+ },
408
556
  }
409
557
 
410
558
  /** Methods wrapped, and the wire's positional arguments after the scope. */
411
- const WRAPPED_METHODS = ['read', 'readBytes', 'stat', 'list']
559
+ const WRAPPED_METHODS = ['read', 'readBytes', 'stat', 'list', 'search']
412
560
 
413
561
  /**
414
562
  * Wrap the core `workspaceFiles` service so mirror sessions are served from
@@ -456,7 +604,10 @@ export function installWorkspaceFilesRemote(ctx, opts = {}) {
456
604
  }
457
605
  installed = { restore }
458
606
  if (typeof scope.effect === 'function') {
459
- scope.effect(() => {
607
+ // cordis runs an effect body immediately and keeps its RETURN VALUE as
608
+ // the disposer. Running restore() in the body undid every wrapper in the
609
+ // same tick, so the seam never actually served a mirror session.
610
+ scope.effect(() => () => {
460
611
  unregistered = true
461
612
  restore()
462
613
  })