dsh-plugin-wsl-env 0.29.0 → 0.29.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.
Files changed (78) hide show
  1. package/CHANGELOG.md +342 -0
  2. package/CONTRIBUTING.md +68 -12
  3. package/CONTRIBUTING.zh.md +34 -4
  4. package/README.md +1 -1
  5. package/agent/native/linux-aarch64/dsh-wsl-agent +0 -0
  6. package/agent/native/linux-x86_64/dsh-wsl-agent +0 -0
  7. package/agent/wsl-agent.sh +15 -4
  8. package/client.js +454 -110
  9. package/cordis.patch.yml +28 -7
  10. package/docs/AGENT-PROTOCOL-V7.md +4 -2
  11. package/docs/ARCHITECTURE.md +3 -1
  12. package/docs/ARCHITECTURE.zh.md +3 -1
  13. package/docs/COMPATIBILITY.md +1 -1
  14. package/docs/COMPATIBILITY.zh.md +1 -1
  15. package/docs/CONFIGURATION.md +19 -7
  16. package/docs/CONFIGURATION.zh.md +13 -5
  17. package/docs/DIAGNOSTICS.md +31 -5
  18. package/docs/DIAGNOSTICS.zh.md +22 -5
  19. package/docs/LIMITATIONS.md +65 -6
  20. package/docs/LIMITATIONS.zh.md +51 -6
  21. package/docs/PERFORMANCE.md +29 -1
  22. package/docs/PERFORMANCE.zh.md +23 -1
  23. package/docs/QUICKSTART.md +1 -1
  24. package/docs/QUICKSTART.zh.md +1 -1
  25. package/docs/README.zh.md +1 -1
  26. package/docs/RELEASING.md +29 -6
  27. package/docs/RELEASING.zh.md +9 -0
  28. package/docs/adr/0002-native-agent.md +50 -2
  29. package/lib/agent-confined.js +15 -4
  30. package/lib/agent-errors.d.ts +16 -0
  31. package/lib/agent-errors.js +19 -0
  32. package/lib/agent-exec.d.ts +8 -1
  33. package/lib/agent-exec.js +2 -1
  34. package/lib/agent-shared.d.ts +85 -2
  35. package/lib/agent-shared.js +167 -38
  36. package/lib/agent.d.ts +60 -6
  37. package/lib/agent.js +177 -28
  38. package/lib/auto-preset.js +7 -2
  39. package/lib/doctor-live.d.ts +36 -7
  40. package/lib/doctor-live.js +61 -12
  41. package/lib/doctor-process.d.ts +68 -0
  42. package/lib/doctor-process.js +139 -0
  43. package/lib/doctor-report.js +11 -109
  44. package/lib/fs-substrate.js +3 -3
  45. package/lib/fsio-agent.d.ts +57 -6
  46. package/lib/fsio-agent.js +168 -75
  47. package/lib/git-exec.d.ts +7 -1
  48. package/lib/git-exec.js +14 -2
  49. package/lib/native-agent.d.ts +25 -4
  50. package/lib/native-agent.js +52 -9
  51. package/lib/picker.d.ts +2 -1
  52. package/lib/picker.js +30 -13
  53. package/lib/plugin-update.js +18 -14
  54. package/lib/provider-common.d.ts +112 -0
  55. package/lib/provider-common.js +171 -0
  56. package/lib/sandbox-core.js +52 -13
  57. package/lib/search-exec.d.ts +6 -0
  58. package/lib/search-exec.js +10 -2
  59. package/lib/session-runtime.d.ts +46 -1
  60. package/lib/session-runtime.js +57 -7
  61. package/lib/session-scope.d.ts +22 -1
  62. package/lib/session-scope.js +33 -7
  63. package/lib/shell-env.js +125 -12
  64. package/lib/socket-isolation.d.ts +12 -4
  65. package/lib/socket-isolation.js +27 -10
  66. package/lib/status.js +53 -4
  67. package/lib/subprocess.js +3 -3
  68. package/lib/terminal-activity.js +6 -9
  69. package/lib/wsl-doctor-command.js +36 -80
  70. package/lib/wsl-filesystem.d.ts +9 -4
  71. package/lib/wsl-filesystem.js +26 -10
  72. package/lib/wsl-shell.d.ts +27 -17
  73. package/lib/wsl-shell.js +83 -24
  74. package/lib/wsl.d.ts +3 -1
  75. package/lib/wsl.js +82 -7
  76. package/package.json +5 -4
  77. package/scripts/bootstrap.sh +36 -12
  78. package/scripts/doctor.mjs +514 -201
@@ -242,18 +242,32 @@ export function overrideLocale(flag) {
242
242
 
243
243
  const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
244
244
  let WSL = "wsl.exe";
245
- const CMD = "cmd.exe";
245
+ let CMD = "cmd.exe";
246
246
  const TIMEOUT_MS = 60_000;
247
+ /**
248
+ * How long one package install may take. `apt-get` downloads and configures
249
+ * packages, and the 60 s deadline every other host command shares cut that
250
+ * short on a slow network — a `dpkg` killed mid-configure is left
251
+ * half-configured.
252
+ */
253
+ const INSTALL_TIMEOUT_MS = 600_000;
247
254
 
248
255
  /** The package families the install remedies know, in probe order. */
249
256
  const FAMILIES = ["apt-get", "dnf", "pacman", "zypper", "apk"];
250
257
  /** The package names the plugin uses, per family. */
251
258
  const PACKAGES = "bubblewrap git ripgrep inotify-tools";
252
- /** One install command per family; `zypper` spells its non-interactive flag differently. */
259
+ /**
260
+ * One install command per family; `zypper` spells its non-interactive flag
261
+ * differently. apt refreshes its package index first — a freshly installed
262
+ * Debian or Ubuntu has none, and `install` alone answers `E: Unable to locate
263
+ * package` — and pacman takes `-S`, not `-Sy`: refreshing the index without
264
+ * upgrading the system is the partial-upgrade form Arch advises against.
265
+ * The commands run through `sh -c`, so apt's `&&` is the distro's to read.
266
+ */
253
267
  const INSTALL = /** @type {Record<string, string>} */ ({
254
- "apt-get": `apt-get install -y ${PACKAGES}`,
268
+ "apt-get": `apt-get update -qq && apt-get install -y --no-install-recommends ${PACKAGES}`,
255
269
  dnf: `dnf install -y ${PACKAGES}`,
256
- pacman: `pacman -Sy --noconfirm ${PACKAGES}`,
270
+ pacman: `pacman -S --noconfirm --needed ${PACKAGES}`,
257
271
  zypper: `zypper --non-interactive install ${PACKAGES}`,
258
272
  apk: `apk add --no-cache ${PACKAGES}`,
259
273
  });
@@ -265,16 +279,22 @@ const FINDUTILS = /** @type {Record<string, string>} */ ({
265
279
  zypper: "zypper --non-interactive install findutils",
266
280
  apk: "apk add --no-cache findutils",
267
281
  });
268
- /** The read-only stale-scope report; `--fix` runs the shipped sweep instead. */
269
- const STALE_SCOPE_REPORT = [
282
+ /**
283
+ * The read-only stale-scope report; `--fix` runs the shipped sweep instead.
284
+ * Exported for the test that runs it against a fake `systemctl`.
285
+ */
286
+ export const STALE_SCOPE_REPORT = [
270
287
  "systemctl --user is-system-running >/dev/null 2>&1 || { echo none; exit 0; }",
271
288
  "systemctl --user list-units 'dsh-wsl-*.scope' --all --plain --no-legend --no-pager 2>/dev/null | while read -r unit _; do",
272
289
  ' [ -n "$unit" ] || continue',
273
290
  ' cg=$(systemctl --user show -p ControlGroup --value "$unit" 2>/dev/null)',
274
291
  " alive=0",
292
+ ' pids=""',
275
293
  ' if [ -n "$cg" ] && [ -r "/sys/fs/cgroup$cg/cgroup.procs" ]; then',
276
294
  ' while read -r pid; do',
277
- ' [ -n "$pid" ] || continue',
295
+ // WSL's own cgroup for non-systemd sessions lists a `0` no process owns;
296
+ // reading its cmdline is noise on stderr, not a finding.
297
+ ' case "$pid" in ""|0|*[!0-9]*) continue ;; esac',
278
298
  " if tr '\\0' ' ' < \"/proc/$pid/cmdline\" 2>/dev/null | grep -q -e 'wsl-agent.sh' -e 'dsh-wsl-agent'; then alive=1; pids=\"$pids $pid\"; fi",
279
299
  ' done < "/sys/fs/cgroup$cg/cgroup.procs"',
280
300
  " fi",
@@ -301,6 +321,132 @@ const CACHE_REPORT = [
301
321
  "done",
302
322
  ].join("\n");
303
323
 
324
+ /**
325
+ * Which probe groups a composed batch carries. Every flag is the caller's
326
+ * section gate already folded with the config-aware conditions (`sandbox`
327
+ * means "sandbox wanted AND the effective configuration enables it"), so the
328
+ * composers stay pure string builders.
329
+ * @typedef {object} BatchInclude
330
+ * @property {boolean} sandbox - the bubblewrap path/usability and socket-facts probes.
331
+ * @property {boolean} session - the PID-1 and systemd-run probes in batch A;
332
+ * the user-manager, linger and scope probes in batch B.
333
+ * @property {boolean} conf - the binfmt probe.
334
+ * @property {boolean} net - the resolv.conf and DNS probes.
335
+ * @property {boolean} host - the optional-tools probe.
336
+ * @property {boolean} agent - the architecture, cache and home probes in
337
+ * batch A; the agent-script readability probe in batch B.
338
+ */
339
+
340
+ /** How long one DNS lookup may take inside the batch: a query parked on a dead resolver otherwise holds every later fact hostage until the transport deadline. */
341
+ const DNS_TIMEOUT_S = 5;
342
+ /** How long one systemd-class command may take inside batch B. `systemctl --user` against a half-booted user manager can sit far longer than the answer is worth. */
343
+ const SYSTEMD_TIMEOUT_S = 10;
344
+ /** Wraps one command in the distro's `timeout` when it has one, so a hung command costs its own slice instead of the whole batch.
345
+ * @param {string} seconds - the timeout, in seconds.
346
+ * @param {string} command - the command line to wrap.
347
+ * @returns {string} the guarded command. */
348
+ const withTimeout = (seconds, command) => `if command -v timeout >/dev/null 2>&1; then timeout ${seconds} ${command}; else ${command}; fi`;
349
+
350
+ /**
351
+ * The pure-read batch: one `wsl.exe` spawn answers every fact that cannot
352
+ * hang, each emitter producing one `KEY=value` line. Multiline readings ride
353
+ * base64 (`*_B64`), and every emitter is guarded so one failing command costs
354
+ * its own key, not the batch.
355
+ * @param {BatchInclude} include - the probe groups to emit.
356
+ * @returns {string} the `sh -c` body.
357
+ */
358
+ export function composeBatch(include) {
359
+ /** @type {string[]} */
360
+ const lines = [
361
+ "printf 'DSHBATCH=ok\\n'",
362
+ `s=$(getent passwd "$(id -u)" 2>/dev/null | cut -d: -f7); [ -n "$s" ] || s=$SHELL; printf 'SH=%s\\nHM=%s\\n' "$s" "$HOME"`,
363
+ `printf 'FAMILY=%s\\n' "$(for f in ${FAMILIES.join(" ")}; do command -v "$f" >/dev/null 2>&1 && { printf %s "$f"; exit 0; }; done; printf unknown)"`,
364
+ `printf 'DF=%s\\n' "$(df -Pm / 2>/dev/null | sed -n '2p')"`,
365
+ `printf 'DATE=%s\\n' "$(date +%s 2>/dev/null)"`,
366
+ `printf 'CONF_B64=%s\\n' "$(cat /etc/wsl.conf 2>/dev/null | base64 | tr -d '\\n')"`,
367
+ ];
368
+ if (include.sandbox) {
369
+ lines.push(
370
+ `printf 'BWRAP=%s\\n' "$(command -v bwrap 2>/dev/null)"`,
371
+ `printf 'BWTEST=%s\\n' "$(bwrap --ro-bind / / -- true >/dev/null 2>&1 && printf ok || printf no)"`,
372
+ `printf 'SOCK_B64=%s\\n' "$( { ${socketIsolationProbeScript()} ; } 2>/dev/null | base64 | tr -d '\\n' )"`,
373
+ );
374
+ }
375
+ if (include.session) {
376
+ lines.push(
377
+ `printf 'PID1=%s\\n' "$(if [ -d /run/systemd/system ]; then printf 'systemd %s' "$(cat /proc/1/comm 2>/dev/null)"; else printf 'none %s' "$(cat /proc/1/comm 2>/dev/null)"; fi)"`,
378
+ `printf 'SYSTEMD_RUN=%s\\n' "$(command -v systemd-run 2>/dev/null)"`,
379
+ );
380
+ }
381
+ if (include.conf) {
382
+ lines.push(`printf 'BINFMT=%s\\n' "$([ -e /proc/sys/fs/binfmt_misc/WSLInterop ] && printf yes || printf no)"`);
383
+ }
384
+ if (include.net) {
385
+ lines.push(
386
+ `printf 'RESOLV=%s\\n' "$(wc -c < /etc/resolv.conf 2>/dev/null || printf 0)"`,
387
+ `printf 'DNS=%s\\n' "$( ${withTimeout(String(DNS_TIMEOUT_S), "getent hosts deb.debian.org 2>/dev/null")} | head -n 1 )"`,
388
+ );
389
+ }
390
+ if (include.host) {
391
+ lines.push(`printf 'TOOLS_B64=%s\\n' "$(for t in rg git inotifywait; do if p=$(command -v "$t" 2>/dev/null); then printf 'found %s %s\\n' "$t" "$p"; else printf 'missing %s\\n' "$t"; fi; done | base64 | tr -d '\\n')"`);
392
+ }
393
+ if (include.agent) {
394
+ lines.push(
395
+ `printf 'ARCH=%s\\n' "$(uname -m 2>/dev/null)"`,
396
+ `printf 'CACHE_B64=%s\\n' "$( { ${CACHE_REPORT} ; } 2>/dev/null | base64 | tr -d '\\n' )"`,
397
+ `printf 'HOMEEXEC=%s\\n' "$(d=$(mktemp -d "$HOME/.dsh-doctor-XXXXXXXX" 2>/dev/null) || { printf nowrite; exit 0; }; trap 'rm -rf "\${d:-}" 2>/dev/null || :' EXIT; printf '#!/bin/sh\\n' > "$d/x" && chmod 755 "$d/x" && "$d/x" >/dev/null 2>&1 && printf ok || printf noexec; rm -rf "$d")"`,
398
+ );
399
+ }
400
+ return lines.join("\n");
401
+ }
402
+
403
+ /**
404
+ * The systemd-class batch: the commands that talk to the user manager each
405
+ * ride their own `timeout`, in a spawn of their own so a wedged manager
406
+ * cannot hold the pure-read batch's facts hostage. It runs AFTER batch A
407
+ * because the agent-script readability probe needs the automount root the
408
+ * conf read produced.
409
+ * @param {BatchInclude} include - the probe groups to emit.
410
+ * @param {string} agentReadPath - the agent script as a Linux path inside the distro; empty emits nothing.
411
+ * @returns {string} the `sh -c` body.
412
+ */
413
+ export function composeSystemdBatch(include, agentReadPath) {
414
+ /** @type {string[]} */
415
+ const lines = ["printf 'DSHBATCHB=ok\\n'"];
416
+ if (include.session) {
417
+ lines.push(
418
+ `printf 'USER=%s\\n' "$( ${withTimeout(String(SYSTEMD_TIMEOUT_S), "systemctl --user is-system-running 2>/dev/null")} || true )"`,
419
+ `printf 'LINGER=%s\\n' "$( ${withTimeout(String(SYSTEMD_TIMEOUT_S), `loginctl show-user "$(id -un)" -p Linger 2>/dev/null`)} || true )"`,
420
+ `printf 'SCOPES_B64=%s\\n' "$( { ${STALE_SCOPE_REPORT} ; } 2>/dev/null | base64 | tr -d '\\n' )"`,
421
+ );
422
+ }
423
+ if (include.agent && agentReadPath.length > 0) {
424
+ lines.push(`printf 'AGENT_READ=%s\\n' "$([ -f "${agentReadPath}" ] && printf yes || printf no)"`);
425
+ }
426
+ return lines.join("\n");
427
+ }
428
+
429
+ /**
430
+ * Reads one composed batch's `KEY=value` lines. Values of `*_B64` keys are
431
+ * decoded from base64; unknown or malformed lines are ignored, and a missing
432
+ * key simply stays absent — every consumer treats absence the way it treated
433
+ * a failed standalone probe before the batches.
434
+ * @param {string} stdout - the batch's stdout.
435
+ * @returns {Record<string, string>} the facts, multiline values decoded.
436
+ */
437
+ export function parseBatchFacts(stdout) {
438
+ /** @type {Record<string, string>} */
439
+ const facts = {};
440
+ for (const line of stdout.split(/\r?\n/)) {
441
+ const eq = line.indexOf("=");
442
+ if (eq <= 0) continue;
443
+ const key = line.slice(0, eq);
444
+ const value = line.slice(eq + 1);
445
+ facts[key] = key.endsWith("_B64") ? Buffer.from(value, "base64").toString("utf8") : value;
446
+ }
447
+ return facts;
448
+ }
449
+
304
450
  /**
305
451
  * One check result.
306
452
  * @typedef {object} Check
@@ -359,9 +505,10 @@ const QUICK_SECTIONS = ["host", "session", "sandbox"];
359
505
  /**
360
506
  * Run one host command; never throws.
361
507
  * @param {string[]} argv - executable and arguments.
508
+ * @param {number} [timeoutMs] - the deadline; a package install passes its own.
362
509
  * @returns {Promise<{ ok: boolean, stdout: string, stderr: string, code?: string, timedOut?: boolean }>} the capture.
363
510
  */
364
- function run(argv) {
511
+ function run(argv, timeoutMs = TIMEOUT_MS) {
365
512
  return new Promise((settle) => {
366
513
  const [file, ...args] = argv;
367
514
  if (file === undefined) throw new Error("doctor: empty argv");
@@ -375,10 +522,73 @@ function run(argv) {
375
522
  const timedOut = error !== null && /** @type {NodeJS.ErrnoException & { signal?: string }} */ (error).signal === "SIGTERM";
376
523
  settle({ ok: error === null, stdout: stdout ?? "", stderr: stderr ?? "", code, timedOut });
377
524
  };
378
- execFile(file, args, { encoding: "utf8", timeout: TIMEOUT_MS, windowsHide: true, env: { ...process.env, WSL_UTF8: "1" } }, done);
525
+ // The test seam (`--wsl <script.mjs>` / `--cmd <script.mjs>`): Windows
526
+ // resolves the real `System32\wsl.exe`/`cmd.exe` before PATH, so the
527
+ // cross-platform fakes are Node scripts run under this runtime. No
528
+ // production path names a `.mjs`; a nonsensical value fails closed.
529
+ const scripted = file.endsWith(".mjs");
530
+ execFile(scripted ? process.execPath : file, scripted ? [file, ...args] : args, { encoding: "utf8", timeout: timeoutMs, windowsHide: true, env: { ...process.env, WSL_UTF8: "1" } }, done);
379
531
  });
380
532
  }
381
533
 
534
+ /**
535
+ * The spawn argv for one `wsl.exe` invocation, honouring the `.mjs` test seam
536
+ * `run()` honours — the two direct `spawn()` sites (the resident handshake and
537
+ * the smoke legs) go through here so every wsl.exe path shares one convention.
538
+ *
539
+ * @param {string} wslExe - the configured `wsl.exe` path.
540
+ * @param {string[]} rest - the argv after the program.
541
+ * @returns {{ file: string, args: string[] }} the spawn's program and argv.
542
+ */
543
+ function wslSpawn(wslExe, rest) {
544
+ return wslExe.endsWith(".mjs") ? { file: process.execPath, args: [wslExe, ...rest] } : { file: wslExe, args: rest };
545
+ }
546
+
547
+ /** How much of a failed command's output a fix row quotes. */
548
+ const OUTPUT_TAIL = 300;
549
+
550
+ /**
551
+ * The end of a failed command's output, for a fix row that says why it failed.
552
+ *
553
+ * `run()` captures output and prints none of it, so a row that said "see the
554
+ * output above" pointed at output nobody could see; the tail rides the row.
555
+ *
556
+ * @param {{ stdout: string, stderr: string }} answer - the capture.
557
+ * @returns {string} ` (last output: "…")`, or an empty string when there was no output.
558
+ */
559
+ export function outputTail(answer) {
560
+ const text = `${answer.stdout}\n${answer.stderr}`.replace(/\s+/g, " ").trim();
561
+ if (text.length === 0) return "";
562
+ return ` (last output: "${text.length > OUTPUT_TAIL ? `…${text.slice(-OUTPUT_TAIL)}` : text}")`;
563
+ }
564
+
565
+ /**
566
+ * wsl.exe's own error class in a capture (`Wsl/Service/WSAETIMEDOUT` and the
567
+ * like). The sentence around it is localized and long, the class is neither.
568
+ * @param {string} text - the capture's output.
569
+ * @returns {string | undefined} the class, when there is one.
570
+ */
571
+ export function wslErrorClass(text) {
572
+ return /\bWsl\/[A-Za-z]+\/[A-Za-z0-9_]+/i.exec(text)?.[0];
573
+ }
574
+
575
+ /**
576
+ * Why a recheck's answer cannot be trusted: the deadline fired, wsl.exe
577
+ * reported a wedged service (a transport flake), or the read itself failed —
578
+ * each with the error class or the output's first line.
579
+ *
580
+ * @param {{ stderr: string, stdout: string, code?: string, timedOut?: boolean }} answer - the capture.
581
+ * @returns {string} the reason.
582
+ */
583
+ function unreadReason(answer) {
584
+ const output = `${answer.stderr}\n${answer.stdout}`.replace(/\s+/g, " ").trim();
585
+ const wsl = wslErrorClass(output);
586
+ if (answer.timedOut === true) return `wsl.exe timed out${wsl === undefined ? "" : ` (${wsl})`}`;
587
+ if (isFlake(answer)) return `wsl.exe reported a wedged service${wsl === undefined ? "" : ` (${wsl})`}`;
588
+ const first = output.slice(0, 80);
589
+ return `the read failed${answer.code === undefined ? "" : ` with ${answer.code}`}${first.length > 0 ? `: ${first}` : ""}`;
590
+ }
591
+
382
592
  /**
383
593
  * Parse `wsl.exe -l -v`'s table. The state column is localized, so only the
384
594
  * shape is trusted: `NAME[*] <state> <version>` — with the default marker
@@ -693,8 +903,8 @@ export function effectiveConfig(dshHome, root) {
693
903
  * @param {string} script - the shell script.
694
904
  * @returns {Promise<{ ok: boolean, stdout: string, stderr: string, code?: string }>} the capture.
695
905
  */
696
- function inDistro(distro, script) {
697
- return run([WSL, "-d", distro, "--exec", "sh", "-c", script]);
906
+ function inDistro(distro, script, timeoutMs = TIMEOUT_MS) {
907
+ return run([WSL, "-d", distro, "--exec", "sh", "-c", script], timeoutMs);
698
908
  }
699
909
 
700
910
  /**
@@ -706,7 +916,10 @@ function inDistro(distro, script) {
706
916
  * arrive exactly when a cold distro is mid-boot, and trusting them produced
707
917
  * the wrong class of report: static config (`wsl.conf`, resolv.conf) read as
708
918
  * broken when the read itself was the casualty.
709
- * @param {{ ok: boolean, stdout: string, stderr: string, timedOut?: boolean }} answer - the capture.
919
+ * Only the deadline flag and the output are read, so a bare `{ stdout, stderr }`
920
+ * qualifies too.
921
+ *
922
+ * @param {{ stdout: string, stderr: string, timedOut?: boolean }} answer - the capture.
710
923
  * @returns {boolean} true when the capture must not feed a config verdict.
711
924
  */
712
925
  export function isFlake(answer) {
@@ -723,25 +936,27 @@ const FLAKE_SETTLE_MS = 2_000;
723
936
  * `unknown` instead of a configuration verdict built on a wedged read.
724
937
  * @param {string} distro - the distro name.
725
938
  * @param {string} script - the shell script.
939
+ * @param {number} [timeoutMs] - the capture deadline; the default is the shared 60 s one.
726
940
  * @returns {Promise<{ ok: boolean, stdout: string, stderr: string, code?: string, timedOut?: boolean, flaked: boolean }>} the capture plus the flake flag.
727
941
  */
728
- async function askDistro(distro, script) {
729
- const first = await inDistro(distro, script);
942
+ async function askDistro(distro, script, timeoutMs = TIMEOUT_MS) {
943
+ const first = await inDistro(distro, script, timeoutMs);
730
944
  if (first.ok || !isFlake(first)) return { ...first, flaked: isFlake(first) };
731
945
  await new Promise((resolve) => setTimeout(resolve, FLAKE_SETTLE_MS));
732
- const second = await inDistro(distro, script);
946
+ const second = await inDistro(distro, script, timeoutMs);
733
947
  return { ...second, flaked: isFlake(second) };
734
948
  }
735
949
 
736
950
  /**
737
951
  * Parse the doctor's own arguments.
738
952
  * @param {string[]} argv - `process.argv.slice(2)`.
739
- * @returns {{ distro: string, wsl: string, json: boolean, fix: boolean, fixOwned: boolean, install: boolean, yes: boolean, readOnly: boolean, all: boolean, bundle: string, redact: boolean, sections: string, quick: boolean, help: boolean, locale: string }} the options.
953
+ * @returns {{ distro: string, wsl: string, cmd: string, json: boolean, fix: boolean, fixOwned: boolean, install: boolean, yes: boolean, readOnly: boolean, all: boolean, bundle: string, redact: boolean, sections: string, quick: boolean, help: boolean, locale: string, probeTimeout: number }} the options.
740
954
  */
741
955
  function parseArgs(argv) {
742
956
  const options = {
743
957
  distro: "",
744
958
  wsl: "",
959
+ cmd: "",
745
960
  json: false,
746
961
  fix: false,
747
962
  fixOwned: false,
@@ -755,6 +970,15 @@ function parseArgs(argv) {
755
970
  quick: false,
756
971
  help: false,
757
972
  locale: "",
973
+ probeTimeout: 0,
974
+ };
975
+ /** Reads a positive-integer millisecond value, rejecting the rest.
976
+ * @param {string} value - the raw flag value.
977
+ * @returns {number} the milliseconds. */
978
+ const ms = (value) => {
979
+ const parsed = Number(value);
980
+ if (!Number.isInteger(parsed) || parsed <= 0) throw new Error(`doctor: --probe-timeout needs a positive integer of milliseconds, got "${value}"`);
981
+ return parsed;
758
982
  };
759
983
  for (let i = 0; i < argv.length; i += 1) {
760
984
  const arg = argv[i] ?? "";
@@ -774,10 +998,14 @@ function parseArgs(argv) {
774
998
  else if (arg.startsWith("--bundle=")) options.bundle = arg.slice("--bundle=".length);
775
999
  else if (arg === "--redact") options.redact = true;
776
1000
  else if (arg === "--help" || arg === "-h") options.help = true;
1001
+ else if (arg === "--probe-timeout") options.probeTimeout = ms(argv[++i] ?? "");
1002
+ else if (arg.startsWith("--probe-timeout=")) options.probeTimeout = ms(arg.slice("--probe-timeout=".length));
777
1003
  else if (arg === "--distro") options.distro = argv[++i] ?? "";
778
1004
  else if (arg.startsWith("--distro=")) options.distro = arg.slice("--distro=".length);
779
1005
  else if (arg === "--wsl") options.wsl = argv[++i] ?? "";
780
1006
  else if (arg.startsWith("--wsl=")) options.wsl = arg.slice("--wsl=".length);
1007
+ else if (arg === "--cmd") options.cmd = argv[++i] ?? "";
1008
+ else if (arg.startsWith("--cmd=")) options.cmd = arg.slice("--cmd=".length);
781
1009
  else if (arg.startsWith("-")) throw new Error(`doctor: unknown option "${arg}"`);
782
1010
  else options.distro = arg;
783
1011
  }
@@ -972,13 +1200,16 @@ function hostPeerVersions() {
972
1200
  }
973
1201
 
974
1202
  /**
975
- * The install remedy for one distro and family.
1203
+ * The install remedy for one distro and family: the very command `--fix
1204
+ * --install` runs, spelled for a Windows shell. `sh -c "…"` keeps the apt
1205
+ * command's `&&` inside the distro in cmd, PowerShell 5.1 and PowerShell 7
1206
+ * alike — pasted bare, each of those shells would run the second half itself.
976
1207
  * @param {string} distro - the distro name.
977
1208
  * @param {string} family - the detected family, or `unknown`.
978
1209
  * @returns {string} the copy-paste command.
979
1210
  */
980
- function installRemedy(distro, family) {
981
- return `wsl.exe -d ${distro} -u root -- ${INSTALL[family] ?? INSTALL["apt-get"]}`;
1211
+ export function installRemedy(distro, family) {
1212
+ return `wsl.exe -d ${distro} -u root -- sh -c "${INSTALL[family] ?? INSTALL["apt-get"]}"`;
982
1213
  }
983
1214
 
984
1215
  /**
@@ -1056,9 +1287,11 @@ async function main(options) {
1056
1287
  if (options.readOnly && (options.fix || options.install)) return rejectReadOnly();
1057
1288
  // One rebinding covers every probe below (`-l -q`, `inDistro`, the
1058
1289
  // resident handshake, the sessions survey): an explicit `--wsl` replaces
1059
- // the module-level default for this whole run.
1290
+ // the module-level default for this whole run, and `--cmd` does the same
1291
+ // for the Windows-side reads (build, registry, .wslconfig).
1060
1292
  const wslExe = options.wsl.length > 0 ? options.wsl : WSL;
1061
1293
  WSL = wslExe;
1294
+ if (options.cmd.length > 0) CMD = options.cmd;
1062
1295
  /** @type {Check[]} */
1063
1296
  const checks = [];
1064
1297
  // A5: per-phase wall clock. The doctor must be fast enough to run twice;
@@ -1270,22 +1503,56 @@ async function main(options) {
1270
1503
  const check = (/** @type {string} */ id, /** @type {Check["status"]} */ status, /** @type {string} */ title, /** @type {string | undefined} */ detail = undefined, /** @type {string | undefined} */ remedy = undefined) => {
1271
1504
  collected.push({ id, status, title, ...(detail === undefined ? {} : { detail }), ...(remedy === undefined ? {} : { remedy }), distro: target });
1272
1505
  };
1273
- /** One in-distro probe with the flake retry. */
1274
- const probe = (/** @type {string} */ script) => askDistro(target, script);
1506
+ /** One in-distro probe with the flake retry, on this run's probe deadline. */
1507
+ const probeTimeout = options.probeTimeout > 0 ? options.probeTimeout : TIMEOUT_MS;
1508
+ const probe = (/** @type {string} */ script) => askDistro(target, script, probeTimeout);
1275
1509
  /** The `unknown` row a transport flake earns instead of a config verdict. */
1276
1510
  const flakeCheck = (/** @type {string} */ id, /** @type {string} */ title, /** @type {{ stderr: string, stdout: string }} */ answer) => check(id, "unknown", title,
1277
1511
  `transport flake — wsl.exe timed out or wedged (${(answer.stderr || answer.stdout || "no output").trim().split(/\r?\n/)[0]?.slice(0, 80) || "no output"}); this read is not trusted as a configuration verdict`,
1278
1512
  `rerun the doctor; if the flake repeats, "wsl.exe -t ${target}" (terminate just this distro) and rerun again`);
1279
- const alive = await probe("printf %s ok");
1280
- if (!alive.ok && alive.flaked) {
1281
- flakeCheck("distro.reachable", `Distro "${target}"`, alive);
1513
+ // The per-distro reads go out as two composed batches — the pure reads in
1514
+ // one `wsl.exe`, the systemd-class commands in another, each under its own
1515
+ // `timeout` — instead of one spawn per fact. The batch is the reach probe:
1516
+ // a distro that answers it answers everything it carries.
1517
+ const sandboxDisabled = effective.sandbox === "false" && effective.sessionSandbox === "false";
1518
+ const include = {
1519
+ sandbox: want("sandbox") && !sandboxDisabled,
1520
+ session: want("session"),
1521
+ conf: want("conf"),
1522
+ net: want("net"),
1523
+ host: want("host"),
1524
+ agent: want("agent"),
1525
+ };
1526
+ const batchAnswer = await probe(composeBatch(include));
1527
+ if (!batchAnswer.ok && batchAnswer.flaked) {
1528
+ flakeCheck("distro.reachable", `Distro "${target}"`, batchAnswer);
1282
1529
  return { checks: collected, reachable: false, bwrapPath: "", stale: 0, cacheEntries: 0, cacheBad: 0, cacheExecPath: "", family: "unknown", agentScriptDistro: undefined };
1283
1530
  }
1284
- if (!alive.ok || alive.stdout.trim() !== "ok") {
1531
+ const facts = parseBatchFacts(batchAnswer.stdout);
1532
+ if (!batchAnswer.ok || facts.DSHBATCH !== "ok") {
1285
1533
  check("distro.reachable", "fail", `Distro "${target}"`, "wsl.exe could not run a command in it (stopped, wedged, or missing)", `wsl.exe -d ${target} -- true; if that hangs, wsl.exe --shutdown, then retry`);
1286
1534
  return { checks: collected, reachable: false, bwrapPath: "", stale: 0, cacheEntries: 0, cacheBad: 0, cacheExecPath: "", family: "unknown", agentScriptDistro: undefined };
1287
1535
  }
1288
1536
  check("distro.reachable", "ok", `Distro "${target}"`, "answers commands");
1537
+ // The conf read rides batch A; its derived values gate batch B (the
1538
+ // agent-script readability probe needs the automount root).
1539
+ const confText = facts.CONF_B64 ?? "";
1540
+ const conf = parseIni(confText);
1541
+ const noConf = confText.trim().length === 0;
1542
+ const automountEnabled = ((noConf ? undefined : conf.automount?.enabled) ?? "").trim().toLowerCase();
1543
+ const automountRoot = ((noConf ? undefined : conf.automount?.root) ?? "").trim();
1544
+ /** Where the distro mounts Windows drives; the host->distro translation uses it. */
1545
+ const mountRoot = automountRoot.length > 0 ? automountRoot : "/mnt";
1546
+ /** The shell agent as the distro sees it; undefined when it cannot be reached from there. */
1547
+ const agentScriptDistro = automountEnabled === "false" ? undefined : distroPath(agentScript, mountRoot);
1548
+ /** Batch B: the systemd-class reads plus the conf-dependent readability probe. Absent keys mean the emitter was out of scope; a flaked batch earns `unknown` rows on every gated row that reads it. */
1549
+ let factsB = /** @type {Record<string, string>} */ ({});
1550
+ let batchB = /** @type {Awaited<ReturnType<typeof askDistro>> | undefined} */ (undefined);
1551
+ if (include.session || (include.agent && agentScriptDistro !== undefined)) {
1552
+ batchB = await probe(composeSystemdBatch({ ...include, agent: include.agent && agentScriptDistro !== undefined }, agentScriptDistro ?? ""));
1553
+ factsB = parseBatchFacts(batchB.stdout);
1554
+ }
1555
+ const batchBFlaked = batchB !== undefined && !batchB.ok && batchB.flaked;
1289
1556
 
1290
1557
  // ---- Windows share reachability (host section) ---------------------------
1291
1558
  // The GUI file service, the workspace picker and open-in-app read the
@@ -1308,20 +1575,14 @@ async function main(options) {
1308
1575
  // and one probe: both are consumed by the executor's shell resolution and
1309
1576
  // the agent cache, and a broken entry fails both at once. The family probe
1310
1577
  // stays (the install remedy needs it) but no longer has a row of its own.
1311
- let family = "unknown";
1312
- const identityAnswer = await probe('s=$(getent passwd "$(id -u)" | cut -d: -f7); [ -n "$s" ] || s=$SHELL; printf "SH=%s\\nHM=%s\\n" "$s" "$HOME"');
1313
- if (!identityAnswer.ok && identityAnswer.flaked) flakeCheck("distro.identity", "Login shell and home", identityAnswer);
1314
- else {
1315
- const shell = /^SH=(.*)$/m.exec(identityAnswer.stdout)?.[1]?.trim() ?? "";
1316
- const home = /^HM=(.*)$/m.exec(identityAnswer.stdout)?.[1]?.trim() ?? "";
1317
- const shellOk = shell.startsWith("/");
1318
- const homeOk = home.startsWith("/");
1319
- if (shellOk && homeOk) check("distro.identity", "ok", "Login shell and home", `${shell}, ${home}`);
1320
- else check("distro.identity", "fail", "Login shell and home", `shell=${shell.length === 0 ? "(none)" : shell}, home=${home.length === 0 ? "(none)" : home}`, `check the user's /etc/passwd entry in "${target}": getent passwd "$(id -u)"`);
1321
- }
1322
-
1323
- const familyAnswer = await probe(`for f in ${FAMILIES.join(" ")}; do command -v "$f" >/dev/null 2>&1 && { echo "$f"; exit 0; }; done; echo unknown`);
1324
- if (familyAnswer.ok) family = familyAnswer.stdout.trim();
1578
+ let family = (facts.FAMILY ?? "unknown").trim();
1579
+ if (family.length === 0) family = "unknown";
1580
+ const shell = (facts.SH ?? "").trim();
1581
+ const home = (facts.HM ?? "").trim();
1582
+ const shellOk = shell.startsWith("/");
1583
+ const homeOk = home.startsWith("/");
1584
+ if (shellOk && homeOk) check("distro.identity", "ok", "Login shell and home", `${shell}, ${home}`);
1585
+ else check("distro.identity", "fail", "Login shell and home", `shell=${shell.length === 0 ? "(none)" : shell}, home=${home.length === 0 ? "(none)" : home}`, `check the user's /etc/passwd entry in "${target}": getent passwd "$(id -u)"`);
1325
1586
 
1326
1587
  // ---- WSL mode ------------------------------------------------------------
1327
1588
  // WSL1 is a declared non-goal, but until now it failed unexplained: the
@@ -1341,23 +1602,19 @@ async function main(options) {
1341
1602
  // the ext4 VHDX stops growing (or the Windows drive holding it is full)
1342
1603
  // and every write failure surfaces as something unrelated. One df call;
1343
1604
  // the fail line at 97% is where the first cache write starts to break.
1344
- const dfAnswer = await probe("df -Pm /");
1345
- if (!dfAnswer.ok && dfAnswer.flaked) flakeCheck("distro.disk", "Disk", dfAnswer);
1346
- else {
1347
- const dfLine = dfAnswer.stdout.trim().split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0)[1] ?? "";
1348
- const dfFields = dfLine.split(/\s+/);
1349
- const dfCapacity = Number((dfFields[4] ?? "").replace(/%$/, ""));
1350
- const dfTotal = dfFields[1] ?? "?";
1351
- const dfAvail = dfFields[3] ?? "?";
1352
- if (!Number.isFinite(dfCapacity)) {
1353
- check("distro.disk", "info", "Disk", "unreadable — df did not answer in the expected shape");
1354
- } else if (dfCapacity >= 97) {
1355
- check("distro.disk", "fail", "Disk", `/${dfCapacity}% used (${dfAvail} MiB free of ${dfTotal} MiB) — writes into the distro will start failing`, `free space inside "${target}" or on the Windows drive holding the ext4 VHDX; sparse VHD (the .wslconfig sparseVhd key) lets "wsl.exe --shutdown" shrink it back`);
1356
- } else if (dfCapacity >= 90) {
1357
- check("distro.disk", "warn", "Disk", `/${dfCapacity}% used (${dfAvail} MiB free of ${dfTotal} MiB)`, "plan a cleanup before the 97% line, where writes start to fail");
1358
- } else {
1359
- check("distro.disk", "ok", "Disk", `/${dfCapacity}% used (${dfAvail} MiB free of ${dfTotal} MiB)`);
1360
- }
1605
+ const dfLine = (facts.DF ?? "").trim();
1606
+ const dfFields = dfLine.split(/\s+/);
1607
+ const dfCapacity = Number((dfFields[4] ?? "").replace(/%$/, ""));
1608
+ const dfTotal = dfFields[1] ?? "?";
1609
+ const dfAvail = dfFields[3] ?? "?";
1610
+ if (!Number.isFinite(dfCapacity)) {
1611
+ check("distro.disk", "info", "Disk", "unreadable — df did not answer in the expected shape");
1612
+ } else if (dfCapacity >= 97) {
1613
+ check("distro.disk", "fail", "Disk", `/${dfCapacity}% used (${dfAvail} MiB free of ${dfTotal} MiB) — writes into the distro will start failing`, `free space inside "${target}" or on the Windows drive holding the ext4 VHDX; sparse VHD (the .wslconfig sparseVhd key) lets "wsl.exe --shutdown" shrink it back`);
1614
+ } else if (dfCapacity >= 90) {
1615
+ check("distro.disk", "warn", "Disk", `/${dfCapacity}% used (${dfAvail} MiB free of ${dfTotal} MiB)`, "plan a cleanup before the 97% line, where writes start to fail");
1616
+ } else {
1617
+ check("distro.disk", "ok", "Disk", `/${dfCapacity}% used (${dfAvail} MiB free of ${dfTotal} MiB)`);
1361
1618
  }
1362
1619
 
1363
1620
  // ---- sandbox prerequisites ----------------------------------------------
@@ -1367,7 +1624,6 @@ async function main(options) {
1367
1624
  // loud warning, not a silent `info`. The fence smoke is skipped with it.
1368
1625
  let bwrapUsable = false;
1369
1626
  let bwrapPath = "";
1370
- const sandboxDisabled = effective.sandbox === "false" && effective.sessionSandbox === "false";
1371
1627
  const install = installRemedy(target, family);
1372
1628
  if (!want("sandbox")) {
1373
1629
  // sandbox section out of scope: bwrapPath stays "" and the fence smoke
@@ -1378,22 +1634,16 @@ async function main(options) {
1378
1634
  'set sandbox: true on wsl-shell, wsl-fs and fs-routing (and sessionSandbox: true) to enforce the fence, then rerun the doctor');
1379
1635
  check("sandbox.bwrap-usable", "skipped", "bubblewrap usability", "skipped: the sandbox is disabled by configuration");
1380
1636
  } else {
1381
- const bwrapAnswer = await probe("command -v bwrap");
1382
- if (!bwrapAnswer.ok && bwrapAnswer.flaked) flakeCheck("sandbox.bwrap", "bubblewrap", bwrapAnswer);
1383
- else {
1384
- bwrapPath = bwrapAnswer.stdout.trim();
1637
+ bwrapPath = (facts.BWRAP ?? "").trim();
1385
1638
  if (bwrapPath.length === 0) {
1386
1639
  check("sandbox.bwrap", "fail", "bubblewrap", "missing; every confined command fails closed without it", `${install}, or run "pnpm run bootstrap ${target} --install"`);
1387
1640
  } else {
1388
1641
  check("sandbox.bwrap", "ok", "bubblewrap", bwrapPath);
1389
- const userns = await probe("bwrap --ro-bind / / -- true");
1390
- if (!userns.ok && userns.flaked) flakeCheck("sandbox.bwrap-usable", "bubblewrap usability", userns);
1391
- else if (userns.ok) {
1642
+ if ((facts.BWTEST ?? "") === "ok") {
1392
1643
  check("sandbox.bwrap-usable", "ok", "bubblewrap usability", "a read-only profile runs");
1393
1644
  bwrapUsable = true;
1394
1645
  } else check("sandbox.bwrap-usable", "fail", "bubblewrap usability", "installed but the read-only profile failed", "the kernel likely disables unprivileged user namespaces; reinstalling will not help — see docs/LIMITATIONS.md");
1395
1646
  }
1396
- }
1397
1647
  }
1398
1648
 
1399
1649
  // ---- writable roots ------------------------------------------------------
@@ -1446,8 +1696,7 @@ async function main(options) {
1446
1696
  /** @type {string} */
1447
1697
  let home = "";
1448
1698
  if (configured.some((root) => root === "~" || root.startsWith("~/"))) {
1449
- const homeAnswer = await probe('printf %s "$HOME"');
1450
- if (homeAnswer.ok) home = homeAnswer.stdout.trim();
1699
+ home = (facts.HM ?? "").trim();
1451
1700
  if (home.length === 0 || !home.startsWith("/")) {
1452
1701
  failure = "the distro home did not answer, so ~ in writableRoots cannot be resolved";
1453
1702
  remedy = `run "wsl.exe -d ${target} --exec sh -c 'printf %s \\"$HOME\\"'" and retry`;
@@ -1455,7 +1704,7 @@ async function main(options) {
1455
1704
  }
1456
1705
  if (failure === undefined) {
1457
1706
  roots = configured.map((root) => normalize(root === "~" ? home : root.startsWith("~/") ? `${home}/${root.slice(2)}` : root));
1458
- const answer = await run(writableRootsCheckArgv(WSL, target, roots));
1707
+ const answer = await run(writableRootsCheckArgv(WSL, target, roots), probeTimeout);
1459
1708
  if (!answer.ok) {
1460
1709
  const match = /(\d+)\|(missing|unreadable|symlink)(?: -> (.*))?/u.exec(`${answer.stdout}\n${answer.stderr}`);
1461
1710
  const index = match === null ? -1 : Number(match[1] ?? -1);
@@ -1505,19 +1754,17 @@ async function main(options) {
1505
1754
  check("sandbox.isolation", "skipped", "Socket isolation", "skipped: the sandbox is disabled; no socket masks are applied");
1506
1755
  } else {
1507
1756
  const stance = effective.socketIsolation;
1508
- const answer = await probe(socketIsolationProbeScript());
1509
- if (!answer.ok && answer.flaked) {
1510
- flakeCheck("sandbox.isolation", "Socket isolation", answer);
1511
- } else if (!answer.ok) {
1757
+ const sockText = facts.SOCK_B64 ?? "";
1758
+ if (sockText.length === 0) {
1512
1759
  check("sandbox.isolation", "unknown", "Socket isolation", "the socket-facts probe did not answer", "rerun the doctor; if it persists, check that wsl.exe can run a command in the distro");
1513
1760
  } else {
1514
1761
  const valid = stance === "off" || stance === "session-bus" || stance === "strict";
1515
1762
  if (!valid) {
1516
1763
  check("sandbox.isolation", "warn", "Socket isolation", `unknown stance ${JSON.stringify(stance)} in the effective configuration`, "use off, session-bus or strict on the confined rows");
1517
1764
  } else {
1518
- const facts = parseSocketIsolationFacts(answer.stdout);
1519
- const masks = socketMaskPaths(stance, facts);
1520
- const detected = [...facts.userSockets, ...facts.strictSockets];
1765
+ const sockFacts = parseSocketIsolationFacts(sockText);
1766
+ const masks = socketMaskPaths(stance, sockFacts);
1767
+ const detected = [...sockFacts.userSockets, ...sockFacts.strictSockets];
1521
1768
  const surfaceText = detected.length === 0 ? "no matching socket detected" : detected.join(", ");
1522
1769
  if (stance === "off") {
1523
1770
  check("sandbox.isolation", "info", "Socket isolation", `off — confined commands can reach the user manager, system bus, container sockets and the interop transport; detected: ${surfaceText}`, "set socketIsolation: session-bus or strict on the confined rows (and fs-routing) to mask the sockets");
@@ -1548,37 +1795,30 @@ async function main(options) {
1548
1795
  /** Whether the effective config makes the native backend mandatory. */
1549
1796
  const nativeRequired = effective.agentBackend === "native";
1550
1797
  if (want("session")) {
1551
- const systemd = await probe('if [ -d /run/systemd/system ]; then printf "systemd %s" "$(cat /proc/1/comm)"; else printf "none %s" "$(cat /proc/1/comm)"; fi');
1552
- if (!systemd.ok && systemd.flaked) flakeCheck("session.systemd", "systemd as PID 1", systemd);
1553
- else if (!systemd.stdout.startsWith("systemd")) {
1554
- check("session.systemd", sessionStatus(), "systemd as PID 1", withScopeNote(systemd.stdout.trim().length > 0 ? systemd.stdout.trim() : "not systemd"), `set [boot] systemd=true in /etc/wsl.conf inside "${target}", run "wsl.exe --shutdown", then reopen the session. Without it, sessionSandbox cannot run`);
1798
+ const pid1 = (facts.PID1 ?? "").trim();
1799
+ if (!pid1.startsWith("systemd")) {
1800
+ check("session.systemd", sessionStatus(), "systemd as PID 1", withScopeNote(pid1.length > 0 ? pid1 : "not systemd"), `set [boot] systemd=true in /etc/wsl.conf inside "${target}", run "wsl.exe --shutdown", then reopen the session. Without it, sessionSandbox cannot run`);
1555
1801
  } else check("session.systemd", "ok", "systemd as PID 1", "running");
1556
1802
 
1557
- const systemdRun = await probe("command -v systemd-run");
1558
- if (!systemdRun.ok && systemdRun.flaked) flakeCheck("session.systemd-run", "systemd-run", systemdRun);
1559
- else {
1560
- const systemdRunPath = systemdRun.stdout.trim();
1561
- if (systemdRunPath.length > 0) check("session.systemd-run", "ok", "systemd-run", systemdRunPath);
1562
- else check("session.systemd-run", sessionStatus(), "systemd-run", withScopeNote("missing; the distro's systemd package is incomplete"), `reinstall systemd inside "${target}" (apt-get install --reinstall systemd, or the family's equivalent)`);
1563
- }
1803
+ const systemdRunPath = (facts.SYSTEMD_RUN ?? "").trim();
1804
+ if (systemdRunPath.length > 0) check("session.systemd-run", "ok", "systemd-run", systemdRunPath);
1805
+ else check("session.systemd-run", sessionStatus(), "systemd-run", withScopeNote("missing; the distro's systemd package is incomplete"), `reinstall systemd inside "${target}" (apt-get install --reinstall systemd, or the family's equivalent)`);
1564
1806
 
1565
- const userManager = await probe("systemctl --user is-system-running 2>/dev/null || true");
1566
- if (!userManager.ok && userManager.flaked) flakeCheck("session.user-manager", "systemd user manager", userManager);
1807
+ if (batchBFlaked) flakeCheck("session.user-manager", "systemd user manager", batchB ?? { stderr: "", stdout: "" });
1567
1808
  else {
1568
- const userState = userManager.stdout.trim();
1809
+ const userState = (factsB.USER ?? "").trim();
1569
1810
  if (userState === "running" || userState === "degraded") check("session.user-manager", "ok", "systemd user manager", userState);
1570
1811
  else check("session.user-manager", sessionStatus(), "systemd user manager", withScopeNote(userState.length > 0 ? userState : "unreachable"), `log in to "${target}" once, or enable lingering (next remedy), then retry`);
1571
1812
  }
1572
1813
 
1573
- const linger = await probe('loginctl show-user "$(id -un)" -p Linger 2>/dev/null');
1574
- if (!linger.ok && linger.flaked) flakeCheck("session.linger", "Linger", linger);
1814
+ if (batchBFlaked) flakeCheck("session.linger", "Linger", batchB ?? { stderr: "", stdout: "" });
1575
1815
  else {
1576
- const lingerState = linger.stdout.trim();
1816
+ const lingerState = (factsB.LINGER ?? "").trim();
1577
1817
  if (lingerState === "Linger=yes") check("session.linger", "ok", "Linger", lingerState);
1578
1818
  else check("session.linger", sessionStatus(), "Linger", withScopeNote(lingerState.length > 0 ? lingerState : "unset"), `wsl.exe -d ${target} -- loginctl enable-linger "$(id -un)" (this needs the user's own session; run it inside the distro)`);
1579
1819
  }
1580
- runtimeSystemd = systemd.stdout.startsWith("systemd");
1581
- systemdPid = systemd.stdout.trim();
1820
+ runtimeSystemd = pid1.startsWith("systemd");
1821
+ systemdPid = pid1;
1582
1822
  }
1583
1823
 
1584
1824
  // ---- /etc/wsl.conf cross-checks ------------------------------------------
@@ -1588,27 +1828,11 @@ async function main(options) {
1588
1828
  // value that is not in effect is a different problem from one that is.
1589
1829
  // A flaked read earns three `unknown` rows, never a verdict: the conf is
1590
1830
  // on disk, and the read — not the file — is what failed.
1591
- const confAnswer = await probe("cat /etc/wsl.conf 2>/dev/null || true");
1592
- const confFlaked = !confAnswer.ok && confAnswer.flaked;
1593
- const conf = parseIni(confAnswer.stdout);
1594
- const noConf = confAnswer.stdout.trim().length === 0;
1595
- const automountEnabled = ((noConf ? undefined : conf.automount?.enabled) ?? "").trim().toLowerCase();
1596
- const automountRoot = ((noConf ? undefined : conf.automount?.root) ?? "").trim();
1597
- /** Where the distro mounts Windows drives; the host->distro translation uses it. */
1598
- const mountRoot = automountRoot.length > 0 ? automountRoot : "/mnt";
1599
- /** The shell agent as the distro sees it; undefined when it cannot be reached from there. */
1600
- const agentScriptDistro = automountEnabled === "false" ? undefined : distroPath(agentScript, mountRoot);
1601
1831
  const confWanted = want("session") || want("conf");
1602
1832
  if (!confWanted) {
1603
1833
  // Scoped run: neither the boot cross-check nor the interop/automount
1604
- // rows are in scope — the conf read above stays (one cheap call that
1605
- // the section rows share), but no rows report.
1606
- } else if (confFlaked) {
1607
- if (want("session")) flakeCheck("distro.wsl-conf-boot", "/etc/wsl.conf [boot]", confAnswer);
1608
- if (want("conf")) {
1609
- flakeCheck("distro.wsl-conf-interop", "/etc/wsl.conf [interop]", confAnswer);
1610
- flakeCheck("distro.wsl-conf-automount", "/etc/wsl.conf [automount]", confAnswer);
1611
- }
1834
+ // rows are in scope — the conf read rode batch A (the section rows
1835
+ // share it), but no rows report.
1612
1836
  } else {
1613
1837
  const bootSystemd = ((noConf ? undefined : conf.boot?.systemd) ?? "").trim().toLowerCase();
1614
1838
  if (!want("session")) {
@@ -1632,10 +1856,8 @@ async function main(options) {
1632
1856
  // /proc that was not mounted), and every Windows-tool path — git.exe,
1633
1857
  // explorer.exe, the cmd.exe probes — fails with a confusing command-not-
1634
1858
  // found instead of naming interop. Probe it in BOTH directions.
1635
- const binfmtProbe = await probe("[ -e /proc/sys/fs/binfmt_misc/WSLInterop ] && printf yes || printf no");
1636
- if (!binfmtProbe.ok && binfmtProbe.flaked) flakeCheck("distro.wsl-conf-interop", "/etc/wsl.conf [interop]", binfmtProbe);
1637
- else {
1638
- const binfmt = binfmtProbe.ok ? binfmtProbe.stdout.trim() : "unreadable";
1859
+ {
1860
+ const binfmt = (facts.BINFMT ?? "").trim() || "unreadable";
1639
1861
  if (interopEnabled === "false") {
1640
1862
  check("distro.wsl-conf-interop", "warn", "/etc/wsl.conf [interop]", `interop is disabled in wsl.conf${binfmt === "yes" ? " but the WSLInterop handler is still loaded (stale boot)" : ""} — Windows git, open-in-app and the cmd.exe probes are unreachable from this distro`, `remove the [interop] enabled=false line in /etc/wsl.conf, then wsl.exe --terminate ${target}`);
1641
1863
  } else if (binfmt === "no") {
@@ -1666,10 +1888,8 @@ async function main(options) {
1666
1888
  // A sleeping host desyncs the WSL clock (the VM's clock stops with it);
1667
1889
  // the classic symptom is TLS and git failing with certificate or
1668
1890
  // timestamp errors minutes after resume. One comparison, one remedy.
1669
- const clockAnswer = await probe("date +%s");
1670
- if (!clockAnswer.ok && clockAnswer.flaked) flakeCheck("distro.clock", "Clock", clockAnswer);
1671
- else {
1672
- const distroEpoch = Number(clockAnswer.stdout.trim());
1891
+ {
1892
+ const distroEpoch = Number((facts.DATE ?? "").trim());
1673
1893
  if (!Number.isFinite(distroEpoch) || distroEpoch <= 0) {
1674
1894
  check("distro.clock", "info", "Clock", "unreadable — date did not answer an epoch");
1675
1895
  } else {
@@ -1688,14 +1908,12 @@ async function main(options) {
1688
1908
  // the VPN-tunnel class where the file looks fine but queries die. The
1689
1909
  // probe is warn-grade and honest about offline — a machine without a
1690
1910
  // network answers the same as a broken resolver.
1691
- const resolvAnswer = want("net") ? await probe("wc -c < /etc/resolv.conf 2>/dev/null || printf 0") : undefined;
1692
- if (resolvAnswer !== undefined && !resolvAnswer.ok && resolvAnswer.flaked) flakeCheck("distro.dns", "DNS", resolvAnswer);
1693
- else if (resolvAnswer !== undefined) {
1694
- const resolvBytes = Number(resolvAnswer.stdout.trim());
1911
+ if (want("net")) {
1912
+ const resolvBytes = Number((facts.RESOLV ?? "").trim());
1695
1913
  if (!Number.isFinite(resolvBytes) || resolvBytes === 0) {
1696
1914
  check("distro.dns", "warn", "DNS", "/etc/resolv.conf is missing or empty — name resolution fails (npm, git fetch, bootstrap installs)", `wsl.conf [network] generateResolvConf controls the file; "wsl.exe --shutdown" regenerates it unless disabled`);
1697
1915
  } else {
1698
- const resolved = (await probe("getent hosts deb.debian.org 2>/dev/null | head -1")).stdout.trim();
1916
+ const resolved = (facts.DNS ?? "").trim();
1699
1917
  if (resolved.length > 0) {
1700
1918
  check("distro.dns", "ok", "DNS", `resolv.conf present (${resolvBytes} bytes); ${(resolved.split(/\s+/)[0] ?? "?")} resolved the probe name`);
1701
1919
  } else {
@@ -1715,19 +1933,17 @@ async function main(options) {
1715
1933
  /** The optional tools, in the order users notice them losing. */
1716
1934
  /** @type {Array<[string, string]>} */
1717
1935
  const optionalTools = [["rg", "the fs-search tool fails (exit 127); the model can still run grep in a shell, slower"], ["git", "change review falls back to file-tool edits"], ["inotifywait", "the watcher falls back to polling"]];
1718
- // One `wsl.exe` for the set: every name is answered in the same shell, so
1719
- // the quick profile pays one spawn, not three, for the full tool list.
1720
- const toolAnswer = await probe(`for t in ${optionalTools.map(([tool]) => tool).join(" ")}; do if p=$(command -v "$t" 2>/dev/null); then printf 'found %s %s\\n' "$t" "$p"; else printf 'missing %s\\n' "$t"; fi; done`);
1936
+ // The combined probe rides batch A: every name is answered in the same
1937
+ // shell, so the quick profile pays nothing extra for the full tool list.
1721
1938
  /** @type {Map<string, string>} */
1722
1939
  const toolPaths = new Map();
1723
- for (const line of toolAnswer.stdout.split(/\r?\n/)) {
1940
+ for (const line of (facts.TOOLS_B64 ?? "").split(/\r?\n/)) {
1724
1941
  const match = /^(?:found|missing)\s+([a-z]+)(?:\s+(.*))?$/.exec(line.trim());
1725
1942
  if (match !== null && match[1] !== undefined) toolPaths.set(match[1], match[2] ?? "");
1726
1943
  }
1727
1944
  for (const [tool, cost] of optionalTools) {
1728
1945
  const found = toolPaths.get(tool);
1729
- if (!toolAnswer.ok && toolAnswer.flaked) flakeCheck(`tools.${tool}`, tool, toolAnswer);
1730
- else if (found === undefined) check(`tools.${tool}`, "info", tool, "the combined probe answered nothing for this tool, so this run cannot say whether it is installed");
1946
+ if (found === undefined) check(`tools.${tool}`, "info", tool, "the combined probe answered nothing for this tool, so this run cannot say whether it is installed");
1731
1947
  else if (found.length > 0) check(`tools.${tool}`, "ok", tool, found);
1732
1948
  else check(`tools.${tool}`, "warn", tool, `missing; ${cost}`, install);
1733
1949
  }
@@ -1742,10 +1958,8 @@ async function main(options) {
1742
1958
  // check is config-aware because the consequence differs: a missing or
1743
1959
  // unrunnable binary degrades to the shell agent under `auto`, but fails
1744
1960
  // the first command (and every file operation) under `native`.
1745
- const archAnswer = await probe("uname -m");
1746
- if (!archAnswer.ok && archAnswer.flaked) flakeCheck("agent.native", "Native agent", archAnswer);
1747
- else {
1748
- const arch = archAnswer.stdout.trim();
1961
+ {
1962
+ const arch = (facts.ARCH ?? "").trim();
1749
1963
  const packaged = ["x86_64", "aarch64"].includes(arch) ? join(ROOT, "agent", "native", `linux-${arch}`, "dsh-wsl-agent") : "";
1750
1964
  if (arch === "") {
1751
1965
  check("agent.native", nativeRequired ? "fail" : "info", "Native agent", "the distro architecture is unreadable, so the packaged native agent cannot be named", nativeRequired ? "probe the distro by hand (uname -m), or use agentBackend: auto" : undefined);
@@ -1759,10 +1973,8 @@ async function main(options) {
1759
1973
  }
1760
1974
  }
1761
1975
 
1762
- const cacheAnswer = await probe(CACHE_REPORT);
1763
- if (!cacheAnswer.ok && cacheAnswer.flaked) flakeCheck("agent.cache", "Agent cache", cacheAnswer);
1764
- else {
1765
- const cache = cacheAnswer.stdout.trim();
1976
+ {
1977
+ const cache = (facts.CACHE_B64 ?? "").trim();
1766
1978
  if (cache === "none" || cache.length === 0) check("agent.cache", "info", "Agent cache", "empty (a first command populates it)");
1767
1979
  else {
1768
1980
  const entries = cache.split(/\r?\n/).filter((line) => line.trim().length > 0);
@@ -1781,10 +1993,8 @@ async function main(options) {
1781
1993
  // executed from there; a read-only home, or a home on a `noexec` mount
1782
1994
  // (DrvFs when HOME points at /mnt/c), breaks that before any command runs.
1783
1995
  // One temp dir answers both facts and is removed again.
1784
- const homeProbe = await probe('d=$(mktemp -d "$HOME/.dsh-doctor-XXXXXXXX" 2>/dev/null) || { echo nowrite; exit 0; }; printf "#!/bin/sh\\n" > "$d/x" && chmod 755 "$d/x" && "$d/x" >/dev/null 2>&1 && printf ok || printf noexec; rm -rf "$d"');
1785
- if (!homeProbe.ok && homeProbe.flaked) flakeCheck("agent.home-writable", "Home writability", homeProbe);
1786
- else {
1787
- const homeState = homeProbe.stdout.trim();
1996
+ {
1997
+ const homeState = (facts.HOMEEXEC ?? "").trim();
1788
1998
  const homeTone = (/** @type {"fail" | "warn" | "info"} */ tone) => nativeRequired ? "fail" : effective.agentBackend === "shell" ? "info" : tone;
1789
1999
  if (homeState === "ok") check("agent.home-writable", "ok", "Home writability", "a temp dir under $HOME was writable and executable (the native cache can live there)");
1790
2000
  else if (homeState === "noexec") check("agent.home-writable", homeTone("warn"), "Home writability", `$HOME is writable but files there cannot execute (a noexec mount) — the native agent cache cannot run${effective.agentBackend === "shell" ? "; agentBackend: shell does not need it" : "; auto falls back to the shell agent"}`, "move HOME onto an exec-capable Linux filesystem (DrvFs is often noexec), or use agentBackend: shell");
@@ -1793,7 +2003,6 @@ async function main(options) {
1793
2003
  }
1794
2004
 
1795
2005
  // ---- session scopes (section: session) ------------------------------------
1796
- const scopesAnswer = want("session") ? await probe(STALE_SCOPE_REPORT) : undefined;
1797
2006
  let stale = 0;
1798
2007
  /** @type {string[]} */
1799
2008
  let livePids = [];
@@ -1803,16 +2012,18 @@ async function main(options) {
1803
2012
  let handshakeState = "info";
1804
2013
  /** The shell-agent smoke, kept so the native legs can say whether the fallback works. */
1805
2014
  let shellSmoke = /** @type {{ execOk: boolean, fsOk: boolean } | undefined} */ (undefined);
1806
- if (scopesAnswer !== undefined && !scopesAnswer.ok && scopesAnswer.flaked) flakeCheck("runtime.scopes", "Session scopes", scopesAnswer);
1807
- else if (scopesAnswer !== undefined) {
1808
- const scopes = scopesAnswer.stdout.trim();
1809
- scopeLines = scopes === "none" || scopes.length === 0 ? [] : scopes.split(/\r?\n/);
1810
- stale = scopeLines.filter((line) => /\sstale(\s|$)/.test(line)).length;
1811
- livePids = scopeLines.flatMap((line) => {
1812
- const m = /\spids:([0-9 ]+)$/.exec(line);
1813
- if (m === null) return [];
1814
- return (m[1] ?? "").trim().split(/\s+/).filter((p) => p.length > 0);
1815
- });
2015
+ if (want("session")) {
2016
+ if (batchBFlaked) flakeCheck("runtime.scopes", "Session scopes", batchB ?? { stderr: "", stdout: "" });
2017
+ else {
2018
+ const scopes = (factsB.SCOPES_B64 ?? "").trim();
2019
+ scopeLines = scopes === "none" || scopes.length === 0 ? [] : scopes.split(/\r?\n/);
2020
+ stale = scopeLines.filter((line) => /\sstale(\s|$)/.test(line)).length;
2021
+ livePids = scopeLines.flatMap((line) => {
2022
+ const m = /\spids:([0-9 ]+)$/.exec(line);
2023
+ if (m === null) return [];
2024
+ return (m[1] ?? "").trim().split(/\s+/).filter((p) => p.length > 0);
2025
+ });
2026
+ }
1816
2027
  }
1817
2028
 
1818
2029
  // ---- resident handshake (section: agent) ----------------------------------
@@ -1828,19 +2039,19 @@ async function main(options) {
1828
2039
  } else {
1829
2040
  // The script is a Linux path in the checkout's OWN distro; another
1830
2041
  // distro cannot read it, and "exited before its HELLO" would be a
1831
- // lie about a broken install. Probe readability first, honestly.
1832
- const readable = (await inDistro(target, `[ -f "${agentScriptDistro}" ] && printf yes || printf no`)).stdout.trim() === "yes";
2042
+ // lie about a broken install. The readability probe rode batch B.
2043
+ const readable = (factsB.AGENT_READ ?? "").trim() === "yes";
1833
2044
  if (!readable) {
1834
2045
  check("agent.handshake", "info", "Agent handshake", `skipped: agent/wsl-agent.sh is not readable at ${agentScriptDistro} inside "${target}" — this doctor runs from the ${(process.env.WSL_DISTRO_NAME ?? "host")} filesystem; run it from Windows or inside "${target}"`);
1835
2046
  } else {
1836
- const handshake = await probeResident(target, agentScriptDistro, wslExe, agentScript);
2047
+ const handshake = await probeHandshake(target, agentScriptDistro, wslExe, agentScript);
1837
2048
  handshakeState = handshake.ok && handshake.digestMatches ? "ok" : "fail";
1838
2049
  if (handshake.ok) {
1839
2050
  const live = livePids.length > 0
1840
2051
  ? `; a live resident (pid${livePids.length > 1 ? "s" : ""} ${livePids.join(", ")}) is already running in this distro — this check starts a fresh one, which cannot read its last error; the app-side doctorReport() merge surfaces it`
1841
2052
  : "";
1842
2053
  check("agent.handshake", handshake.digestMatches ? "ok" : "fail", "Agent handshake",
1843
- `probed: a fresh resident, pid ${handshake.pid}, protocol ${PROTOCOL_VERSION}, digest ${handshake.digestMatches ? "matches" : "MISMATCH — the distro reads a different script than this package"}${live}`,
2054
+ `probed: a fresh resident, pid ${handshake.pid}, protocol ${PROTOCOL_VERSION}, digest ${handshake.digestMatches ? "matches" : "MISMATCH — the distro reads a different script than this package"}${live}${handshake.detail === undefined ? "" : `; ${handshake.detail}`}`,
1844
2055
  handshake.digestMatches ? undefined : "resync the runtime copy (pnpm run sync:windows), then restart the app");
1845
2056
  } else {
1846
2057
  check("agent.handshake", "fail", "Agent handshake", handshake.detail, "restart the DSH app; if it persists, delete ~/.cache/dsh-wsl/agent inside the distro and rerun the doctor");
@@ -2005,9 +2216,10 @@ async function main(options) {
2005
2216
  // ({ ok, stdout, code }); `-q` prints plain names, and the running list's
2006
2217
  // header is dropped by the intersection with them. The default distro
2007
2218
  // carries a localized marker ("ubuntu (默认值)" / "ubuntu (default)") —
2008
- // strip a trailing parenthesized note before the intersection.
2009
- const distroNames = ((await run([WSL, "--list", "-q"])).stdout ?? "").split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0);
2010
- const running = ((await run([WSL, "--list", "--running"])).stdout ?? "").split(/\r?\n/).map((line) => line.trim().replace(/\s+\([^)]*\)$/, "")).filter((line) => distroNames.includes(line));
2219
+ // strip a trailing parenthesized note before the intersection. Both spawns
2220
+ // answer the human surveys alone — a `--json` run never reads them.
2221
+ const distroNames = options.json ? [] : ((await run([WSL, "--list", "-q"])).stdout ?? "").split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0);
2222
+ const running = options.json ? [] : ((await run([WSL, "--list", "--running"])).stdout ?? "").split(/\r?\n/).map((line) => line.trim().replace(/\s+\([^)]*\)$/, "")).filter((line) => distroNames.includes(line));
2011
2223
  if (!options.json) {
2012
2224
  console.log("");
2013
2225
  console.log(doctorT("sessions.title"));
@@ -2184,14 +2396,27 @@ async function main(options) {
2184
2396
  };
2185
2397
  if (state.stale > 0) {
2186
2398
  const swept = await inDistro(target, sessionScopeSweepScript());
2187
- const afterReport = (await inDistro(target, STALE_SCOPE_REPORT)).stdout.trim();
2188
- const afterLines = afterReport === "none" || afterReport.length === 0 ? [] : afterReport.split(/\r?\n/);
2189
- const afterStale = afterLines.filter((line) => /\sstale(\s|$)/.test(line)).length;
2190
- const fixed = swept.ok && afterStale === 0;
2191
- fixCheck("fix.scopes", fixed ? "ok" : "warn", "Swept stale scopes", `${state.stale} stale before → ${afterStale} after`, fixed ? undefined : `systemctl --user list-units 'dsh-wsl-*.scope' inside "${target}"`);
2192
- reviseCheck("runtime.scopes", target, afterLines.length === 0
2193
- ? { status: "info", detail: "none (the fix above swept them)", remedy: undefined }
2194
- : { status: afterStale === 0 ? "ok" : "warn", detail: `${afterLines.length} live, ${afterStale} stale after the fix`, remedy: afterStale === 0 ? undefined : "--fix stops them; they are safe to stop when no agent process is inside" });
2399
+ // The recheck takes the flake-aware probe like every first-pass read.
2400
+ // A read that did not answer used to count as "0 stale" and record the
2401
+ // sweep as done; it proves nothing either way, so it earns `unknown`.
2402
+ const after = await askDistro(target, STALE_SCOPE_REPORT);
2403
+ if (!after.ok || after.flaked) {
2404
+ fixCheck("fix.scopes", swept.ok ? "unknown" : "warn", "Swept stale scopes",
2405
+ `the sweep ${swept.ok ? "ran" : `did not complete${outputTail(swept)}`}, but its recheck did not answer (${unreadReason(after)}); ${state.stale} stale before → unknown after`,
2406
+ `rerun the doctor; if stale scopes remain, systemctl --user list-units 'dsh-wsl-*.scope' inside "${target}"`);
2407
+ reviseCheck("runtime.scopes", target, { status: "unknown", detail: `${state.stale} stale before the fix; the recheck after it did not answer`, remedy: "rerun the doctor" });
2408
+ } else {
2409
+ const afterReport = after.stdout.trim();
2410
+ const afterLines = afterReport === "none" || afterReport.length === 0 ? [] : afterReport.split(/\r?\n/);
2411
+ const afterStale = afterLines.filter((line) => /\sstale(\s|$)/.test(line)).length;
2412
+ const fixed = swept.ok && afterStale === 0;
2413
+ fixCheck("fix.scopes", fixed ? "ok" : "warn", "Swept stale scopes",
2414
+ `${state.stale} stale before → ${afterStale} after${fixed ? "" : outputTail(swept)}`,
2415
+ fixed ? undefined : `systemctl --user list-units 'dsh-wsl-*.scope' inside "${target}"`);
2416
+ reviseCheck("runtime.scopes", target, afterLines.length === 0
2417
+ ? { status: "info", detail: "none (the fix above swept them)", remedy: undefined }
2418
+ : { status: afterStale === 0 ? "ok" : "warn", detail: `${afterLines.length} live, ${afterStale} stale after the fix`, remedy: afterStale === 0 ? undefined : "--fix stops them; they are safe to stop when no agent process is inside" });
2419
+ }
2195
2420
  }
2196
2421
  if (state.cacheBad > 0) {
2197
2422
  // The cache is plugin-owned and content-addressed: every entry is
@@ -2200,24 +2425,37 @@ async function main(options) {
2200
2425
  // a failed handshake is re-probed because a corrupt cache is one of its
2201
2426
  // causes.
2202
2427
  const purged = await inDistro(target, 'rm -rf "$HOME/.cache/dsh-wsl/agent"');
2203
- const afterRaw = (await inDistro(target, CACHE_REPORT)).stdout.trim();
2204
- const afterLines = afterRaw === "none" || afterRaw.length === 0 ? [] : afterRaw.split(/\r?\n/).filter((line) => line.trim().length > 0);
2205
- const afterBad = afterLines.filter((line) => line.startsWith("noexec ") || line.startsWith("broken ")).length;
2206
- const fixed = purged.ok && afterBad === 0;
2207
- const cacheTone = fixed ? "ok" : effective.agentBackend === "native" ? "fail" : "warn";
2208
- fixCheck("fix.cache", fixed ? "ok" : "warn", "Purged the agent cache",
2209
- `${state.cacheEntries} cached, ${state.cacheBad} invalid before → ${afterLines.length} cached, ${afterBad} invalid after`,
2210
- fixed ? undefined : `rm -rf ~/.cache/dsh-wsl/agent inside "${target}"; the next command repopulates it`);
2211
- reviseCheck("agent.cache", target, afterLines.length === 0
2212
- ? { status: cacheTone === "ok" ? "info" : cacheTone, detail: "empty after the fix (the next command repopulates it)", remedy: undefined }
2213
- : { status: cacheTone, detail: `${afterLines.length} cached binary(ies)${afterBad > 0 ? `, ${afterBad} not executable or not runnable after the fix` : ""}`, remedy: fixed ? undefined : `rm -rf ~/.cache/dsh-wsl/agent inside "${target}"; the next command repopulates it` });
2428
+ // Same guard as the scope recheck: an inventory that did not answer is
2429
+ // not "0 invalid". The before-state row keeps its verdict here — an
2430
+ // invalid cache blocks the native backend, and stays a blocker until a
2431
+ // read says otherwise — and only the fix row says the purge is
2432
+ // unverified.
2433
+ const after = await askDistro(target, CACHE_REPORT);
2434
+ if (!after.ok || after.flaked) {
2435
+ fixCheck("fix.cache", purged.ok ? "unknown" : "warn", "Purged the agent cache",
2436
+ `the purge ${purged.ok ? "ran" : `did not complete${outputTail(purged)}`}, but its recheck did not answer (${unreadReason(after)}); ${state.cacheEntries} cached, ${state.cacheBad} invalid before → unknown after`,
2437
+ `rerun the doctor; rm -rf ~/.cache/dsh-wsl/agent inside "${target}" is safe to repeat, and the next command repopulates it`);
2438
+ reviseCheck("agent.cache", target, { remedy: "the purge above ran, but its recheck did not answer — rerun the doctor; until a read says otherwise this row keeps its before-the-fix verdict" });
2439
+ } else {
2440
+ const afterRaw = after.stdout.trim();
2441
+ const afterLines = afterRaw === "none" || afterRaw.length === 0 ? [] : afterRaw.split(/\r?\n/).filter((line) => line.trim().length > 0);
2442
+ const afterBad = afterLines.filter((line) => line.startsWith("noexec ") || line.startsWith("broken ")).length;
2443
+ const fixed = purged.ok && afterBad === 0;
2444
+ const cacheTone = fixed ? "ok" : effective.agentBackend === "native" ? "fail" : "warn";
2445
+ fixCheck("fix.cache", fixed ? "ok" : "warn", "Purged the agent cache",
2446
+ `${state.cacheEntries} cached, ${state.cacheBad} invalid before → ${afterLines.length} cached, ${afterBad} invalid after${fixed ? "" : outputTail(purged)}`,
2447
+ fixed ? undefined : `rm -rf ~/.cache/dsh-wsl/agent inside "${target}"; the next command repopulates it`);
2448
+ reviseCheck("agent.cache", target, afterLines.length === 0
2449
+ ? { status: cacheTone === "ok" ? "info" : cacheTone, detail: "empty after the fix (the next command repopulates it)", remedy: undefined }
2450
+ : { status: cacheTone, detail: `${afterLines.length} cached binary(ies)${afterBad > 0 ? `, ${afterBad} not executable or not runnable after the fix` : ""}`, remedy: fixed ? undefined : `rm -rf ~/.cache/dsh-wsl/agent inside "${target}"; the next command repopulates it` });
2451
+ }
2214
2452
  const handshakeEntry = checks.find((entry) => entry.id === "agent.handshake" && entry.distro === target);
2215
2453
  const scriptPath = state.agentScriptDistro;
2216
2454
  const scriptProbe = scriptPath !== undefined && existsSync(join(ROOT, "agent", "wsl-agent.sh"))
2217
2455
  ? (await inDistro(target, `[ -f "${scriptPath}" ] && printf yes || printf no`)).stdout.trim()
2218
2456
  : "no";
2219
2457
  if (handshakeEntry !== undefined && handshakeEntry.status === "fail" && scriptProbe === "yes" && scriptPath !== undefined) {
2220
- const again = await probeResident(target, scriptPath, wslExe, join(ROOT, "agent", "wsl-agent.sh"));
2458
+ const again = await probeHandshake(target, scriptPath, wslExe, join(ROOT, "agent", "wsl-agent.sh"));
2221
2459
  reviseCheck("agent.handshake", target, again.ok && again.digestMatches
2222
2460
  ? { status: "ok", detail: `re-probed after the cache purge: pid ${again.pid}, protocol ${PROTOCOL_VERSION}, digest matches`, remedy: undefined }
2223
2461
  : { detail: `re-probed after the cache purge: ${again.ok ? "digest MISMATCH — the distro reads a different script than this package" : again.detail}` });
@@ -2230,14 +2468,18 @@ async function main(options) {
2230
2468
  } else if (!(await confirm(doctorT("confirm.install", { packages: PACKAGES, distro: target }), options.yes))) {
2231
2469
  fixCheck("fix.install", "info", "Package installation", "declined", install);
2232
2470
  } else {
2233
- const command = INSTALL[state.family] ?? INSTALL["apt-get"] ?? `apt-get install -y ${PACKAGES}`;
2234
- const installed = await run([WSL, "-d", target, "-u", "root", "--", "sh", "-c", command]);
2235
- const bwrapAfter = (await inDistro(target, "command -v bwrap")).stdout.trim();
2236
- const usableAfter = bwrapAfter.length > 0 ? (await inDistro(target, "bwrap --ro-bind / / -- true")).ok : false;
2471
+ const command = INSTALL[state.family] ?? INSTALL["apt-get"] ?? `apt-get update -qq && apt-get install -y --no-install-recommends ${PACKAGES}`;
2472
+ // Its own deadline: an install downloads and configures, and one cut
2473
+ // short leaves the package manager's state half-applied.
2474
+ const installed = await run([WSL, "-d", target, "-u", "root", "--", "sh", "-c", command], INSTALL_TIMEOUT_MS);
2475
+ const bwrapAfter = (await askDistro(target, "command -v bwrap")).stdout.trim();
2476
+ const usableAfter = bwrapAfter.length > 0 ? (await askDistro(target, "bwrap --ro-bind / / -- true")).ok : false;
2237
2477
  const done = installed.ok && bwrapAfter.length > 0;
2238
2478
  fixCheck("fix.install", done ? "ok" : "warn", "Package installation", installed.ok
2239
2479
  ? `completed; bubblewrap ${bwrapAfter.length > 0 ? `now at ${bwrapAfter}${usableAfter ? ", a read-only profile runs" : ", but the read-only profile still fails"}` : "STILL MISSING after the install"}`
2240
- : "failed; see the output above", done ? undefined : install);
2480
+ : installed.timedOut
2481
+ ? `timed out after ${Math.round(INSTALL_TIMEOUT_MS / 60_000)} minutes${outputTail(installed)} — the package manager may have been interrupted; run the same command inside the distro again to let it finish`
2482
+ : `failed${outputTail(installed)}`, done ? undefined : install);
2241
2483
  reviseCheck("sandbox.bwrap", target, bwrapAfter.length > 0
2242
2484
  ? { status: "ok", detail: bwrapAfter, remedy: undefined }
2243
2485
  : { status: "fail", detail: "still missing after the install", remedy: install });
@@ -2261,7 +2503,7 @@ async function main(options) {
2261
2503
  reviseCheck("git.win-safe", undefined, whitelisted
2262
2504
  ? { status: "ok", detail: `the \\wsl.localhost share is whitelisted (${entries.length} entr${entries.length === 1 ? "y" : "ies"}) — it was untrusted before this run's fix`, remedy: undefined }
2263
2505
  : {});
2264
- checks.push({ id: "fix.git-trust", status: added.ok && whitelisted ? "ok" : "warn", title: "Git trust whitelist", detail: added.ok && whitelisted ? 'added "//wsl.localhost/*" to the Windows git safe.directory whitelist' : "the add did not take effect; see the output above", remedy: added.ok && whitelisted ? undefined : 'on Windows: git config --global --add safe.directory "//wsl.localhost/*", then restart the app' });
2506
+ checks.push({ id: "fix.git-trust", status: added.ok && whitelisted ? "ok" : "warn", title: "Git trust whitelist", detail: added.ok && whitelisted ? 'added "//wsl.localhost/*" to the Windows git safe.directory whitelist' : `the add did not take effect${outputTail(added)}`, remedy: added.ok && whitelisted ? undefined : 'on Windows: git config --global --add safe.directory "//wsl.localhost/*", then restart the app' });
2265
2507
  } else {
2266
2508
  checks.push({ id: "fix.git-trust", status: "info", title: "Git trust whitelist", detail: "declined", remedy: 're-run with --fix (and --yes for a non-interactive run), or on Windows: git config --global --add safe.directory "//wsl.localhost/*"' });
2267
2509
  }
@@ -2274,21 +2516,46 @@ async function main(options) {
2274
2516
  return report(checks, { json: options.json }, runInfo);
2275
2517
  }
2276
2518
 
2519
+ /** How long a fresh resident gets to print its HELLO. */
2520
+ const HELLO_MS = 15_000;
2521
+
2522
+ /**
2523
+ * A resident probe's verdict: the pid and the digest comparison on success,
2524
+ * the reason otherwise — with `flaked` when the reason smells like a transport
2525
+ * problem rather than a broken agent.
2526
+ *
2527
+ * @typedef {object} ResidentVerdict
2528
+ * @property {boolean} ok - whether a well-formed HELLO arrived.
2529
+ * @property {number} [pid] - the resident's pid, on success.
2530
+ * @property {boolean} [digestMatches] - whether the HELLO's digest is the shipped script's, on success.
2531
+ * @property {string} [detail] - why not, on failure.
2532
+ * @property {boolean} [flaked] - whether the failure is transport-shaped, on failure.
2533
+ */
2534
+
2277
2535
  /**
2278
2536
  * Probe a fresh resident: start the shipped shell agent in the distro, read its
2279
2537
  * HELLO, verify the script digest, and stop it. This proves the agent path can
2280
2538
  * start and that the file the distro reads is the one this package shipped.
2281
2539
  *
2540
+ * A failure is `flaked` when the HELLO deadline fired, wsl.exe itself failed
2541
+ * to spawn or reported its wedged-service error on stderr — the shapes a cold
2542
+ * distro mid-boot produces under the doctor's concurrent probing. A wrong
2543
+ * first line, another protocol number or an agent that exits on its own are
2544
+ * answers, not flakes, and say so.
2545
+ *
2282
2546
  * @param {string} distro - the distro to probe.
2283
2547
  * @param {string} scriptPath - the agent script as a Linux path inside the distro.
2284
2548
  * @param {string} [wslExe] - the wsl.exe to spawn.
2285
2549
  * @param {string} [hostPath] - the same script as this host names it, for the digest (defaults to scriptPath).
2286
- * @returns {Promise<{ ok: true, pid: number, digestMatches: boolean } | { ok: false, detail: string }>} the verdict, with the pid on success.
2550
+ * @param {number} [helloMs] - how long the HELLO may take; tests shrink it.
2551
+ * @returns {Promise<ResidentVerdict>} the verdict.
2287
2552
  */
2288
- function probeResident(distro, scriptPath, wslExe = WSL, hostPath = scriptPath) {
2553
+ function probeResident(distro, scriptPath, wslExe = WSL, hostPath = scriptPath, helloMs = HELLO_MS) {
2289
2554
  return new Promise((settle) => {
2290
2555
  let settled = false;
2291
- /** @param {{ ok: true, pid: number, digestMatches: boolean } | { ok: false, detail: string }} value - the verdict. */
2556
+ /** Everything wsl.exe wrote to stderr: its own errors land here, not in the agent's stdout. */
2557
+ let errors = "";
2558
+ /** @param {ResidentVerdict} value - the verdict. */
2292
2559
  const finish = (value) => {
2293
2560
  if (settled) return;
2294
2561
  settled = true;
@@ -2296,13 +2563,15 @@ function probeResident(distro, scriptPath, wslExe = WSL, hostPath = scriptPath)
2296
2563
  child.kill();
2297
2564
  settle(value);
2298
2565
  };
2299
- const child = spawn(wslExe, ["-d", distro, "--exec", "sh", scriptPath], {
2566
+ const { file: spawnFile, args: spawnArgs } = wslSpawn(wslExe, ["-d", distro, "--exec", "sh", scriptPath]);
2567
+ const child = spawn(spawnFile, spawnArgs, {
2300
2568
  stdio: ["pipe", "pipe", "pipe"],
2301
2569
  windowsHide: true,
2302
2570
  env: { ...process.env, WSL_UTF8: "1" },
2303
2571
  });
2304
- const timer = setTimeout(() => finish({ ok: false, detail: "no HELLO within 5 s" }), 5000);
2572
+ const timer = setTimeout(() => finish({ ok: false, detail: `no HELLO within ${Math.round(helloMs / 1000)} s`, flaked: true }), helloMs);
2305
2573
  let buffered = "";
2574
+ child.stderr.on("data", (chunk) => { errors += String(chunk); });
2306
2575
  child.stdout.on("data", (chunk) => {
2307
2576
  buffered += String(chunk);
2308
2577
  const newline = buffered.indexOf("\n");
@@ -2310,17 +2579,17 @@ function probeResident(distro, scriptPath, wslExe = WSL, hostPath = scriptPath)
2310
2579
  const line = buffered.slice(0, newline).trim();
2311
2580
  const [kind, name, version, digest, pid] = line.split("|");
2312
2581
  if (kind !== "HELLO" || name !== AGENT_NAME) {
2313
- finish({ ok: false, detail: `unexpected first line: ${line.slice(0, 80)}` });
2582
+ finish({ ok: false, detail: `unexpected first line: ${line.slice(0, 80)}`, flaked: false });
2314
2583
  return;
2315
2584
  }
2316
2585
  if (Number(version) !== PROTOCOL_VERSION) {
2317
- finish({ ok: false, detail: `protocol ${version}, expected ${PROTOCOL_VERSION}` });
2586
+ finish({ ok: false, detail: `protocol ${version}, expected ${PROTOCOL_VERSION}`, flaked: false });
2318
2587
  return;
2319
2588
  }
2320
2589
  const expected = createHash("sha256").update(readFileSync(hostPath)).digest("hex");
2321
2590
  finish({ ok: true, pid: Number(pid), digestMatches: digest === expected });
2322
2591
  });
2323
- child.on("error", (error) => finish({ ok: false, detail: error.message }));
2592
+ child.on("error", (error) => finish({ ok: false, detail: error.message, flaked: true }));
2324
2593
  child.on("close", () => {
2325
2594
  if (settled) return;
2326
2595
  // 'exit' can fire before the stdio pipes are drained — the HELLO sits
@@ -2336,12 +2605,43 @@ function probeResident(distro, scriptPath, wslExe = WSL, hostPath = scriptPath)
2336
2605
  return;
2337
2606
  }
2338
2607
  }
2339
- finish({ ok: false, detail: `agent exited before its HELLO (${buffered.trim().slice(0, 80)})` });
2608
+ // An exit with nothing on stdout is the agent's doing or wsl.exe's;
2609
+ // its own stderr error is what tells a wedged service from a broken
2610
+ // script, and wsl.exe's error class says more in 80 characters than the
2611
+ // localized sentence around it.
2612
+ const reason = (wslErrorClass(errors) ?? errors.trim() ?? buffered.trim()).slice(0, 80);
2613
+ finish({ ok: false, detail: `agent exited before its HELLO (${reason})`, flaked: isFlake({ stderr: errors, stdout: "" }) });
2340
2614
  });
2341
2615
  child.stdin.end();
2342
2616
  });
2343
2617
  }
2344
2618
 
2619
+ /**
2620
+ * The handshake probe with the retry every other in-distro read gets: an
2621
+ * attempt that came back `flaked` is tried once more after the settle delay.
2622
+ *
2623
+ * The handshake is blocking-level — its `fail` turns the verdict `blocked` and
2624
+ * skips both smoke legs — yet it alone ran on one 5-second attempt with no
2625
+ * retry, while the warn-level smoke legs had 30 seconds and a second try. A
2626
+ * deterministic failure is answered at once: only a transport-shaped one pays
2627
+ * for another round trip.
2628
+ *
2629
+ * @param {string} distro - the distro to probe.
2630
+ * @param {string} scriptPath - the agent script as a Linux path inside the distro.
2631
+ * @param {string} [wslExe] - the wsl.exe to spawn.
2632
+ * @param {string} [hostPath] - the same script as this host names it, for the digest (defaults to scriptPath).
2633
+ * @param {{ helloMs?: number, settleMs?: number }} [timing] - the HELLO deadline and the settle delay; tests shrink both.
2634
+ * @returns {Promise<ResidentVerdict>} the final attempt's verdict, its detail noting the second try when that one flaked too.
2635
+ */
2636
+ export async function probeHandshake(distro, scriptPath, wslExe = WSL, hostPath = scriptPath, timing = {}) {
2637
+ const helloMs = timing.helloMs ?? HELLO_MS;
2638
+ const first = await probeResident(distro, scriptPath, wslExe, hostPath, helloMs);
2639
+ if (first.ok || !first.flaked) return first;
2640
+ await new Promise((resolve) => setTimeout(resolve, timing.settleMs ?? FLAKE_SETTLE_MS));
2641
+ const second = await probeResident(distro, scriptPath, wslExe, hostPath, helloMs);
2642
+ return second.ok ? { ...second, detail: `the first attempt flaked (${first.detail}); the retry answered` } : second.flaked ? { ...second, detail: `${second.detail} (tried twice)` } : second;
2643
+ }
2644
+
2345
2645
  /**
2346
2646
  * One smoke session against a fresh resident: spawn it, read the HELLO, run
2347
2647
  * one EXEC round trip (`uname -m`), create a temp dir over the same transport,
@@ -2358,7 +2658,8 @@ function probeResident(distro, scriptPath, wslExe = WSL, hostPath = scriptPath)
2358
2658
  */
2359
2659
  function runSmokeLegs(distro, residentArgv, wslExe = WSL, expectedDigest = "") {
2360
2660
  return new Promise((settle) => {
2361
- const child = spawn(wslExe, ["-d", distro, "--exec", ...residentArgv], {
2661
+ const { file: spawnFile, args: spawnArgs } = wslSpawn(wslExe, ["-d", distro, "--exec", ...residentArgv]);
2662
+ const child = spawn(spawnFile, spawnArgs, {
2362
2663
  stdio: ["pipe", "pipe", "pipe"],
2363
2664
  windowsHide: true,
2364
2665
  env: { ...process.env, WSL_UTF8: "1" },
@@ -2536,7 +2837,9 @@ async function runSandboxSmoke(distro) {
2536
2837
  async function confirm(question, yes) {
2537
2838
  if (yes) return true;
2538
2839
  if (!process.stdin.isTTY) return false;
2539
- const rl = createInterface({ input: process.stdin, output: process.stdout });
2840
+ // The question goes to stderr: with `--json`, stdout is the report and
2841
+ // nothing else, and a prompt is not part of it.
2842
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
2540
2843
  try {
2541
2844
  const answer = await rl.question(`${question} [y/N] `);
2542
2845
  return /^y(es)?$/i.test(answer.trim());
@@ -2647,10 +2950,20 @@ function report(checks, options, runInfo = {}) {
2647
2950
  if (runInfo.bundle.redact) {
2648
2951
  const homeReal = homedir();
2649
2952
  const dshReal = process.env.DSH_HOME !== undefined && process.env.DSH_HOME.length > 0 ? process.env.DSH_HOME : join(homeReal, ".dsh");
2953
+ // The DISTRO user's home rides the identity row ("shell, /home/name"),
2954
+ // and on a real Windows machine it is not the host's home — the split
2955
+ // below never touched it, so `--redact` left the distro user name in
2956
+ // the bundle. Replace it wherever it appears.
2957
+ const distroHome = checks
2958
+ .filter((entry) => entry.id === "distro.identity")
2959
+ .map((entry) => /^[^,]+, (\/[^,]*)$/.exec(String(entry.detail ?? ""))?.[1] ?? "")
2960
+ .find((value) => value.length > 1);
2650
2961
  payload = payload.split(homeReal).join("<redacted-home>").split(dshReal).join("<redacted-dsh-home>");
2962
+ if (distroHome !== undefined) payload = payload.split(distroHome).join("<redacted-home>");
2651
2963
  }
2652
2964
  writeFileSync(runInfo.bundle.path, payload);
2653
- console.log(doctorT("bundle.written", { path: runInfo.bundle.path, bytes: payload.length, redacted: runInfo.bundle.redact ? doctorT("bundle.redacted") : "" }));
2965
+ // A note about a file, not report content: `--json` keeps stdout to the report.
2966
+ console.error(doctorT("bundle.written", { path: runInfo.bundle.path, bytes: payload.length, redacted: runInfo.bundle.redact ? doctorT("bundle.redacted") : "" }));
2654
2967
  }
2655
2968
  return verdict === "blocked" ? 1 : 0;
2656
2969
  }
@@ -2658,7 +2971,7 @@ function report(checks, options, runInfo = {}) {
2658
2971
  if (process.argv[1] !== undefined && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
2659
2972
  const options = parseArgs(process.argv.slice(2));
2660
2973
  if (options.help) {
2661
- console.log("node scripts/doctor.mjs [distro] [--all] [--json] [--quick] [--sections host,sandbox,session,conf,net,agent] [--fix] [--fix-owned] [--install] [--yes] [--read-only] [--bundle <path>] [--redact] [--locale <tag>]");
2974
+ console.log("node scripts/doctor.mjs [distro] [--all] [--json] [--quick] [--sections host,sandbox,session,conf,net,agent] [--probe-timeout <ms>] [--wsl <path>] [--cmd <path>] [--fix] [--fix-owned] [--install] [--yes] [--read-only] [--bundle <path>] [--redact] [--locale <tag>]");
2662
2975
  } else {
2663
2976
  process.exitCode = await main(options);
2664
2977
  }