dsh-plugin-wsl-env 0.19.0 → 0.22.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 (48) hide show
  1. package/CHANGELOG.md +188 -1
  2. package/README.md +2 -2
  3. package/client.d.ts +5 -0
  4. package/client.js +218 -0
  5. package/cordis.patch.yml +75 -1
  6. package/docs/API.md +1 -0
  7. package/docs/CONFIGURATION.md +48 -5
  8. package/docs/CONFIGURATION.zh.md +15 -1
  9. package/docs/DIAGNOSTICS.md +110 -0
  10. package/docs/DIAGNOSTICS.zh.md +96 -0
  11. package/docs/LIMITATIONS.md +25 -0
  12. package/docs/LIMITATIONS.zh.md +7 -0
  13. package/docs/MIGRATION.md +1 -1
  14. package/docs/QUICKSTART.md +19 -3
  15. package/docs/RELEASING.md +3 -0
  16. package/docs/ROADMAP-1.0.md +49 -4
  17. package/docs/UPSTREAM-FILE-REFERENCE-SEAM.md +5 -0
  18. package/docs/UPSTREAM-OPEN-IN-APP.md +33 -0
  19. package/lib/client-host.d.ts +29 -0
  20. package/lib/client-host.js +29 -0
  21. package/lib/cwd-prompt-tool.d.ts +88 -0
  22. package/lib/cwd-prompt-tool.js +94 -0
  23. package/lib/cwd-prompt.d.ts +166 -0
  24. package/lib/cwd-prompt.js +203 -0
  25. package/lib/doctor-live.d.ts +5 -1
  26. package/lib/doctor-live.js +3 -2
  27. package/lib/index.d.ts +11 -0
  28. package/lib/index.js +10 -8
  29. package/lib/messages.d.ts +238 -0
  30. package/lib/messages.js +292 -0
  31. package/lib/preflight.d.ts +24 -0
  32. package/lib/preflight.js +111 -11
  33. package/lib/sandbox-core.js +7 -14
  34. package/lib/session-scope.js +10 -5
  35. package/lib/shell-env.d.ts +25 -0
  36. package/lib/shell-env.js +56 -0
  37. package/lib/shell.d.ts +3 -1
  38. package/lib/shell.js +3 -1
  39. package/lib/update-check.d.ts +197 -0
  40. package/lib/update-check.js +211 -0
  41. package/lib/wsl-doctor-command.d.ts +105 -0
  42. package/lib/wsl-doctor-command.js +240 -0
  43. package/lib/wsl-doctor-tool.d.ts +214 -0
  44. package/lib/wsl-doctor-tool.js +423 -0
  45. package/locale/doctor/en.json +30 -0
  46. package/locale/doctor/zh.json +30 -0
  47. package/package.json +47 -5
  48. package/scripts/doctor.mjs +1606 -171
@@ -1,28 +1,47 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * One-command environment doctor for this plugin (P0.2 / WSL-102).
3
+ * One-command environment doctor for this plugin (P0.2 / WSL-102; the verdict
4
+ * and per-distro shape: WSL-316).
4
5
  *
5
6
  * Answers "will this plugin work here, and if not, what do I paste?" in one
6
7
  * read-only pass: Windows and WSL versions, the distro and its shell, bubblewrap
7
8
  * usability, systemd / the user manager / `systemd-run` / Linger, the optional
8
9
  * tools, the peer versions the plugin is loaded against, the native-agent cache,
9
- * a fresh-agent handshake, stale session scopes, and the known profile-patch trap.
10
+ * a fresh-agent handshake, stale session scopes, the known profile-patch trap,
11
+ * and whether a newer stable release exists on the registry.
10
12
  *
11
13
  * node scripts/doctor.mjs [distro] [--json] [--fix] [--install] [--yes] [--read-only]
12
14
  * [--wsl <path to wsl.exe>]
13
15
  *
14
- * Exit status is 0 when nothing failed and 1 when a `fail` check did; warnings
15
- * (optional tools, a missing cache) do not fail the run. `--fix` performs only
16
- * safe actions: it sweeps stale `dsh-wsl-*.scope` units (the same sweep the
17
- * session preflight runs). Installing packages needs `--install` *and* an
18
- * explicit confirmation (`--yes` skips the prompt, not the flag), so a fix run
19
- * can never install silently.
16
+ * Exit status is 0 when the verdict is `ready` and 1 when it is `blocked`;
17
+ * `ready` means every check that can fail the first command passed **under the
18
+ * effective configuration** (the profile layers the app actually loads, not the
19
+ * shipped defaults). The blocking rule has one invariant: a `fail` blocks —
20
+ * config-awareness downgrades a check's *status* (a missing systemd only fails
21
+ * under `sessionSandbox: true`; `auto` and `false` downgrade it to a warning),
22
+ * so there is no per-id exception table to drift. `skipped` marks a check that
23
+ * could not run because another check failed. `unknown` marks a read the
24
+ * wsl.exe transport could not vouch for (a flake that survived one retry) —
25
+ * it never blocks and never feeds a config verdict; rerun for a clean answer. `--fix` performs only safe
26
+ * 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.
20
30
  *
21
31
  * `--read-only` refuses `--fix`/`--install`; `scripts/diagnose.sh` uses it to stay an
22
32
  * alias that can never change the machine.
23
33
  *
24
34
  * `--json` prints one machine-readable report instead of the human sections.
25
- * The report shape is versioned (`schemaVersion`).
35
+ * The report shape is versioned (`schemaVersion: 2`): `verdict`, `blockers`,
36
+ * `distroVerdicts`, the effective `config`, and per-check `distro` /
37
+ * `blocksFirstCommand` fields.
38
+ *
39
+ * The doctor is the standalone surface by design: it loads **no peer
40
+ * dependency and no host service**, so it still starts when the plugin's own
41
+ * runtime is the thing that is broken (the chicken-and-egg failure the
42
+ * 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
44
+ * below and drift-pinned by test.
26
45
  *
27
46
  * This CLI always probes a **fresh** resident — the app process's live
28
47
  * resident's `deaths`/`lastError` are host-private (no IPC), and the report
@@ -35,16 +54,153 @@
35
54
  import { execFile, spawn } from "node:child_process";
36
55
  import { createHash } from "node:crypto";
37
56
  import { createRequire } from "node:module";
38
- import { existsSync, readdirSync, readFileSync } from "node:fs";
57
+ import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
39
58
  import { homedir } from "node:os";
40
59
  import { dirname, join, resolve } from "node:path";
41
60
  import { createInterface } from "node:readline/promises";
42
61
  import { fileURLToPath } from "node:url";
62
+ // Pure, peer-free lib modules stay imported: `lint:build` pins them byte-for-byte
63
+ // to `src/`, so the doctor probes exactly the shipped behavior without loading
64
+ // any peer dependency (see the inlining note below).
43
65
  import { parseDistroList } from "../lib/wsl.js";
44
- import { AGENT_NAME, PROTOCOL_VERSION } from "../lib/agent-protocol.js";
66
+ import { AGENT_NAME, PROTOCOL_VERSION, encodeExecFrame, encodeFsbFrame, parseAgentLine } from "../lib/agent-protocol.js";
67
+ import { bwrapArgvPrefix } from "../lib/bwrap.js";
45
68
  import { sessionScopeSweepScript } from "../lib/session-scope.js";
46
69
  import { parseListeningPorts, procNetScript } from "../lib/ports.js";
47
70
 
71
+ // ── Peer-free inlining of the two peer-tainted helpers ────────────────────────
72
+ //
73
+ // 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:
75
+ //
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`:
85
+ /**
86
+ * Whether confined profiles shadow `/mnt` under this config.
87
+ *
88
+ * @param {{ interopVisibility?: "visible" | "masked" | "disabled", maskWindowsDrive?: boolean }} config - anything carrying the two keys.
89
+ * @returns {boolean} whether confined profiles shadow `/mnt`.
90
+ */
91
+ export function effectiveMaskWindowsDrive(config) {
92
+ if (config.interopVisibility !== undefined) return config.interopVisibility !== "visible";
93
+ return config.maskWindowsDrive === true;
94
+ }
95
+
96
+ // Inlined from `src/update-check.ts` `updateFactMessage`:
97
+ /**
98
+ * One human line about an available update.
99
+ *
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.
102
+ */
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}`;
110
+ }
111
+
112
+ // ── Host-locale output catalogs ──────────────────────────────────────────────
113
+ //
114
+ // The human output renders in the host's language: the doctor detects the
115
+ // Windows locale through the registry (fast, no PowerShell startup), the
116
+ // `--locale` flag and `DSH_WSL_DOCTOR_LOCALE` override it, and `--json` stays
117
+ // language-independent. Only the fixed skeleton is cataloged (verdict,
118
+ // summary, section marks, hints); per-check titles/details/remedies stay
119
+ // English — remedies carry copy-paste commands. The catalogs live in
120
+ // `locale/doctor/{en,zh}.json`; a test pins their key parity.
121
+
122
+ /** The languages the doctor's own catalogs ship. @type {Record<string, Record<string, string> | undefined>} */
123
+ const CATALOGS = {};
124
+ /** The active catalog language; English until a detection or flag selects otherwise. */
125
+ let LOCALE = "en";
126
+
127
+ /**
128
+ * Load one catalog, falling back to the English file when the requested one
129
+ * is missing or unreadable (a truncated install must not break the run).
130
+ *
131
+ * @param {string} name - the catalog language id.
132
+ * @returns {Record<string, string>} the catalog table.
133
+ */
134
+ function doctorCatalog(name) {
135
+ if (CATALOGS[name] === undefined) {
136
+ try {
137
+ CATALOGS[name] = JSON.parse(readFileSync(join(ROOT, "locale", "doctor", `${name}.json`), "utf8"));
138
+ } catch {
139
+ CATALOGS[name] = {};
140
+ }
141
+ }
142
+ return CATALOGS[name] ?? {};
143
+ }
144
+
145
+ /**
146
+ * Select the output language. `zh` requires its catalog to have loaded; any
147
+ * other id renders English.
148
+ *
149
+ * @param {string} name - the requested language id.
150
+ */
151
+ export function setDoctorLocale(name) {
152
+ LOCALE = name === "zh" && Object.keys(doctorCatalog("zh")).length > 0 ? "zh" : "en";
153
+ }
154
+
155
+ /**
156
+ * Render one catalog message in the active language, substituting
157
+ * `{placeholder}` tokens; a key the active catalog lacks falls back to the
158
+ * English entry.
159
+ *
160
+ * @param {string} key - the catalog key.
161
+ * @param {Record<string, string | number>} [params] - the placeholder values.
162
+ * @returns {string} the rendered line.
163
+ */
164
+ export function doctorT(key, params = {}) {
165
+ const template = doctorCatalog(LOCALE)[key] ?? doctorCatalog("en")[key] ?? key;
166
+ return template.replace(/\{(\w+)\}/gu, (whole, name) => (params[name] === undefined ? whole : String(params[name])));
167
+ }
168
+
169
+ /**
170
+ * Extract the locale name from a `reg query ... /v LocaleName` answer.
171
+ *
172
+ * @param {string} text - the command's stdout.
173
+ * @returns {string} the `LocaleName` value, or "" when the answer names none.
174
+ */
175
+ export function localeNameFromReg(text) {
176
+ const match = text.match(/LocaleName\s+REG_SZ\s+(\S+)/);
177
+ return match === null ? "" : match[1] ?? "";
178
+ }
179
+
180
+ /**
181
+ * Map a BCP 47-style tag onto a catalog language: `zh*` renders Chinese,
182
+ * everything else English.
183
+ *
184
+ * @param {string} tag - the locale tag (may be empty).
185
+ * @returns {"en" | "zh"} the catalog language.
186
+ */
187
+ export function localeFromTag(tag) {
188
+ return /^zh/iu.test(tag) ? "zh" : "en";
189
+ }
190
+
191
+ /**
192
+ * Resolve the output language: the `--locale` flag wins, then
193
+ * `DSH_WSL_DOCTOR_LOCALE`, then English (the caller probes the registry only
194
+ * when neither override is set).
195
+ *
196
+ * @param {string} flag - the `--locale` value, possibly empty.
197
+ * @returns {"en" | "zh"} the catalog language the overrides select, when they select one.
198
+ */
199
+ export function overrideLocale(flag) {
200
+ const tag = flag.length > 0 ? flag : process.env.DSH_WSL_DOCTOR_LOCALE ?? "";
201
+ return tag.length > 0 ? localeFromTag(tag) : "en";
202
+ }
203
+
48
204
  const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
49
205
  let WSL = "wsl.exe";
50
206
  const CMD = "cmd.exe";
@@ -91,16 +247,58 @@ const CACHE_REPORT = [
91
247
  * One check result.
92
248
  * @typedef {object} Check
93
249
  * @property {string} id - stable dotted id.
94
- * @property {"ok"|"warn"|"fail"|"info"} status - the verdict.
250
+ * @property {"ok"|"warn"|"fail"|"info"|"skipped"|"unknown"} status - the verdict.
251
+ * `unknown` marks a read the transport could not vouch for (a wsl.exe flake
252
+ * that survived one retry): it never blocks, and it never feeds a config
253
+ * verdict — a flaked read of `wsl.conf` must not report the file broken.
95
254
  * @property {string} title - what was checked.
96
255
  * @property {string} [detail] - the evidence.
97
256
  * @property {string} [remedy] - a copy-paste next step when not ok.
257
+ * @property {string} [distro] - the distro the check ran against (distro-scoped checks only).
258
+ * @property {boolean} [blocksFirstCommand] - whether a `fail` here blocks the first command (stamped by `report()`: true for every `fail`; config-awareness downgrades statuses rather than keeping a per-id exception table).
259
+ */
260
+
261
+ /** The check sections a scoped run can select, in the order the tool names them. */
262
+ export const SECTIONS = ["host", "sandbox", "session", "conf", "net", "agent"];
263
+
264
+ /**
265
+ * The section one check id belongs to — the single mapping the CLI's
266
+ * `--sections` filter and the `wsl_doctor` tool's per-section summary both
267
+ * read, so a tool digest and the report can never disagree about where a
268
+ * check lives. `host` is the default: the cheap environment basics every
269
+ * scoped run still probes.
270
+ * @param {string} id - the check id.
271
+ * @returns {"host"|"sandbox"|"session"|"conf"|"net"|"agent"} the section.
272
+ */
273
+ export function sectionOf(id) {
274
+ if (id.startsWith("sandbox.") || id === "functional.sandbox") return "sandbox";
275
+ if (id.startsWith("session.") || id === "runtime.scopes" || id === "distro.wsl-conf-boot") return "session";
276
+ if (id.startsWith("config.") || id === "distro.wsl-conf-interop" || id === "distro.wsl-conf-automount") return "conf";
277
+ if (id === "distro.dns") return "net";
278
+ if (id.startsWith("agent.") || id === "functional.exec" || id === "functional.fs") return "agent";
279
+ return "host";
280
+ }
281
+
282
+ /** The sections a `--quick` run selects: first-command prerequisites only. */
283
+ const QUICK_SECTIONS = ["host", "session", "sandbox"];
284
+
285
+ /**
286
+ * The effective configuration the blocking verdict answers under.
287
+ * @typedef {object} EffectiveConfig
288
+ * @property {string} distro - `auto`, `default` or a pinned distro name.
289
+ * @property {string} sessionSandbox - `true`, `false` or `auto`.
290
+ * @property {string} agentBackend - `auto`, `native` or `shell`.
291
+ * @property {string} sandbox - the fs-routing confinement stance.
292
+ * @property {string} maskWindowsDrive - the drive-masking stance (when `interopVisibility` is unset).
293
+ * @property {string} interopVisibility - the one-key stance (`""` unset, `visible`, `masked` or `disabled`); when set it takes precedence over `maskWindowsDrive`.
294
+ * @property {string} source - where the values came from.
295
+ * @property {string[]} overrides - the profile layers that changed keys, "`<name>`: `<keys>`".
98
296
  */
99
297
 
100
298
  /**
101
299
  * Run one host command; never throws.
102
300
  * @param {string[]} argv - executable and arguments.
103
- * @returns {Promise<{ ok: boolean, stdout: string, stderr: string, code?: string }>} the capture.
301
+ * @returns {Promise<{ ok: boolean, stdout: string, stderr: string, code?: string, timedOut?: boolean }>} the capture.
104
302
  */
105
303
  function run(argv) {
106
304
  return new Promise((settle) => {
@@ -113,12 +311,257 @@ function run(argv) {
113
311
  */
114
312
  const done = (error, stdout, stderr) => {
115
313
  const code = error === null ? undefined : /** @type {NodeJS.ErrnoException} */ (error).code ?? "1";
116
- settle({ ok: error === null, stdout: stdout ?? "", stderr: stderr ?? "", code });
314
+ const timedOut = error !== null && /** @type {NodeJS.ErrnoException & { signal?: string }} */ (error).signal === "SIGTERM";
315
+ settle({ ok: error === null, stdout: stdout ?? "", stderr: stderr ?? "", code, timedOut });
117
316
  };
118
317
  execFile(file, args, { encoding: "utf8", timeout: TIMEOUT_MS, windowsHide: true, env: { ...process.env, WSL_UTF8: "1" } }, done);
119
318
  });
120
319
  }
121
320
 
321
+ /**
322
+ * Parse `wsl.exe -l -v`'s table. The state column is localized, so only the
323
+ * shape is trusted: `NAME[*] <state> <version>` — with the default marker
324
+ * BEFORE the name on WSL 3.x (`* ubuntu`) and after it on 2.x (`ubuntu*`).
325
+ * The version digit is what `distro.wsl-mode` classifies.
326
+ * @param {string} stdout - the command's output, nulls stripped.
327
+ * @returns {Array<{ name: string, isDefault: boolean, version: string }>} one entry per table row; the header drops out by shape.
328
+ */
329
+ export function parseWslVerbose(stdout) {
330
+ /** @type {Array<{ name: string, isDefault: boolean, version: string }>} */
331
+ const entries = [];
332
+ for (const line of stdout.split(/\r?\n/)) {
333
+ let rest = line.trim();
334
+ let isDefault = false;
335
+ if (rest.startsWith("* ")) {
336
+ isDefault = true;
337
+ rest = rest.slice(2).trim();
338
+ }
339
+ const match = /^(\S+?)(\*)?\s+\S+\s+(\d+)\s*$/.exec(rest);
340
+ if (match === null) continue;
341
+ const columns = /** @type {RegExpExecArray} */ (match);
342
+ entries.push({
343
+ name: (columns[1] ?? "").replace(/\*$/, ""),
344
+ isDefault: isDefault || columns[2] === "*",
345
+ version: columns[3] ?? "",
346
+ });
347
+ }
348
+ return entries;
349
+ }
350
+
351
+ /** The `[wsl2]` keys the `.wslconfig` validator knows; anything else is reported as ignored by WSL. */
352
+ const WSLCONFIG_KEYS = new Set([
353
+ "kernel", "kernelCommandLine", "memory", "processors", "swap", "swapFile", "pageReporting",
354
+ "localhostForwarding", "nestedVirtualization", "guiApplications", "debugConsole",
355
+ "earlyBootLogging", "vmIdleTimeout", "safeMode", "defaultVhdSize", "networkingMode",
356
+ "dnsTunneling", "firewall", "autoProxy",
357
+ ]);
358
+ /** The `[experimental]` keys the validator knows. */
359
+ const WSLCONFIG_EXPERIMENTAL_KEYS = new Set(["sparseVhd", "autoMemoryReclaim", "hostAddressLoopback", "guiApplications"]);
360
+
361
+ /**
362
+ * Byte-parse one WSL size scalar ("4GB", "512MB", "8368805888", "0").
363
+ * @param {string} value - the raw scalar.
364
+ * @returns {number | undefined} the size in bytes, or undefined when the shape is not a size.
365
+ */
366
+ export function parseWslSize(value) {
367
+ const match = /^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb|tb)?$/i.exec(value.trim());
368
+ if (match === null) return undefined;
369
+ const columns = /** @type {RegExpExecArray} */ (match);
370
+ const scale = { b: 1, kb: 1024, mb: 1024 ** 2, gb: 1024 ** 3, tb: 1024 ** 4 }[(columns[2] ?? "b").toLowerCase()] ?? 1;
371
+ return Math.round(Number(columns[1] ?? 0) * scale);
372
+ }
373
+
374
+ /**
375
+ * Parse and validate `%USERPROFILE%\.wslconfig`. WSL **silently ignores** a
376
+ * malformed file and unknown keys, so this parser is the only place the trap
377
+ * gets named; known keys with semantic hazards (no memory, tiny memory, the
378
+ * localhost forwarding the port survey depends on) are called out with their
379
+ * consequence. Findings are warnings, never blockers — the file degrades
380
+ * advice, not the first command.
381
+ * @param {string} text - the file's text.
382
+ * @returns {{ problems: string[], keyCount: number }} the findings, each naming its line.
383
+ */
384
+ export function parseWslConfig(text) {
385
+ /** @type {string[]} */
386
+ const problems = [];
387
+ let keyCount = 0;
388
+ let section = "";
389
+ for (const [index, rawLine] of text.split(/\r?\n/).entries()) {
390
+ const line = rawLine.trim();
391
+ if (line.length === 0 || line.startsWith("#") || line.startsWith(";")) continue;
392
+ const heading = /^\[(.+)\]$/.exec(line);
393
+ if (heading !== null) {
394
+ section = (/** @type {RegExpExecArray} */ (heading)[1] ?? "").trim().toLowerCase();
395
+ continue;
396
+ }
397
+ const eq = line.indexOf("=");
398
+ if (eq <= 0) {
399
+ problems.push(`line ${index + 1} is not "key = value" — WSL silently ignores a malformed file`);
400
+ continue;
401
+ }
402
+ const key = line.slice(0, eq).trim();
403
+ const value = line.slice(eq + 1).trim();
404
+ keyCount += 1;
405
+ const known = section === "wsl2" ? WSLCONFIG_KEYS : section === "experimental" ? WSLCONFIG_EXPERIMENTAL_KEYS : null;
406
+ if (known === null) {
407
+ problems.push(`line ${index + 1}: unknown section [${section}] — WSL ignores it`);
408
+ continue;
409
+ }
410
+ if (!known.has(key)) {
411
+ problems.push(`line ${index + 1}: unknown key "${key}" in [${section}] — WSL ignores it`);
412
+ continue;
413
+ }
414
+ if ((key === "memory" || key === "swap") && section === "wsl2") {
415
+ const bytes = parseWslSize(value);
416
+ if (bytes === undefined) problems.push(`line ${index + 1}: ${key}="${value}" is not a size (expect 4GB, 512MB, …)`);
417
+ else if (key === "memory" && bytes === 0) problems.push(`line ${index + 1}: memory=0 — the VM gets no memory and every distro misbehaves`);
418
+ else if (key === "memory" && bytes < 512 * 1024 * 1024) problems.push(`line ${index + 1}: memory="${value}" is below 512MB — the VM will thrash or OOM`);
419
+ }
420
+ if (key === "localhostForwarding" && section === "wsl2" && value === "false") {
421
+ problems.push(`line ${index + 1}: localhostForwarding=false — the port survey's http://localhost:<port> URLs will not resolve on the Windows side`);
422
+ }
423
+ }
424
+ return { problems, keyCount };
425
+ }
426
+
427
+ /**
428
+ * Parse an INI-shaped file (`wsl.conf` and `.wslconfig` share the shape) into
429
+ * sections. Section and key names are lowercased for lookup; the last value
430
+ * per key wins; comment lines and lines without `=` are skipped.
431
+ * @param {string} text - the file's text.
432
+ * @returns {Record<string, Record<string, string>>} the sections, keyed by their lowercase name.
433
+ */
434
+ export function parseIni(text) {
435
+ /** @type {Record<string, Record<string, string>>} */
436
+ const sections = {};
437
+ let current = "";
438
+ for (const rawLine of text.split(/\r?\n/)) {
439
+ const line = rawLine.trim();
440
+ if (line.length === 0 || line.startsWith("#") || line.startsWith(";")) continue;
441
+ const heading = /^\[(.+)\]$/.exec(line);
442
+ if (heading !== null) {
443
+ current = (/** @type {RegExpExecArray} */ (heading)[1] ?? "").trim().toLowerCase();
444
+ sections[current] ??= {};
445
+ continue;
446
+ }
447
+ const eq = line.indexOf("=");
448
+ if (eq <= 0) continue;
449
+ const section = sections[current] ?? (sections[current] = {});
450
+ section[line.slice(0, eq).trim().toLowerCase()] = line.slice(eq + 1).trim();
451
+ }
452
+ return sections;
453
+ }
454
+
455
+ /**
456
+ * The text of one patch row (`- id: <rowId>` down to the next row at the same
457
+ * or shallower indent). This is the same line discipline the preset helper
458
+ * applies to the shipped patch, so both tools read rows identically by
459
+ * construction.
460
+ * @param {string} text - the patch file's text.
461
+ * @param {string} rowId - the row id to extract.
462
+ * @returns {string} the row's text, or "" when the file names no such row.
463
+ */
464
+ export function rowBlock(text, rowId) {
465
+ const lines = text.split(/\r?\n/);
466
+ const start = lines.findIndex((line) => new RegExp(`^\\s*- id: ${rowId}\\s*$`).test(line));
467
+ if (start < 0) return "";
468
+ const header = /** @type {string} */ (lines[start]);
469
+ const indent = header.length - header.trimStart().length;
470
+ let end = start + 1;
471
+ while (end < lines.length) {
472
+ const line = /** @type {string} */ (lines[end]);
473
+ if (line.trim().length > 0 && line.length - line.trimStart().length <= indent) break;
474
+ end += 1;
475
+ }
476
+ return lines.slice(start, end).join("\n");
477
+ }
478
+
479
+ /**
480
+ * The value one key sets inside a row block: the FIRST occurrence wins, which
481
+ * inside `preset-wsl` means the `wsl-shell` row's value (the command plane is
482
+ * the first-command gate this verdict answers for). Comment lines never match
483
+ * — the anchor requires the key at line start after indent.
484
+ * @param {string} block - the row block's text.
485
+ * @param {string} key - the YAML key.
486
+ * @returns {string | undefined} the scalar with quotes stripped, or undefined when unset.
487
+ */
488
+ export function rowKey(block, key) {
489
+ const match = new RegExp(`^\\s*${key}: (.*)$`, "m").exec(block);
490
+ if (match === null) return undefined;
491
+ return (/** @type {RegExpExecArray} */ (match)[1] ?? "").trim().replace(/^['"]|['"]$/g, "");
492
+ }
493
+
494
+ /**
495
+ * Read the configuration the blocking verdict must answer under: the shipped
496
+ * preset's values, overlaid by every profile layer under `$DSH_HOME/profiles/*`
497
+ * that carries a `preset-wsl` row (the preset helper's output shape) or an
498
+ * `fs-routing` patch (a root-plane row, patchable by id). A profile file whose
499
+ * rows name none of the five keys changes nothing and is not an error — the
500
+ * recognizer only claims the shapes it knows, and the `config.effective` check
501
+ * reports exactly what was read and from where.
502
+ * @param {string} dshHome - the harness home (`DSH_HOME` or `~/.dsh`).
503
+ * @param {string} root - the package root holding the shipped `cordis.patch.yml`.
504
+ * @returns {{ config: EffectiveConfig, recognized: boolean }} the effective values and whether the shipped rows were recognized at all.
505
+ */
506
+ export function effectiveConfig(dshHome, root) {
507
+ /** @type {EffectiveConfig} */
508
+ let config = { distro: "auto", sessionSandbox: "true", agentBackend: "auto", sandbox: "true", maskWindowsDrive: "false", interopVisibility: "", source: "the shipped preset", overrides: [] };
509
+ let recognized = false;
510
+ const shipped = readFileSync(join(root, "cordis.patch.yml"), "utf8");
511
+ const preset = rowBlock(shipped, "preset-wsl");
512
+ const routing = rowBlock(shipped, "fs-routing");
513
+ const distro = rowKey(preset, "distro");
514
+ const sessionSandbox = rowKey(preset, "sessionSandbox");
515
+ const agentBackend = rowKey(preset, "agentBackend");
516
+ const sandbox = rowKey(routing, "sandbox");
517
+ const maskWindowsDrive = rowKey(routing, "maskWindowsDrive");
518
+ if (sessionSandbox !== undefined) {
519
+ recognized = true;
520
+ config = {
521
+ distro: distro === "" || distro === undefined ? "auto" : distro,
522
+ sessionSandbox: sessionSandbox === "false" ? "false" : sessionSandbox === "auto" ? "auto" : "true",
523
+ agentBackend: agentBackend ?? "auto",
524
+ sandbox: sandbox ?? "true",
525
+ maskWindowsDrive: maskWindowsDrive ?? "false",
526
+ interopVisibility: rowKey(routing, "interopVisibility") ?? "",
527
+ source: "the shipped preset",
528
+ overrides: [],
529
+ };
530
+ }
531
+ const profilesDir = join(dshHome, "profiles");
532
+ if (!existsSync(profilesDir)) return { config, recognized };
533
+ for (const entry of readdirSync(profilesDir, { withFileTypes: true })) {
534
+ if (!entry.isDirectory()) continue;
535
+ const patch = join(profilesDir, entry.name, "cordis.patch.yml");
536
+ if (!existsSync(patch)) continue;
537
+ const text = readFileSync(patch, "utf8");
538
+ /** @type {string[]} */
539
+ const changed = [];
540
+ const next = { ...config };
541
+ const layerPreset = rowBlock(text, "preset-wsl");
542
+ const layerRouting = rowBlock(text, "fs-routing");
543
+ for (const [block, keys] of [[layerPreset, ["distro", "sessionSandbox", "agentBackend"]], [layerRouting, ["sandbox", "maskWindowsDrive"]]]) {
544
+ const source = /** @type {string} */ (block);
545
+ /** The scalar keys the overlay may change; `source`/`overrides` are bookkeeping, not overlay inputs. */
546
+ const scalar = /** @type {const} */ (["distro", "sessionSandbox", "agentBackend", "sandbox", "maskWindowsDrive", "interopVisibility"]);
547
+ for (const key of /** @type {string[]} */ (keys)) {
548
+ const value = rowKey(source, key);
549
+ if (value === undefined || value === next[/** @type {keyof EffectiveConfig} */ (key)]) continue;
550
+ const normalized = key === "distro" && value === "" ? "auto" : key === "sessionSandbox" ? (value === "false" ? "false" : value === "auto" ? "auto" : "true") : value;
551
+ if (normalized === next[/** @type {keyof EffectiveConfig} */ (key)]) continue;
552
+ next[/** @type {(typeof scalar)[number]} */ (key)] = normalized;
553
+ changed.push(key);
554
+ }
555
+ }
556
+ if (changed.length > 0) {
557
+ next.source = `profile "${entry.name}"`;
558
+ next.overrides = [...config.overrides, `${entry.name}: ${changed.join(", ")}`];
559
+ config = next;
560
+ }
561
+ }
562
+ return { config, recognized };
563
+ }
564
+
122
565
  /**
123
566
  * Run one `sh -c` script inside the distro.
124
567
  * @param {string} distro - the distro name.
@@ -129,10 +572,46 @@ function inDistro(distro, script) {
129
572
  return run([WSL, "-d", distro, "--exec", "sh", "-c", script]);
130
573
  }
131
574
 
575
+ /**
576
+ * Whether one capture smells like a `wsl.exe` transport flake rather than an
577
+ * answer from the distro: the execFile deadline fired, or the output carries
578
+ * WSL's own wedged-service error (`Wsl/Service/WSAETIMEDOUT` and friends —
579
+ * localized text is fine, the error class rides every language). Under the
580
+ * doctor's concurrent probing of several distros on one VM, these flakes
581
+ * arrive exactly when a cold distro is mid-boot, and trusting them produced
582
+ * the wrong class of report: static config (`wsl.conf`, resolv.conf) read as
583
+ * broken when the read itself was the casualty.
584
+ * @param {{ ok: boolean, stdout: string, stderr: string, timedOut?: boolean }} answer - the capture.
585
+ * @returns {boolean} true when the capture must not feed a config verdict.
586
+ */
587
+ export function isFlake(answer) {
588
+ return answer.timedOut === true || /WSAETIMEDOUT|Wsl\/Service/i.test(`${answer.stderr}\n${answer.stdout}`);
589
+ }
590
+
591
+ /** How long one retry waits for the VM to settle before probing again. */
592
+ const FLAKE_SETTLE_MS = 2_000;
593
+
594
+ /**
595
+ * One in-distro probe with a transport-flake retry: a capture that smells like
596
+ * a flake is retried once after a settle delay, and the result carries whether
597
+ * the FINAL answer is still untrusted (`flaked`), so a caller can report
598
+ * `unknown` instead of a configuration verdict built on a wedged read.
599
+ * @param {string} distro - the distro name.
600
+ * @param {string} script - the shell script.
601
+ * @returns {Promise<{ ok: boolean, stdout: string, stderr: string, code?: string, timedOut?: boolean, flaked: boolean }>} the capture plus the flake flag.
602
+ */
603
+ async function askDistro(distro, script) {
604
+ const first = await inDistro(distro, script);
605
+ if (first.ok || !isFlake(first)) return { ...first, flaked: isFlake(first) };
606
+ await new Promise((resolve) => setTimeout(resolve, FLAKE_SETTLE_MS));
607
+ const second = await inDistro(distro, script);
608
+ return { ...second, flaked: isFlake(second) };
609
+ }
610
+
132
611
  /**
133
612
  * Parse the doctor's own arguments.
134
613
  * @param {string[]} argv - `process.argv.slice(2)`.
135
- * @returns {{ distro: string, wsl: string, json: boolean, fix: boolean, install: boolean, yes: boolean, readOnly: boolean, help: boolean }} the options.
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.
136
615
  */
137
616
  function parseArgs(argv) {
138
617
  const options = {
@@ -143,15 +622,30 @@ function parseArgs(argv) {
143
622
  install: false,
144
623
  yes: false,
145
624
  readOnly: false,
625
+ all: false,
626
+ bundle: "",
627
+ redact: false,
628
+ sections: "",
629
+ quick: false,
146
630
  help: false,
631
+ locale: "",
147
632
  };
148
633
  for (let i = 0; i < argv.length; i += 1) {
149
634
  const arg = argv[i] ?? "";
150
635
  if (arg === "--json") options.json = true;
636
+ else if (arg === "--locale") options.locale = argv[++i] ?? "";
637
+ else if (arg.startsWith("--locale=")) options.locale = arg.slice("--locale=".length);
151
638
  else if (arg === "--fix") options.fix = true;
152
639
  else if (arg === "--install") options.install = true;
153
640
  else if (arg === "--yes" || arg === "-y") options.yes = true;
154
641
  else if (arg === "--read-only") options.readOnly = true;
642
+ else if (arg === "--all") options.all = true;
643
+ else if (arg === "--quick") options.quick = true;
644
+ else if (arg === "--sections") options.sections = argv[++i] ?? "";
645
+ else if (arg.startsWith("--sections=")) options.sections = arg.slice("--sections=".length);
646
+ else if (arg === "--bundle") options.bundle = argv[++i] ?? "";
647
+ else if (arg.startsWith("--bundle=")) options.bundle = arg.slice("--bundle=".length);
648
+ else if (arg === "--redact") options.redact = true;
155
649
  else if (arg === "--help" || arg === "-h") options.help = true;
156
650
  else if (arg === "--distro") options.distro = argv[++i] ?? "";
157
651
  else if (arg.startsWith("--distro=")) options.distro = arg.slice("--distro=".length);
@@ -258,6 +752,72 @@ function installedPeer(packageName) {
258
752
  }
259
753
  }
260
754
 
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
+
261
821
  /**
262
822
  * The install remedy for one distro and family.
263
823
  * @param {string} distro - the distro name.
@@ -273,16 +833,66 @@ function installRemedy(distro, family) {
273
833
  * @returns {number} the exit status.
274
834
  */
275
835
  function rejectReadOnly() {
276
- console.error("doctor: --read-only refuses --fix/--install; run `pnpm run doctor --fix` instead");
836
+ console.error(doctorT("refusal.read-only"));
277
837
  return 2;
278
838
  }
279
839
 
840
+ /**
841
+ * Map over items with at most `limit` workers running at once, preserving the
842
+ * input order in the results. The distro collection uses this: the distros
843
+ * are independent (the two-distro probe proves the wsl.exe command path is
844
+ * concurrent), and the A5 measurement says the wall clock is real — nine
845
+ * distros cost 151 s sequentially on the Tier 1 machine.
846
+ * @template T, R
847
+ * @param {T[]} items - the items.
848
+ * @param {number} limit - the worker count.
849
+ * @param {(item: T, index: number) => Promise<R>} worker - one item's work.
850
+ * @returns {Promise<R[]>} the results, in input order.
851
+ */
852
+ async function mapWithConcurrency(items, limit, worker) {
853
+ /** @type {R[]} */
854
+ const results = new Array(items.length);
855
+ let next = 0;
856
+ const runners = Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, async () => {
857
+ for (;;) {
858
+ const index = next;
859
+ next += 1;
860
+ if (index >= items.length) return;
861
+ results[index] = await worker(/** @type {T} */ (items[index]), index);
862
+ }
863
+ });
864
+ await Promise.all(runners);
865
+ return results;
866
+ }
867
+
868
+ /** The distro-collection worker count: three concurrent distros keep the
869
+ * wsl.exe fan-out polite while cutting the nine-distro wall clock to about
870
+ * a third. */
871
+ const DISTRO_CONCURRENCY = 3;
872
+
280
873
  /**
281
874
  * Run the doctor.
282
- * @param {{ distro: string, wsl: string, json: boolean, fix: boolean, install: boolean, yes: boolean, readOnly: boolean, help: boolean }} options - the parsed options.
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.
283
876
  * @returns {Promise<number>} the exit status.
284
877
  */
878
+ /**
879
+ * The doctor run: collect the checks under the effective configuration and
880
+ * the requested scope, then report.
881
+ * @param {ReturnType<typeof parseArgs>} options - the parsed arguments.
882
+ * @returns {Promise<number>} 0 when the verdict is `ready`, 1 when `blocked`.
883
+ */
285
884
  async function main(options) {
885
+ // The output language: an explicit `--locale` / `DSH_WSL_DOCTOR_LOCALE`
886
+ // wins without probing; otherwise a human run detects the Windows locale
887
+ // through the registry (fast, no PowerShell startup) — the refusals below
888
+ // render in the detected language too. `--json` stays language-independent
889
+ // and pays no extra subprocess.
890
+ if (options.json) setDoctorLocale("en");
891
+ else setDoctorLocale(overrideLocale(options.locale));
892
+ if (!options.json && options.locale.length === 0 && (process.env.DSH_WSL_DOCTOR_LOCALE ?? "").length === 0) {
893
+ const query = await run([CMD, "/c", "reg query \"HKCU\\Control Panel\\International\" /v LocaleName"]);
894
+ setDoctorLocale(localeFromTag(localeNameFromReg(query.stdout)));
895
+ }
286
896
  if (options.readOnly && (options.fix || options.install)) return rejectReadOnly();
287
897
  // One rebinding covers every probe below (`-l -q`, `inDistro`, the
288
898
  // resident handshake, the sessions survey): an explicit `--wsl` replaces
@@ -291,6 +901,21 @@ async function main(options) {
291
901
  WSL = wslExe;
292
902
  /** @type {Check[]} */
293
903
  const checks = [];
904
+ // A5: per-phase wall clock. The doctor must be fast enough to run twice;
905
+ // the timings make a slow machine visible instead of felt, and give support
906
+ // triage the per-section duration without a separate durations column.
907
+ const runStart = Date.now();
908
+ let phaseStart = Date.now();
909
+ // The package manifest, read once: the peers check and the bundle both need it.
910
+ const manifest = /** @type {{ name?: string, version?: string, peerDependencies?: Record<string, string> }} */ (JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")));
911
+ /** @type {Record<string, number>} */
912
+ const timingsMs = {};
913
+ /** Close the open phase under `name` and open the next one.
914
+ * @param {string} name - the phase that just ended. */
915
+ const phase = (name) => {
916
+ timingsMs[name] = Date.now() - phaseStart;
917
+ phaseStart = Date.now();
918
+ };
294
919
  /**
295
920
  * @param {string} id - the check id.
296
921
  * @param {Check["status"]} status - the verdict.
@@ -302,6 +927,31 @@ async function main(options) {
302
927
  checks.push({ id, status, title, ...(detail === undefined ? {} : { detail }), ...(remedy === undefined ? {} : { remedy }) });
303
928
  };
304
929
 
930
+ // ---- scope ----------------------------------------------------------------
931
+ // `--quick` and `--sections` bound what this run probes and reports: a
932
+ // scoped run still probes `distro.reachable` (the transport gate) but its
933
+ // report carries only the requested sections, and the expensive legs — the
934
+ // resident smokes, the fence smoke, the registry query, the port survey —
935
+ // run only when their section is selected and the run is not quick. A full
936
+ // run (the default) sets `wanted = null`: every section, no gating.
937
+ const wanted = options.quick
938
+ ? new Set(QUICK_SECTIONS)
939
+ : options.sections.length > 0
940
+ ? (() => {
941
+ /** @param {string} s - one comma-separated section token. @returns {boolean} whether it names a section. */
942
+ const known = (s) => SECTIONS.includes(s);
943
+ const picked = options.sections.split(",").map((s) => s.trim()).filter(known);
944
+ if (picked.length === 0) return null;
945
+ return new Set(picked);
946
+ })()
947
+ : null;
948
+ const quick = options.quick;
949
+ /** Whether a section is in this run's scope. */
950
+ const want = (/** @type {string} */ section) => wanted === null || wanted.has(section);
951
+ /** @type {{ sections: string[], quick: boolean } | undefined} */
952
+ let scope;
953
+ if (wanted !== null) scope = { sections: [...wanted], quick };
954
+
305
955
  // ---- host ----------------------------------------------------------------
306
956
  const windows = await run([CMD, "/c", "ver"]);
307
957
  const build = /[0-9][0-9.]*/.exec(windows.stdout.replace(/\0/g, ""));
@@ -313,6 +963,31 @@ async function main(options) {
313
963
  if (version.ok && wslVersion.length > 0) check("host.wsl", "ok", "WSL version", wslVersion);
314
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)");
315
965
 
966
+ phase("host");
967
+ // ---- .wslconfig (the global VM config; host-level) ------------------------
968
+ // WSL silently ignores a malformed file, so interop/masking advice can fail
969
+ // 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
971
+ // works from Windows and from a WSL with interop regardless of where the
972
+ // automount root sits — the route's own failure is reported, not guessed.
973
+ const userProfile = (await run([CMD, "/c", "echo %USERPROFILE%"])).stdout.replace(/\0/g, "").trim();
974
+ if (!/^[A-Za-z]:\\/.test(userProfile)) {
975
+ check("config.wslconfig", "info", ".wslconfig", "USERPROFILE unreadable through cmd.exe — run the doctor from Windows or a WSL with interop to inspect the global VM config");
976
+ } else {
977
+ const answer = await run([CMD, "/c", `type "${userProfile}\\.wslconfig"`]);
978
+ const text = answer.ok ? answer.stdout.replace(/\0/g, "") : "";
979
+ if (text.trim().length === 0) {
980
+ check("config.wslconfig", "ok", ".wslconfig", `no content in ${userProfile}\\.wslconfig (WSL defaults apply)`);
981
+ } else {
982
+ const { problems, keyCount } = parseWslConfig(text);
983
+ if (problems.length > 0) {
984
+ check("config.wslconfig", "warn", ".wslconfig", `${keyCount} key(s) read; ${problems.length} finding(s): ${problems.join("; ")}`, `fix ${userProfile}\\.wslconfig, then run "wsl.exe --shutdown" — the VM returns ~8 s later and reads the file fresh`);
985
+ } else {
986
+ check("config.wslconfig", "ok", ".wslconfig", `${keyCount} key(s) parsed from ${userProfile}\\.wslconfig, no findings`);
987
+ }
988
+ }
989
+ }
990
+
316
991
  const listed = await run([wslExe, "-l", "-q"]);
317
992
  const distros = listed.ok ? parseDistroList(listed.stdout.replace(/\0/g, "")) : [];
318
993
  if (distros.length === 0) {
@@ -320,103 +995,513 @@ async function main(options) {
320
995
  } else {
321
996
  check("host.distros", "ok", "Installed distros", distros.join(", "));
322
997
  }
323
- const distro = options.distro.length > 0 ? options.distro : distros[0] ?? "";
324
- if (distro.length === 0) return report(checks, { json: options.json });
998
+ // ---- effective configuration (read once, before anything config-gated) ---
999
+ // The blocking verdict answers under the values the user actually runs, so
1000
+ // the shipped preset is overlaid by the profile layers before the target
1001
+ // set is derived (an effective `distro` pin narrows it) and the session
1002
+ // checks below assign their statuses. The `config.effective` row is emitted
1003
+ // later, in the config section, so the human output keeps its grouping.
1004
+ const dshHomeEarly = process.env.DSH_HOME !== undefined && process.env.DSH_HOME.length > 0 ? process.env.DSH_HOME : join(homedir(), ".dsh");
1005
+ const { config: effective, recognized: configRecognized } = effectiveConfig(dshHomeEarly, ROOT);
1006
+ const scopeMode = effective.sessionSandbox;
1007
+ /** The status a session-scope prerequisite gets when it is missing. */
1008
+ const sessionStatus = () => (scopeMode === "true" ? "fail" : "warn");
1009
+ const scopeNote = scopeMode === "auto"
1010
+ ? " — sessionSandbox: auto falls back to the per-command bwrap profile"
1011
+ : scopeMode === "false"
1012
+ ? " — sessionSandbox: false does not use the session scope"
1013
+ : "";
1014
+ /** Append the config-aware note to a prerequisite's evidence when the scope is not required.
1015
+ * @param {string} detail - the prerequisite's own evidence.
1016
+ * @returns {string} the evidence, with the fallback named when the scope is optional. */
1017
+ const withScopeNote = (detail) => (scopeMode === "true" ? detail : `${detail}${scopeNote}`);
1018
+ /** The drive-masking stance in effect, computed with the shipped precedence (interopVisibility over maskWindowsDrive). */
1019
+ const interopMasked = effectiveMaskWindowsDrive({
1020
+ interopVisibility: effective.interopVisibility === "" ? undefined : /** @type {"visible" | "masked" | "disabled"} */ (effective.interopVisibility),
1021
+ maskWindowsDrive: effective.maskWindowsDrive === "true",
1022
+ });
325
1023
 
326
- if (options.distro.length > 0 && !distros.includes(options.distro)) {
327
- check("distro.present", "fail", `Distro "${distro}"`, `not in [${distros.join(", ")}]`, `wsl.exe --install -d ${distro}; this doctor never installs a distro for you`);
328
- return report(checks, { json: options.json });
1024
+ phase("wslconfig");
1025
+ // ---- target selection ----------------------------------------------------
1026
+ // An explicit `--distro` wins; `--all` checks every installed distro;
1027
+ // otherwise the effective configuration decides: `auto` (the shipped
1028
+ // default) means the workspace decides, so every installed distro is a
1029
+ // candidate and all are checked; `default` resolves to the distro WSL
1030
+ // itself marks as default; a pinned name checks exactly that one.
1031
+ const runInfo = /** @type {{ distros: string[], config?: EffectiveConfig, timingsMs?: Record<string, number>, scope?: { sections: string[], quick: boolean }, bundle?: { path: string, redact: boolean, manifest: { name?: string, version?: string, peerDependencies?: Record<string, string> } } }} */ ({ distros: [], timingsMs });
1032
+ if (options.bundle.length > 0) runInfo.bundle = { path: options.bundle, redact: options.redact, manifest };
1033
+ runInfo.config = { ...effective };
1034
+ if (options.fix && wanted !== null) {
1035
+ console.error(doctorT("refusal.scoped-fix"));
1036
+ return 2;
329
1037
  }
1038
+ if (scope !== undefined) runInfo.scope = scope;
1039
+ /** The `wsl.exe -l -v` table, parsed once: the default marker feeds target selection, the VERSION column feeds `distro.wsl-mode`. */
1040
+ const wslTable = parseWslVerbose((await run([wslExe, "-l", "-v"])).stdout.replace(/\0/g, ""));
1041
+ /** @type {string[]} */
1042
+ const targets = [];
1043
+ if (options.distro.length > 0) targets.push(options.distro);
1044
+ else if (options.all) targets.push(...distros);
1045
+ else if (effective.distro === "auto") targets.push(...distros);
1046
+ else if (effective.distro === "default") {
1047
+ const defaultDistro = wslTable.find((entry) => entry.isDefault)?.name;
1048
+ targets.push(...(defaultDistro !== undefined ? [defaultDistro] : distros));
1049
+ } else targets.push(effective.distro);
330
1050
 
331
- const alive = await inDistro(distro, "printf %s ok");
332
- if (!alive.ok || alive.stdout.trim() !== "ok") {
333
- check("distro.reachable", "fail", `Distro "${distro}"`, "wsl.exe could not run a command in it (stopped, wedged, or missing)", `wsl.exe -d ${distro} -- true; if that hangs, wsl.exe --shutdown, then retry`);
334
- return report(checks, { json: options.json });
335
- }
336
- check("distro.reachable", "ok", `Distro "${distro}"`, "answers commands");
337
-
338
- // ---- distro facts --------------------------------------------------------
339
- const shellAnswer = await inDistro(distro, 's=$(getent passwd "$(id -u)" | cut -d: -f7); [ -n "$s" ] || s=$SHELL; printf %s "$s"');
340
- const shell = shellAnswer.stdout.trim();
341
- if (shell.startsWith("/")) check("distro.shell", "ok", "Login shell", shell);
342
- else check("distro.shell", "fail", "Login shell", shell.length === 0 ? "no shell reported" : shell, `check the user's /etc/passwd entry in "${distro}": getent passwd "$(id -u)"`);
343
-
344
- const homeAnswer = await inDistro(distro, 'printf %s "$HOME"');
345
- const home = homeAnswer.stdout.trim();
346
- if (home.startsWith("/")) check("distro.home", "ok", "Home", home);
347
- else check("distro.home", "fail", "Home", home.length === 0 ? "no home reported" : home, `check the default user's home in "${distro}": getent passwd "$(id -u)"`);
348
-
349
- const kernel = (await inDistro(distro, "uname -r")).stdout.trim();
350
- check("distro.kernel", "info", "Kernel", kernel.length > 0 ? kernel : "unreadable");
351
-
352
- const familyAnswer = await inDistro(distro, `for f in ${FAMILIES.join(" ")}; do command -v "$f" >/dev/null 2>&1 && { echo "$f"; exit 0; }; done; echo unknown`);
353
- const family = familyAnswer.stdout.trim();
354
- check("distro.family", "info", "Package family", family.length > 0 ? family : "unknown");
355
-
356
- // ---- sandbox prerequisites ----------------------------------------------
357
- const bwrapPath = (await inDistro(distro, "command -v bwrap")).stdout.trim();
358
- const install = installRemedy(distro, family);
359
- if (bwrapPath.length === 0) {
360
- check("sandbox.bwrap", "fail", "bubblewrap", "missing; every confined command fails closed without it", `${install}, or run "pnpm run bootstrap ${distro} --install"`);
361
- } else {
362
- check("sandbox.bwrap", "ok", "bubblewrap", bwrapPath);
363
- const userns = await inDistro(distro, "bwrap --ro-bind / / -- true");
364
- if (userns.ok) check("sandbox.bwrap-usable", "ok", "bubblewrap usability", "a read-only profile runs");
365
- 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");
1051
+ const missing = targets.filter((target) => !distros.includes(target));
1052
+ if (missing.length > 0) {
1053
+ for (const name of missing) {
1054
+ checks.push({ id: "distro.present", status: "fail", title: `Distro "${name}"`, detail: `not in [${distros.join(", ")}]`, remedy: `wsl.exe --install -d ${name}; this doctor never installs a distro for you`, distro: name });
1055
+ }
1056
+ runInfo.distros = missing;
1057
+ return report(checks, { json: options.json }, runInfo);
366
1058
  }
1059
+ if (targets.length === 0) return report(checks, { json: options.json }, runInfo);
1060
+ runInfo.distros = targets;
367
1061
 
368
- // ---- session sandbox prerequisites --------------------------------------
369
- const systemd = await inDistro(distro, 'if [ -d /run/systemd/system ]; then printf "systemd %s" "$(cat /proc/1/comm)"; else printf "none %s" "$(cat /proc/1/comm)"; fi');
370
- if (!systemd.stdout.startsWith("systemd")) {
371
- check("session.systemd", "fail", "systemd as PID 1", systemd.stdout.trim().length > 0 ? systemd.stdout.trim() : "not systemd", `set [boot] systemd=true in /etc/wsl.conf inside "${distro}", run "wsl.exe --shutdown", then reopen the session. Without it, sessionSandbox cannot run`);
372
- } else check("session.systemd", "ok", "systemd as PID 1", "running");
373
-
374
- const systemdRun = (await inDistro(distro, "command -v systemd-run")).stdout.trim();
375
- if (systemdRun.length > 0) check("session.systemd-run", "ok", "systemd-run", systemdRun);
376
- else check("session.systemd-run", "fail", "systemd-run", "missing; the distro's systemd package is incomplete", `reinstall systemd inside "${distro}" (apt-get install --reinstall systemd, or the family's equivalent)`);
377
-
378
- const userManager = (await inDistro(distro, "systemctl --user is-system-running 2>/dev/null || true")).stdout.trim();
379
- if (userManager === "running" || userManager === "degraded") check("session.user-manager", "ok", "systemd user manager", userManager);
380
- else check("session.user-manager", "fail", "systemd user manager", userManager.length > 0 ? userManager : "unreachable", `log in to "${distro}" once, or enable lingering (next remedy), then retry`);
381
-
382
- const linger = (await inDistro(distro, 'loginctl show-user "$(id -un)" -p Linger 2>/dev/null')).stdout.trim();
383
- if (linger === "Linger=yes") check("session.linger", "ok", "Linger", linger);
384
- else check("session.linger", "fail", "Linger", linger.length > 0 ? linger : "unset", `wsl.exe -d ${distro} -- loginctl enable-linger "$(id -un)" (this needs the user's own session; run it inside the distro)`);
385
-
386
- // ---- optional tools ------------------------------------------------------
387
- /** The optional tools, in the order users notice them losing. */
388
- /** @type {Array<[string, string]>} */
389
- const optionalTools = [["rg", "in-distro search"], ["git", "workspace-change baselines"], ["inotifywait", "the watcher's primary backend"]];
390
- for (const [tool, purpose] of optionalTools) {
391
- const found = (await inDistro(distro, `command -v ${tool}`)).stdout.trim();
392
- if (found.length > 0) check(`tools.${tool}`, "ok", tool, found);
393
- else check(`tools.${tool}`, "warn", tool, `missing; ${purpose} degrades to a slower fallback`, install);
394
- }
1062
+ /**
1063
+ * The distro-scoped checks for one target, pushed with the distro stamped
1064
+ * so the report can aggregate per-distro verdicts. An unreachable distro
1065
+ * fails its own reachability check and contributes nothing further — one
1066
+ * wedged distro must not mask the others.
1067
+ * @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.
1069
+ */
1070
+ const collectDistroChecks = async (target) => {
1071
+ /** @type {Check[]} */
1072
+ const collected = [];
1073
+ const check = (/** @type {string} */ id, /** @type {Check["status"]} */ status, /** @type {string} */ title, /** @type {string | undefined} */ detail = undefined, /** @type {string | undefined} */ remedy = undefined) => {
1074
+ collected.push({ id, status, title, ...(detail === undefined ? {} : { detail }), ...(remedy === undefined ? {} : { remedy }), distro: target });
1075
+ };
1076
+ /** One in-distro probe with the flake retry. */
1077
+ const probe = (/** @type {string} */ script) => askDistro(target, script);
1078
+ /** The `unknown` row a transport flake earns instead of a config verdict. */
1079
+ const flakeCheck = (/** @type {string} */ id, /** @type {string} */ title, /** @type {{ stderr: string, stdout: string }} */ answer) => check(id, "unknown", title,
1080
+ `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`,
1081
+ `rerun the doctor; if the flake repeats, "wsl.exe -t ${target}" (terminate just this distro) and rerun again`);
1082
+ const alive = await probe("printf %s ok");
1083
+ if (!alive.ok && alive.flaked) {
1084
+ flakeCheck("distro.reachable", `Distro "${target}"`, alive);
1085
+ return { checks: collected, reachable: false, bwrapPath: "", stale: 0, family: "unknown" };
1086
+ }
1087
+ if (!alive.ok || alive.stdout.trim() !== "ok") {
1088
+ 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" };
1090
+ }
1091
+ check("distro.reachable", "ok", `Distro "${target}"`, "answers commands");
395
1092
 
396
- // ---- agents and caches ---------------------------------------------------
397
- const arch = (await inDistro(distro, "uname -m")).stdout.trim();
398
- const packaged = ["x86_64", "aarch64"].includes(arch) ? join(ROOT, "agent", "native", `linux-${arch}`, "dsh-wsl-agent") : "";
399
- if (arch.length === 0) check("agent.arch", "info", "Distro architecture", "unreadable");
400
- else if (packaged.length === 0) check("agent.arch", "info", "Distro architecture", `${arch} has no packaged native agent; the shell agent is the only backend`);
401
- else if (existsSync(packaged)) check("agent.native", "ok", "Packaged native agent", packaged.slice(ROOT.length + 1));
402
- else check("agent.native", "warn", "Packaged native agent", `missing for ${arch}`, "reinstall the plugin (the binaries ship with the package), or use agentBackend: shell");
403
-
404
- const cache = (await inDistro(distro, CACHE_REPORT)).stdout.trim();
405
- if (cache === "none" || cache.length === 0) check("agent.cache", "info", "Agent cache", "empty (a first command populates it)");
406
- else {
407
- const entries = cache.split(/\r?\n/).filter((line) => line.trim().length > 0);
408
- const bad = entries.filter((line) => line.startsWith("noexec ")).length;
409
- 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 "${distro}"; the next command repopulates it` : undefined);
410
- }
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)"`);
1109
+ }
1110
+
1111
+ const kernelAnswer = await probe("uname -r");
1112
+ if (!kernelAnswer.ok && kernelAnswer.flaked) flakeCheck("distro.kernel", "Kernel", kernelAnswer);
1113
+ else {
1114
+ const kernel = kernelAnswer.stdout.trim();
1115
+ check("distro.kernel", "info", "Kernel", kernel.length > 0 ? kernel : "unreadable");
1116
+ }
1117
+
1118
+ 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
+ }
1124
+
1125
+ // ---- WSL mode ------------------------------------------------------------
1126
+ // WSL1 is a declared non-goal, but until now it failed unexplained: the
1127
+ // session prerequisites named remedies, never the root cause. The -l -v
1128
+ // table carries the VERSION per distro, so name the cause.
1129
+ const wslMode = wslTable.find((entry) => entry.name === target)?.version ?? "";
1130
+ if (wslMode === "1") {
1131
+ check("distro.wsl-mode", "fail", "WSL mode", `WSL 1 — a declared non-goal: no systemd (no session scope, no Linger) and no unprivileged user namespaces (no bubblewrap)`, `wsl.exe --set-version ${target} 2 (the distro's files stay), then "wsl.exe --shutdown" and reopen the session`);
1132
+ } else if (wslMode === "") {
1133
+ check("distro.wsl-mode", "info", "WSL mode", `unreadable — the -l -v table named no version for "${target}"`);
1134
+ } else {
1135
+ check("distro.wsl-mode", "ok", "WSL mode", `WSL ${wslMode}`);
1136
+ }
1137
+
1138
+ // ---- disk -----------------------------------------------------------------
1139
+ // A full root is the classic WSL "everything mysteriously fails" class:
1140
+ // the ext4 VHDX stops growing (or the Windows drive holding it is full)
1141
+ // and every write failure surfaces as something unrelated. One df call;
1142
+ // the fail line at 97% is where the first cache write starts to break.
1143
+ const dfAnswer = await probe("df -Pm /");
1144
+ if (!dfAnswer.ok && dfAnswer.flaked) flakeCheck("distro.disk", "Disk", dfAnswer);
1145
+ else {
1146
+ const dfLine = dfAnswer.stdout.trim().split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0)[1] ?? "";
1147
+ const dfFields = dfLine.split(/\s+/);
1148
+ const dfCapacity = Number((dfFields[4] ?? "").replace(/%$/, ""));
1149
+ const dfTotal = dfFields[1] ?? "?";
1150
+ const dfAvail = dfFields[3] ?? "?";
1151
+ if (!Number.isFinite(dfCapacity)) {
1152
+ check("distro.disk", "info", "Disk", "unreadable — df did not answer in the expected shape");
1153
+ } else if (dfCapacity >= 97) {
1154
+ 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`);
1155
+ } else if (dfCapacity >= 90) {
1156
+ 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");
1157
+ } else {
1158
+ check("distro.disk", "ok", "Disk", `/${dfCapacity}% used (${dfAvail} MiB free of ${dfTotal} MiB)`);
1159
+ }
1160
+ }
1161
+
1162
+ // ---- sandbox prerequisites ----------------------------------------------
1163
+ let bwrapUsable = false;
1164
+ let bwrapPath = "";
1165
+ const install = installRemedy(target, family);
1166
+ if (!want("sandbox")) {
1167
+ // sandbox section out of scope: bwrapPath stays "" and the fence smoke
1168
+ // below is skipped with it.
1169
+ } else {
1170
+ const bwrapAnswer = await probe("command -v bwrap");
1171
+ if (!bwrapAnswer.ok && bwrapAnswer.flaked) flakeCheck("sandbox.bwrap", "bubblewrap", bwrapAnswer);
1172
+ else {
1173
+ bwrapPath = bwrapAnswer.stdout.trim();
1174
+ if (bwrapPath.length === 0) {
1175
+ check("sandbox.bwrap", "fail", "bubblewrap", "missing; every confined command fails closed without it", `${install}, or run "pnpm run bootstrap ${target} --install"`);
1176
+ } else {
1177
+ check("sandbox.bwrap", "ok", "bubblewrap", bwrapPath);
1178
+ const userns = await probe("bwrap --ro-bind / / -- true");
1179
+ if (!userns.ok && userns.flaked) flakeCheck("sandbox.bwrap-usable", "bubblewrap usability", userns);
1180
+ else if (userns.ok) {
1181
+ check("sandbox.bwrap-usable", "ok", "bubblewrap usability", "a read-only profile runs");
1182
+ bwrapUsable = true;
1183
+ } 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");
1184
+ }
1185
+ }
1186
+ }
1187
+
1188
+ // ---- session sandbox prerequisites --------------------------------------
1189
+ // The statuses are config-aware: the scope is only *required* under
1190
+ // `sessionSandbox: true` (the shipped default); `auto` falls back to the
1191
+ // per-command bwrap profile and `false` does not use the scope at all, so
1192
+ // in both cases a missing prerequisite downgrades to a warning — a `fail`
1193
+ // always blocks, which is the invariant the verdict leans on.
1194
+ let runtimeSystemd = false;
1195
+ let systemdPid = "";
1196
+ if (want("session")) {
1197
+ 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
+ if (!systemd.ok && systemd.flaked) flakeCheck("session.systemd", "systemd as PID 1", systemd);
1199
+ else if (!systemd.stdout.startsWith("systemd")) {
1200
+ 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`);
1201
+ } else check("session.systemd", "ok", "systemd as PID 1", "running");
1202
+
1203
+ const systemdRun = await probe("command -v systemd-run");
1204
+ if (!systemdRun.ok && systemdRun.flaked) flakeCheck("session.systemd-run", "systemd-run", systemdRun);
1205
+ else {
1206
+ const systemdRunPath = systemdRun.stdout.trim();
1207
+ if (systemdRunPath.length > 0) check("session.systemd-run", "ok", "systemd-run", systemdRunPath);
1208
+ 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)`);
1209
+ }
1210
+
1211
+ const userManager = await probe("systemctl --user is-system-running 2>/dev/null || true");
1212
+ if (!userManager.ok && userManager.flaked) flakeCheck("session.user-manager", "systemd user manager", userManager);
1213
+ else {
1214
+ const userState = userManager.stdout.trim();
1215
+ if (userState === "running" || userState === "degraded") check("session.user-manager", "ok", "systemd user manager", userState);
1216
+ 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`);
1217
+ }
1218
+
1219
+ const linger = await probe('loginctl show-user "$(id -un)" -p Linger 2>/dev/null');
1220
+ if (!linger.ok && linger.flaked) flakeCheck("session.linger", "Linger", linger);
1221
+ else {
1222
+ const lingerState = linger.stdout.trim();
1223
+ if (lingerState === "Linger=yes") check("session.linger", "ok", "Linger", lingerState);
1224
+ 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)`);
1225
+ }
1226
+ runtimeSystemd = systemd.stdout.startsWith("systemd");
1227
+ systemdPid = systemd.stdout.trim();
1228
+ }
1229
+
1230
+ // ---- /etc/wsl.conf cross-checks ------------------------------------------
1231
+ // The distro-level settings the plugin cannot change (LIMITATIONS): boot,
1232
+ // interop, automount. Each check reads the conf against the runtime facts
1233
+ // the probes above collected and names the terminate semantics — a conf
1234
+ // value that is not in effect is a different problem from one that is.
1235
+ // A flaked read earns three `unknown` rows, never a verdict: the conf is
1236
+ // on disk, and the read — not the file — is what failed.
1237
+ const confAnswer = await probe("cat /etc/wsl.conf 2>/dev/null || true");
1238
+ const confFlaked = !confAnswer.ok && confAnswer.flaked;
1239
+ const conf = parseIni(confAnswer.stdout);
1240
+ const noConf = confAnswer.stdout.trim().length === 0;
1241
+ const confWanted = want("session") || want("conf");
1242
+ if (!confWanted) {
1243
+ // Scoped run: neither the boot cross-check nor the interop/automount
1244
+ // rows are in scope — the conf read above stays (one cheap call that
1245
+ // the section rows share), but no rows report.
1246
+ } else if (confFlaked) {
1247
+ if (want("session")) flakeCheck("distro.wsl-conf-boot", "/etc/wsl.conf [boot]", confAnswer);
1248
+ if (want("conf")) {
1249
+ flakeCheck("distro.wsl-conf-interop", "/etc/wsl.conf [interop]", confAnswer);
1250
+ flakeCheck("distro.wsl-conf-automount", "/etc/wsl.conf [automount]", confAnswer);
1251
+ }
1252
+ } else {
1253
+ const bootSystemd = ((noConf ? undefined : conf.boot?.systemd) ?? "").trim().toLowerCase();
1254
+ if (!want("session")) {
1255
+ // boot row out of scope
1256
+ } else if (noConf) {
1257
+ check("distro.wsl-conf-boot", "info", "/etc/wsl.conf [boot]", "no /etc/wsl.conf — the default (systemd off) applies, and the runtime matches it");
1258
+ } else if (bootSystemd === "true" && !runtimeSystemd) {
1259
+ check("distro.wsl-conf-boot", "warn", "/etc/wsl.conf [boot]", `[boot] systemd=true but PID 1 is ${systemdPid || "not systemd"} — the value is set but not in effect`, `wsl.exe --terminate ${target} (or "wsl.exe --shutdown"), then reopen the session`);
1260
+ } else if (bootSystemd === "false" && runtimeSystemd) {
1261
+ check("distro.wsl-conf-boot", "warn", "/etc/wsl.conf [boot]", "[boot] systemd=false but PID 1 is systemd — the running boot predates the value", `wsl.exe --terminate ${target} applies it; check sessionSandbox first, because the scope needs systemd`);
1262
+ } else {
1263
+ check("distro.wsl-conf-boot", "ok", "/etc/wsl.conf [boot]", bootSystemd === "" ? "no [boot] systemd line (the off default) — the runtime matches" : `[boot] systemd=${bootSystemd} — the runtime matches`);
1264
+ }
1265
+
1266
+ const interopEnabled = ((noConf ? undefined : conf.interop?.enabled) ?? "").trim().toLowerCase();
1267
+ if (!want("conf")) {
1268
+ // 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
+ } 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)" : ""}`);
1278
+ }
1279
+
1280
+ const automountEnabled = ((noConf ? undefined : conf.automount?.enabled) ?? "").trim().toLowerCase();
1281
+ const automountRoot = ((noConf ? undefined : conf.automount?.root) ?? "").trim();
1282
+ if (!want("conf")) {
1283
+ // automount row out of scope
1284
+ } else if (automountEnabled === "false") {
1285
+ check("distro.wsl-conf-automount", "warn", "/etc/wsl.conf [automount]", "automount is disabled — /mnt has no Windows drives and Windows files are unreachable from this distro; the masking stance is moot", `remove [automount] enabled=false in /etc/wsl.conf, then wsl.exe --terminate ${target}`);
1286
+ } else if (automountRoot.length > 0 && automountRoot !== "/mnt" && interopMasked) {
1287
+ check("distro.wsl-conf-automount", "warn", "/etc/wsl.conf [automount]", `the automount root is ${automountRoot}, not /mnt — the drive-masking stance is in effect and targets /mnt, so ${automountRoot} is not covered`, `reset [automount] root to /mnt in /etc/wsl.conf, then wsl.exe --terminate ${target}`);
1288
+ } else {
1289
+ check("distro.wsl-conf-automount", "ok", "/etc/wsl.conf [automount]", noConf
1290
+ ? "no /etc/wsl.conf — /mnt mounts (the default)"
1291
+ : `enabled=${automountEnabled || "true (the default)"}, root=${automountRoot || "/mnt"}`);
1292
+ }
1293
+ }
1294
+
1295
+ // ---- clock ----------------------------------------------------------------
1296
+ // A sleeping host desyncs the WSL clock (the VM's clock stops with it);
1297
+ // the classic symptom is TLS and git failing with certificate or
1298
+ // timestamp errors minutes after resume. One comparison, one remedy.
1299
+ const clockAnswer = await probe("date +%s");
1300
+ if (!clockAnswer.ok && clockAnswer.flaked) flakeCheck("distro.clock", "Clock", clockAnswer);
1301
+ else {
1302
+ const distroEpoch = Number(clockAnswer.stdout.trim());
1303
+ if (!Number.isFinite(distroEpoch) || distroEpoch <= 0) {
1304
+ check("distro.clock", "info", "Clock", "unreadable — date did not answer an epoch");
1305
+ } else {
1306
+ const skew = Math.abs(distroEpoch - Math.floor(Date.now() / 1000));
1307
+ if (skew > 60) {
1308
+ check("distro.clock", "warn", "Clock", `the distro clock is ${skew}s off the host — TLS and git fail with certificate/timestamp errors after a host sleep`, `"wsl.exe --shutdown", then reopen — the VM resyncs on boot`);
1309
+ } else {
1310
+ check("distro.clock", "ok", "Clock", `within ${skew}s of the host`);
1311
+ }
1312
+ }
1313
+ }
1314
+
1315
+ // ---- dns ------------------------------------------------------------------
1316
+ // Name resolution breaks in two WSL-specific ways: the auto-generated
1317
+ // /etc/resolv.conf lost its nameserver (or generation was disabled), and
1318
+ // the VPN-tunnel class where the file looks fine but queries die. The
1319
+ // probe is warn-grade and honest about offline — a machine without a
1320
+ // network answers the same as a broken resolver.
1321
+ const resolvAnswer = want("net") ? await probe("wc -c < /etc/resolv.conf 2>/dev/null || printf 0") : undefined;
1322
+ if (resolvAnswer !== undefined && !resolvAnswer.ok && resolvAnswer.flaked) flakeCheck("distro.dns", "DNS", resolvAnswer);
1323
+ else if (resolvAnswer !== undefined) {
1324
+ const resolvBytes = Number(resolvAnswer.stdout.trim());
1325
+ if (!Number.isFinite(resolvBytes) || resolvBytes === 0) {
1326
+ 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`);
1327
+ } else {
1328
+ const resolved = (await probe("getent hosts deb.debian.org 2>/dev/null | head -1")).stdout.trim();
1329
+ if (resolved.length > 0) {
1330
+ check("distro.dns", "ok", "DNS", `resolv.conf present (${resolvBytes} bytes); ${(resolved.split(/\s+/)[0] ?? "?")} resolved the probe name`);
1331
+ } else {
1332
+ check("distro.dns", "warn", "DNS", `resolv.conf present (${resolvBytes} bytes) but the probe name did not resolve — offline, or the resolver is broken (the VPN-tunnel class)`, "check the network; with a VPN up, see the WSL DNS tunneling notes in docs/CONFIGURATION.md");
1333
+ }
1334
+ }
1335
+ }
1336
+
1337
+ // ---- 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);
1348
+ }
1349
+ }
1350
+
1351
+ // ---- agents and caches ---------------------------------------------------
1352
+ // Gated on the agent section: this region is the expensive chain (arch,
1353
+ // cache inventory, handshake, resident smokes). A scoped run without it
1354
+ // (quick included) stops after the session rows.
1355
+ if (want("agent")) {
1356
+ const archAnswer = await probe("uname -m");
1357
+ if (!archAnswer.ok && archAnswer.flaked) flakeCheck("agent.arch", "Distro architecture", archAnswer);
1358
+ else {
1359
+ const arch = archAnswer.stdout.trim();
1360
+ 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");
1365
+ }
1366
+
1367
+ const cacheAnswer = await probe(CACHE_REPORT);
1368
+ if (!cacheAnswer.ok && cacheAnswer.flaked) flakeCheck("agent.cache", "Agent cache", cacheAnswer);
1369
+ else {
1370
+ const cache = cacheAnswer.stdout.trim();
1371
+ if (cache === "none" || cache.length === 0) check("agent.cache", "info", "Agent cache", "empty (a first command populates it)");
1372
+ else {
1373
+ 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);
1376
+ }
1377
+ }
1378
+ }
1379
+
1380
+ // ---- session scopes (section: session) ------------------------------------
1381
+ const scopesAnswer = want("session") ? await probe(STALE_SCOPE_REPORT) : undefined;
1382
+ let stale = 0;
1383
+ /** @type {string[]} */
1384
+ let livePids = [];
1385
+ /** @type {string[]} */
1386
+ let scopeLines = [];
1387
+ /** ok | fail | info — the handshake state the smoke legs read. */
1388
+ let handshakeState = "info";
1389
+ if (scopesAnswer !== undefined && !scopesAnswer.ok && scopesAnswer.flaked) flakeCheck("runtime.scopes", "Session scopes", scopesAnswer);
1390
+ else if (scopesAnswer !== undefined) {
1391
+ const scopes = scopesAnswer.stdout.trim();
1392
+ scopeLines = scopes === "none" || scopes.length === 0 ? [] : scopes.split(/\r?\n/);
1393
+ stale = scopeLines.filter((line) => /\sstale(\s|$)/.test(line)).length;
1394
+ livePids = scopeLines.flatMap((line) => {
1395
+ const m = /\spids:([0-9 ]+)$/.exec(line);
1396
+ if (m === null) return [];
1397
+ return (m[1] ?? "").trim().split(/\s+/).filter((p) => p.length > 0);
1398
+ });
1399
+ }
1400
+
1401
+ // ---- resident handshake (section: agent) ----------------------------------
1402
+ const agentScript = join(ROOT, "agent", "wsl-agent.sh");
1403
+ /** ok | fail | info — the legs skip with a story that matches. */
1404
+ handshakeState = "info";
1405
+ if (!want("agent")) {
1406
+ // 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
+ } else if (!existsSync(agentScript)) {
1410
+ 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
+ handshakeState = "fail";
1412
+ } else {
1413
+ // The script is a Linux path in the checkout's OWN distro; another
1414
+ // distro cannot read it, and "exited before its HELLO" would be a
1415
+ // lie about a broken install. Probe readability first, honestly.
1416
+ const readable = (await inDistro(target, `[ -f "${agentScript}" ] && printf yes || printf no`)).stdout.trim() === "yes";
1417
+ 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}"`);
1419
+ } else {
1420
+ const handshake = await probeResident(target, agentScript, wslExe);
1421
+ handshakeState = handshake.ok && handshake.digestMatches ? "ok" : "fail";
1422
+ if (handshake.ok) {
1423
+ const live = livePids.length > 0
1424
+ ? `; 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`
1425
+ : "";
1426
+ check("agent.handshake", handshake.digestMatches ? "ok" : "fail", "Agent handshake",
1427
+ `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}`,
1428
+ handshake.digestMatches ? undefined : "resync the runtime copy (pnpm run sync:windows), then restart the app");
1429
+ } else {
1430
+ 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");
1431
+ }
1432
+ }
1433
+ }
1434
+
1435
+ // ---- stale session scopes ------------------------------------------------
1436
+ if (!want("session")) {
1437
+ // session section out of scope
1438
+ } else if (scopeLines.length === 0) check("runtime.scopes", "info", "Session scopes", "none (no user manager, or none left behind)");
1439
+ else if (stale === 0) check("runtime.scopes", "ok", "Session scopes", `${scopeLines.length} live, none stale`);
1440
+ else check("runtime.scopes", "warn", "Session scopes", `${stale} stale of ${scopeLines.length}`, "--fix stops them (the same sweep the session preflight runs); they are safe to stop when no agent process is inside");
1441
+
1442
+ // ---- smoke legs ----------------------------------------------------------
1443
+ // The handshake proves HELLO; the legs prove the chain the session rides:
1444
+ // one EXEC round trip, the confined profile's allow/refuse shape, and one
1445
+ // FSB stat+list batch over a temp dir (cleaned after). A leg whose
1446
+ // prerequisite failed is `skipped` with the blocker named — absence is
1447
+ // never silent, and a skipped leg never blocks (its blocker already does).
1448
+ const residentBlocked = handshakeState !== "ok";
1449
+ const sandboxBlocked = bwrapPath.length === 0 || !bwrapUsable;
1450
+ const residentBlocker = handshakeState === "fail" ? "blocked by agent.handshake" : "the handshake could not run in this distro";
1451
+ // A quick run skips both smokes — their worth is the deep verdict, and
1452
+ // the quick profile's promise is a fast prerequisite answer.
1453
+ const residentSmokeWanted = want("agent") && !quick;
1454
+ const sandboxSmokeWanted = want("sandbox") && !quick;
1455
+ if (!residentSmokeWanted) {
1456
+ // resident smokes out of scope (or quick)
1457
+ } else if (residentBlocked) {
1458
+ check("functional.exec", "skipped", "Smoke: EXEC", `skipped: ${residentBlocker}`);
1459
+ check("functional.fs", "skipped", "Smoke: FSB batch", `skipped: ${residentBlocker}`);
1460
+ } else {
1461
+ // One retry for both smoke sessions: under concurrent probing a wedge
1462
+ // can kill an otherwise healthy chain, and a smoke `fail` is the most
1463
+ // alarming row the report can carry — it must not rest on one flaked
1464
+ // transport.
1465
+ let smoke = await runSmokeLegs(target, agentScript, wslExe);
1466
+ if (!smoke.execOk || !smoke.fsOk) {
1467
+ await new Promise((resolve) => setTimeout(resolve, FLAKE_SETTLE_MS));
1468
+ smoke = await runSmokeLegs(target, agentScript, wslExe);
1469
+ }
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
+ }
1473
+ if (!sandboxSmokeWanted) {
1474
+ // fence smoke out of scope (or quick)
1475
+ } else if (sandboxBlocked) {
1476
+ check("functional.sandbox", "skipped", "Smoke: confined profile", `skipped: blocked by ${bwrapPath.length === 0 ? "sandbox.bwrap" : "sandbox.bwrap-usable"}`);
1477
+ } else {
1478
+ let sandbox = await runSandboxSmoke(target);
1479
+ if (!sandbox.ok && !sandbox.flaked) {
1480
+ await new Promise((resolve) => setTimeout(resolve, FLAKE_SETTLE_MS));
1481
+ sandbox = await runSandboxSmoke(target);
1482
+ }
1483
+ if (sandbox.flaked) flakeCheck("functional.sandbox", "Smoke: confined profile", { stderr: sandbox.detail, stdout: "" });
1484
+ 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
+ }
1486
+
1487
+ return { checks: collected, reachable: true, bwrapPath, stale, family };
1488
+ };
411
1489
 
412
- const scopes = (await inDistro(distro, STALE_SCOPE_REPORT)).stdout.trim();
413
- const scopeLines = scopes === "none" || scopes.length === 0 ? [] : scopes.split(/\r?\n/);
414
- const stale = scopeLines.filter((line) => /\sstale(\s|$)/.test(line)).length;
415
- const livePids = scopeLines.flatMap((line) => {
416
- const m = /\spids:([0-9 ]+)$/.exec(line);
417
- if (m === null) return [];
418
- return (m[1] ?? "").trim().split(/\s+/).filter((p) => p.length > 0);
1490
+ phase("target");
1491
+ /** @type {Map<string, { checks: Check[], reachable: boolean, bwrapPath: string, stale: number, family: string }>} */
1492
+ const states = new Map();
1493
+ const outcomes = await mapWithConcurrency(targets, DISTRO_CONCURRENCY, async (target) => {
1494
+ const distroStart = Date.now();
1495
+ const outcome = await collectDistroChecks(target);
1496
+ return { target, outcome, ms: Date.now() - distroStart };
419
1497
  });
1498
+ for (const { target, outcome, ms } of outcomes) {
1499
+ checks.push(...outcome.checks);
1500
+ states.set(target, outcome);
1501
+ timingsMs[`distro:${target}`] = ms;
1502
+ phaseStart = Date.now();
1503
+ }
1504
+
420
1505
  // ---- Windows git trust (WSL change review) ------------------------------
421
1506
  // The change-review pipeline's discovery call runs the WINDOWS git against
422
1507
  // a \\wsl.localhost UNC when Windows git is installed; git's
@@ -425,10 +1510,16 @@ async function main(options) {
425
1510
  // WSL workspaces). A machine without Windows git is fine too — the provider
426
1511
  // resolves git to a distro sentinel and routes everything. What the doctor
427
1512
  // can probe cheaply from here is interop git.exe and its whitelist.
1513
+ let winGitOk = false;
1514
+ if (quick) {
1515
+ // quick profile: the trust check needs interop git.exe and is advice, not
1516
+ // a prerequisite — a scoped run leaves it out.
1517
+ } else {
428
1518
  const winGitVersion = await run(["git.exe", "--version"]);
429
1519
  if (!winGitVersion.ok) {
430
1520
  check("git.win-safe", "info", "Windows git trust", "Windows git not found through interop — WSL change review uses the distro fallback; host (C:\\...) workspaces would need git for their own review");
431
1521
  } else {
1522
+ winGitOk = true;
432
1523
  const entries = (await run(["git.exe", "config", "--global", "--get-all", "safe.directory"])).stdout.split(/\r?\n/).filter(Boolean);
433
1524
  const whitelisted = entries.some((entry) => /wsl\.localhost/i.test(entry));
434
1525
  check("git.win-safe", whitelisted ? "ok" : "warn", "Windows git trust",
@@ -436,32 +1527,9 @@ async function main(options) {
436
1527
  : "Windows git does not trust the \\\\wsl.localhost share; WSL workspaces' change review silently degrades to file-tool edits",
437
1528
  whitelisted ? undefined : 'on Windows: git config --global --add safe.directory "//wsl.localhost/*", then restart the app');
438
1529
  }
439
-
440
- // ---- resident handshake --------------------------------------------------
441
- const agentScript = join(ROOT, "agent", "wsl-agent.sh");
442
- if (!agentScript.startsWith("/")) {
443
- check("agent.handshake", "info", "Agent handshake", "skipped: run the doctor from inside the distro (the script path is a Windows path)");
444
- } else if (!existsSync(agentScript)) {
445
- 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");
446
- } else {
447
- const handshake = await probeResident(distro, agentScript, wslExe);
448
- if (handshake.ok) {
449
- const live = livePids.length > 0
450
- ? `; 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`
451
- : "";
452
- check("agent.handshake", handshake.digestMatches ? "ok" : "fail", "Agent handshake",
453
- `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}`,
454
- handshake.digestMatches ? undefined : "resync the runtime copy (pnpm run sync:windows), then restart the app");
455
- } else {
456
- 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");
457
- }
458
1530
  }
459
1531
 
460
- // ---- stale session scopes ------------------------------------------------
461
- if (scopeLines.length === 0) check("runtime.scopes", "info", "Session scopes", "none (no user manager, or none left behind)");
462
- else if (stale === 0) check("runtime.scopes", "ok", "Session scopes", `${scopeLines.length} live, none stale`);
463
- else check("runtime.scopes", "warn", "Session scopes", `${stale} stale of ${scopeLines.length}`, "--fix stops them (the same sweep the session preflight runs); they are safe to stop when no agent process is inside");
464
-
1532
+ phase("git");
465
1533
  // ---- sessions across running distros (WSL-309) ----------------------------
466
1534
  // The single-distro checks above answer "is this distro healthy?"; this
467
1535
  // survey answers "what is running right now, everywhere?" — the concurrent
@@ -477,19 +1545,19 @@ async function main(options) {
477
1545
  const running = ((await run([WSL, "--list", "--running"])).stdout ?? "").split(/\r?\n/).map((line) => line.trim().replace(/\s+\([^)]*\)$/, "")).filter((line) => distroNames.includes(line));
478
1546
  if (!options.json) {
479
1547
  console.log("");
480
- console.log("sessions across running distros");
1548
+ console.log(doctorT("sessions.title"));
481
1549
  if (running.length === 0) {
482
- console.log(" (none)");
1550
+ console.log(doctorT("sessions.none"));
483
1551
  } else {
484
1552
  for (const d of running) {
485
1553
  const report = (await inDistro(d, STALE_SCOPE_REPORT)).stdout.trim();
486
1554
  const lines = report === "none" || report.length === 0 ? [] : report.split(/\r?\n/);
487
1555
  if (report === "none") {
488
- console.log(` ${d} no user manager — scopes unavailable`);
1556
+ console.log(` ${d} ${doctorT("sessions.no-user-manager")}`);
489
1557
  continue;
490
1558
  }
491
1559
  if (lines.length === 0) {
492
- console.log(` ${d} no session scopes`);
1560
+ console.log(` ${d} ${doctorT("sessions.no-scopes")}`);
493
1561
  continue;
494
1562
  }
495
1563
  for (const line of lines) {
@@ -509,7 +1577,7 @@ async function main(options) {
509
1577
  // serves the human, with the two actions the facts imply: the localhost URL
510
1578
  // WSL2's forwarding already makes reachable, and the netsh line that would
511
1579
  // extend reach beyond the host (printed, never applied).
512
- if (!options.json) {
1580
+ if (!options.json && !quick) {
513
1581
  const portScript = procNetScript();
514
1582
  let anyPorts = false;
515
1583
  for (const d of running) {
@@ -519,16 +1587,15 @@ async function main(options) {
519
1587
  anyPorts = true;
520
1588
  const ip = ((await inDistro(d, "hostname -I")).stdout ?? "").trim().split(/\s+/)[0] ?? "";
521
1589
  console.log("");
522
- console.log(`listening ports in ${d}`);
1590
+ console.log(doctorT("ports.title", { distro: d }));
523
1591
  for (const port of ports) {
524
1592
  console.log(` :${port} http://localhost:${port} (LAN: netsh interface portproxy add v4tov4 listenport=${port} listenaddress=0.0.0.0 connectport=${port} connectaddress=${ip})`);
525
1593
  }
526
1594
  }
527
- if (!anyPorts && running.length > 0) console.log("\nno listening ports in the running distros");
1595
+ if (!anyPorts && running.length > 0) console.log(doctorT("ports.none"));
528
1596
  }
529
1597
 
530
1598
  // ---- peers ---------------------------------------------------------------
531
- const manifest = /** @type {{ peerDependencies?: Record<string, string> }} */ (JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")));
532
1599
  const peers = Object.entries(manifest.peerDependencies ?? {});
533
1600
  const badPeers = [];
534
1601
  const unknownPeers = [];
@@ -541,14 +1608,47 @@ async function main(options) {
541
1608
  if (badPeers.length === 0) check("peers.versions", "ok", "Peer versions", `${peers.length} pinned peer(s) match${unknownPeers.length > 0 ? `; ${unknownPeers.length} unchecked` : ""}`);
542
1609
  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");
543
1610
 
544
- // ---- profile-patch trap --------------------------------------------------
1611
+ 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
+ // ---- effective configuration (verdict inputs, reported) ------------------
1633
+ check("config.effective", configRecognized ? "ok" : "info", "Effective configuration",
1634
+ configRecognized
1635
+ ? `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
+ : "the shipped preset rows were not recognized; the conservative defaults apply (sessionSandbox: true, so a missing systemd blocks) — see docs/CONFIGURATION.md");
1637
+
1638
+ phase("update-peers");
1639
+ // ---- profile-patch trap and deprecated keys ------------------------------
545
1640
  const dshHome = process.env.DSH_HOME !== undefined && process.env.DSH_HOME.length > 0 ? process.env.DSH_HOME : join(homedir(), ".dsh");
546
1641
  const profilesDir = join(dshHome, "profiles");
547
1642
  if (!existsSync(profilesDir)) {
548
1643
  check("config.profiles", "info", "Profile patches", `no profiles under ${profilesDir}`);
1644
+ check("config.deprecated", "info", "Deprecated keys", "no profile layers to scan");
549
1645
  } else {
550
1646
  /** @type {string[]} */
551
1647
  const trapped = [];
1648
+ /** @type {string[]} */
1649
+ const retired = [];
1650
+ /** @type {string[]} */
1651
+ const emptyDistro = [];
552
1652
  let seen = 0;
553
1653
  for (const entry of readdirSync(profilesDir, { withFileTypes: true })) {
554
1654
  if (!entry.isDirectory()) continue;
@@ -557,34 +1657,114 @@ async function main(options) {
557
1657
  seen += 1;
558
1658
  const text = readFileSync(patch, "utf8");
559
1659
  if (/^\s*-\s*id:\s*(wsl-shell|wsl-fs)\s*$/m.test(text)) trapped.push(entry.name);
1660
+ if (/substrate:\s*["']?share["']?/m.test(text)) retired.push(entry.name);
1661
+ if (/^\s*distro:\s*['"]['"]\s*$/m.test(text)) emptyDistro.push(entry.name);
560
1662
  }
561
1663
  if (trapped.length > 0) {
562
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");
563
1665
  } else {
564
1666
  check("config.profiles", "ok", "Profile patches", `${seen} profile patch(es) scanned`);
565
1667
  }
1668
+ 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");
1670
+ } else if (emptyDistro.length > 0) {
1671
+ 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
+ } else {
1673
+ check("config.deprecated", "ok", "Deprecated keys", `${seen} profile patch(es) scanned, none carry retired keys`);
1674
+ }
566
1675
  }
567
1676
 
568
- // ---- fixes ---------------------------------------------------------------
1677
+ phase("config");
1678
+ // ---- 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
1681
+ // fix is followed by a fresh probe of what it claims to have fixed — the
1682
+ // revised check carries the after state (so the verdict at the end is the
1683
+ // post-fix verdict, ready or the remaining blockers), and the fix.* row
1684
+ // narrates the before → after transition. A distro that never became
1685
+ // reachable has no state to fix.
569
1686
  if (options.fix) {
570
- if (stale > 0) {
571
- const swept = await inDistro(distro, sessionScopeSweepScript());
572
- check("fix.scopes", swept.ok ? "ok" : "warn", "Swept stale scopes", swept.ok ? `${stale} stale scope(s) stopped` : "the sweep failed", swept.ok ? undefined : `systemctl --user list-units 'dsh-wsl-*.scope' inside "${distro}"`);
573
- }
574
- if (bwrapPath.length === 0) {
575
- if (!options.install) {
576
- check("fix.install", "info", "Package installation", "not attempted", "re-run with --fix --install (and --yes for a non-interactive run)");
577
- } else if (!(await confirm(`Install ${PACKAGES} in "${distro}" as root?`, options.yes))) {
578
- check("fix.install", "info", "Package installation", "declined", install);
579
- } else {
580
- const command = INSTALL[family] ?? INSTALL["apt-get"] ?? `apt-get install -y ${PACKAGES}`;
581
- const installed = await run([WSL, "-d", distro, "-u", "root", "--", "sh", "-c", command]);
582
- check("fix.install", installed.ok ? "ok" : "warn", "Package installation", installed.ok ? "completed" : "failed; see the output above", installed.ok ? undefined : install);
1687
+ /** Replace one pushed check's verdict in place — the fix loop's "after".
1688
+ * @param {string} id - the check id.
1689
+ * @param {string | undefined} distro - the distro scope, for distro-scoped ids.
1690
+ * @param {Partial<Check>} patch - the fields to revise. */
1691
+ const reviseCheck = (/** @type {string} */ id, /** @type {string | undefined} */ distro, /** @type {Partial<Check>} */ patch, /** @type {string | undefined} */ title = undefined) => {
1692
+ const entry = checks.find((entry) => entry.id === id && (distro === undefined || entry.distro === distro));
1693
+ if (entry === undefined) {
1694
+ // A check the first pass never pushed (its prerequisite was missing)
1695
+ // still deserves an after-state row once the fix created it.
1696
+ if (title === undefined) return;
1697
+ const created = /** @type {Check} */ ({ id, status: "ok", title: title ?? id, detail: "", ...(distro === undefined ? {} : { distro }) });
1698
+ Object.assign(created, patch);
1699
+ checks.push(created);
1700
+ return;
1701
+ }
1702
+ Object.assign(entry, patch);
1703
+ };
1704
+ for (const [target, state] of states) {
1705
+ if (!state.reachable) continue;
1706
+ const fixCheck = (/** @type {string} */ id, /** @type {Check["status"]} */ status, /** @type {string} */ title, /** @type {string | undefined} */ detail = undefined, /** @type {string | undefined} */ remedy = undefined) => {
1707
+ checks.push({ id, status, title, ...(detail === undefined ? {} : { detail }), ...(remedy === undefined ? {} : { remedy }), distro: target });
1708
+ };
1709
+ if (state.stale > 0) {
1710
+ const swept = await inDistro(target, sessionScopeSweepScript());
1711
+ const afterReport = (await inDistro(target, STALE_SCOPE_REPORT)).stdout.trim();
1712
+ const afterLines = afterReport === "none" || afterReport.length === 0 ? [] : afterReport.split(/\r?\n/);
1713
+ const afterStale = afterLines.filter((line) => /\sstale(\s|$)/.test(line)).length;
1714
+ const fixed = swept.ok && afterStale === 0;
1715
+ 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}"`);
1716
+ reviseCheck("runtime.scopes", target, afterLines.length === 0
1717
+ ? { status: "info", detail: "none (the fix above swept them)", remedy: undefined }
1718
+ : { 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
+ }
1720
+ if (state.bwrapPath.length === 0) {
1721
+ const install = installRemedy(target, state.family);
1722
+ if (!options.install) {
1723
+ fixCheck("fix.install", "info", "Package installation", "not attempted", "re-run with --fix --install (and --yes for a non-interactive run)");
1724
+ } else if (!(await confirm(doctorT("confirm.install", { packages: PACKAGES, distro: target }), options.yes))) {
1725
+ fixCheck("fix.install", "info", "Package installation", "declined", install);
1726
+ } else {
1727
+ const command = INSTALL[state.family] ?? INSTALL["apt-get"] ?? `apt-get install -y ${PACKAGES}`;
1728
+ const installed = await run([WSL, "-d", target, "-u", "root", "--", "sh", "-c", command]);
1729
+ const bwrapAfter = (await inDistro(target, "command -v bwrap")).stdout.trim();
1730
+ const usableAfter = bwrapAfter.length > 0 ? (await inDistro(target, "bwrap --ro-bind / / -- true")).ok : false;
1731
+ const done = installed.ok && bwrapAfter.length > 0;
1732
+ fixCheck("fix.install", done ? "ok" : "warn", "Package installation", installed.ok
1733
+ ? `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"}`
1734
+ : "failed; see the output above", done ? undefined : install);
1735
+ reviseCheck("sandbox.bwrap", target, bwrapAfter.length > 0
1736
+ ? { status: "ok", detail: bwrapAfter, remedy: undefined }
1737
+ : { status: "fail", detail: "still missing after the install", remedy: install });
1738
+ reviseCheck("sandbox.bwrap-usable", target, bwrapAfter.length > 0
1739
+ ? { status: usableAfter ? "ok" : "fail", detail: usableAfter ? "a read-only profile runs" : "installed but the read-only profile failed", remedy: usableAfter ? undefined : "the kernel likely disables unprivileged user namespaces; reinstalling will not help — see docs/LIMITATIONS.md" }
1740
+ : {}, "bubblewrap usability");
1741
+ }
1742
+ }
1743
+ }
1744
+ // B3: the Windows git whitelist is user-scoped and reversible — the same
1745
+ // 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) {
1748
+ const gitEntry = checks.find((entry) => entry.id === "git.win-safe");
1749
+ if (gitEntry !== undefined && gitEntry.status === "warn") {
1750
+ if (await confirm('Add "//wsl.localhost/*" to the Windows git safe.directory whitelist?', options.yes)) {
1751
+ const added = await run(["git.exe", "config", "--global", "--add", "safe.directory", "//wsl.localhost/*"]);
1752
+ const entries = (await run(["git.exe", "config", "--global", "--get-all", "safe.directory"])).stdout.split(/\r?\n/).filter(Boolean);
1753
+ const whitelisted = entries.some((entry) => /wsl\.localhost/i.test(entry));
1754
+ reviseCheck("git.win-safe", undefined, whitelisted
1755
+ ? { 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 }
1756
+ : {});
1757
+ 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' });
1758
+ } else {
1759
+ 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/*"' });
1760
+ }
583
1761
  }
584
1762
  }
585
1763
  }
586
1764
 
587
- return report(checks, { json: options.json });
1765
+ phase("fix");
1766
+ timingsMs.total = Date.now() - runStart;
1767
+ return report(checks, { json: options.json }, runInfo);
588
1768
  }
589
1769
 
590
1770
  /**
@@ -632,13 +1812,189 @@ function probeResident(distro, scriptPath, wslExe = WSL) {
632
1812
  finish({ ok: true, pid: Number(pid), digestMatches: digest === expected });
633
1813
  });
634
1814
  child.on("error", (error) => finish({ ok: false, detail: error.message }));
635
- child.on("exit", () => {
636
- if (!settled) finish({ ok: false, detail: `agent exited before its HELLO (${buffered.trim().slice(0, 80)})` });
1815
+ child.on("close", () => {
1816
+ if (settled) return;
1817
+ // 'exit' can fire before the stdio pipes are drained — the HELLO sits
1818
+ // in the pipe while the parent-side buffer looks empty (a loaded host
1819
+ // widens the window). 'close' fires after the streams flush, so the
1820
+ // harvest here sees everything the agent wrote.
1821
+ const first = buffered.split("\n")[0]?.trim() ?? "";
1822
+ if (first.startsWith("HELLO|")) {
1823
+ const [kind, name, version, digest, pid] = first.split("|");
1824
+ if (kind === "HELLO" && name === AGENT_NAME && Number(version) === PROTOCOL_VERSION) {
1825
+ const expected = createHash("sha256").update(readFileSync(scriptPath)).digest("hex");
1826
+ finish({ ok: true, pid: Number(pid), digestMatches: digest === expected });
1827
+ return;
1828
+ }
1829
+ }
1830
+ finish({ ok: false, detail: `agent exited before its HELLO (${buffered.trim().slice(0, 80)})` });
637
1831
  });
638
1832
  child.stdin.end();
639
1833
  });
640
1834
  }
641
1835
 
1836
+ /**
1837
+ * One smoke session against a fresh resident: spawn it, read the HELLO, run
1838
+ * one EXEC round trip (`uname -m`), create a temp dir over the same transport,
1839
+ * send one FSB batch (stat + list) against it, remove the dir, shut the
1840
+ * resident down. This is the chain the session actually rides — frame I/O and
1841
+ * the protocol v7 substrate — not a parallel probe path. Every failure names
1842
+ * its leg; a resident that dies mid-smoke fails fast instead of hanging.
1843
+ *
1844
+ * @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.
1848
+ */
1849
+ function runSmokeLegs(distro, scriptPath, wslExe = WSL) {
1850
+ return new Promise((settle) => {
1851
+ const child = spawn(wslExe, ["-d", distro, "--exec", "sh", scriptPath], {
1852
+ stdio: ["pipe", "pipe", "pipe"],
1853
+ windowsHide: true,
1854
+ env: { ...process.env, WSL_UTF8: "1" },
1855
+ });
1856
+ let settled = false;
1857
+ let buffer = "";
1858
+ let helloSeen = false;
1859
+ /** @type {Map<string, (line: string) => void>} */
1860
+ const waiters = new Map();
1861
+ let helloResolve = /** @type {((value: boolean) => void) | undefined} */ (undefined);
1862
+ const helloPromise = new Promise((resolve) => { helloResolve = resolve; });
1863
+ const timer = setTimeout(() => finish({ execOk: false, execDetail: "the smoke session timed out", fsOk: false, fsDetail: "the smoke session timed out" }), 30_000);
1864
+ /** @param {{ execOk: boolean, execDetail: string, fsOk: boolean, fsDetail: string }} value - the leg verdicts. */
1865
+ const finish = (value) => {
1866
+ if (settled) return;
1867
+ settled = true;
1868
+ clearTimeout(timer);
1869
+ try { child.stdin.write("SHUTDOWN\n"); } catch { /* the resident may already be gone */ }
1870
+ setTimeout(() => {
1871
+ try { child.kill(); } catch { /* already gone */ }
1872
+ settle(value);
1873
+ }, 150);
1874
+ };
1875
+ child.stdout.on("data", (chunk) => {
1876
+ buffer += String(chunk);
1877
+ for (;;) {
1878
+ const newline = buffer.indexOf("\n");
1879
+ if (newline < 0) break;
1880
+ const line = buffer.slice(0, newline).trim();
1881
+ buffer = buffer.slice(newline + 1);
1882
+ if (line.length === 0) continue;
1883
+ const parsed = parseAgentLine(line);
1884
+ if (parsed.type === "hello") {
1885
+ helloSeen = true;
1886
+ helloResolve?.(true);
1887
+ continue;
1888
+ }
1889
+ if (parsed.type === "ack" || parsed.type === "pong" || parsed.type === "unknown") continue;
1890
+ const id = parsed.type === "result" || parsed.type === "agentError" || parsed.type === "fsError" ? parsed.id : "";
1891
+ const waiter = waiters.get(id);
1892
+ if (waiter !== undefined) {
1893
+ waiters.delete(id);
1894
+ waiter(line);
1895
+ }
1896
+ }
1897
+ });
1898
+ let childGone = false;
1899
+ child.on("error", (error) => finish({ execOk: false, execDetail: error.message, fsOk: false, fsDetail: error.message }));
1900
+ // A dead resident's pipe surfaces as EPIPE on the write side; the exit
1901
+ // handler names the cause, so the write-side error is swallowed.
1902
+ child.stdin.on("error", () => { /* named by the exit handler */ });
1903
+ child.on("close", () => {
1904
+ childGone = true;
1905
+ if (settled) return;
1906
+ // The same pipe-ordering race the handshake probe guards: a buffered
1907
+ // HELLO counts even when the data event has not fired yet.
1908
+ if (!helloSeen && buffer.includes("HELLO|")) {
1909
+ helloSeen = true;
1910
+ helloResolve?.(true);
1911
+ }
1912
+ if (!settled && waiters.size > 0) finish({ execOk: false, execDetail: "the resident exited mid-smoke", fsOk: false, fsDetail: "the resident exited mid-smoke" });
1913
+ });
1914
+ /** Send one request and resolve with the reply line that answers it.
1915
+ * @param {string} id - the request id.
1916
+ * @param {string[]} lines - the frame's lines. */
1917
+ const request = (id, lines) => new Promise((resolve) => {
1918
+ waiters.set(id, resolve);
1919
+ child.stdin.write(`${lines.join("\n")}\n`);
1920
+ });
1921
+ (async () => {
1922
+ // The race's losing timer must be cleared: a live timer keeps the
1923
+ // process lingering ~5 s past the report — per invocation.
1924
+ await new Promise((resolve) => {
1925
+ const wait = setTimeout(resolve, 5000);
1926
+ helloPromise.then(() => { clearTimeout(wait); resolve(true); });
1927
+ });
1928
+ if (!helloSeen) return finish({ execOk: false, execDetail: "no HELLO", fsOk: false, fsDetail: "no HELLO" });
1929
+ if (childGone) return finish({ execOk: false, execDetail: "the resident exited mid-smoke", fsOk: false, fsDetail: "the resident exited mid-smoke" });
1930
+ const execId = "smoke-exec";
1931
+ const execLine = await request(execId, encodeExecFrame({ id: execId, cwd: "/tmp", argv: ["uname", "-m"], timeoutMs: 15_000, maxOutputBytes: 4096 }));
1932
+ const execParsed = parseAgentLine(execLine);
1933
+ const execAnswer = execParsed.type === "result" ? execParsed.stdout.toString("utf8").trim() : "";
1934
+ const execOk = execParsed.type === "result" && execParsed.exitCode === 0 && execAnswer.length > 0;
1935
+ const execDetail = execOk
1936
+ ? `uname -m answered "${execAnswer}" over the frame round trip`
1937
+ : execParsed.type === "result"
1938
+ ? `exit ${execParsed.exitCode}: ${execParsed.stderr.toString("utf8").slice(0, 120)}`
1939
+ : execParsed.type === "agentError"
1940
+ ? `${execParsed.reason}: ${execParsed.message}`
1941
+ : `unexpected reply: ${execLine.slice(0, 80)}`;
1942
+ const mkId = "smoke-mktemp";
1943
+ const mkLine = await request(mkId, encodeExecFrame({ id: mkId, cwd: "/tmp", argv: ["mktemp", "-d", "/tmp/dsh-doctor-smoke-XXXXXXXX"], timeoutMs: 15_000, maxOutputBytes: 4096 }));
1944
+ const mkParsed = parseAgentLine(mkLine);
1945
+ const dir = mkParsed.type === "result" && mkParsed.exitCode === 0 ? mkParsed.stdout.toString("utf8").trim() : "";
1946
+ if (dir.length === 0) {
1947
+ return finish({ execOk, execDetail, fsOk: false, fsDetail: "the temp dir for the batch leg could not be created" });
1948
+ }
1949
+ const fsbId = "smoke-fsb";
1950
+ const fsbLine = await request(fsbId, encodeFsbFrame({ id: fsbId, timeoutMs: 15_000, ops: [{ op: "stat", args: [dir] }, { op: "list", args: [dir] }] }));
1951
+ const fsbParsed = parseAgentLine(fsbLine);
1952
+ const payload = fsbParsed.type === "result" ? fsbParsed.stdout.toString("utf8") : "";
1953
+ const fsOk = fsbParsed.type === "result" && fsbParsed.exitCode === 0 && payload.includes("OK 1") && payload.includes("OK 2");
1954
+ const rmId = "smoke-cleanup";
1955
+ const rmLine = await request(rmId, encodeExecFrame({ id: rmId, cwd: "/tmp", argv: ["rm", "-rf", dir], timeoutMs: 15_000, maxOutputBytes: 4096 }));
1956
+ const rmParsed = parseAgentLine(rmLine);
1957
+ const cleanupOk = rmParsed.type === "result" && rmParsed.exitCode === 0;
1958
+ const fsDetail = fsOk
1959
+ ? `stat + list over ${dir} answered one batch round trip${cleanupOk ? "; the dir is removed" : `; CLEANUP FAILED — ${dir} is left behind`}`
1960
+ : fsbParsed.type === "result"
1961
+ ? `exit ${fsbParsed.exitCode}: ${payload.slice(0, 120)}${cleanupOk ? "" : `; cleanup failed, ${dir} is left behind`}`
1962
+ : fsbParsed.type === "fsError"
1963
+ ? `${fsbParsed.reason}: ${fsbParsed.message}`
1964
+ : `unexpected reply: ${fsbLine.slice(0, 80)}`;
1965
+ return finish({ execOk, execDetail, fsOk, fsDetail });
1966
+ })().catch((error) => finish({ execOk: false, execDetail: /** @type {Error} */ (error).message, fsOk: false, fsDetail: /** @type {Error} */ (error).message }));
1967
+ });
1968
+ }
1969
+
1970
+ /**
1971
+ * The confined-profile smoke: the shipped bwrap builder's per-command shape,
1972
+ * run against a distro temp dir — a write inside the granted root must run,
1973
+ * a write outside it (into the read-only-bound /etc) must be refused. These
1974
+ * are the two assertions `probe:sandbox` makes, in miniature, so the doctor's
1975
+ * verdict covers the fence and not just the binary.
1976
+ * @param {string} distro - the distro.
1977
+ * @returns {Promise<{ ok: boolean, flaked: boolean, detail: string }>} the fence verdict.
1978
+ */
1979
+ async function runSandboxSmoke(distro) {
1980
+ const dirAnswer = await askDistro(distro, 'd=$(mktemp -d /tmp/dsh-doctor-smoke-XXXXXXXX) && printf %s "$d"');
1981
+ const dir = dirAnswer.stdout.trim();
1982
+ if (dir.length === 0) return { ok: false, flaked: !dirAnswer.ok && dirAnswer.flaked, detail: "the temp dir for the fence leg could not be created" };
1983
+ const prefix = bwrapArgvPrefix({ mode: "workspace-write", workspaceRoot: dir }, {});
1984
+ const inside = await run([WSL, "-d", distro, "--exec", ...prefix, "sh", "-c", 'printf ok > "$0" && cat "$0"', `${dir}/inside`]);
1985
+ const outside = await run([WSL, "-d", distro, "--exec", ...prefix, "sh", "-c", 'printf no > "$0" 2>/dev/null', "/etc/dsh-doctor-smoke-refuse"]);
1986
+ const cleanup = await askDistro(distro, `rm -rf "${dir}"`);
1987
+ const flaked = [inside, outside, cleanup].some((answer) => isFlake(answer));
1988
+ const insideOk = inside.ok && inside.stdout.trim() === "ok";
1989
+ const outsideRefused = !outside.ok;
1990
+ const ok = insideOk && outsideRefused;
1991
+ return {
1992
+ ok,
1993
+ flaked,
1994
+ detail: `a write inside ${dir} ${insideOk ? "ran" : "was REFUSED (the profile broke)"} and a write to /etc ${outsideRefused ? "was refused" : "RAN (the fence is open)"} — the shipped workspace-write shape${cleanup.ok ? "" : `; CLEANUP FAILED — ${dir} is left behind`}`,
1995
+ };
1996
+ }
1997
+
642
1998
  /**
643
1999
  * Ask one yes/no question on the terminal.
644
2000
  * @param {string} question - the prompt.
@@ -658,40 +2014,119 @@ async function confirm(question, yes) {
658
2014
  }
659
2015
 
660
2016
  /**
661
- * Print the report and return the exit status.
662
- * @param {Check[]} checks - the collected checks.
2017
+ * Assemble the report: stamp the blocking flag onto every check, compute the
2018
+ * per-distro and overall verdicts, print, and return the exit status.
2019
+ *
2020
+ * The blocking invariant is structural: a `fail` blocks, everything else does
2021
+ * not — config-awareness lives in the statuses (see the session checks), never
2022
+ * in a per-id exception here. A `skipped` check is a consequence of a blocker,
2023
+ * not a blocker itself.
2024
+ *
2025
+ * @param {Check[]} checks - the collected checks (distro-scoped ones carry their `distro`).
663
2026
  * @param {{ json: boolean }} options - the output mode.
664
- * @returns {number} 0 when nothing failed, 1 otherwise.
2027
+ * @param {{ distros?: string[], config?: EffectiveConfig, timingsMs?: Record<string, number>, scope?: { sections: string[], quick: boolean }, bundle?: { path: string, redact: boolean, manifest: { name?: string, version?: string, peerDependencies?: Record<string, string> } } }} [runInfo] - the target distros, the effective configuration, the run scope, the per-phase wall clock, and the bundle request.
2028
+ * @returns {number} 0 when the verdict is `ready`, 1 when `blocked`.
665
2029
  */
666
- function report(checks, options) {
2030
+ function report(checks, options, runInfo = {}) {
2031
+ // Scoped run: keep only the requested sections. `distro.reachable` is the
2032
+ // transport gate every scoped run probes, so it always stays — a scoped
2033
+ // verdict answers "is this distro healthy *within the requested scope*".
2034
+ const wantedSections = runInfo.scope === undefined ? null : new Set(runInfo.scope.sections);
2035
+ /** @param {{ id: string }} entry - the check. @returns {boolean} whether it survives the scope. */
2036
+ const inScope = (entry) => wantedSections === null || wantedSections.has(sectionOf(entry.id)) || entry.id === "distro.reachable";
2037
+ const scoped = checks.filter(inScope);
2038
+ const stamped = scoped.map((entry) => ({
2039
+ ...entry,
2040
+ blocksFirstCommand: entry.status === "fail",
2041
+ }));
667
2042
  /** @param {string} status - the status to count. @returns {number} how many checks carry it. */
668
- const count = (status) => checks.filter((entry) => entry.status === status).length;
669
- const summary = { ok: count("ok"), warn: count("warn"), fail: count("fail"), info: count("info") };
2043
+ const count = (status) => stamped.filter((entry) => entry.status === status).length;
2044
+ const summary = { ok: count("ok"), warn: count("warn"), fail: count("fail"), info: count("info"), skipped: count("skipped"), unknown: count("unknown") };
2045
+ const blockers = stamped.filter((entry) => entry.blocksFirstCommand).map((entry) => entry.id);
2046
+ const verdict = blockers.length === 0 ? "ready" : "blocked";
2047
+ /** The blockers a distro verdict owns: its own fails plus the host-level ones.
2048
+ * @param {string} name - the distro name.
2049
+ * @returns {string[]} the blocking ids. */
2050
+ const distroBlockers = (name) => stamped
2051
+ .filter((entry) => entry.blocksFirstCommand && (entry.distro === name || entry.distro === undefined))
2052
+ .map((entry) => entry.id);
2053
+ const targets = runInfo.distros ?? [];
2054
+ const distroVerdicts = targets.map((name) => ({
2055
+ name,
2056
+ verdict: distroBlockers(name).length === 0 ? "ready" : "blocked",
2057
+ blockers: distroBlockers(name),
2058
+ }));
670
2059
  if (options.json) {
671
- console.log(JSON.stringify({ schemaVersion: 1, generatedAt: new Date().toISOString(), checks, summary }, null, 2));
2060
+ console.log(JSON.stringify({
2061
+ schemaVersion: 2,
2062
+ generatedAt: new Date().toISOString(),
2063
+ ...(runInfo.config === undefined ? {} : { config: runInfo.config }),
2064
+ ...(runInfo.scope === undefined ? {} : { scope: runInfo.scope }),
2065
+ checks: stamped,
2066
+ summary,
2067
+ distroVerdicts,
2068
+ verdict,
2069
+ blockers,
2070
+ ...(runInfo.timingsMs === undefined ? {} : { timingsMs: runInfo.timingsMs }),
2071
+ }, null, 2));
672
2072
  } else {
673
- console.log("dsh-plugin-wsl-env doctor");
2073
+ console.log(doctorT("app"));
674
2074
  let section = "";
675
- for (const entry of checks) {
2075
+ let lastDistro = /** @type {string | undefined} */ (undefined);
2076
+ for (const entry of stamped) {
2077
+ if (entry.distro !== undefined && entry.distro !== lastDistro && targets.length > 1) {
2078
+ console.log(`\n[${entry.distro}]`);
2079
+ section = "";
2080
+ lastDistro = entry.distro;
2081
+ }
676
2082
  const current = entry.id.split(".")[0] ?? "";
677
2083
  if (current !== section) {
678
2084
  section = current;
679
2085
  console.log(`\n${section}`);
680
2086
  }
681
- const mark = entry.status === "ok" ? "ok " : entry.status === "warn" ? "warn" : entry.status === "fail" ? "fail" : "info";
2087
+ const mark = doctorT(`mark.${entry.status}`);
682
2088
  console.log(` ${mark} ${entry.title}${entry.detail === undefined ? "" : ` — ${entry.detail}`}`);
683
- if (entry.remedy !== undefined) console.log(` fix: ${entry.remedy}`);
2089
+ if (entry.remedy !== undefined) console.log(doctorT("fix.prefix", { remedy: entry.remedy }));
2090
+ }
2091
+ const summaryLine = doctorT("summary", { ok: summary.ok, warn: summary.warn, fail: summary.fail, info: summary.info })
2092
+ + (summary.skipped > 0 ? doctorT("summary.skipped", { n: summary.skipped }) : "")
2093
+ + (summary.unknown > 0 ? doctorT("summary.unknown", { n: summary.unknown }) : "");
2094
+ console.log(`\n${summaryLine}`);
2095
+ const timingLine = Object.entries(runInfo.timingsMs ?? {}).filter(([key]) => key !== "total").map(([key, ms]) => `${key} ${ms}ms`).join(", ");
2096
+ if (timingLine.length > 0) console.log(doctorT("timings", { line: timingLine, total: runInfo.timingsMs?.total ?? "?" }));
2097
+ if (verdict === "ready") console.log(targets.length === 1 && targets[0] !== undefined
2098
+ ? doctorT("verdict.ready.one", { target: targets[0] })
2099
+ : targets.length > 1
2100
+ ? doctorT("verdict.ready.many", { targets: targets.join(", ") })
2101
+ : doctorT("verdict.ready.none"));
2102
+ else console.log(doctorT("verdict.blocked", { blockers: blockers.join(", ") }));
2103
+ if (summary.fail > 0 || summary.skipped > 0) console.log(doctorT("fix.hint"));
2104
+ }
2105
+ if (runInfo.bundle !== undefined) {
2106
+ const bundle = {
2107
+ kind: "dsh-plugin-wsl-env doctor bundle",
2108
+ contentNote: "the doctor report, the plugin and peer versions, and the effective configuration. No file contents, no environment variables, no telemetry — attach this file to a setup report.",
2109
+ plugin: { name: runInfo.bundle.manifest.name ?? "dsh-plugin-wsl-env", version: runInfo.bundle.manifest.version ?? "", peers: runInfo.bundle.manifest.peerDependencies ?? {} },
2110
+ ...(runInfo.config === undefined ? {} : { config: runInfo.config }),
2111
+ report: { schemaVersion: 2, generatedAt: new Date().toISOString(), checks: stamped, summary, distroVerdicts, verdict, blockers, ...(runInfo.timingsMs === undefined ? {} : { timingsMs: runInfo.timingsMs }) },
2112
+ redacted: runInfo.bundle.redact ? "home and DSH paths replaced with <redacted-*>" : false,
2113
+ };
2114
+ let payload = `${JSON.stringify(bundle, null, 2)}\n`;
2115
+ if (runInfo.bundle.redact) {
2116
+ const homeReal = homedir();
2117
+ const dshReal = process.env.DSH_HOME !== undefined && process.env.DSH_HOME.length > 0 ? process.env.DSH_HOME : join(homeReal, ".dsh");
2118
+ payload = payload.split(homeReal).join("<redacted-home>").split(dshReal).join("<redacted-dsh-home>");
684
2119
  }
685
- console.log(`\n${summary.ok} ok, ${summary.warn} warn, ${summary.fail} fail, ${summary.info} info`);
686
- if (summary.fail > 0) console.log("run with --fix to sweep stale scopes; --fix --install asks before installing packages");
2120
+ writeFileSync(runInfo.bundle.path, payload);
2121
+ console.log(doctorT("bundle.written", { path: runInfo.bundle.path, bytes: payload.length, redacted: runInfo.bundle.redact ? doctorT("bundle.redacted") : "" }));
687
2122
  }
688
- return summary.fail > 0 ? 1 : 0;
2123
+ return verdict === "blocked" ? 1 : 0;
689
2124
  }
690
2125
 
691
2126
  if (process.argv[1] !== undefined && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
692
2127
  const options = parseArgs(process.argv.slice(2));
693
2128
  if (options.help) {
694
- console.log("node scripts/doctor.mjs [distro] [--json] [--fix] [--install] [--yes] [--read-only]");
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>]");
695
2130
  } else {
696
2131
  process.exitCode = await main(options);
697
2132
  }