dsh-plugin-wsl-env 0.23.1 → 0.25.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.
Files changed (77) hide show
  1. package/CHANGELOG.md +212 -0
  2. package/README.md +9 -5
  3. package/SECURITY.md +10 -0
  4. package/client.js +974 -165
  5. package/cordis.patch.yml +28 -3
  6. package/docs/API.md +2 -1
  7. package/docs/ARCHITECTURE.md +36 -13
  8. package/docs/COMPATIBILITY.md +5 -0
  9. package/docs/CONFIGURATION.md +80 -9
  10. package/docs/CONFIGURATION.zh.md +64 -8
  11. package/docs/DIAGNOSTICS.md +48 -20
  12. package/docs/DIAGNOSTICS.zh.md +36 -14
  13. package/docs/LIMITATIONS.md +36 -9
  14. package/docs/LIMITATIONS.zh.md +26 -7
  15. package/docs/MIGRATION.md +1 -1
  16. package/docs/PEER-PARITY.md +4 -4
  17. package/docs/QUICKSTART.md +42 -12
  18. package/docs/QUICKSTART.zh.md +29 -8
  19. package/docs/README.zh.md +9 -5
  20. package/docs/RELEASING.md +17 -13
  21. package/docs/REQUIREMENTS.zh.md +5 -4
  22. package/docs/UPSTREAM-FSIO-EXPORT.md +5 -4
  23. package/docs/UPSTREAM-PROMPT-ADAPTERS.md +85 -0
  24. package/docs/root-fs-routing.md +1 -1
  25. package/lib/agent-confined.d.ts +7 -1
  26. package/lib/agent-confined.js +3 -3
  27. package/lib/auto-preset.d.ts +27 -0
  28. package/lib/auto-preset.js +40 -3
  29. package/lib/bwrap.d.ts +14 -0
  30. package/lib/bwrap.js +11 -0
  31. package/lib/client-host.d.ts +2 -2
  32. package/lib/client-host.js +2 -2
  33. package/lib/cwd-prompt.d.ts +41 -3
  34. package/lib/cwd-prompt.js +125 -8
  35. package/lib/doctor-report.d.ts +50 -0
  36. package/lib/doctor-report.js +172 -0
  37. package/lib/fs-routing.d.ts +1 -1
  38. package/lib/fs-routing.js +1 -1
  39. package/lib/fs.d.ts +1 -1
  40. package/lib/fs.js +1 -1
  41. package/lib/index.d.ts +6 -1464
  42. package/lib/index.js +5 -2120
  43. package/lib/listing.d.ts +21 -9
  44. package/lib/listing.js +25 -21
  45. package/lib/messages.d.ts +1 -1
  46. package/lib/messages.js +3 -3
  47. package/lib/picker.d.ts +50 -16
  48. package/lib/picker.js +103 -23
  49. package/lib/preflight.d.ts +7 -4
  50. package/lib/preflight.js +27 -13
  51. package/lib/preset-choice.d.ts +22 -3
  52. package/lib/preset-choice.js +36 -3
  53. package/lib/provider-common.d.ts +58 -0
  54. package/lib/provider-common.js +123 -0
  55. package/lib/sandbox-core.d.ts +1 -0
  56. package/lib/sandbox-core.js +4 -2
  57. package/lib/session-runtime.d.ts +7 -1
  58. package/lib/session-runtime.js +9 -2
  59. package/lib/shell.d.ts +1 -1
  60. package/lib/shell.js +1 -1
  61. package/lib/status.d.ts +261 -0
  62. package/lib/status.js +425 -0
  63. package/lib/writable-roots.d.ts +109 -0
  64. package/lib/writable-roots.js +257 -0
  65. package/lib/wsl-doctor-tool.d.ts +8 -0
  66. package/lib/wsl-doctor-tool.js +18 -20
  67. package/lib/wsl-filesystem.d.ts +692 -0
  68. package/lib/wsl-filesystem.js +897 -0
  69. package/lib/wsl-shell.d.ts +742 -0
  70. package/lib/wsl-shell.js +965 -0
  71. package/lib/wsl.d.ts +13 -1
  72. package/lib/wsl.js +16 -1
  73. package/locale/doctor/en.json +3 -2
  74. package/locale/doctor/zh.json +3 -2
  75. package/package.json +12 -4
  76. package/scripts/doctor.mjs +436 -226
  77. package/scripts/profile-preset.mjs +17 -5
@@ -4,13 +4,16 @@
4
4
  * and per-distro shape: WSL-316).
5
5
  *
6
6
  * Answers "will this plugin work here, and if not, what do I paste?" in one
7
- * read-only pass: Windows and WSL versions, the distro and its shell, bubblewrap
7
+ * read-only pass: the Windows/WSL platform, the distro identity, bubblewrap
8
8
  * usability, systemd / the user manager / `systemd-run` / Linger, the optional
9
- * tools, the peer versions the plugin is loaded against, the native-agent cache,
10
- * a fresh-agent handshake, stale session scopes, the known profile-patch trap,
11
- * and whether a newer stable release exists on the registry.
9
+ * tools, the peer versions the plugin is loaded against, the native agent and
10
+ * its cache, a fresh-agent handshake, the shell and native smoke legs, stale
11
+ * session scopes, the host volume and the Windows share, and the known
12
+ * profile-patch / deprecated-key traps. The update check is deliberately NOT
13
+ * here: it is not a diagnosis, and the plugin's delegated update service plus
14
+ * the app's Versions page already answer it without a registry GET per run.
12
15
  *
13
- * node scripts/doctor.mjs [distro] [--json] [--fix] [--install] [--yes] [--read-only]
16
+ * node scripts/doctor.mjs [distro] [--json] [--fix] [--fix-owned] [--install] [--yes] [--read-only]
14
17
  * [--wsl <path to wsl.exe>]
15
18
  *
16
19
  * Exit status is 0 when the verdict is `ready` and 1 when it is `blocked`;
@@ -24,9 +27,13 @@
24
27
  * wsl.exe transport could not vouch for (a flake that survived one retry) —
25
28
  * it never blocks and never feeds a config verdict; rerun for a clean answer. `--fix` performs only safe
26
29
  * actions: it sweeps stale `dsh-wsl-*.scope` units (the same sweep the session
27
- * preflight runs). Installing packages needs `--install` *and* an explicit
28
- * confirmation (`--yes` skips the prompt, not the flag), so a fix run can never
29
- * install silently.
30
+ * preflight runs) and purges the plugin-owned agent cache when an entry is not
31
+ * executable, re-probing both afterwards. Installing packages needs `--install`
32
+ * *and* an explicit confirmation (`--yes` skips the prompt, not the flag), so a
33
+ * fix run can never install silently. `--fix-owned` narrows the fix loop to the
34
+ * plugin-owned state (the scope sweep and the cache purge): it skips the
35
+ * package install and the Windows git whitelist, and it cannot be combined
36
+ * with `--install`. The sidebar's status panel uses it for its repair action.
30
37
  *
31
38
  * `--read-only` refuses `--fix`/`--install`; `scripts/diagnose.sh` uses it to stay an
32
39
  * alias that can never change the machine.
@@ -40,7 +47,7 @@
40
47
  * dependency and no host service**, so it still starts when the plugin's own
41
48
  * runtime is the thing that is broken (the chicken-and-egg failure the
42
49
  * in-process tool path cannot escape). Only pure, peer-free lib modules are
43
- * imported; the two helpers that lived behind peer-tainted modules are inlined
50
+ * imported; the one helper that lived behind a peer-tainted module is inlined
44
51
  * below and drift-pinned by test.
45
52
  *
46
53
  * This CLI always probes a **fresh** resident — the app process's live
@@ -54,7 +61,7 @@
54
61
  import { execFile, spawn } from "node:child_process";
55
62
  import { createHash } from "node:crypto";
56
63
  import { createRequire } from "node:module";
57
- import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
64
+ import { existsSync, readdirSync, readFileSync, statfsSync, writeFileSync } from "node:fs";
58
65
  import { homedir } from "node:os";
59
66
  import { dirname, join, resolve } from "node:path";
60
67
  import { createInterface } from "node:readline/promises";
@@ -68,20 +75,16 @@ import { bwrapArgvPrefix } from "../lib/bwrap.js";
68
75
  import { sessionScopeSweepScript } from "../lib/session-scope.js";
69
76
  import { parseListeningPorts, procNetScript } from "../lib/ports.js";
70
77
 
71
- // ── Peer-free inlining of the two peer-tainted helpers ────────────────────────
78
+ // ── Peer-free inlining of the one peer-tainted helper ─────────────────────────
72
79
  //
73
80
  // The doctor must start even when the plugin's runtime is the thing that is
74
- // broken. Two of the lib modules it used to import are unsafe for that:
81
+ // broken. `lib/index.js` pulls the whole plugin graph and every
82
+ // `@deepseek-ai/dsh-*` peer dependency at load time, and the helper below is a
83
+ // pure two-liner, so it is inlined here instead. A test in
84
+ // `test/doctor.test.mjs` compares the copy against the lib export to pin it
85
+ // against drift.
75
86
  //
76
- // - `lib/index.js` pulls the whole plugin graph and every `@deepseek-ai/dsh-*`
77
- // peer dependency at load time;
78
- // - `lib/update-check.js` imports `@deepseek-ai/schemastery` at the top level.
79
- //
80
- // Both helpers are pure two-liners, so they are inlined here instead. A test in
81
- // `test/doctor.test.mjs` compares these copies against the lib exports to pin
82
- // them against drift.
83
- //
84
- // Inlined from `src/index.ts` `effectiveMaskWindowsDrive`:
87
+ // Inlined from `src/provider-common.ts` `effectiveMaskWindowsDrive`:
85
88
  /**
86
89
  * Whether confined profiles shadow `/mnt` under this config.
87
90
  *
@@ -93,20 +96,54 @@ export function effectiveMaskWindowsDrive(config) {
93
96
  return config.maskWindowsDrive === true;
94
97
  }
95
98
 
96
- // Inlined from `src/update-check.ts` `updateFactMessage`:
97
99
  /**
98
- * One human line about an available update.
100
+ * The path one distro sees for a host file. A POSIX host path (the doctor
101
+ * running inside a distro) is returned as-is; a Windows drive path is
102
+ * translated through the distro's automount root, so the Windows entry can
103
+ * hand `wsl.exe` a script path the distro can actually read. Anything else
104
+ * (a UNC root, an unreadable root) is undefined — the caller reports why
105
+ * instead of passing a Windows path to `sh`.
106
+ *
107
+ * @param {string} hostPath - the path as this host names it.
108
+ * @param {string} mountRoot - the distro's automount root (`/mnt` when unset).
109
+ * @returns {string | undefined} the distro-side path, or undefined when it cannot be expressed.
110
+ */
111
+ export function distroPath(hostPath, mountRoot) {
112
+ if (hostPath.startsWith("/")) return hostPath;
113
+ const match = /^([A-Za-z]):[\\/](.*)$/.exec(hostPath);
114
+ if (match === null) return undefined;
115
+ const drive = (match[1] ?? "").toLowerCase();
116
+ const rest = (match[2] ?? "").replace(/\\/g, "/");
117
+ return `${mountRoot.replace(/\/+$/, "")}/${drive}/${rest}`;
118
+ }
119
+
120
+ /**
121
+ * The host-volume verdict: the Windows drive holding the distro (the VHDX)
122
+ * fails writes the moment it is full, even while the distro's own `df` looks
123
+ * healthy, so this row answers that volume rather than the ext4 one.
99
124
  *
100
- * @param {{ latest: string, installed: string, incompatible?: boolean, deprecated?: string, checkedAt?: number } | undefined} update - the update fact, or undefined when none.
101
- * @returns {string} the message, empty when there is no update.
125
+ * @param {number} freeBytes - bytes available to the current user.
126
+ * @param {number} totalBytes - the volume's size.
127
+ * @returns {{ status: "ok" | "warn" | "fail", detail: string, remedy: string | undefined }} the verdict.
102
128
  */
103
- export function updateFactMessage(update) {
104
- if (update === undefined) return "";
105
- const marks = [];
106
- if (update.incompatible) marks.push("requires a newer DSH first");
107
- if (update.deprecated !== undefined) marks.push(`deprecated: ${update.deprecated}`);
108
- const tail = marks.length === 0 ? "" : ` — ${marks.join("; ")}`;
109
- return `${update.latest} available (installed ${update.installed})${tail}`;
129
+ export function hostDiskVerdict(freeBytes, totalBytes) {
130
+ const gib = (/** @type {number} */ bytes) => `${(bytes / 1024 ** 3).toFixed(1)} GiB`;
131
+ const detail = `${gib(freeBytes)} free of ${gib(totalBytes)}`;
132
+ if (freeBytes < 2 * 1024 ** 3) {
133
+ return {
134
+ status: "fail",
135
+ detail: `${detail} — the Windows volume holding the distro is nearly full; writes into the ext4 VHDX fail even when the distro's own df looks fine`,
136
+ remedy: 'free space on that Windows volume, or move the distro ("wsl --export" then "wsl --import" to another drive); sparseVhd plus "wsl.exe --shutdown" reclaims deleted data',
137
+ };
138
+ }
139
+ if (freeBytes < 5 * 1024 ** 3) {
140
+ return {
141
+ status: "warn",
142
+ detail: `${detail} — plan a cleanup before writes start failing`,
143
+ remedy: 'free space on the Windows volume holding the distro, or enable sparseVhd and "wsl.exe --shutdown" to shrink the VHDX',
144
+ };
145
+ }
146
+ return { status: "ok", detail, remedy: undefined };
110
147
  }
111
148
 
112
149
  // ── Host-locale output catalogs ──────────────────────────────────────────────
@@ -207,7 +244,7 @@ const CMD = "cmd.exe";
207
244
  const TIMEOUT_MS = 60_000;
208
245
 
209
246
  /** The package families the install remedies know, in probe order. */
210
- const FAMILIES = ["apt-get", "dnf", "pacman", "zypper"];
247
+ const FAMILIES = ["apt-get", "dnf", "pacman", "zypper", "apk"];
211
248
  /** The package names the plugin uses, per family. */
212
249
  const PACKAGES = "bubblewrap git ripgrep inotify-tools";
213
250
  /** One install command per family; `zypper` spells its non-interactive flag differently. */
@@ -216,6 +253,15 @@ const INSTALL = /** @type {Record<string, string>} */ ({
216
253
  dnf: `dnf install -y ${PACKAGES}`,
217
254
  pacman: `pacman -Sy --noconfirm ${PACKAGES}`,
218
255
  zypper: `zypper --non-interactive install ${PACKAGES}`,
256
+ apk: `apk add --no-cache ${PACKAGES}`,
257
+ });
258
+ /** The one package the shell agent needs beyond the generic set: GNU find. */
259
+ const FINDUTILS = /** @type {Record<string, string>} */ ({
260
+ "apt-get": "apt-get install -y findutils",
261
+ dnf: "dnf install -y findutils",
262
+ pacman: "pacman -S --noconfirm findutils",
263
+ zypper: "zypper --non-interactive install findutils",
264
+ apk: "apk add --no-cache findutils",
219
265
  });
220
266
  /** The read-only stale-scope report; `--fix` runs the shipped sweep instead. */
221
267
  const STALE_SCOPE_REPORT = [
@@ -239,7 +285,17 @@ const CACHE_REPORT = [
239
285
  '[ -d "$d" ] || { echo none; exit 0; }',
240
286
  'for f in "$d"/*/dsh-wsl-agent; do',
241
287
  " [ -e \"$f\" ] || continue",
242
- ' if [ -x "$f" ]; then echo "exec $(basename "$(dirname "$f")")"; else echo "noexec $(basename "$(dirname "$f")")"; fi',
288
+ ' name=$(basename "$(dirname "$f")")',
289
+ // The cache is content-addressed: only a 64-hex directory name is an agent
290
+ // entry. A stray directory (a probe fixture, a hand-made copy) is not, and
291
+ // must not turn into a cache warning the user cannot explain.
292
+ ' printf "%s" "$name" | grep -Eq "^[0-9a-f]{64}$" || continue',
293
+ ' if [ ! -x "$f" ]; then echo "noexec $f"; continue; fi',
294
+ ' if command -v timeout >/dev/null 2>&1; then',
295
+ ' if timeout 3 "$f" </dev/null >/dev/null 2>&1; then echo "exec $f"; else echo "broken $f"; fi',
296
+ ' else',
297
+ ' if "$f" </dev/null >/dev/null 2>&1; then echo "exec $f"; else echo "broken $f"; fi',
298
+ ' fi',
243
299
  "done",
244
300
  ].join("\n");
245
301
 
@@ -275,7 +331,7 @@ export function sectionOf(id) {
275
331
  if (id.startsWith("session.") || id === "runtime.scopes" || id === "distro.wsl-conf-boot") return "session";
276
332
  if (id.startsWith("config.") || id === "distro.wsl-conf-interop" || id === "distro.wsl-conf-automount") return "conf";
277
333
  if (id === "distro.dns") return "net";
278
- if (id.startsWith("agent.") || id === "functional.exec" || id === "functional.fs") return "agent";
334
+ if (id.startsWith("agent.") || id === "functional.exec" || id === "functional.fs" || id === "functional.native") return "agent";
279
335
  return "host";
280
336
  }
281
337
 
@@ -513,7 +569,14 @@ export function effectiveConfig(dshHome, root) {
513
569
  const distro = rowKey(preset, "distro");
514
570
  const sessionSandbox = rowKey(preset, "sessionSandbox");
515
571
  const agentBackend = rowKey(preset, "agentBackend");
516
- const sandbox = rowKey(routing, "sandbox");
572
+ // Confinement is on when ANY surface turns it on: the command row
573
+ // (`wsl-shell`), the file row (`wsl-fs`), or the mutation fence
574
+ // (`fs-routing`). The single effective key answers "does anything need
575
+ // bubblewrap", which is the question the sandbox checks and the verdict ask.
576
+ const shellSandbox = rowKey(rowBlock(preset, "wsl-shell"), "sandbox");
577
+ const fsSandbox = rowKey(rowBlock(preset, "wsl-fs"), "sandbox");
578
+ const routingSandbox = rowKey(routing, "sandbox");
579
+ const sandbox = shellSandbox ?? fsSandbox ?? routingSandbox;
517
580
  const maskWindowsDrive = rowKey(routing, "maskWindowsDrive");
518
581
  if (sessionSandbox !== undefined) {
519
582
  recognized = true;
@@ -540,7 +603,7 @@ export function effectiveConfig(dshHome, root) {
540
603
  const next = { ...config };
541
604
  const layerPreset = rowBlock(text, "preset-wsl");
542
605
  const layerRouting = rowBlock(text, "fs-routing");
543
- for (const [block, keys] of [[layerPreset, ["distro", "sessionSandbox", "agentBackend"]], [layerRouting, ["sandbox", "maskWindowsDrive"]]]) {
606
+ for (const [block, keys] of [[layerPreset, ["distro", "sessionSandbox", "agentBackend", "sandbox"]], [layerRouting, ["sandbox", "maskWindowsDrive"]]]) {
544
607
  const source = /** @type {string} */ (block);
545
608
  /** The scalar keys the overlay may change; `source`/`overrides` are bookkeeping, not overlay inputs. */
546
609
  const scalar = /** @type {const} */ (["distro", "sessionSandbox", "agentBackend", "sandbox", "maskWindowsDrive", "interopVisibility"]);
@@ -611,7 +674,7 @@ async function askDistro(distro, script) {
611
674
  /**
612
675
  * Parse the doctor's own arguments.
613
676
  * @param {string[]} argv - `process.argv.slice(2)`.
614
- * @returns {{ distro: string, wsl: string, json: boolean, fix: boolean, install: boolean, yes: boolean, readOnly: boolean, all: boolean, bundle: string, redact: boolean, sections: string, quick: boolean, help: boolean, locale: string }} the options.
677
+ * @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.
615
678
  */
616
679
  function parseArgs(argv) {
617
680
  const options = {
@@ -619,6 +682,7 @@ function parseArgs(argv) {
619
682
  wsl: "",
620
683
  json: false,
621
684
  fix: false,
685
+ fixOwned: false,
622
686
  install: false,
623
687
  yes: false,
624
688
  readOnly: false,
@@ -636,6 +700,7 @@ function parseArgs(argv) {
636
700
  else if (arg === "--locale") options.locale = argv[++i] ?? "";
637
701
  else if (arg.startsWith("--locale=")) options.locale = arg.slice("--locale=".length);
638
702
  else if (arg === "--fix") options.fix = true;
703
+ else if (arg === "--fix-owned") options.fixOwned = true;
639
704
  else if (arg === "--install") options.install = true;
640
705
  else if (arg === "--yes" || arg === "-y") options.yes = true;
641
706
  else if (arg === "--read-only") options.readOnly = true;
@@ -752,72 +817,6 @@ function installedPeer(packageName) {
752
817
  }
753
818
  }
754
819
 
755
- /** The registries the update check asks, in order; the official one first. */
756
- const UPDATE_REGISTRIES = ["https://registry.npmjs.org", "https://registry.npmmirror.com"];
757
-
758
- /**
759
- * The registries one run asks: `DSH_UPDATE_REGISTRIES` overrides the defaults
760
- * (comma-separated, for an operator pinned to one mirror); set it empty to ask
761
- * none at all — an air-gapped machine's way to keep the check silent without
762
- * paying two connect timeouts.
763
- * @returns {string[]} the registry base URLs.
764
- */
765
- function updateRegistries() {
766
- const configured = process.env.DSH_UPDATE_REGISTRIES;
767
- if (configured !== undefined) return configured.split(",").map((entry) => entry.trim()).filter((entry) => entry.length > 0);
768
- return UPDATE_REGISTRIES;
769
- }
770
-
771
- /**
772
- * Read the stable channel's newest release off one registry packument. The
773
- * full document (not the abbreviated one) is requested, because only it
774
- * carries the per-version deprecation message.
775
- * @param {unknown} body - the parsed packument JSON.
776
- * @returns {{ version: string, deprecated?: string, publishedAt?: string } | undefined} the release, or undefined when the document names none.
777
- */
778
- export function latestFromPackument(body) {
779
- if (typeof body !== "object" || body === null) return undefined;
780
- const packument = /** @type {{ "dist-tags"?: Record<string, unknown>, versions?: Record<string, unknown> }} */ (body);
781
- const tags = packument["dist-tags"];
782
- const versions = packument.versions;
783
- if (typeof tags !== "object" || tags === null || typeof versions !== "object" || versions === null) return undefined;
784
- const latest = tags.latest;
785
- if (typeof latest !== "string" || latest.length === 0) return undefined;
786
- const manifest = /** @type {{ deprecated?: unknown } | undefined} */ (versions[latest]);
787
- if (manifest === undefined || typeof manifest !== "object") return undefined;
788
- return {
789
- version: latest,
790
- ...(typeof manifest.deprecated === "string" && manifest.deprecated.length > 0 ? { deprecated: manifest.deprecated } : {}),
791
- };
792
- }
793
-
794
- /**
795
- * Ask the registries for the stable channel's newest release, official first,
796
- * mirror second — the same fallback order the harness's plugin install uses.
797
- * A short timeout keeps an offline run from stalling; every failure is an
798
- * undefined, never a throw.
799
- * @param {string[]} [registries] - the registries to ask; absent, `DSH_UPDATE_REGISTRIES` or the defaults (see {@link updateRegistries}).
800
- * @param {number} [timeoutMs] - per-registry timeout, for tests.
801
- * @returns {Promise<{ version: string, deprecated?: string, registry: string } | undefined>} the release and the registry that answered.
802
- */
803
- export async function fetchLatestRelease(registries, timeoutMs = 5_000) {
804
- for (const registry of registries ?? updateRegistries()) {
805
- try {
806
- const response = await fetch(`${registry}/dsh-plugin-wsl-env`, {
807
- headers: { accept: "application/json" },
808
- signal: AbortSignal.timeout(timeoutMs),
809
- });
810
- if (!response.ok) continue;
811
- const latest = latestFromPackument(await response.json());
812
- if (latest !== undefined) return { ...latest, registry };
813
- } catch {
814
- // Offline, a blocked proxy, or a mirror that does not answer: the next
815
- // registry (or the undefined) speaks for this run.
816
- }
817
- }
818
- return undefined;
819
- }
820
-
821
820
  /**
822
821
  * The install remedy for one distro and family.
823
822
  * @param {string} distro - the distro name.
@@ -872,7 +871,7 @@ const DISTRO_CONCURRENCY = 3;
872
871
 
873
872
  /**
874
873
  * Run the doctor.
875
- * @param {{ distro: string, wsl: string, json: boolean, fix: boolean, install: boolean, yes: boolean, readOnly: boolean, all: boolean, bundle: string, redact: boolean, help: boolean }} options - the parsed options.
874
+ * @param {{ distro: string, wsl: string, json: boolean, fix: boolean, fixOwned: boolean, install: boolean, yes: boolean, readOnly: boolean, all: boolean, bundle: string, redact: boolean, help: boolean }} options - the parsed options.
876
875
  * @returns {Promise<number>} the exit status.
877
876
  */
878
877
  /**
@@ -893,6 +892,13 @@ async function main(options) {
893
892
  const query = await run([CMD, "/c", "reg query \"HKCU\\Control Panel\\International\" /v LocaleName"]);
894
893
  setDoctorLocale(localeFromTag(localeNameFromReg(query.stdout)));
895
894
  }
895
+ if (options.fixOwned && options.install) {
896
+ console.error(doctorT("refusal.owned-install"));
897
+ return 2;
898
+ }
899
+ // `--fix-owned` names a fix subset, so it implies the fix loop; the
900
+ // read-only gate below then still refuses it.
901
+ if (options.fixOwned) options.fix = true;
896
902
  if (options.readOnly && (options.fix || options.install)) return rejectReadOnly();
897
903
  // One rebinding covers every probe below (`-l -q`, `inDistro`, the
898
904
  // resident handshake, the sessions survey): an explicit `--wsl` replaces
@@ -952,22 +958,33 @@ async function main(options) {
952
958
  let scope;
953
959
  if (wanted !== null) scope = { sections: [...wanted], quick };
954
960
 
955
- // ---- host ----------------------------------------------------------------
961
+ // ---- host platform -------------------------------------------------------
962
+ // One row for the two facts that gate WSL 2 itself: the Windows build (WSL 2
963
+ // needs 19041 or later) and the WSL version string. A build below that floor
964
+ // cannot run the plugin at all, so it fails rather than reading as context;
965
+ // an unreadable host (the doctor running inside a distro without interop)
966
+ // stays `info` — the distro checks below still speak for themselves.
956
967
  const windows = await run([CMD, "/c", "ver"]);
957
- const build = /[0-9][0-9.]*/.exec(windows.stdout.replace(/\0/g, ""));
958
- if (build !== null) check("host.windows", "ok", "Windows build", build[0]);
959
- else check("host.windows", "info", "Windows build", "unreadable through cmd.exe; run this from Windows or a WSL with interop enabled");
960
-
968
+ const buildText = /[0-9]+\.[0-9]+\.[0-9]+(?:\.[0-9]+)?/.exec(windows.stdout.replace(/\0/g, ""))?.[0] ?? "";
969
+ const buildNumber = buildText === "" ? 0 : Number(buildText.split(".")[2] ?? 0);
961
970
  const version = await run([wslExe, "--version"]);
962
- const wslVersion = version.stdout.replace(/\0/g, "").split(/\r?\n/).filter((line) => line.trim().length > 0).slice(0, 2).join(" ");
963
- if (version.ok && wslVersion.length > 0) check("host.wsl", "ok", "WSL version", wslVersion);
964
- else check("host.wsl", "warn", "WSL version", "wsl.exe --version failed; WSL 1 or a very old build", "wsl.exe --update, then confirm the distro runs as WSL 2 (wsl.exe -l -v shows VERSION 2)");
971
+ const wslVersion = version.stdout.replace(/\0/g, "").split(/\r?\n/).filter((line) => line.trim().length > 0).slice(0, 2).join(" ").trim();
972
+ const platformDetail = [buildText === "" ? "" : `Windows ${buildText}`, wslVersion].filter((part) => part.length > 0).join("; ");
973
+ if (buildText === "" && wslVersion === "") {
974
+ check("host.platform", "info", "Windows and WSL", "neither the Windows build nor the WSL version is readable through cmd.exe — run the doctor from Windows or a WSL with interop enabled");
975
+ } else if (buildNumber > 0 && buildNumber < 19041) {
976
+ check("host.platform", "fail", "Windows and WSL", `${platformDetail} — WSL 2 needs Windows 10 build 19041 or later`, "upgrade Windows to a WSL 2-capable build; this plugin runs commands only in WSL 2 distros");
977
+ } else if (!version.ok || wslVersion === "") {
978
+ check("host.platform", "warn", "Windows and WSL", `${buildText === "" ? "the Windows build is unreadable" : `Windows ${buildText}`}; wsl.exe --version failed — WSL 1 or an old WSL 2 build`, "wsl.exe --update, then confirm the distro runs as WSL 2 (wsl.exe -l -v shows VERSION 2)");
979
+ } else {
980
+ check("host.platform", "ok", "Windows and WSL", platformDetail);
981
+ }
965
982
 
966
983
  phase("host");
967
984
  // ---- .wslconfig (the global VM config; host-level) ------------------------
968
985
  // WSL silently ignores a malformed file, so interop/masking advice can fail
969
986
  // to apply without a trace; this parser is where the trap gets named. The
970
- // read rides cmd.exe (the same interop path `host.windows` uses), which
987
+ // read rides cmd.exe (the same interop path `host.platform` uses), which
971
988
  // works from Windows and from a WSL with interop regardless of where the
972
989
  // automount root sits — the route's own failure is reported, not guessed.
973
990
  const userProfile = (await run([CMD, "/c", "echo %USERPROFILE%"])).stdout.replace(/\0/g, "").trim();
@@ -995,6 +1012,30 @@ async function main(options) {
995
1012
  } else {
996
1013
  check("host.distros", "ok", "Installed distros", distros.join(", "));
997
1014
  }
1015
+
1016
+ // ---- host volume (the drive holding the distro) ---------------------------
1017
+ // `distro.disk` reads the ext4 volume's own `df`; when the Windows volume
1018
+ // that holds the VHDX is full, that df still looks healthy and every write
1019
+ // fails anyway. The default distro location lives under `%LOCALAPPDATA%`, so
1020
+ // that drive is the one this check answers for.
1021
+ if (process.platform !== "win32") {
1022
+ check("host.disk", "info", "Host disk", "only the Windows entry can read the volume holding the distro (this doctor runs inside a distro)");
1023
+ } else {
1024
+ const drive = /^([A-Za-z]):/.exec(process.env.LOCALAPPDATA ?? "")?.[1] ?? /^([A-Za-z]):/.exec(ROOT)?.[1] ?? "";
1025
+ if (drive === "") {
1026
+ check("host.disk", "info", "Host disk", "the volume holding the distro is unknown (%LOCALAPPDATA% is unreadable)");
1027
+ } else {
1028
+ try {
1029
+ const stats = statfsSync(`${drive}:\\`);
1030
+ const freeBytes = Number(stats.bavail) * Number(stats.bsize);
1031
+ const totalBytes = Number(stats.blocks) * Number(stats.bsize);
1032
+ const verdict = hostDiskVerdict(freeBytes, totalBytes);
1033
+ check("host.disk", verdict.status, "Host disk", `${drive}: ${verdict.detail} (the default distro location under %LOCALAPPDATA%)`, verdict.remedy);
1034
+ } catch (error) {
1035
+ check("host.disk", "info", "Host disk", `unreadable (${/** @type {Error} */ (error).message})`);
1036
+ }
1037
+ }
1038
+ }
998
1039
  // ---- effective configuration (read once, before anything config-gated) ---
999
1040
  // The blocking verdict answers under the values the user actually runs, so
1000
1041
  // the shipped preset is overlaid by the profile layers before the target
@@ -1065,11 +1106,13 @@ async function main(options) {
1065
1106
  * fails its own reachability check and contributes nothing further — one
1066
1107
  * wedged distro must not mask the others.
1067
1108
  * @param {string} target - the distro name.
1068
- * @returns {Promise<{ checks: Check[], reachable: boolean, bwrapPath: string, stale: number, family: string }>} the distro's own checks and the state the fix section needs.
1109
+ * @returns {Promise<{ checks: Check[], reachable: boolean, bwrapPath: string, stale: number, cacheEntries: number, cacheBad: number, cacheExecPath: string, family: string, agentScriptDistro: string | undefined }>} the distro's own checks and the state the fix section needs.
1069
1110
  */
1070
1111
  const collectDistroChecks = async (target) => {
1071
1112
  /** @type {Check[]} */
1072
1113
  const collected = [];
1114
+ /** The shipped shell agent, as this host names it (Windows or POSIX). */
1115
+ const agentScript = join(ROOT, "agent", "wsl-agent.sh");
1073
1116
  const check = (/** @type {string} */ id, /** @type {Check["status"]} */ status, /** @type {string} */ title, /** @type {string | undefined} */ detail = undefined, /** @type {string | undefined} */ remedy = undefined) => {
1074
1117
  collected.push({ id, status, title, ...(detail === undefined ? {} : { detail }), ...(remedy === undefined ? {} : { remedy }), distro: target });
1075
1118
  };
@@ -1082,45 +1125,49 @@ async function main(options) {
1082
1125
  const alive = await probe("printf %s ok");
1083
1126
  if (!alive.ok && alive.flaked) {
1084
1127
  flakeCheck("distro.reachable", `Distro "${target}"`, alive);
1085
- return { checks: collected, reachable: false, bwrapPath: "", stale: 0, family: "unknown" };
1128
+ return { checks: collected, reachable: false, bwrapPath: "", stale: 0, cacheEntries: 0, cacheBad: 0, cacheExecPath: "", family: "unknown", agentScriptDistro: undefined };
1086
1129
  }
1087
1130
  if (!alive.ok || alive.stdout.trim() !== "ok") {
1088
1131
  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`);
1089
- return { checks: collected, reachable: false, bwrapPath: "", stale: 0, family: "unknown" };
1132
+ return { checks: collected, reachable: false, bwrapPath: "", stale: 0, cacheEntries: 0, cacheBad: 0, cacheExecPath: "", family: "unknown", agentScriptDistro: undefined };
1090
1133
  }
1091
1134
  check("distro.reachable", "ok", `Distro "${target}"`, "answers commands");
1092
1135
 
1093
- // ---- distro facts --------------------------------------------------------
1094
- let family = "unknown";
1095
- const shellAnswer = await probe('s=$(getent passwd "$(id -u)" | cut -d: -f7); [ -n "$s" ] || s=$SHELL; printf %s "$s"');
1096
- if (!shellAnswer.ok && shellAnswer.flaked) flakeCheck("distro.shell", "Login shell", shellAnswer);
1097
- else {
1098
- const shell = shellAnswer.stdout.trim();
1099
- if (shell.startsWith("/")) check("distro.shell", "ok", "Login shell", shell);
1100
- else check("distro.shell", "fail", "Login shell", shell.length === 0 ? "no shell reported" : shell, `check the user's /etc/passwd entry in "${target}": getent passwd "$(id -u)"`);
1101
- }
1102
-
1103
- const homeAnswer = await probe('printf %s "$HOME"');
1104
- if (!homeAnswer.ok && homeAnswer.flaked) flakeCheck("distro.home", "Home", homeAnswer);
1105
- else {
1106
- const home = homeAnswer.stdout.trim();
1107
- if (home.startsWith("/")) check("distro.home", "ok", "Home", home);
1108
- else check("distro.home", "fail", "Home", home.length === 0 ? "no home reported" : home, `check the default user's home in "${target}": getent passwd "$(id -u)"`);
1136
+ // ---- Windows share reachability (host section) ---------------------------
1137
+ // The GUI file service, the workspace picker and open-in-app read the
1138
+ // `\\wsl.localhost` share from the WINDOWS side; the agent path does not.
1139
+ // A share Windows cannot read is a silent feature loss, so name it. The
1140
+ // probe is meaningless from inside a distro (and from another distro's
1141
+ // filesystem), so it reports that instead of guessing.
1142
+ if (process.platform === "win32") {
1143
+ const unc = `\\\\wsl.localhost\\${target}`;
1144
+ const readable = existsSync(unc);
1145
+ check("distro.unc", readable ? "ok" : "warn", "Windows share",
1146
+ readable ? `${unc} is readable from Windows` : `Windows cannot read ${unc} — the GUI file service, workspace picker and open-in-app use this share`,
1147
+ readable ? undefined : `wsl.exe --terminate ${target}, then retry; if it persists, check that the 9p/Plan9 service is not blocked by security software`);
1148
+ } else {
1149
+ check("distro.unc", "info", "Windows share", "only the Windows entry can test the \\\\wsl.localhost share (this doctor runs inside a distro)");
1109
1150
  }
1110
1151
 
1111
- const kernelAnswer = await probe("uname -r");
1112
- if (!kernelAnswer.ok && kernelAnswer.flaked) flakeCheck("distro.kernel", "Kernel", kernelAnswer);
1152
+ // ---- distro identity -----------------------------------------------------
1153
+ // The login shell and the home directory are one fact (the passwd entry)
1154
+ // and one probe: both are consumed by the executor's shell resolution and
1155
+ // the agent cache, and a broken entry fails both at once. The family probe
1156
+ // stays (the install remedy needs it) but no longer has a row of its own.
1157
+ let family = "unknown";
1158
+ const identityAnswer = await probe('s=$(getent passwd "$(id -u)" | cut -d: -f7); [ -n "$s" ] || s=$SHELL; printf "SH=%s\\nHM=%s\\n" "$s" "$HOME"');
1159
+ if (!identityAnswer.ok && identityAnswer.flaked) flakeCheck("distro.identity", "Login shell and home", identityAnswer);
1113
1160
  else {
1114
- const kernel = kernelAnswer.stdout.trim();
1115
- check("distro.kernel", "info", "Kernel", kernel.length > 0 ? kernel : "unreadable");
1161
+ const shell = /^SH=(.*)$/m.exec(identityAnswer.stdout)?.[1]?.trim() ?? "";
1162
+ const home = /^HM=(.*)$/m.exec(identityAnswer.stdout)?.[1]?.trim() ?? "";
1163
+ const shellOk = shell.startsWith("/");
1164
+ const homeOk = home.startsWith("/");
1165
+ if (shellOk && homeOk) check("distro.identity", "ok", "Login shell and home", `${shell}, ${home}`);
1166
+ 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)"`);
1116
1167
  }
1117
1168
 
1118
1169
  const familyAnswer = await probe(`for f in ${FAMILIES.join(" ")}; do command -v "$f" >/dev/null 2>&1 && { echo "$f"; exit 0; }; done; echo unknown`);
1119
- if (!familyAnswer.ok && familyAnswer.flaked) flakeCheck("distro.family", "Package family", familyAnswer);
1120
- else {
1121
- family = familyAnswer.stdout.trim();
1122
- check("distro.family", "info", "Package family", family.length > 0 ? family : "unknown");
1123
- }
1170
+ if (familyAnswer.ok) family = familyAnswer.stdout.trim();
1124
1171
 
1125
1172
  // ---- WSL mode ------------------------------------------------------------
1126
1173
  // WSL1 is a declared non-goal, but until now it failed unexplained: the
@@ -1160,12 +1207,22 @@ async function main(options) {
1160
1207
  }
1161
1208
 
1162
1209
  // ---- sandbox prerequisites ----------------------------------------------
1210
+ // Config-aware like the session rows: with `sandbox: false` on every row
1211
+ // AND `sessionSandbox: false`, nothing this plugin runs is confined, so a
1212
+ // missing bwrap is not a failure — but it is a security posture worth a
1213
+ // loud warning, not a silent `info`. The fence smoke is skipped with it.
1163
1214
  let bwrapUsable = false;
1164
1215
  let bwrapPath = "";
1216
+ const sandboxDisabled = effective.sandbox === "false" && effective.sessionSandbox === "false";
1165
1217
  const install = installRemedy(target, family);
1166
1218
  if (!want("sandbox")) {
1167
1219
  // sandbox section out of scope: bwrapPath stays "" and the fence smoke
1168
1220
  // below is skipped with it.
1221
+ } else if (sandboxDisabled) {
1222
+ check("sandbox.bwrap", "warn", "bubblewrap (sandbox disabled)",
1223
+ "the effective configuration disables confinement (sandbox: false on every row and sessionSandbox: false) — commands and writes run UNCONFINED; bubblewrap is not required",
1224
+ 'set sandbox: true on wsl-shell, wsl-fs and fs-routing (and sessionSandbox: true) to enforce the fence, then rerun the doctor');
1225
+ check("sandbox.bwrap-usable", "skipped", "bubblewrap usability", "skipped: the sandbox is disabled by configuration");
1169
1226
  } else {
1170
1227
  const bwrapAnswer = await probe("command -v bwrap");
1171
1228
  if (!bwrapAnswer.ok && bwrapAnswer.flaked) flakeCheck("sandbox.bwrap", "bubblewrap", bwrapAnswer);
@@ -1193,6 +1250,15 @@ async function main(options) {
1193
1250
  // always blocks, which is the invariant the verdict leans on.
1194
1251
  let runtimeSystemd = false;
1195
1252
  let systemdPid = "";
1253
+ /** The agent-cache inventory the fix loop consumes: entries and unusable ones. */
1254
+ let cacheEntries = 0;
1255
+ let cacheBad = 0;
1256
+ /** The first cached native binary that passed its own exec check. */
1257
+ let cacheExecPath = "";
1258
+ /** Whether this package ships a native agent for the distro's architecture. */
1259
+ let nativePackaged = false;
1260
+ /** Whether the effective config makes the native backend mandatory. */
1261
+ const nativeRequired = effective.agentBackend === "native";
1196
1262
  if (want("session")) {
1197
1263
  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');
1198
1264
  if (!systemd.ok && systemd.flaked) flakeCheck("session.systemd", "systemd as PID 1", systemd);
@@ -1238,6 +1304,12 @@ async function main(options) {
1238
1304
  const confFlaked = !confAnswer.ok && confAnswer.flaked;
1239
1305
  const conf = parseIni(confAnswer.stdout);
1240
1306
  const noConf = confAnswer.stdout.trim().length === 0;
1307
+ const automountEnabled = ((noConf ? undefined : conf.automount?.enabled) ?? "").trim().toLowerCase();
1308
+ const automountRoot = ((noConf ? undefined : conf.automount?.root) ?? "").trim();
1309
+ /** Where the distro mounts Windows drives; the host->distro translation uses it. */
1310
+ const mountRoot = automountRoot.length > 0 ? automountRoot : "/mnt";
1311
+ /** The shell agent as the distro sees it; undefined when it cannot be reached from there. */
1312
+ const agentScriptDistro = automountEnabled === "false" ? undefined : distroPath(agentScript, mountRoot);
1241
1313
  const confWanted = want("session") || want("conf");
1242
1314
  if (!confWanted) {
1243
1315
  // Scoped run: neither the boot cross-check nor the interop/automount
@@ -1266,19 +1338,29 @@ async function main(options) {
1266
1338
  const interopEnabled = ((noConf ? undefined : conf.interop?.enabled) ?? "").trim().toLowerCase();
1267
1339
  if (!want("conf")) {
1268
1340
  // interop/automount rows out of scope
1269
- } else if (interopEnabled === "false") {
1270
- const binfmtProbe = await probe("[ -e /proc/sys/fs/binfmt_misc/WSLInterop ] && printf yes || printf no");
1271
- const binfmt = binfmtProbe.ok && !binfmtProbe.flaked ? binfmtProbe.stdout.trim() : "unreadable";
1272
- 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)" : binfmt === "unreadable" ? " (the binfmt cross-check flaked — treat the stale-boot note as unverified)" : ""} — 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}`);
1273
1341
  } else {
1274
- const appendWindowsPath = ((noConf ? undefined : conf.interop?.appendWindowsPath) ?? "").trim().toLowerCase();
1275
- check("distro.wsl-conf-interop", "ok", "/etc/wsl.conf [interop]", noConf
1276
- ? "no /etc/wsl.conf — interop on (the default)"
1277
- : `enabled=${interopEnabled || "true (the default)"}${appendWindowsPath === "false" ? "; appendWindowsPath=false (Windows PATH not appended — Windows tools need full paths)" : ""}`);
1342
+ // The binfmt handler is the runtime fact behind the conf value: a conf
1343
+ // that says enabled while the handler is absent is a stale boot (or a
1344
+ // /proc that was not mounted), and every Windows-tool path — git.exe,
1345
+ // explorer.exe, the cmd.exe probes — fails with a confusing command-not-
1346
+ // found instead of naming interop. Probe it in BOTH directions.
1347
+ const binfmtProbe = await probe("[ -e /proc/sys/fs/binfmt_misc/WSLInterop ] && printf yes || printf no");
1348
+ if (!binfmtProbe.ok && binfmtProbe.flaked) flakeCheck("distro.wsl-conf-interop", "/etc/wsl.conf [interop]", binfmtProbe);
1349
+ else {
1350
+ const binfmt = binfmtProbe.ok ? binfmtProbe.stdout.trim() : "unreadable";
1351
+ if (interopEnabled === "false") {
1352
+ 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}`);
1353
+ } else if (binfmt === "no") {
1354
+ check("distro.wsl-conf-interop", "warn", "/etc/wsl.conf [interop]", `interop is enabled${noConf ? " (the default)" : " in wsl.conf"} but the WSLInterop handler is not registered — a stale boot, or /proc/sys/fs/binfmt_misc was not mounted; Windows git, open-in-app and the cmd.exe probes fail from this distro`, `wsl.exe --terminate ${target}; if it persists, check that /proc/sys/fs/binfmt_misc is mounted (WSL mounts it at boot)`);
1355
+ } else {
1356
+ const appendWindowsPath = ((noConf ? undefined : conf.interop?.appendWindowsPath) ?? "").trim().toLowerCase();
1357
+ check("distro.wsl-conf-interop", "ok", "/etc/wsl.conf [interop]", noConf
1358
+ ? "no /etc/wsl.conf — interop on (the default), and the WSLInterop handler is registered"
1359
+ : `enabled=${interopEnabled || "true (the default)"}, the WSLInterop handler is registered${appendWindowsPath === "false" ? "; appendWindowsPath=false (Windows PATH not appended — Windows tools need full paths)" : ""}`);
1360
+ }
1361
+ }
1278
1362
  }
1279
1363
 
1280
- const automountEnabled = ((noConf ? undefined : conf.automount?.enabled) ?? "").trim().toLowerCase();
1281
- const automountRoot = ((noConf ? undefined : conf.automount?.root) ?? "").trim();
1282
1364
  if (!want("conf")) {
1283
1365
  // automount row out of scope
1284
1366
  } else if (automountEnabled === "false") {
@@ -1335,16 +1417,23 @@ async function main(options) {
1335
1417
  }
1336
1418
 
1337
1419
  // ---- optional tools ------------------------------------------------------
1338
- /** The optional tools, in the order users notice them losing. */
1339
- /** @type {Array<[string, string]>} */
1340
- const optionalTools = [["rg", "in-distro search"], ["git", "workspace-change baselines"], ["inotifywait", "the watcher's primary backend"]];
1341
- for (const [tool, purpose] of optionalTools) {
1342
- const toolAnswer = await probe(`command -v ${tool}`);
1343
- if (!toolAnswer.ok && toolAnswer.flaked) flakeCheck(`tools.${tool}`, tool, toolAnswer);
1344
- else {
1345
- const found = toolAnswer.stdout.trim();
1346
- if (found.length > 0) check(`tools.${tool}`, "ok", tool, found);
1347
- else check(`tools.${tool}`, "warn", tool, `missing; ${purpose} degrades to a slower fallback`, install);
1420
+ // Feature-degradation warnings, not first-command prerequisites: the quick
1421
+ // profile skips them (three process spawns a distro) and the full run names
1422
+ // what each missing tool costs. None is a fallback-free break — a missing
1423
+ // rg still leaves the model bash grep, a missing git still leaves
1424
+ // file-tool edits, a missing inotifywait still polls.
1425
+ if (!quick) {
1426
+ /** The optional tools, in the order users notice them losing. */
1427
+ /** @type {Array<[string, string]>} */
1428
+ const optionalTools = [["rg", "the fs-search tool needs rg; 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"]];
1429
+ for (const [tool, cost] of optionalTools) {
1430
+ const toolAnswer = await probe(`command -v ${tool}`);
1431
+ if (!toolAnswer.ok && toolAnswer.flaked) flakeCheck(`tools.${tool}`, tool, toolAnswer);
1432
+ else {
1433
+ const found = toolAnswer.stdout.trim();
1434
+ if (found.length > 0) check(`tools.${tool}`, "ok", tool, found);
1435
+ else check(`tools.${tool}`, "warn", tool, `missing; ${cost}`, install);
1436
+ }
1348
1437
  }
1349
1438
  }
1350
1439
 
@@ -1353,15 +1442,25 @@ async function main(options) {
1353
1442
  // cache inventory, handshake, resident smokes). A scoped run without it
1354
1443
  // (quick included) stops after the session rows.
1355
1444
  if (want("agent")) {
1445
+ // The native backend is preferred by `auto` and required by `native`; the
1446
+ // check is config-aware because the consequence differs: a missing or
1447
+ // unrunnable binary degrades to the shell agent under `auto`, but fails
1448
+ // the first command (and every file operation) under `native`.
1356
1449
  const archAnswer = await probe("uname -m");
1357
- if (!archAnswer.ok && archAnswer.flaked) flakeCheck("agent.arch", "Distro architecture", archAnswer);
1450
+ if (!archAnswer.ok && archAnswer.flaked) flakeCheck("agent.native", "Native agent", archAnswer);
1358
1451
  else {
1359
1452
  const arch = archAnswer.stdout.trim();
1360
1453
  const packaged = ["x86_64", "aarch64"].includes(arch) ? join(ROOT, "agent", "native", `linux-${arch}`, "dsh-wsl-agent") : "";
1361
- if (arch.length === 0) check("agent.arch", "info", "Distro architecture", "unreadable");
1362
- else if (packaged.length === 0) check("agent.arch", "info", "Distro architecture", `${arch} has no packaged native agent; the shell agent is the only backend`);
1363
- else if (existsSync(packaged)) check("agent.native", "ok", "Packaged native agent", packaged.slice(ROOT.length + 1));
1364
- else check("agent.native", "warn", "Packaged native agent", `missing for ${arch}`, "reinstall the plugin (the binaries ship with the package), or use agentBackend: shell");
1454
+ if (arch === "") {
1455
+ 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);
1456
+ } else if (packaged === "") {
1457
+ check("agent.native", nativeRequired ? "fail" : "info", "Native agent", `${arch} has no packaged native agent; only the shell agent can serve this distro`, nativeRequired ? "use agentBackend: auto (falls back to the shell agent) or shell" : undefined);
1458
+ } else if (existsSync(packaged)) {
1459
+ nativePackaged = true;
1460
+ check("agent.native", "ok", "Native agent", `${packaged.slice(ROOT.length + 1)} for ${arch}${effective.agentBackend === "shell" ? " (agentBackend: shell does not use it)" : ""}`);
1461
+ } else {
1462
+ check("agent.native", nativeRequired ? "fail" : effective.agentBackend === "shell" ? "info" : "warn", "Native agent", `missing for ${arch}${effective.agentBackend === "shell" ? "; agentBackend: shell does not use it" : ""}`, "reinstall the plugin (the binaries ship with the package), or use agentBackend: auto/shell");
1463
+ }
1365
1464
  }
1366
1465
 
1367
1466
  const cacheAnswer = await probe(CACHE_REPORT);
@@ -1371,10 +1470,30 @@ async function main(options) {
1371
1470
  if (cache === "none" || cache.length === 0) check("agent.cache", "info", "Agent cache", "empty (a first command populates it)");
1372
1471
  else {
1373
1472
  const entries = cache.split(/\r?\n/).filter((line) => line.trim().length > 0);
1374
- const bad = entries.filter((line) => line.startsWith("noexec ")).length;
1375
- check("agent.cache", bad > 0 ? "warn" : "ok", "Agent cache", `${entries.length} cached binary(ies)${bad > 0 ? `, ${bad} not executable` : ""}`, bad > 0 ? `rm -rf ~/.cache/dsh-wsl/agent inside "${target}"; the next command repopulates it` : undefined);
1473
+ const bad = entries.filter((line) => line.startsWith("noexec ") || line.startsWith("broken ")).length;
1474
+ cacheEntries = entries.length;
1475
+ cacheBad = bad;
1476
+ cacheExecPath = entries.find((line) => line.startsWith("exec "))?.slice("exec ".length).trim() ?? "";
1477
+ const badNote = bad > 0 ? `, ${bad} not executable or not runnable` : "";
1478
+ const cacheTone = bad === 0 ? "ok" : nativeRequired ? "fail" : effective.agentBackend === "shell" ? "info" : "warn";
1479
+ check("agent.cache", cacheTone, "Agent cache", `${entries.length} cached binary(ies)${badNote}${bad > 0 && effective.agentBackend === "shell" ? " (agentBackend: shell does not use the cache)" : ""}`, bad > 0 ? `rm -rf ~/.cache/dsh-wsl/agent inside "${target}"; the next command repopulates it` : undefined);
1376
1480
  }
1377
1481
  }
1482
+
1483
+ // ---- home writability and execution -------------------------------------
1484
+ // The native agent is streamed into `$HOME/.cache/dsh-wsl/agent` and
1485
+ // executed from there; a read-only home, or a home on a `noexec` mount
1486
+ // (DrvFs when HOME points at /mnt/c), breaks that before any command runs.
1487
+ // One temp dir answers both facts and is removed again.
1488
+ 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"');
1489
+ if (!homeProbe.ok && homeProbe.flaked) flakeCheck("agent.home-writable", "Home writability", homeProbe);
1490
+ else {
1491
+ const homeState = homeProbe.stdout.trim();
1492
+ const homeTone = (/** @type {"fail" | "warn" | "info"} */ tone) => nativeRequired ? "fail" : effective.agentBackend === "shell" ? "info" : tone;
1493
+ 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)");
1494
+ 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");
1495
+ else check("agent.home-writable", homeTone("warn"), "Home writability", `a temp dir under $HOME could not be created — the native agent cache cannot be extracted${effective.agentBackend === "shell" ? "; agentBackend: shell does not need it" : "; auto falls back to the shell agent"}`, "make $HOME writable (it is a read-only mount, or the user's entry is wrong), or use agentBackend: shell");
1496
+ }
1378
1497
  }
1379
1498
 
1380
1499
  // ---- session scopes (section: session) ------------------------------------
@@ -1386,6 +1505,8 @@ async function main(options) {
1386
1505
  let scopeLines = [];
1387
1506
  /** ok | fail | info — the handshake state the smoke legs read. */
1388
1507
  let handshakeState = "info";
1508
+ /** The shell-agent smoke, kept so the native legs can say whether the fallback works. */
1509
+ let shellSmoke = /** @type {{ execOk: boolean, fsOk: boolean } | undefined} */ (undefined);
1389
1510
  if (scopesAnswer !== undefined && !scopesAnswer.ok && scopesAnswer.flaked) flakeCheck("runtime.scopes", "Session scopes", scopesAnswer);
1390
1511
  else if (scopesAnswer !== undefined) {
1391
1512
  const scopes = scopesAnswer.stdout.trim();
@@ -1399,25 +1520,24 @@ async function main(options) {
1399
1520
  }
1400
1521
 
1401
1522
  // ---- resident handshake (section: agent) ----------------------------------
1402
- const agentScript = join(ROOT, "agent", "wsl-agent.sh");
1403
1523
  /** ok | fail | info — the legs skip with a story that matches. */
1404
1524
  handshakeState = "info";
1405
1525
  if (!want("agent")) {
1406
1526
  // agent section out of scope: no handshake, no resident smokes.
1407
- } else if (!agentScript.startsWith("/")) {
1408
- check("agent.handshake", "info", "Agent handshake", "skipped: run the doctor from inside the distro (the script path is a Windows path)");
1409
1527
  } else if (!existsSync(agentScript)) {
1410
1528
  check("agent.handshake", "fail", "Agent handshake", "agent/wsl-agent.sh is missing from this install", "reinstall the plugin; the shell agent ships with the package");
1411
1529
  handshakeState = "fail";
1530
+ } else if (agentScriptDistro === undefined) {
1531
+ check("agent.handshake", "info", "Agent handshake", `skipped: the package root (${ROOT}) has no path inside "${target}" — ${automountEnabled === "false" ? "automount is disabled in /etc/wsl.conf, so Windows drives are not mounted there" : "run the doctor from Windows or from inside the target"}`);
1412
1532
  } else {
1413
1533
  // The script is a Linux path in the checkout's OWN distro; another
1414
1534
  // distro cannot read it, and "exited before its HELLO" would be a
1415
1535
  // lie about a broken install. Probe readability first, honestly.
1416
- const readable = (await inDistro(target, `[ -f "${agentScript}" ] && printf yes || printf no`)).stdout.trim() === "yes";
1536
+ const readable = (await inDistro(target, `[ -f "${agentScriptDistro}" ] && printf yes || printf no`)).stdout.trim() === "yes";
1417
1537
  if (!readable) {
1418
- check("agent.handshake", "info", "Agent handshake", `skipped: agent/wsl-agent.sh is not readable inside "${target}" — this doctor runs from the ${(process.env.WSL_DISTRO_NAME ?? "host")} filesystem; run it from Windows (the deployed layout reads the \\mnt\\c mirror) or inside "${target}"`);
1538
+ 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}"`);
1419
1539
  } else {
1420
- const handshake = await probeResident(target, agentScript, wslExe);
1540
+ const handshake = await probeResident(target, agentScriptDistro, wslExe, agentScript);
1421
1541
  handshakeState = handshake.ok && handshake.digestMatches ? "ok" : "fail";
1422
1542
  if (handshake.ok) {
1423
1543
  const live = livePids.length > 0
@@ -1446,7 +1566,7 @@ async function main(options) {
1446
1566
  // prerequisite failed is `skipped` with the blocker named — absence is
1447
1567
  // never silent, and a skipped leg never blocks (its blocker already does).
1448
1568
  const residentBlocked = handshakeState !== "ok";
1449
- const sandboxBlocked = bwrapPath.length === 0 || !bwrapUsable;
1569
+ const sandboxBlocked = !sandboxDisabled && (bwrapPath.length === 0 || !bwrapUsable);
1450
1570
  const residentBlocker = handshakeState === "fail" ? "blocked by agent.handshake" : "the handshake could not run in this distro";
1451
1571
  // A quick run skips both smokes — their worth is the deep verdict, and
1452
1572
  // the quick profile's promise is a fast prerequisite answer.
@@ -1462,16 +1582,65 @@ async function main(options) {
1462
1582
  // can kill an otherwise healthy chain, and a smoke `fail` is the most
1463
1583
  // alarming row the report can carry — it must not rest on one flaked
1464
1584
  // transport.
1465
- let smoke = await runSmokeLegs(target, agentScript, wslExe);
1585
+ let smoke = await runSmokeLegs(target, ["sh", agentScriptDistro ?? ""], wslExe);
1466
1586
  if (!smoke.execOk || !smoke.fsOk) {
1467
1587
  await new Promise((resolve) => setTimeout(resolve, FLAKE_SETTLE_MS));
1468
- smoke = await runSmokeLegs(target, agentScript, wslExe);
1588
+ smoke = await runSmokeLegs(target, ["sh", agentScriptDistro ?? ""], wslExe);
1589
+ }
1590
+ // The shell agent is the fallback once `auto` can use the native binary
1591
+ // (and the only path under `agentBackend: shell`). A BusyBox distro
1592
+ // without GNU findures breaks the fallback's FSB enumeration, not the
1593
+ // selected path — so it warns with the real cause instead of blocking.
1594
+ const shellFallback = effective.agentBackend !== "shell" && nativePackaged;
1595
+ const shellTone = shellFallback ? "warn" : "fail";
1596
+ const fallbackNote = shellFallback ? ` (the shell agent is the fallback; agentBackend: ${effective.agentBackend} runs the native agent)` : "";
1597
+ const findutilsHint = smoke.fsError !== undefined && /find: unrecognized: -printf|BusyBox/i.test(smoke.fsError.message)
1598
+ ? `the shell agent needs GNU findutils (BusyBox find lacks -printf): wsl.exe -d ${target} -u root -- ${FINDUTILS[family] ?? FINDUTILS["apt-get"]}; or set agentBackend: auto/native`
1599
+ : "restart the DSH app; if it persists, delete ~/.cache/dsh-wsl/agent inside the distro and rerun the doctor";
1600
+ shellSmoke = smoke;
1601
+ check("functional.exec", smoke.execOk ? "ok" : shellTone, "Smoke: EXEC", `shell agent: ${smoke.execDetail}${smoke.execOk ? "" : fallbackNote}`, smoke.execOk ? undefined : "restart the DSH app; if it persists, delete ~/.cache/dsh-wsl/agent inside the distro and rerun the doctor");
1602
+ check("functional.fs", smoke.fsOk ? "ok" : shellTone, "Smoke: FSB batch", `shell agent: ${smoke.fsDetail}${smoke.fsOk ? "" : fallbackNote}`, smoke.fsOk ? undefined : findutilsHint);
1603
+ }
1604
+
1605
+ // ---- native smoke (section: agent) ---------------------------------------
1606
+ // The legs above prove the SHELL agent; `auto` prefers the native binary,
1607
+ // so the binary the session will actually exec runs the SAME chain here:
1608
+ // HELLO, one EXEC round trip, one FSB batch. The cache directory is named
1609
+ // after the binary's sha256, so the HELLO self-digest binds the running
1610
+ // process to the cache entry without reading the bytes again. A fresh
1611
+ // machine has no cache yet (the first command extracts one), and `shell`
1612
+ // never uses it.
1613
+ if (!residentSmokeWanted) {
1614
+ // out of scope (quick runs skip it too)
1615
+ } else if (effective.agentBackend === "shell") {
1616
+ check("functional.native", "skipped", "Smoke: native agent", "skipped: agentBackend: shell");
1617
+ } else if (cacheExecPath === "") {
1618
+ check("functional.native", "skipped", "Smoke: native agent", "skipped: no executable native binary in ~/.cache/dsh-wsl/agent yet — the first command extracts one");
1619
+ } else {
1620
+ const cachedDigest = cacheExecPath.split("/").slice(-2)[0] ?? "";
1621
+ let native = await runSmokeLegs(target, [cacheExecPath], wslExe, cachedDigest);
1622
+ if (!native.execOk || !native.fsOk) {
1623
+ await new Promise((resolve) => setTimeout(resolve, FLAKE_SETTLE_MS));
1624
+ native = await runSmokeLegs(target, [cacheExecPath], wslExe, cachedDigest);
1625
+ }
1626
+ const nativeOk = native.execOk && native.fsOk && native.digestMatches;
1627
+ // `auto` falls back to the shell agent, so a native failure alone is a
1628
+ // warning — unless the fallback fails too (then neither backend serves
1629
+ // the session) or the backend is pinned.
1630
+ const shellWorks = shellSmoke !== undefined && shellSmoke.execOk && shellSmoke.fsOk;
1631
+ if (nativeOk) {
1632
+ check("functional.native", "ok", "Smoke: native agent", `native agent: ${native.execDetail}; ${native.fsDetail}`);
1633
+ } else if (!native.digestMatches) {
1634
+ check("functional.native", nativeRequired ? "fail" : "warn", "Smoke: native agent", "native agent: the HELLO self-digest does not match the cache directory — the entry is stale or corrupt", "purge ~/.cache/dsh-wsl/agent inside the distro; the next command re-extracts it");
1635
+ } else {
1636
+ const nativeTone = nativeRequired || (effective.agentBackend === "auto" && !shellWorks) ? "fail" : "warn";
1637
+ check("functional.native", nativeTone, "Smoke: native agent", `native agent: ${native.execDetail}; ${native.fsDetail}${nativeTone === "fail" && !nativeRequired ? " (the shell fallback failed too — neither backend answers the chain)" : ""}`, nativeTone === "fail" ? "agentBackend: native cannot fall back; use auto/shell, or reinstall the plugin" : "auto falls back to the shell agent; purge ~/.cache/dsh-wsl/agent to re-extract");
1469
1638
  }
1470
- check("functional.exec", smoke.execOk ? "ok" : "fail", "Smoke: EXEC", smoke.execDetail, smoke.execOk ? undefined : "restart the DSH app; if it persists, delete ~/.cache/dsh-wsl/agent inside the distro and rerun the doctor");
1471
- check("functional.fs", smoke.fsOk ? "ok" : "fail", "Smoke: FSB batch", smoke.fsDetail, smoke.fsOk ? undefined : "restart the DSH app; if it persists, delete ~/.cache/dsh-wsl/agent inside the distro and rerun the doctor");
1472
1639
  }
1473
1640
  if (!sandboxSmokeWanted) {
1474
1641
  // fence smoke out of scope (or quick)
1642
+ } else if (sandboxDisabled) {
1643
+ check("functional.sandbox", "skipped", "Smoke: confined profile", "skipped: the sandbox is disabled by configuration");
1475
1644
  } else if (sandboxBlocked) {
1476
1645
  check("functional.sandbox", "skipped", "Smoke: confined profile", `skipped: blocked by ${bwrapPath.length === 0 ? "sandbox.bwrap" : "sandbox.bwrap-usable"}`);
1477
1646
  } else {
@@ -1484,11 +1653,11 @@ async function main(options) {
1484
1653
  else check("functional.sandbox", sandbox.ok ? "ok" : "fail", "Smoke: confined profile", sandbox.detail, sandbox.ok ? undefined : "the shipped profile refused a write it must allow, or allowed one it must refuse — see docs/LIMITATIONS.md and pnpm run probe:sandbox");
1485
1654
  }
1486
1655
 
1487
- return { checks: collected, reachable: true, bwrapPath, stale, family };
1656
+ return { checks: collected, reachable: true, bwrapPath, stale, cacheEntries, cacheBad, cacheExecPath, family, agentScriptDistro };
1488
1657
  };
1489
1658
 
1490
1659
  phase("target");
1491
- /** @type {Map<string, { checks: Check[], reachable: boolean, bwrapPath: string, stale: number, family: string }>} */
1660
+ /** @type {Map<string, { checks: Check[], reachable: boolean, bwrapPath: string, stale: number, cacheEntries: number, cacheBad: number, cacheExecPath: string, family: string, agentScriptDistro: string | undefined }>} */
1492
1661
  const states = new Map();
1493
1662
  const outcomes = await mapWithConcurrency(targets, DISTRO_CONCURRENCY, async (target) => {
1494
1663
  const distroStart = Date.now();
@@ -1609,39 +1778,18 @@ async function main(options) {
1609
1778
  else check("peers.versions", "fail", "Peer versions", badPeers.join("; "), "install the peer set this plugin pins (pnpm install in the plugin, or reinstall/upgrade it against this harness); see docs/PEER-PARITY.md");
1610
1779
 
1611
1780
  phase("surveys");
1612
- // ---- update check ----------------------------------------------------------
1613
- // The same question the app's Versions page asks, answered on demand: the
1614
- // stable channel's newest release against this checkout's version. A
1615
- // registry the doctor cannot reach is normal (offline, a proxy), so it
1616
- // reports as `info` and points at the page that asks it live — never a
1617
- // warning, and never a network side effect beyond the two GETs. The quick
1618
- // profile skips it: no network on the fast path.
1619
- const installedVersion = manifest.version ?? "";
1620
- const latest = !quick && installedVersion.length > 0 ? await fetchLatestRelease() : undefined;
1621
- if (quick) {
1622
- // quick profile: no update row at all — the registry stays untouched.
1623
- } else if (latest === undefined) {
1624
- check("update.latest", "info", "Update check", "the registry was unreachable (offline, or a proxy is in the way); the app's Versions page asks the same question live");
1625
- } else if (compareVersions(latest.version, installedVersion) > 0) {
1626
- const message = updateFactMessage({ installed: installedVersion, latest: latest.version, incompatible: false, ...(latest.deprecated === undefined ? {} : { deprecated: latest.deprecated }), checkedAt: 0 });
1627
- check("update.latest", "info", "Update check", `${message} (from ${latest.registry})`, "the app's Plugins page, Versions section, or `dsh plugin --profile <name> add dsh-plugin-wsl-env`, then restart DSH");
1628
- } else {
1629
- check("update.latest", "ok", "Update check", `${installedVersion} is the newest stable release`);
1630
- }
1631
-
1632
1781
  // ---- effective configuration (verdict inputs, reported) ------------------
1633
1782
  check("config.effective", configRecognized ? "ok" : "info", "Effective configuration",
1634
1783
  configRecognized
1635
1784
  ? `distro=${effective.distro}, sessionSandbox=${effective.sessionSandbox}, agentBackend=${effective.agentBackend}, sandbox=${effective.sandbox}, maskWindowsDrive=${effective.maskWindowsDrive}, interopVisibility=${effective.interopVisibility || "unset"} — from ${effective.source}${effective.overrides.length > 0 ? ` (overrides: ${effective.overrides.join("; ")})` : ""}`
1636
1785
  : "the shipped preset rows were not recognized; the conservative defaults apply (sessionSandbox: true, so a missing systemd blocks) — see docs/CONFIGURATION.md");
1637
1786
 
1638
- phase("update-peers");
1787
+ phase("profiles");
1639
1788
  // ---- profile-patch trap and deprecated keys ------------------------------
1640
1789
  const dshHome = process.env.DSH_HOME !== undefined && process.env.DSH_HOME.length > 0 ? process.env.DSH_HOME : join(homedir(), ".dsh");
1641
1790
  const profilesDir = join(dshHome, "profiles");
1642
1791
  if (!existsSync(profilesDir)) {
1643
- check("config.profiles", "info", "Profile patches", `no profiles under ${profilesDir}`);
1644
- check("config.deprecated", "info", "Deprecated keys", "no profile layers to scan");
1792
+ check("config.deprecated", "info", "Deprecated keys", `no profile layers under ${profilesDir} to scan`);
1645
1793
  } else {
1646
1794
  /** @type {string[]} */
1647
1795
  const trapped = [];
@@ -1656,17 +1804,21 @@ async function main(options) {
1656
1804
  if (!existsSync(patch)) continue;
1657
1805
  seen += 1;
1658
1806
  const text = readFileSync(patch, "utf8");
1659
- if (/^\s*-\s*id:\s*(wsl-shell|wsl-fs)\s*$/m.test(text)) trapped.push(entry.name);
1807
+ // Only a ROOT-level `- id:` entry is a patch by id. An entry indented
1808
+ // under `insert:` adds a real top-level row (the probe profiles do
1809
+ // exactly that), so matching it would warn about a patch that is not
1810
+ // there.
1811
+ if (/^-\s*id:\s*(wsl-shell|wsl-fs)\s*(?:#.*)?$/m.test(text)) trapped.push(entry.name);
1660
1812
  if (/substrate:\s*["']?share["']?/m.test(text)) retired.push(entry.name);
1661
1813
  if (/^\s*distro:\s*['"]['"]\s*$/m.test(text)) emptyDistro.push(entry.name);
1662
1814
  }
1663
1815
  if (trapped.length > 0) {
1664
- check("config.preset-trap", "warn", "Profile patches", `nested rows patched by id in: ${trapped.join(", ")}`, "wsl-shell and wsl-fs live inside preset-wsl; an id patch matches nothing and is ignored with a warning. Run \"pnpm run preset --check <patch>\" to get the complete block, or see docs/CONFIGURATION.md#configure-wsl-shell-and-wsl-fs");
1665
- } else {
1666
- check("config.profiles", "ok", "Profile patches", `${seen} profile patch(es) scanned`);
1816
+ check("config.preset-trap", "warn", "Nested row patches",
1817
+ `root-level id patch for a nested row in: ${trapped.join(", ")} — the wsl-shell / wsl-fs entry matches no top-level row and is ignored`,
1818
+ 'those names are profile directories; to add these providers at the top level use "- insert:", and to change the preset\'s nested rows replace the whole preset-wsl row. Run "pnpm run preset --check <patch>" for the complete block, or see docs/CONFIGURATION.md#configure-wsl-shell-and-wsl-fs');
1667
1819
  }
1668
1820
  if (retired.length > 0) {
1669
- check("config.deprecated", "warn", "Deprecated keys", `substrate: share in ${retired.join(", ")} — the plugin refuses to boot this profile, because serving the 9p share is exactly what it must not do`, "delete the substrate line (the agent substrate is the only shape), then restart the session — docs/MIGRATION.md#keeping-the-old-spelling");
1821
+ check("config.deprecated", "fail", "Deprecated keys", `substrate: share in ${retired.join(", ")} — the plugin refuses to boot this profile, because serving the 9p share is exactly what it must not do`, "delete the substrate line (the agent substrate is the only shape), then restart the session — docs/MIGRATION.md#keeping-the-old-spelling");
1670
1822
  } else if (emptyDistro.length > 0) {
1671
1823
  check("config.deprecated", "info", "Deprecated keys", `distro: '' in ${emptyDistro.join(", ")} — empty has meant auto (follow the workspace) since 0.12.0, not WSL's default`, `pin distro: default on both rows to keep the old posture — docs/MIGRATION.md#case-study-distro-0120`);
1672
1824
  } else {
@@ -1676,8 +1828,10 @@ async function main(options) {
1676
1828
 
1677
1829
  phase("config");
1678
1830
  // ---- fixes (the loop ends in a re-verified report) ------------------------
1679
- // Safe actions only, per target: the sweep the session preflight runs, and
1680
- // package installation behind --install plus an explicit confirmation. Every
1831
+ // Safe, reversible actions only, per target: the sweep the session preflight
1832
+ // runs, a purge of the plugin-owned agent cache, and — outside
1833
+ // `--fix-owned` — package installation behind --install plus an explicit
1834
+ // confirmation and the Windows git whitelist behind the same gate. Every
1681
1835
  // fix is followed by a fresh probe of what it claims to have fixed — the
1682
1836
  // revised check carries the after state (so the verdict at the end is the
1683
1837
  // post-fix verdict, ready or the remaining blockers), and the fix.* row
@@ -1717,7 +1871,37 @@ async function main(options) {
1717
1871
  ? { status: "info", detail: "none (the fix above swept them)", remedy: undefined }
1718
1872
  : { 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" });
1719
1873
  }
1720
- if (state.bwrapPath.length === 0) {
1874
+ if (state.cacheBad > 0) {
1875
+ // The cache is plugin-owned and content-addressed: every entry is
1876
+ // re-extracted from the shipped agent on the next command, so purging
1877
+ // it is safe and reversible. The after-state is a fresh inventory, and
1878
+ // a failed handshake is re-probed because a corrupt cache is one of its
1879
+ // causes.
1880
+ const purged = await inDistro(target, 'rm -rf "$HOME/.cache/dsh-wsl/agent"');
1881
+ const afterRaw = (await inDistro(target, CACHE_REPORT)).stdout.trim();
1882
+ const afterLines = afterRaw === "none" || afterRaw.length === 0 ? [] : afterRaw.split(/\r?\n/).filter((line) => line.trim().length > 0);
1883
+ const afterBad = afterLines.filter((line) => line.startsWith("noexec ") || line.startsWith("broken ")).length;
1884
+ const fixed = purged.ok && afterBad === 0;
1885
+ const cacheTone = fixed ? "ok" : effective.agentBackend === "native" ? "fail" : "warn";
1886
+ fixCheck("fix.cache", fixed ? "ok" : "warn", "Purged the agent cache",
1887
+ `${state.cacheEntries} cached, ${state.cacheBad} invalid before → ${afterLines.length} cached, ${afterBad} invalid after`,
1888
+ fixed ? undefined : `rm -rf ~/.cache/dsh-wsl/agent inside "${target}"; the next command repopulates it`);
1889
+ reviseCheck("agent.cache", target, afterLines.length === 0
1890
+ ? { status: cacheTone === "ok" ? "info" : cacheTone, detail: "empty after the fix (the next command repopulates it)", remedy: undefined }
1891
+ : { 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` });
1892
+ const handshakeEntry = checks.find((entry) => entry.id === "agent.handshake" && entry.distro === target);
1893
+ const scriptPath = state.agentScriptDistro;
1894
+ const scriptProbe = scriptPath !== undefined && existsSync(join(ROOT, "agent", "wsl-agent.sh"))
1895
+ ? (await inDistro(target, `[ -f "${scriptPath}" ] && printf yes || printf no`)).stdout.trim()
1896
+ : "no";
1897
+ if (handshakeEntry !== undefined && handshakeEntry.status === "fail" && scriptProbe === "yes" && scriptPath !== undefined) {
1898
+ const again = await probeResident(target, scriptPath, wslExe, join(ROOT, "agent", "wsl-agent.sh"));
1899
+ reviseCheck("agent.handshake", target, again.ok && again.digestMatches
1900
+ ? { status: "ok", detail: `re-probed after the cache purge: pid ${again.pid}, protocol ${PROTOCOL_VERSION}, digest matches`, remedy: undefined }
1901
+ : { detail: `re-probed after the cache purge: ${again.ok ? "digest MISMATCH — the distro reads a different script than this package" : again.detail}` });
1902
+ }
1903
+ }
1904
+ if (state.bwrapPath.length === 0 && !options.fixOwned) {
1721
1905
  const install = installRemedy(target, state.family);
1722
1906
  if (!options.install) {
1723
1907
  fixCheck("fix.install", "info", "Package installation", "not attempted", "re-run with --fix --install (and --yes for a non-interactive run)");
@@ -1743,8 +1927,9 @@ async function main(options) {
1743
1927
  }
1744
1928
  // B3: the Windows git whitelist is user-scoped and reversible — the same
1745
1929
  // confirmation gate as a package install, then a fresh probe. Without a
1746
- // TTY the fix declines loudly instead of silently doing nothing.
1747
- if (winGitOk) {
1930
+ // TTY the fix declines loudly instead of silently doing nothing. A
1931
+ // `--fix-owned` run leaves Windows-owned state alone.
1932
+ if (winGitOk && !options.fixOwned) {
1748
1933
  const gitEntry = checks.find((entry) => entry.id === "git.win-safe");
1749
1934
  if (gitEntry !== undefined && gitEntry.status === "warn") {
1750
1935
  if (await confirm('Add "//wsl.localhost/*" to the Windows git safe.directory whitelist?', options.yes)) {
@@ -1774,9 +1959,11 @@ async function main(options) {
1774
1959
  *
1775
1960
  * @param {string} distro - the distro to probe.
1776
1961
  * @param {string} scriptPath - the agent script as a Linux path inside the distro.
1962
+ * @param {string} [wslExe] - the wsl.exe to spawn.
1963
+ * @param {string} [hostPath] - the same script as this host names it, for the digest (defaults to scriptPath).
1777
1964
  * @returns {Promise<{ ok: true, pid: number, digestMatches: boolean } | { ok: false, detail: string }>} the verdict, with the pid on success.
1778
1965
  */
1779
- function probeResident(distro, scriptPath, wslExe = WSL) {
1966
+ function probeResident(distro, scriptPath, wslExe = WSL, hostPath = scriptPath) {
1780
1967
  return new Promise((settle) => {
1781
1968
  let settled = false;
1782
1969
  /** @param {{ ok: true, pid: number, digestMatches: boolean } | { ok: false, detail: string }} value - the verdict. */
@@ -1808,7 +1995,7 @@ function probeResident(distro, scriptPath, wslExe = WSL) {
1808
1995
  finish({ ok: false, detail: `protocol ${version}, expected ${PROTOCOL_VERSION}` });
1809
1996
  return;
1810
1997
  }
1811
- const expected = createHash("sha256").update(readFileSync(scriptPath)).digest("hex");
1998
+ const expected = createHash("sha256").update(readFileSync(hostPath)).digest("hex");
1812
1999
  finish({ ok: true, pid: Number(pid), digestMatches: digest === expected });
1813
2000
  });
1814
2001
  child.on("error", (error) => finish({ ok: false, detail: error.message }));
@@ -1822,7 +2009,7 @@ function probeResident(distro, scriptPath, wslExe = WSL) {
1822
2009
  if (first.startsWith("HELLO|")) {
1823
2010
  const [kind, name, version, digest, pid] = first.split("|");
1824
2011
  if (kind === "HELLO" && name === AGENT_NAME && Number(version) === PROTOCOL_VERSION) {
1825
- const expected = createHash("sha256").update(readFileSync(scriptPath)).digest("hex");
2012
+ const expected = createHash("sha256").update(readFileSync(hostPath)).digest("hex");
1826
2013
  finish({ ok: true, pid: Number(pid), digestMatches: digest === expected });
1827
2014
  return;
1828
2015
  }
@@ -1842,13 +2029,14 @@ function probeResident(distro, scriptPath, wslExe = WSL) {
1842
2029
  * its leg; a resident that dies mid-smoke fails fast instead of hanging.
1843
2030
  *
1844
2031
  * @param {string} distro - the distro.
1845
- * @param {string} scriptPath - the agent script as a Linux path inside the distro.
1846
- * @param {string} wslExe - the wsl.exe to spawn.
1847
- * @returns {Promise<{ execOk: boolean, execDetail: string, fsOk: boolean, fsDetail: string }>} the two resident-leg verdicts.
2032
+ * @param {string[]} residentArgv - the argv that starts the resident: `["sh", script]` for the shell agent, `[binaryPath]` for the native one.
2033
+ * @param {string} [wslExe] - the wsl.exe to spawn.
2034
+ * @param {string} [expectedDigest] - the sha256 the HELLO self-digest must equal (the native cache directory's name); empty for the shell agent, whose digest is compared separately.
2035
+ * @returns {Promise<{ execOk: boolean, execDetail: string, fsOk: boolean, fsDetail: string, digestMatches: boolean, fsError: { op: number, reason: string, message: string } | undefined }>} the leg verdicts.
1848
2036
  */
1849
- function runSmokeLegs(distro, scriptPath, wslExe = WSL) {
2037
+ function runSmokeLegs(distro, residentArgv, wslExe = WSL, expectedDigest = "") {
1850
2038
  return new Promise((settle) => {
1851
- const child = spawn(wslExe, ["-d", distro, "--exec", "sh", scriptPath], {
2039
+ const child = spawn(wslExe, ["-d", distro, "--exec", ...residentArgv], {
1852
2040
  stdio: ["pipe", "pipe", "pipe"],
1853
2041
  windowsHide: true,
1854
2042
  env: { ...process.env, WSL_UTF8: "1" },
@@ -1856,6 +2044,10 @@ function runSmokeLegs(distro, scriptPath, wslExe = WSL) {
1856
2044
  let settled = false;
1857
2045
  let buffer = "";
1858
2046
  let helloSeen = false;
2047
+ /** Whether the HELLO self-digest matches the expected one (true when none is expected). */
2048
+ let digestMatches = true;
2049
+ /** The first refused batch operation, decoded — the panel's actual cause. */
2050
+ let fsError = /** @type {{ op: number, reason: string, message: string } | undefined} */ (undefined);
1859
2051
  /** @type {Map<string, (line: string) => void>} */
1860
2052
  const waiters = new Map();
1861
2053
  let helloResolve = /** @type {((value: boolean) => void) | undefined} */ (undefined);
@@ -1869,7 +2061,7 @@ function runSmokeLegs(distro, scriptPath, wslExe = WSL) {
1869
2061
  try { child.stdin.write("SHUTDOWN\n"); } catch { /* the resident may already be gone */ }
1870
2062
  setTimeout(() => {
1871
2063
  try { child.kill(); } catch { /* already gone */ }
1872
- settle(value);
2064
+ settle({ digestMatches, fsError, ...value });
1873
2065
  }, 150);
1874
2066
  };
1875
2067
  child.stdout.on("data", (chunk) => {
@@ -1883,6 +2075,7 @@ function runSmokeLegs(distro, scriptPath, wslExe = WSL) {
1883
2075
  const parsed = parseAgentLine(line);
1884
2076
  if (parsed.type === "hello") {
1885
2077
  helloSeen = true;
2078
+ if (expectedDigest.length > 0 && parsed.digest !== expectedDigest) digestMatches = false;
1886
2079
  helloResolve?.(true);
1887
2080
  continue;
1888
2081
  }
@@ -1951,6 +2144,21 @@ function runSmokeLegs(distro, scriptPath, wslExe = WSL) {
1951
2144
  const fsbParsed = parseAgentLine(fsbLine);
1952
2145
  const payload = fsbParsed.type === "result" ? fsbParsed.stdout.toString("utf8") : "";
1953
2146
  const fsOk = fsbParsed.type === "result" && fsbParsed.exitCode === 0 && payload.includes("OK 1") && payload.includes("OK 2");
2147
+ // A refused batch answers `BAD <op>|<reason>|<base64 message>` inside
2148
+ // the RES payload. Decode it here so the report names the cause instead
2149
+ // of printing base64 at the user.
2150
+ if (!fsOk && fsbParsed.type === "result") {
2151
+ const bad = /^BAD (\d+)\|([a-z]+)\|([A-Za-z0-9+/=]+)/.exec(payload);
2152
+ if (bad !== null) {
2153
+ let message = "";
2154
+ try {
2155
+ message = Buffer.from(bad[3] ?? "", "base64").toString("utf8").trim();
2156
+ } catch {
2157
+ // Undecodable payload: the raw head below still names the op.
2158
+ }
2159
+ fsError = { op: Number(bad[1] ?? 0), reason: bad[2] ?? "io", message };
2160
+ }
2161
+ }
1954
2162
  const rmId = "smoke-cleanup";
1955
2163
  const rmLine = await request(rmId, encodeExecFrame({ id: rmId, cwd: "/tmp", argv: ["rm", "-rf", dir], timeoutMs: 15_000, maxOutputBytes: 4096 }));
1956
2164
  const rmParsed = parseAgentLine(rmLine);
@@ -1958,7 +2166,9 @@ function runSmokeLegs(distro, scriptPath, wslExe = WSL) {
1958
2166
  const fsDetail = fsOk
1959
2167
  ? `stat + list over ${dir} answered one batch round trip${cleanupOk ? "; the dir is removed" : `; CLEANUP FAILED — ${dir} is left behind`}`
1960
2168
  : fsbParsed.type === "result"
1961
- ? `exit ${fsbParsed.exitCode}: ${payload.slice(0, 120)}${cleanupOk ? "" : `; cleanup failed, ${dir} is left behind`}`
2169
+ ? fsError === undefined
2170
+ ? `exit ${fsbParsed.exitCode}: ${payload.slice(0, 120)}${cleanupOk ? "" : `; cleanup failed, ${dir} is left behind`}`
2171
+ : `operation ${fsError.op} (${fsError.reason}): ${fsError.message.slice(0, 160) || payload.slice(0, 120)}${cleanupOk ? "" : `; cleanup failed, ${dir} is left behind`}`
1962
2172
  : fsbParsed.type === "fsError"
1963
2173
  ? `${fsbParsed.reason}: ${fsbParsed.message}`
1964
2174
  : `unexpected reply: ${fsbLine.slice(0, 80)}`;
@@ -2126,7 +2336,7 @@ function report(checks, options, runInfo = {}) {
2126
2336
  if (process.argv[1] !== undefined && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
2127
2337
  const options = parseArgs(process.argv.slice(2));
2128
2338
  if (options.help) {
2129
- console.log("node scripts/doctor.mjs [distro] [--all] [--json] [--quick] [--sections host,sandbox,session,conf,net,agent] [--fix] [--install] [--yes] [--read-only] [--bundle <path>] [--redact] [--locale <tag>]");
2339
+ 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>]");
2130
2340
  } else {
2131
2341
  process.exitCode = await main(options);
2132
2342
  }