dsh-plugin-wsl-env 0.19.0 → 0.21.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 (43) hide show
  1. package/CHANGELOG.md +122 -0
  2. package/README.md +2 -2
  3. package/client.d.ts +5 -0
  4. package/client.js +98 -0
  5. package/cordis.patch.yml +66 -1
  6. package/docs/API.md +1 -0
  7. package/docs/CONFIGURATION.md +39 -5
  8. package/docs/CONFIGURATION.zh.md +15 -1
  9. package/docs/DIAGNOSTICS.md +83 -0
  10. package/docs/DIAGNOSTICS.zh.md +73 -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.js +6 -8
  28. package/lib/messages.d.ts +157 -0
  29. package/lib/messages.js +199 -0
  30. package/lib/preflight.d.ts +24 -0
  31. package/lib/preflight.js +111 -11
  32. package/lib/sandbox-core.js +7 -14
  33. package/lib/session-scope.js +10 -5
  34. package/lib/shell-env.d.ts +25 -0
  35. package/lib/shell-env.js +56 -0
  36. package/lib/shell.d.ts +3 -1
  37. package/lib/shell.js +3 -1
  38. package/lib/update-check.d.ts +197 -0
  39. package/lib/update-check.js +211 -0
  40. package/lib/wsl-doctor-tool.d.ts +122 -0
  41. package/lib/wsl-doctor-tool.js +161 -0
  42. package/package.json +43 -5
  43. package/scripts/doctor.mjs +1167 -160
@@ -1,28 +1,38 @@
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. `--fix` performs only safe
24
+ * actions: it sweeps stale `dsh-wsl-*.scope` units (the same sweep the session
25
+ * preflight runs). Installing packages needs `--install` *and* an explicit
26
+ * confirmation (`--yes` skips the prompt, not the flag), so a fix run can never
27
+ * install silently.
20
28
  *
21
29
  * `--read-only` refuses `--fix`/`--install`; `scripts/diagnose.sh` uses it to stay an
22
30
  * alias that can never change the machine.
23
31
  *
24
32
  * `--json` prints one machine-readable report instead of the human sections.
25
- * The report shape is versioned (`schemaVersion`).
33
+ * The report shape is versioned (`schemaVersion: 2`): `verdict`, `blockers`,
34
+ * `distroVerdicts`, the effective `config`, and per-check `distro` /
35
+ * `blocksFirstCommand` fields.
26
36
  *
27
37
  * This CLI always probes a **fresh** resident — the app process's live
28
38
  * resident's `deaths`/`lastError` are host-private (no IPC), and the report
@@ -35,15 +45,18 @@
35
45
  import { execFile, spawn } from "node:child_process";
36
46
  import { createHash } from "node:crypto";
37
47
  import { createRequire } from "node:module";
38
- import { existsSync, readdirSync, readFileSync } from "node:fs";
48
+ import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
39
49
  import { homedir } from "node:os";
40
50
  import { dirname, join, resolve } from "node:path";
41
51
  import { createInterface } from "node:readline/promises";
42
52
  import { fileURLToPath } from "node:url";
43
53
  import { parseDistroList } from "../lib/wsl.js";
44
- import { AGENT_NAME, PROTOCOL_VERSION } from "../lib/agent-protocol.js";
54
+ import { effectiveMaskWindowsDrive } from "../lib/index.js";
55
+ import { AGENT_NAME, PROTOCOL_VERSION, encodeExecFrame, encodeFsbFrame, parseAgentLine } from "../lib/agent-protocol.js";
56
+ import { bwrapArgvPrefix } from "../lib/bwrap.js";
45
57
  import { sessionScopeSweepScript } from "../lib/session-scope.js";
46
58
  import { parseListeningPorts, procNetScript } from "../lib/ports.js";
59
+ import { updateFactMessage } from "../lib/update-check.js";
47
60
 
48
61
  const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
49
62
  let WSL = "wsl.exe";
@@ -91,10 +104,25 @@ const CACHE_REPORT = [
91
104
  * One check result.
92
105
  * @typedef {object} Check
93
106
  * @property {string} id - stable dotted id.
94
- * @property {"ok"|"warn"|"fail"|"info"} status - the verdict.
107
+ * @property {"ok"|"warn"|"fail"|"info"|"skipped"} status - the verdict.
95
108
  * @property {string} title - what was checked.
96
109
  * @property {string} [detail] - the evidence.
97
110
  * @property {string} [remedy] - a copy-paste next step when not ok.
111
+ * @property {string} [distro] - the distro the check ran against (distro-scoped checks only).
112
+ * @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).
113
+ */
114
+
115
+ /**
116
+ * The effective configuration the blocking verdict answers under.
117
+ * @typedef {object} EffectiveConfig
118
+ * @property {string} distro - `auto`, `default` or a pinned distro name.
119
+ * @property {string} sessionSandbox - `true`, `false` or `auto`.
120
+ * @property {string} agentBackend - `auto`, `native` or `shell`.
121
+ * @property {string} sandbox - the fs-routing confinement stance.
122
+ * @property {string} maskWindowsDrive - the drive-masking stance (when `interopVisibility` is unset).
123
+ * @property {string} interopVisibility - the one-key stance (`""` unset, `visible`, `masked` or `disabled`); when set it takes precedence over `maskWindowsDrive`.
124
+ * @property {string} source - where the values came from.
125
+ * @property {string[]} overrides - the profile layers that changed keys, "`<name>`: `<keys>`".
98
126
  */
99
127
 
100
128
  /**
@@ -119,6 +147,250 @@ function run(argv) {
119
147
  });
120
148
  }
121
149
 
150
+ /**
151
+ * Parse `wsl.exe -l -v`'s table. The state column is localized, so only the
152
+ * shape is trusted: `NAME[*] <state> <version>` — with the default marker
153
+ * BEFORE the name on WSL 3.x (`* ubuntu`) and after it on 2.x (`ubuntu*`).
154
+ * The version digit is what `distro.wsl-mode` classifies.
155
+ * @param {string} stdout - the command's output, nulls stripped.
156
+ * @returns {Array<{ name: string, isDefault: boolean, version: string }>} one entry per table row; the header drops out by shape.
157
+ */
158
+ export function parseWslVerbose(stdout) {
159
+ /** @type {Array<{ name: string, isDefault: boolean, version: string }>} */
160
+ const entries = [];
161
+ for (const line of stdout.split(/\r?\n/)) {
162
+ let rest = line.trim();
163
+ let isDefault = false;
164
+ if (rest.startsWith("* ")) {
165
+ isDefault = true;
166
+ rest = rest.slice(2).trim();
167
+ }
168
+ const match = /^(\S+?)(\*)?\s+\S+\s+(\d+)\s*$/.exec(rest);
169
+ if (match === null) continue;
170
+ const columns = /** @type {RegExpExecArray} */ (match);
171
+ entries.push({
172
+ name: (columns[1] ?? "").replace(/\*$/, ""),
173
+ isDefault: isDefault || columns[2] === "*",
174
+ version: columns[3] ?? "",
175
+ });
176
+ }
177
+ return entries;
178
+ }
179
+
180
+ /** The `[wsl2]` keys the `.wslconfig` validator knows; anything else is reported as ignored by WSL. */
181
+ const WSLCONFIG_KEYS = new Set([
182
+ "kernel", "kernelCommandLine", "memory", "processors", "swap", "swapFile", "pageReporting",
183
+ "localhostForwarding", "nestedVirtualization", "guiApplications", "debugConsole",
184
+ "earlyBootLogging", "vmIdleTimeout", "safeMode", "defaultVhdSize", "networkingMode",
185
+ "dnsTunneling", "firewall", "autoProxy",
186
+ ]);
187
+ /** The `[experimental]` keys the validator knows. */
188
+ const WSLCONFIG_EXPERIMENTAL_KEYS = new Set(["sparseVhd", "autoMemoryReclaim", "hostAddressLoopback", "guiApplications"]);
189
+
190
+ /**
191
+ * Byte-parse one WSL size scalar ("4GB", "512MB", "8368805888", "0").
192
+ * @param {string} value - the raw scalar.
193
+ * @returns {number | undefined} the size in bytes, or undefined when the shape is not a size.
194
+ */
195
+ export function parseWslSize(value) {
196
+ const match = /^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb|tb)?$/i.exec(value.trim());
197
+ if (match === null) return undefined;
198
+ const columns = /** @type {RegExpExecArray} */ (match);
199
+ const scale = { b: 1, kb: 1024, mb: 1024 ** 2, gb: 1024 ** 3, tb: 1024 ** 4 }[(columns[2] ?? "b").toLowerCase()] ?? 1;
200
+ return Math.round(Number(columns[1] ?? 0) * scale);
201
+ }
202
+
203
+ /**
204
+ * Parse and validate `%USERPROFILE%\.wslconfig`. WSL **silently ignores** a
205
+ * malformed file and unknown keys, so this parser is the only place the trap
206
+ * gets named; known keys with semantic hazards (no memory, tiny memory, the
207
+ * localhost forwarding the port survey depends on) are called out with their
208
+ * consequence. Findings are warnings, never blockers — the file degrades
209
+ * advice, not the first command.
210
+ * @param {string} text - the file's text.
211
+ * @returns {{ problems: string[], keyCount: number }} the findings, each naming its line.
212
+ */
213
+ export function parseWslConfig(text) {
214
+ /** @type {string[]} */
215
+ const problems = [];
216
+ let keyCount = 0;
217
+ let section = "";
218
+ for (const [index, rawLine] of text.split(/\r?\n/).entries()) {
219
+ const line = rawLine.trim();
220
+ if (line.length === 0 || line.startsWith("#") || line.startsWith(";")) continue;
221
+ const heading = /^\[(.+)\]$/.exec(line);
222
+ if (heading !== null) {
223
+ section = (/** @type {RegExpExecArray} */ (heading)[1] ?? "").trim().toLowerCase();
224
+ continue;
225
+ }
226
+ const eq = line.indexOf("=");
227
+ if (eq <= 0) {
228
+ problems.push(`line ${index + 1} is not "key = value" — WSL silently ignores a malformed file`);
229
+ continue;
230
+ }
231
+ const key = line.slice(0, eq).trim();
232
+ const value = line.slice(eq + 1).trim();
233
+ keyCount += 1;
234
+ const known = section === "wsl2" ? WSLCONFIG_KEYS : section === "experimental" ? WSLCONFIG_EXPERIMENTAL_KEYS : null;
235
+ if (known === null) {
236
+ problems.push(`line ${index + 1}: unknown section [${section}] — WSL ignores it`);
237
+ continue;
238
+ }
239
+ if (!known.has(key)) {
240
+ problems.push(`line ${index + 1}: unknown key "${key}" in [${section}] — WSL ignores it`);
241
+ continue;
242
+ }
243
+ if ((key === "memory" || key === "swap") && section === "wsl2") {
244
+ const bytes = parseWslSize(value);
245
+ if (bytes === undefined) problems.push(`line ${index + 1}: ${key}="${value}" is not a size (expect 4GB, 512MB, …)`);
246
+ else if (key === "memory" && bytes === 0) problems.push(`line ${index + 1}: memory=0 — the VM gets no memory and every distro misbehaves`);
247
+ else if (key === "memory" && bytes < 512 * 1024 * 1024) problems.push(`line ${index + 1}: memory="${value}" is below 512MB — the VM will thrash or OOM`);
248
+ }
249
+ if (key === "localhostForwarding" && section === "wsl2" && value === "false") {
250
+ problems.push(`line ${index + 1}: localhostForwarding=false — the port survey's http://localhost:<port> URLs will not resolve on the Windows side`);
251
+ }
252
+ }
253
+ return { problems, keyCount };
254
+ }
255
+
256
+ /**
257
+ * Parse an INI-shaped file (`wsl.conf` and `.wslconfig` share the shape) into
258
+ * sections. Section and key names are lowercased for lookup; the last value
259
+ * per key wins; comment lines and lines without `=` are skipped.
260
+ * @param {string} text - the file's text.
261
+ * @returns {Record<string, Record<string, string>>} the sections, keyed by their lowercase name.
262
+ */
263
+ export function parseIni(text) {
264
+ /** @type {Record<string, Record<string, string>>} */
265
+ const sections = {};
266
+ let current = "";
267
+ for (const rawLine of text.split(/\r?\n/)) {
268
+ const line = rawLine.trim();
269
+ if (line.length === 0 || line.startsWith("#") || line.startsWith(";")) continue;
270
+ const heading = /^\[(.+)\]$/.exec(line);
271
+ if (heading !== null) {
272
+ current = (/** @type {RegExpExecArray} */ (heading)[1] ?? "").trim().toLowerCase();
273
+ sections[current] ??= {};
274
+ continue;
275
+ }
276
+ const eq = line.indexOf("=");
277
+ if (eq <= 0) continue;
278
+ const section = sections[current] ?? (sections[current] = {});
279
+ section[line.slice(0, eq).trim().toLowerCase()] = line.slice(eq + 1).trim();
280
+ }
281
+ return sections;
282
+ }
283
+
284
+ /**
285
+ * The text of one patch row (`- id: <rowId>` down to the next row at the same
286
+ * or shallower indent). This is the same line discipline the preset helper
287
+ * applies to the shipped patch, so both tools read rows identically by
288
+ * construction.
289
+ * @param {string} text - the patch file's text.
290
+ * @param {string} rowId - the row id to extract.
291
+ * @returns {string} the row's text, or "" when the file names no such row.
292
+ */
293
+ export function rowBlock(text, rowId) {
294
+ const lines = text.split(/\r?\n/);
295
+ const start = lines.findIndex((line) => new RegExp(`^\\s*- id: ${rowId}\\s*$`).test(line));
296
+ if (start < 0) return "";
297
+ const header = /** @type {string} */ (lines[start]);
298
+ const indent = header.length - header.trimStart().length;
299
+ let end = start + 1;
300
+ while (end < lines.length) {
301
+ const line = /** @type {string} */ (lines[end]);
302
+ if (line.trim().length > 0 && line.length - line.trimStart().length <= indent) break;
303
+ end += 1;
304
+ }
305
+ return lines.slice(start, end).join("\n");
306
+ }
307
+
308
+ /**
309
+ * The value one key sets inside a row block: the FIRST occurrence wins, which
310
+ * inside `preset-wsl` means the `wsl-shell` row's value (the command plane is
311
+ * the first-command gate this verdict answers for). Comment lines never match
312
+ * — the anchor requires the key at line start after indent.
313
+ * @param {string} block - the row block's text.
314
+ * @param {string} key - the YAML key.
315
+ * @returns {string | undefined} the scalar with quotes stripped, or undefined when unset.
316
+ */
317
+ export function rowKey(block, key) {
318
+ const match = new RegExp(`^\\s*${key}: (.*)$`, "m").exec(block);
319
+ if (match === null) return undefined;
320
+ return (/** @type {RegExpExecArray} */ (match)[1] ?? "").trim().replace(/^['"]|['"]$/g, "");
321
+ }
322
+
323
+ /**
324
+ * Read the configuration the blocking verdict must answer under: the shipped
325
+ * preset's values, overlaid by every profile layer under `$DSH_HOME/profiles/*`
326
+ * that carries a `preset-wsl` row (the preset helper's output shape) or an
327
+ * `fs-routing` patch (a root-plane row, patchable by id). A profile file whose
328
+ * rows name none of the five keys changes nothing and is not an error — the
329
+ * recognizer only claims the shapes it knows, and the `config.effective` check
330
+ * reports exactly what was read and from where.
331
+ * @param {string} dshHome - the harness home (`DSH_HOME` or `~/.dsh`).
332
+ * @param {string} root - the package root holding the shipped `cordis.patch.yml`.
333
+ * @returns {{ config: EffectiveConfig, recognized: boolean }} the effective values and whether the shipped rows were recognized at all.
334
+ */
335
+ export function effectiveConfig(dshHome, root) {
336
+ /** @type {EffectiveConfig} */
337
+ let config = { distro: "auto", sessionSandbox: "true", agentBackend: "auto", sandbox: "true", maskWindowsDrive: "false", interopVisibility: "", source: "the shipped preset", overrides: [] };
338
+ let recognized = false;
339
+ const shipped = readFileSync(join(root, "cordis.patch.yml"), "utf8");
340
+ const preset = rowBlock(shipped, "preset-wsl");
341
+ const routing = rowBlock(shipped, "fs-routing");
342
+ const distro = rowKey(preset, "distro");
343
+ const sessionSandbox = rowKey(preset, "sessionSandbox");
344
+ const agentBackend = rowKey(preset, "agentBackend");
345
+ const sandbox = rowKey(routing, "sandbox");
346
+ const maskWindowsDrive = rowKey(routing, "maskWindowsDrive");
347
+ if (sessionSandbox !== undefined) {
348
+ recognized = true;
349
+ config = {
350
+ distro: distro === "" || distro === undefined ? "auto" : distro,
351
+ sessionSandbox: sessionSandbox === "false" ? "false" : sessionSandbox === "auto" ? "auto" : "true",
352
+ agentBackend: agentBackend ?? "auto",
353
+ sandbox: sandbox ?? "true",
354
+ maskWindowsDrive: maskWindowsDrive ?? "false",
355
+ interopVisibility: rowKey(routing, "interopVisibility") ?? "",
356
+ source: "the shipped preset",
357
+ overrides: [],
358
+ };
359
+ }
360
+ const profilesDir = join(dshHome, "profiles");
361
+ if (!existsSync(profilesDir)) return { config, recognized };
362
+ for (const entry of readdirSync(profilesDir, { withFileTypes: true })) {
363
+ if (!entry.isDirectory()) continue;
364
+ const patch = join(profilesDir, entry.name, "cordis.patch.yml");
365
+ if (!existsSync(patch)) continue;
366
+ const text = readFileSync(patch, "utf8");
367
+ /** @type {string[]} */
368
+ const changed = [];
369
+ const next = { ...config };
370
+ const layerPreset = rowBlock(text, "preset-wsl");
371
+ const layerRouting = rowBlock(text, "fs-routing");
372
+ for (const [block, keys] of [[layerPreset, ["distro", "sessionSandbox", "agentBackend"]], [layerRouting, ["sandbox", "maskWindowsDrive"]]]) {
373
+ const source = /** @type {string} */ (block);
374
+ /** The scalar keys the overlay may change; `source`/`overrides` are bookkeeping, not overlay inputs. */
375
+ const scalar = /** @type {const} */ (["distro", "sessionSandbox", "agentBackend", "sandbox", "maskWindowsDrive", "interopVisibility"]);
376
+ for (const key of /** @type {string[]} */ (keys)) {
377
+ const value = rowKey(source, key);
378
+ if (value === undefined || value === next[/** @type {keyof EffectiveConfig} */ (key)]) continue;
379
+ const normalized = key === "distro" && value === "" ? "auto" : key === "sessionSandbox" ? (value === "false" ? "false" : value === "auto" ? "auto" : "true") : value;
380
+ if (normalized === next[/** @type {keyof EffectiveConfig} */ (key)]) continue;
381
+ next[/** @type {(typeof scalar)[number]} */ (key)] = normalized;
382
+ changed.push(key);
383
+ }
384
+ }
385
+ if (changed.length > 0) {
386
+ next.source = `profile "${entry.name}"`;
387
+ next.overrides = [...config.overrides, `${entry.name}: ${changed.join(", ")}`];
388
+ config = next;
389
+ }
390
+ }
391
+ return { config, recognized };
392
+ }
393
+
122
394
  /**
123
395
  * Run one `sh -c` script inside the distro.
124
396
  * @param {string} distro - the distro name.
@@ -132,7 +404,7 @@ function inDistro(distro, script) {
132
404
  /**
133
405
  * Parse the doctor's own arguments.
134
406
  * @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.
407
+ * @returns {{ distro: string, wsl: string, json: boolean, fix: boolean, install: boolean, yes: boolean, readOnly: boolean, all: boolean, bundle: string, redact: boolean, help: boolean }} the options.
136
408
  */
137
409
  function parseArgs(argv) {
138
410
  const options = {
@@ -143,6 +415,9 @@ function parseArgs(argv) {
143
415
  install: false,
144
416
  yes: false,
145
417
  readOnly: false,
418
+ all: false,
419
+ bundle: "",
420
+ redact: false,
146
421
  help: false,
147
422
  };
148
423
  for (let i = 0; i < argv.length; i += 1) {
@@ -152,6 +427,10 @@ function parseArgs(argv) {
152
427
  else if (arg === "--install") options.install = true;
153
428
  else if (arg === "--yes" || arg === "-y") options.yes = true;
154
429
  else if (arg === "--read-only") options.readOnly = true;
430
+ else if (arg === "--all") options.all = true;
431
+ else if (arg === "--bundle") options.bundle = argv[++i] ?? "";
432
+ else if (arg.startsWith("--bundle=")) options.bundle = arg.slice("--bundle=".length);
433
+ else if (arg === "--redact") options.redact = true;
155
434
  else if (arg === "--help" || arg === "-h") options.help = true;
156
435
  else if (arg === "--distro") options.distro = argv[++i] ?? "";
157
436
  else if (arg.startsWith("--distro=")) options.distro = arg.slice("--distro=".length);
@@ -258,6 +537,72 @@ function installedPeer(packageName) {
258
537
  }
259
538
  }
260
539
 
540
+ /** The registries the update check asks, in order; the official one first. */
541
+ const UPDATE_REGISTRIES = ["https://registry.npmjs.org", "https://registry.npmmirror.com"];
542
+
543
+ /**
544
+ * The registries one run asks: `DSH_UPDATE_REGISTRIES` overrides the defaults
545
+ * (comma-separated, for an operator pinned to one mirror); set it empty to ask
546
+ * none at all — an air-gapped machine's way to keep the check silent without
547
+ * paying two connect timeouts.
548
+ * @returns {string[]} the registry base URLs.
549
+ */
550
+ function updateRegistries() {
551
+ const configured = process.env.DSH_UPDATE_REGISTRIES;
552
+ if (configured !== undefined) return configured.split(",").map((entry) => entry.trim()).filter((entry) => entry.length > 0);
553
+ return UPDATE_REGISTRIES;
554
+ }
555
+
556
+ /**
557
+ * Read the stable channel's newest release off one registry packument. The
558
+ * full document (not the abbreviated one) is requested, because only it
559
+ * carries the per-version deprecation message.
560
+ * @param {unknown} body - the parsed packument JSON.
561
+ * @returns {{ version: string, deprecated?: string, publishedAt?: string } | undefined} the release, or undefined when the document names none.
562
+ */
563
+ export function latestFromPackument(body) {
564
+ if (typeof body !== "object" || body === null) return undefined;
565
+ const packument = /** @type {{ "dist-tags"?: Record<string, unknown>, versions?: Record<string, unknown> }} */ (body);
566
+ const tags = packument["dist-tags"];
567
+ const versions = packument.versions;
568
+ if (typeof tags !== "object" || tags === null || typeof versions !== "object" || versions === null) return undefined;
569
+ const latest = tags.latest;
570
+ if (typeof latest !== "string" || latest.length === 0) return undefined;
571
+ const manifest = /** @type {{ deprecated?: unknown } | undefined} */ (versions[latest]);
572
+ if (manifest === undefined || typeof manifest !== "object") return undefined;
573
+ return {
574
+ version: latest,
575
+ ...(typeof manifest.deprecated === "string" && manifest.deprecated.length > 0 ? { deprecated: manifest.deprecated } : {}),
576
+ };
577
+ }
578
+
579
+ /**
580
+ * Ask the registries for the stable channel's newest release, official first,
581
+ * mirror second — the same fallback order the harness's plugin install uses.
582
+ * A short timeout keeps an offline run from stalling; every failure is an
583
+ * undefined, never a throw.
584
+ * @param {string[]} [registries] - the registries to ask; absent, `DSH_UPDATE_REGISTRIES` or the defaults (see {@link updateRegistries}).
585
+ * @param {number} [timeoutMs] - per-registry timeout, for tests.
586
+ * @returns {Promise<{ version: string, deprecated?: string, registry: string } | undefined>} the release and the registry that answered.
587
+ */
588
+ export async function fetchLatestRelease(registries, timeoutMs = 5_000) {
589
+ for (const registry of registries ?? updateRegistries()) {
590
+ try {
591
+ const response = await fetch(`${registry}/dsh-plugin-wsl-env`, {
592
+ headers: { accept: "application/json" },
593
+ signal: AbortSignal.timeout(timeoutMs),
594
+ });
595
+ if (!response.ok) continue;
596
+ const latest = latestFromPackument(await response.json());
597
+ if (latest !== undefined) return { ...latest, registry };
598
+ } catch {
599
+ // Offline, a blocked proxy, or a mirror that does not answer: the next
600
+ // registry (or the undefined) speaks for this run.
601
+ }
602
+ }
603
+ return undefined;
604
+ }
605
+
261
606
  /**
262
607
  * The install remedy for one distro and family.
263
608
  * @param {string} distro - the distro name.
@@ -277,9 +622,42 @@ function rejectReadOnly() {
277
622
  return 2;
278
623
  }
279
624
 
625
+ /**
626
+ * Map over items with at most `limit` workers running at once, preserving the
627
+ * input order in the results. The distro collection uses this: the distros
628
+ * are independent (the two-distro probe proves the wsl.exe command path is
629
+ * concurrent), and the A5 measurement says the wall clock is real — nine
630
+ * distros cost 151 s sequentially on the Tier 1 machine.
631
+ * @template T, R
632
+ * @param {T[]} items - the items.
633
+ * @param {number} limit - the worker count.
634
+ * @param {(item: T, index: number) => Promise<R>} worker - one item's work.
635
+ * @returns {Promise<R[]>} the results, in input order.
636
+ */
637
+ async function mapWithConcurrency(items, limit, worker) {
638
+ /** @type {R[]} */
639
+ const results = new Array(items.length);
640
+ let next = 0;
641
+ const runners = Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, async () => {
642
+ for (;;) {
643
+ const index = next;
644
+ next += 1;
645
+ if (index >= items.length) return;
646
+ results[index] = await worker(/** @type {T} */ (items[index]), index);
647
+ }
648
+ });
649
+ await Promise.all(runners);
650
+ return results;
651
+ }
652
+
653
+ /** The distro-collection worker count: three concurrent distros keep the
654
+ * wsl.exe fan-out polite while cutting the nine-distro wall clock to about
655
+ * a third. */
656
+ const DISTRO_CONCURRENCY = 3;
657
+
280
658
  /**
281
659
  * 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.
660
+ * @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
661
  * @returns {Promise<number>} the exit status.
284
662
  */
285
663
  async function main(options) {
@@ -291,6 +669,21 @@ async function main(options) {
291
669
  WSL = wslExe;
292
670
  /** @type {Check[]} */
293
671
  const checks = [];
672
+ // A5: per-phase wall clock. The doctor must be fast enough to run twice;
673
+ // the timings make a slow machine visible instead of felt, and give support
674
+ // triage the per-section duration without a separate durations column.
675
+ const runStart = Date.now();
676
+ let phaseStart = Date.now();
677
+ // The package manifest, read once: the peers check and the bundle both need it.
678
+ const manifest = /** @type {{ name?: string, version?: string, peerDependencies?: Record<string, string> }} */ (JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")));
679
+ /** @type {Record<string, number>} */
680
+ const timingsMs = {};
681
+ /** Close the open phase under `name` and open the next one.
682
+ * @param {string} name - the phase that just ended. */
683
+ const phase = (name) => {
684
+ timingsMs[name] = Date.now() - phaseStart;
685
+ phaseStart = Date.now();
686
+ };
294
687
  /**
295
688
  * @param {string} id - the check id.
296
689
  * @param {Check["status"]} status - the verdict.
@@ -313,6 +706,31 @@ async function main(options) {
313
706
  if (version.ok && wslVersion.length > 0) check("host.wsl", "ok", "WSL version", wslVersion);
314
707
  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
708
 
709
+ phase("host");
710
+ // ---- .wslconfig (the global VM config; host-level) ------------------------
711
+ // WSL silently ignores a malformed file, so interop/masking advice can fail
712
+ // to apply without a trace; this parser is where the trap gets named. The
713
+ // read rides cmd.exe (the same interop path `host.windows` uses), which
714
+ // works from Windows and from a WSL with interop regardless of where the
715
+ // automount root sits — the route's own failure is reported, not guessed.
716
+ const userProfile = (await run([CMD, "/c", "echo %USERPROFILE%"])).stdout.replace(/\0/g, "").trim();
717
+ if (!/^[A-Za-z]:\\/.test(userProfile)) {
718
+ 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");
719
+ } else {
720
+ const answer = await run([CMD, "/c", `type "${userProfile}\\.wslconfig"`]);
721
+ const text = answer.ok ? answer.stdout.replace(/\0/g, "") : "";
722
+ if (text.trim().length === 0) {
723
+ check("config.wslconfig", "ok", ".wslconfig", `no content in ${userProfile}\\.wslconfig (WSL defaults apply)`);
724
+ } else {
725
+ const { problems, keyCount } = parseWslConfig(text);
726
+ if (problems.length > 0) {
727
+ 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`);
728
+ } else {
729
+ check("config.wslconfig", "ok", ".wslconfig", `${keyCount} key(s) parsed from ${userProfile}\\.wslconfig, no findings`);
730
+ }
731
+ }
732
+ }
733
+
316
734
  const listed = await run([wslExe, "-l", "-q"]);
317
735
  const distros = listed.ok ? parseDistroList(listed.stdout.replace(/\0/g, "")) : [];
318
736
  if (distros.length === 0) {
@@ -320,103 +738,367 @@ async function main(options) {
320
738
  } else {
321
739
  check("host.distros", "ok", "Installed distros", distros.join(", "));
322
740
  }
323
- const distro = options.distro.length > 0 ? options.distro : distros[0] ?? "";
324
- if (distro.length === 0) return report(checks, { json: options.json });
741
+ // ---- effective configuration (read once, before anything config-gated) ---
742
+ // The blocking verdict answers under the values the user actually runs, so
743
+ // the shipped preset is overlaid by the profile layers before the target
744
+ // set is derived (an effective `distro` pin narrows it) and the session
745
+ // checks below assign their statuses. The `config.effective` row is emitted
746
+ // later, in the config section, so the human output keeps its grouping.
747
+ const dshHomeEarly = process.env.DSH_HOME !== undefined && process.env.DSH_HOME.length > 0 ? process.env.DSH_HOME : join(homedir(), ".dsh");
748
+ const { config: effective, recognized: configRecognized } = effectiveConfig(dshHomeEarly, ROOT);
749
+ const scopeMode = effective.sessionSandbox;
750
+ /** The status a session-scope prerequisite gets when it is missing. */
751
+ const sessionStatus = () => (scopeMode === "true" ? "fail" : "warn");
752
+ const scopeNote = scopeMode === "auto"
753
+ ? " — sessionSandbox: auto falls back to the per-command bwrap profile"
754
+ : scopeMode === "false"
755
+ ? " — sessionSandbox: false does not use the session scope"
756
+ : "";
757
+ /** Append the config-aware note to a prerequisite's evidence when the scope is not required.
758
+ * @param {string} detail - the prerequisite's own evidence.
759
+ * @returns {string} the evidence, with the fallback named when the scope is optional. */
760
+ const withScopeNote = (detail) => (scopeMode === "true" ? detail : `${detail}${scopeNote}`);
761
+ /** The drive-masking stance in effect, computed with the shipped precedence (interopVisibility over maskWindowsDrive). */
762
+ const interopMasked = effectiveMaskWindowsDrive({
763
+ interopVisibility: effective.interopVisibility === "" ? undefined : /** @type {"visible" | "masked" | "disabled"} */ (effective.interopVisibility),
764
+ maskWindowsDrive: effective.maskWindowsDrive === "true",
765
+ });
325
766
 
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 });
329
- }
767
+ phase("wslconfig");
768
+ // ---- target selection ----------------------------------------------------
769
+ // An explicit `--distro` wins; `--all` checks every installed distro;
770
+ // otherwise the effective configuration decides: `auto` (the shipped
771
+ // default) means the workspace decides, so every installed distro is a
772
+ // candidate and all are checked; `default` resolves to the distro WSL
773
+ // itself marks as default; a pinned name checks exactly that one.
774
+ const runInfo = /** @type {{ distros: string[], config?: EffectiveConfig, timingsMs?: Record<string, number>, bundle?: { path: string, redact: boolean, manifest: { name?: string, version?: string, peerDependencies?: Record<string, string> } } }} */ ({ distros: [], timingsMs });
775
+ if (options.bundle.length > 0) runInfo.bundle = { path: options.bundle, redact: options.redact, manifest };
776
+ runInfo.config = { ...effective };
777
+ /** The `wsl.exe -l -v` table, parsed once: the default marker feeds target selection, the VERSION column feeds `distro.wsl-mode`. */
778
+ const wslTable = parseWslVerbose((await run([wslExe, "-l", "-v"])).stdout.replace(/\0/g, ""));
779
+ /** @type {string[]} */
780
+ const targets = [];
781
+ if (options.distro.length > 0) targets.push(options.distro);
782
+ else if (options.all) targets.push(...distros);
783
+ else if (effective.distro === "auto") targets.push(...distros);
784
+ else if (effective.distro === "default") {
785
+ const defaultDistro = wslTable.find((entry) => entry.isDefault)?.name;
786
+ targets.push(...(defaultDistro !== undefined ? [defaultDistro] : distros));
787
+ } else targets.push(effective.distro);
330
788
 
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");
789
+ const missing = targets.filter((target) => !distros.includes(target));
790
+ if (missing.length > 0) {
791
+ for (const name of missing) {
792
+ 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 });
793
+ }
794
+ runInfo.distros = missing;
795
+ return report(checks, { json: options.json }, runInfo);
366
796
  }
797
+ if (targets.length === 0) return report(checks, { json: options.json }, runInfo);
798
+ runInfo.distros = targets;
367
799
 
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
- }
800
+ /**
801
+ * The distro-scoped checks for one target, pushed with the distro stamped
802
+ * so the report can aggregate per-distro verdicts. An unreachable distro
803
+ * fails its own reachability check and contributes nothing further — one
804
+ * wedged distro must not mask the others.
805
+ * @param {string} target - the distro name.
806
+ * @returns {Promise<{ checks: Check[], reachable: boolean, bwrapPath: string, stale: number, family: string }>} the distro's own checks and the state the fix section needs.
807
+ */
808
+ const collectDistroChecks = async (target) => {
809
+ /** @type {Check[]} */
810
+ const collected = [];
811
+ const check = (/** @type {string} */ id, /** @type {Check["status"]} */ status, /** @type {string} */ title, /** @type {string | undefined} */ detail = undefined, /** @type {string | undefined} */ remedy = undefined) => {
812
+ collected.push({ id, status, title, ...(detail === undefined ? {} : { detail }), ...(remedy === undefined ? {} : { remedy }), distro: target });
813
+ };
814
+ const alive = await inDistro(target, "printf %s ok");
815
+ if (!alive.ok || alive.stdout.trim() !== "ok") {
816
+ 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`);
817
+ return { checks: collected, reachable: false, bwrapPath: "", stale: 0, family: "unknown" };
818
+ }
819
+ check("distro.reachable", "ok", `Distro "${target}"`, "answers commands");
395
820
 
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
- }
821
+ // ---- distro facts --------------------------------------------------------
822
+ const shellAnswer = await inDistro(target, 's=$(getent passwd "$(id -u)" | cut -d: -f7); [ -n "$s" ] || s=$SHELL; printf %s "$s"');
823
+ const shell = shellAnswer.stdout.trim();
824
+ if (shell.startsWith("/")) check("distro.shell", "ok", "Login shell", shell);
825
+ 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)"`);
826
+
827
+ const homeAnswer = await inDistro(target, 'printf %s "$HOME"');
828
+ const home = homeAnswer.stdout.trim();
829
+ if (home.startsWith("/")) check("distro.home", "ok", "Home", home);
830
+ 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)"`);
831
+
832
+ const kernel = (await inDistro(target, "uname -r")).stdout.trim();
833
+ check("distro.kernel", "info", "Kernel", kernel.length > 0 ? kernel : "unreadable");
834
+
835
+ const familyAnswer = await inDistro(target, `for f in ${FAMILIES.join(" ")}; do command -v "$f" >/dev/null 2>&1 && { echo "$f"; exit 0; }; done; echo unknown`);
836
+ const family = familyAnswer.stdout.trim();
837
+ check("distro.family", "info", "Package family", family.length > 0 ? family : "unknown");
838
+
839
+ // ---- WSL mode ------------------------------------------------------------
840
+ // WSL1 is a declared non-goal, but until now it failed unexplained: the
841
+ // session prerequisites named remedies, never the root cause. The -l -v
842
+ // table carries the VERSION per distro, so name the cause.
843
+ const wslMode = wslTable.find((entry) => entry.name === target)?.version ?? "";
844
+ if (wslMode === "1") {
845
+ 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`);
846
+ } else if (wslMode === "") {
847
+ check("distro.wsl-mode", "info", "WSL mode", `unreadable — the -l -v table named no version for "${target}"`);
848
+ } else {
849
+ check("distro.wsl-mode", "ok", "WSL mode", `WSL ${wslMode}`);
850
+ }
851
+
852
+ // ---- disk -----------------------------------------------------------------
853
+ // A full root is the classic WSL "everything mysteriously fails" class:
854
+ // the ext4 VHDX stops growing (or the Windows drive holding it is full)
855
+ // and every write failure surfaces as something unrelated. One df call;
856
+ // the fail line at 97% is where the first cache write starts to break.
857
+ const dfAnswer = await inDistro(target, "df -Pm /");
858
+ const dfLine = dfAnswer.stdout.trim().split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0)[1] ?? "";
859
+ const dfFields = dfLine.split(/\s+/);
860
+ const dfCapacity = Number((dfFields[4] ?? "").replace(/%$/, ""));
861
+ const dfTotal = dfFields[1] ?? "?";
862
+ const dfAvail = dfFields[3] ?? "?";
863
+ if (!Number.isFinite(dfCapacity)) {
864
+ check("distro.disk", "info", "Disk", "unreadable — df did not answer in the expected shape");
865
+ } else if (dfCapacity >= 97) {
866
+ 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`);
867
+ } else if (dfCapacity >= 90) {
868
+ 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");
869
+ } else {
870
+ check("distro.disk", "ok", "Disk", `/${dfCapacity}% used (${dfAvail} MiB free of ${dfTotal} MiB)`);
871
+ }
872
+
873
+ // ---- sandbox prerequisites ----------------------------------------------
874
+ let bwrapUsable = false;
875
+ const bwrapPath = (await inDistro(target, "command -v bwrap")).stdout.trim();
876
+ const install = installRemedy(target, family);
877
+ if (bwrapPath.length === 0) {
878
+ check("sandbox.bwrap", "fail", "bubblewrap", "missing; every confined command fails closed without it", `${install}, or run "pnpm run bootstrap ${target} --install"`);
879
+ } else {
880
+ check("sandbox.bwrap", "ok", "bubblewrap", bwrapPath);
881
+ const userns = await inDistro(target, "bwrap --ro-bind / / -- true");
882
+ if (userns.ok) {
883
+ check("sandbox.bwrap-usable", "ok", "bubblewrap usability", "a read-only profile runs");
884
+ bwrapUsable = true;
885
+ } 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");
886
+ }
887
+
888
+ // ---- session sandbox prerequisites --------------------------------------
889
+ // The statuses are config-aware: the scope is only *required* under
890
+ // `sessionSandbox: true` (the shipped default); `auto` falls back to the
891
+ // per-command bwrap profile and `false` does not use the scope at all, so
892
+ // in both cases a missing prerequisite downgrades to a warning — a `fail`
893
+ // always blocks, which is the invariant the verdict leans on.
894
+ const systemd = await inDistro(target, 'if [ -d /run/systemd/system ]; then printf "systemd %s" "$(cat /proc/1/comm)"; else printf "none %s" "$(cat /proc/1/comm)"; fi');
895
+ if (!systemd.stdout.startsWith("systemd")) {
896
+ 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`);
897
+ } else check("session.systemd", "ok", "systemd as PID 1", "running");
898
+
899
+ const systemdRun = (await inDistro(target, "command -v systemd-run")).stdout.trim();
900
+ if (systemdRun.length > 0) check("session.systemd-run", "ok", "systemd-run", systemdRun);
901
+ 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)`);
411
902
 
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);
903
+ const userManager = (await inDistro(target, "systemctl --user is-system-running 2>/dev/null || true")).stdout.trim();
904
+ if (userManager === "running" || userManager === "degraded") check("session.user-manager", "ok", "systemd user manager", userManager);
905
+ else check("session.user-manager", sessionStatus(), "systemd user manager", withScopeNote(userManager.length > 0 ? userManager : "unreachable"), `log in to "${target}" once, or enable lingering (next remedy), then retry`);
906
+
907
+ const linger = (await inDistro(target, 'loginctl show-user "$(id -un)" -p Linger 2>/dev/null')).stdout.trim();
908
+ if (linger === "Linger=yes") check("session.linger", "ok", "Linger", linger);
909
+ else check("session.linger", sessionStatus(), "Linger", withScopeNote(linger.length > 0 ? linger : "unset"), `wsl.exe -d ${target} -- loginctl enable-linger "$(id -un)" (this needs the user's own session; run it inside the distro)`);
910
+
911
+ // ---- /etc/wsl.conf cross-checks ------------------------------------------
912
+ // The distro-level settings the plugin cannot change (LIMITATIONS): boot,
913
+ // interop, automount. Each check reads the conf against the runtime facts
914
+ // the probes above collected and names the terminate semantics — a conf
915
+ // value that is not in effect is a different problem from one that is.
916
+ const confAnswer = await inDistro(target, "cat /etc/wsl.conf 2>/dev/null || true");
917
+ const conf = parseIni(confAnswer.stdout);
918
+ const noConf = confAnswer.stdout.trim().length === 0;
919
+ const runtimeSystemd = systemd.stdout.startsWith("systemd");
920
+ const bootSystemd = ((noConf ? undefined : conf.boot?.systemd) ?? "").trim().toLowerCase();
921
+ if (noConf) {
922
+ check("distro.wsl-conf-boot", "info", "/etc/wsl.conf [boot]", "no /etc/wsl.conf — the default (systemd off) applies, and the runtime matches it");
923
+ } else if (bootSystemd === "true" && !runtimeSystemd) {
924
+ check("distro.wsl-conf-boot", "warn", "/etc/wsl.conf [boot]", `[boot] systemd=true but PID 1 is ${systemd.stdout.trim() || "not systemd"} — the value is set but not in effect`, `wsl.exe --terminate ${target} (or "wsl.exe --shutdown"), then reopen the session`);
925
+ } else if (bootSystemd === "false" && runtimeSystemd) {
926
+ 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`);
927
+ } else {
928
+ 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`);
929
+ }
930
+
931
+ const interopEnabled = ((noConf ? undefined : conf.interop?.enabled) ?? "").trim().toLowerCase();
932
+ if (interopEnabled === "false") {
933
+ const binfmt = (await inDistro(target, "[ -e /proc/sys/fs/binfmt_misc/WSLInterop ] && printf yes || printf no")).stdout.trim();
934
+ check("distro.wsl-conf-interop", "warn", "/etc/wsl.conf [interop]", `interop is disabled in wsl.conf${binfmt === "yes" ? " but the WSLInterop handler is still loaded (stale boot)" : ""} — Windows git, open-in-app and the cmd.exe probes are unreachable from this distro`, `remove the [interop] enabled=false line in /etc/wsl.conf, then wsl.exe --terminate ${target}`);
935
+ } else {
936
+ const appendWindowsPath = ((noConf ? undefined : conf.interop?.appendWindowsPath) ?? "").trim().toLowerCase();
937
+ check("distro.wsl-conf-interop", "ok", "/etc/wsl.conf [interop]", noConf
938
+ ? "no /etc/wsl.conf — interop on (the default)"
939
+ : `enabled=${interopEnabled || "true (the default)"}${appendWindowsPath === "false" ? "; appendWindowsPath=false (Windows PATH not appended — Windows tools need full paths)" : ""}`);
940
+ }
941
+
942
+ const automountEnabled = ((noConf ? undefined : conf.automount?.enabled) ?? "").trim().toLowerCase();
943
+ const automountRoot = ((noConf ? undefined : conf.automount?.root) ?? "").trim();
944
+ if (automountEnabled === "false") {
945
+ 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}`);
946
+ } else if (automountRoot.length > 0 && automountRoot !== "/mnt" && interopMasked) {
947
+ 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}`);
948
+ } else {
949
+ check("distro.wsl-conf-automount", "ok", "/etc/wsl.conf [automount]", noConf
950
+ ? "no /etc/wsl.conf — /mnt mounts (the default)"
951
+ : `enabled=${automountEnabled || "true (the default)"}, root=${automountRoot || "/mnt"}`);
952
+ }
953
+
954
+ // ---- clock ----------------------------------------------------------------
955
+ // A sleeping host desyncs the WSL clock (the VM's clock stops with it);
956
+ // the classic symptom is TLS and git failing with certificate or
957
+ // timestamp errors minutes after resume. One comparison, one remedy.
958
+ const distroEpoch = Number((await inDistro(target, "date +%s")).stdout.trim());
959
+ if (!Number.isFinite(distroEpoch) || distroEpoch <= 0) {
960
+ check("distro.clock", "info", "Clock", "unreadable — date did not answer an epoch");
961
+ } else {
962
+ const skew = Math.abs(distroEpoch - Math.floor(Date.now() / 1000));
963
+ if (skew > 60) {
964
+ 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`);
965
+ } else {
966
+ check("distro.clock", "ok", "Clock", `within ${skew}s of the host`);
967
+ }
968
+ }
969
+
970
+ // ---- dns ------------------------------------------------------------------
971
+ // Name resolution breaks in two WSL-specific ways: the auto-generated
972
+ // /etc/resolv.conf lost its nameserver (or generation was disabled), and
973
+ // the VPN-tunnel class where the file looks fine but queries die. The
974
+ // probe is warn-grade and honest about offline — a machine without a
975
+ // network answers the same as a broken resolver.
976
+ const resolvBytes = Number((await inDistro(target, "wc -c < /etc/resolv.conf 2>/dev/null || printf 0")).stdout.trim());
977
+ if (!Number.isFinite(resolvBytes) || resolvBytes === 0) {
978
+ 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`);
979
+ } else {
980
+ const resolved = (await inDistro(target, "getent hosts deb.debian.org 2>/dev/null | head -1")).stdout.trim();
981
+ if (resolved.length > 0) {
982
+ check("distro.dns", "ok", "DNS", `resolv.conf present (${resolvBytes} bytes); ${(resolved.split(/\s+/)[0] ?? "?")} resolved the probe name`);
983
+ } else {
984
+ 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");
985
+ }
986
+ }
987
+
988
+ // ---- optional tools ------------------------------------------------------
989
+ /** The optional tools, in the order users notice them losing. */
990
+ /** @type {Array<[string, string]>} */
991
+ const optionalTools = [["rg", "in-distro search"], ["git", "workspace-change baselines"], ["inotifywait", "the watcher's primary backend"]];
992
+ for (const [tool, purpose] of optionalTools) {
993
+ const found = (await inDistro(target, `command -v ${tool}`)).stdout.trim();
994
+ if (found.length > 0) check(`tools.${tool}`, "ok", tool, found);
995
+ else check(`tools.${tool}`, "warn", tool, `missing; ${purpose} degrades to a slower fallback`, install);
996
+ }
997
+
998
+ // ---- agents and caches ---------------------------------------------------
999
+ const arch = (await inDistro(target, "uname -m")).stdout.trim();
1000
+ const packaged = ["x86_64", "aarch64"].includes(arch) ? join(ROOT, "agent", "native", `linux-${arch}`, "dsh-wsl-agent") : "";
1001
+ if (arch.length === 0) check("agent.arch", "info", "Distro architecture", "unreadable");
1002
+ else if (packaged.length === 0) check("agent.arch", "info", "Distro architecture", `${arch} has no packaged native agent; the shell agent is the only backend`);
1003
+ else if (existsSync(packaged)) check("agent.native", "ok", "Packaged native agent", packaged.slice(ROOT.length + 1));
1004
+ else check("agent.native", "warn", "Packaged native agent", `missing for ${arch}`, "reinstall the plugin (the binaries ship with the package), or use agentBackend: shell");
1005
+
1006
+ const cache = (await inDistro(target, CACHE_REPORT)).stdout.trim();
1007
+ if (cache === "none" || cache.length === 0) check("agent.cache", "info", "Agent cache", "empty (a first command populates it)");
1008
+ else {
1009
+ const entries = cache.split(/\r?\n/).filter((line) => line.trim().length > 0);
1010
+ const bad = entries.filter((line) => line.startsWith("noexec ")).length;
1011
+ 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);
1012
+ }
1013
+
1014
+ const scopes = (await inDistro(target, STALE_SCOPE_REPORT)).stdout.trim();
1015
+ const scopeLines = scopes === "none" || scopes.length === 0 ? [] : scopes.split(/\r?\n/);
1016
+ const stale = scopeLines.filter((line) => /\sstale(\s|$)/.test(line)).length;
1017
+ const livePids = scopeLines.flatMap((line) => {
1018
+ const m = /\spids:([0-9 ]+)$/.exec(line);
1019
+ if (m === null) return [];
1020
+ return (m[1] ?? "").trim().split(/\s+/).filter((p) => p.length > 0);
1021
+ });
1022
+
1023
+ // ---- resident handshake --------------------------------------------------
1024
+ const agentScript = join(ROOT, "agent", "wsl-agent.sh");
1025
+ /** ok | fail | info — the legs skip with a story that matches. */
1026
+ let handshakeState = "info";
1027
+ if (!agentScript.startsWith("/")) {
1028
+ check("agent.handshake", "info", "Agent handshake", "skipped: run the doctor from inside the distro (the script path is a Windows path)");
1029
+ } else if (!existsSync(agentScript)) {
1030
+ 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");
1031
+ handshakeState = "fail";
1032
+ } else {
1033
+ // The script is a Linux path in the checkout's OWN distro; another
1034
+ // distro cannot read it, and "exited before its HELLO" would be a
1035
+ // lie about a broken install. Probe readability first, honestly.
1036
+ const readable = (await inDistro(target, `[ -f "${agentScript}" ] && printf yes || printf no`)).stdout.trim() === "yes";
1037
+ if (!readable) {
1038
+ 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}"`);
1039
+ } else {
1040
+ const handshake = await probeResident(target, agentScript, wslExe);
1041
+ handshakeState = handshake.ok && handshake.digestMatches ? "ok" : "fail";
1042
+ if (handshake.ok) {
1043
+ const live = livePids.length > 0
1044
+ ? `; 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`
1045
+ : "";
1046
+ check("agent.handshake", handshake.digestMatches ? "ok" : "fail", "Agent handshake",
1047
+ `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}`,
1048
+ handshake.digestMatches ? undefined : "resync the runtime copy (pnpm run sync:windows), then restart the app");
1049
+ } else {
1050
+ 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");
1051
+ }
1052
+ }
1053
+ }
1054
+
1055
+ // ---- stale session scopes ------------------------------------------------
1056
+ if (scopeLines.length === 0) check("runtime.scopes", "info", "Session scopes", "none (no user manager, or none left behind)");
1057
+ else if (stale === 0) check("runtime.scopes", "ok", "Session scopes", `${scopeLines.length} live, none stale`);
1058
+ 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");
1059
+
1060
+ // ---- smoke legs ----------------------------------------------------------
1061
+ // The handshake proves HELLO; the legs prove the chain the session rides:
1062
+ // one EXEC round trip, the confined profile's allow/refuse shape, and one
1063
+ // FSB stat+list batch over a temp dir (cleaned after). A leg whose
1064
+ // prerequisite failed is `skipped` with the blocker named — absence is
1065
+ // never silent, and a skipped leg never blocks (its blocker already does).
1066
+ const residentBlocked = handshakeState !== "ok";
1067
+ const sandboxBlocked = bwrapPath.length === 0 || !bwrapUsable;
1068
+ const residentBlocker = handshakeState === "fail" ? "blocked by agent.handshake" : "the handshake could not run in this distro";
1069
+ if (residentBlocked) {
1070
+ check("functional.exec", "skipped", "Smoke: EXEC", `skipped: ${residentBlocker}`);
1071
+ check("functional.fs", "skipped", "Smoke: FSB batch", `skipped: ${residentBlocker}`);
1072
+ } else {
1073
+ const smoke = await runSmokeLegs(target, agentScript, wslExe);
1074
+ 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");
1075
+ 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");
1076
+ }
1077
+ if (sandboxBlocked) {
1078
+ check("functional.sandbox", "skipped", "Smoke: confined profile", `skipped: blocked by ${bwrapPath.length === 0 ? "sandbox.bwrap" : "sandbox.bwrap-usable"}`);
1079
+ } else {
1080
+ const sandbox = await runSandboxSmoke(target);
1081
+ 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");
1082
+ }
1083
+
1084
+ return { checks: collected, reachable: true, bwrapPath, stale, family };
1085
+ };
1086
+
1087
+ phase("target");
1088
+ /** @type {Map<string, { checks: Check[], reachable: boolean, bwrapPath: string, stale: number, family: string }>} */
1089
+ const states = new Map();
1090
+ const outcomes = await mapWithConcurrency(targets, DISTRO_CONCURRENCY, async (target) => {
1091
+ const distroStart = Date.now();
1092
+ const outcome = await collectDistroChecks(target);
1093
+ return { target, outcome, ms: Date.now() - distroStart };
419
1094
  });
1095
+ for (const { target, outcome, ms } of outcomes) {
1096
+ checks.push(...outcome.checks);
1097
+ states.set(target, outcome);
1098
+ timingsMs[`distro:${target}`] = ms;
1099
+ phaseStart = Date.now();
1100
+ }
1101
+
420
1102
  // ---- Windows git trust (WSL change review) ------------------------------
421
1103
  // The change-review pipeline's discovery call runs the WINDOWS git against
422
1104
  // a \\wsl.localhost UNC when Windows git is installed; git's
@@ -425,10 +1107,12 @@ async function main(options) {
425
1107
  // WSL workspaces). A machine without Windows git is fine too — the provider
426
1108
  // resolves git to a distro sentinel and routes everything. What the doctor
427
1109
  // can probe cheaply from here is interop git.exe and its whitelist.
1110
+ let winGitOk = false;
428
1111
  const winGitVersion = await run(["git.exe", "--version"]);
429
1112
  if (!winGitVersion.ok) {
430
1113
  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
1114
  } else {
1115
+ winGitOk = true;
432
1116
  const entries = (await run(["git.exe", "config", "--global", "--get-all", "safe.directory"])).stdout.split(/\r?\n/).filter(Boolean);
433
1117
  const whitelisted = entries.some((entry) => /wsl\.localhost/i.test(entry));
434
1118
  check("git.win-safe", whitelisted ? "ok" : "warn", "Windows git trust",
@@ -437,31 +1121,7 @@ async function main(options) {
437
1121
  whitelisted ? undefined : 'on Windows: git config --global --add safe.directory "//wsl.localhost/*", then restart the app');
438
1122
  }
439
1123
 
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
- }
459
-
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
-
1124
+ phase("git");
465
1125
  // ---- sessions across running distros (WSL-309) ----------------------------
466
1126
  // The single-distro checks above answer "is this distro healthy?"; this
467
1127
  // survey answers "what is running right now, everywhere?" — the concurrent
@@ -528,7 +1188,6 @@ async function main(options) {
528
1188
  }
529
1189
 
530
1190
  // ---- peers ---------------------------------------------------------------
531
- const manifest = /** @type {{ peerDependencies?: Record<string, string> }} */ (JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")));
532
1191
  const peers = Object.entries(manifest.peerDependencies ?? {});
533
1192
  const badPeers = [];
534
1193
  const unknownPeers = [];
@@ -541,14 +1200,44 @@ async function main(options) {
541
1200
  if (badPeers.length === 0) check("peers.versions", "ok", "Peer versions", `${peers.length} pinned peer(s) match${unknownPeers.length > 0 ? `; ${unknownPeers.length} unchecked` : ""}`);
542
1201
  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
1202
 
544
- // ---- profile-patch trap --------------------------------------------------
1203
+ phase("surveys");
1204
+ // ---- update check ----------------------------------------------------------
1205
+ // The same question the app's Versions page asks, answered on demand: the
1206
+ // stable channel's newest release against this checkout's version. A
1207
+ // registry the doctor cannot reach is normal (offline, a proxy), so it
1208
+ // reports as `info` and points at the page that asks it live — never a
1209
+ // warning, and never a network side effect beyond the two GETs.
1210
+ const installedVersion = manifest.version ?? "";
1211
+ const latest = installedVersion.length > 0 ? await fetchLatestRelease() : undefined;
1212
+ if (latest === undefined) {
1213
+ 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");
1214
+ } else if (compareVersions(latest.version, installedVersion) > 0) {
1215
+ const message = updateFactMessage({ installed: installedVersion, latest: latest.version, incompatible: false, ...(latest.deprecated === undefined ? {} : { deprecated: latest.deprecated }), checkedAt: 0 });
1216
+ 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");
1217
+ } else {
1218
+ check("update.latest", "ok", "Update check", `${installedVersion} is the newest stable release`);
1219
+ }
1220
+
1221
+ // ---- effective configuration (verdict inputs, reported) ------------------
1222
+ check("config.effective", configRecognized ? "ok" : "info", "Effective configuration",
1223
+ configRecognized
1224
+ ? `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("; ")})` : ""}`
1225
+ : "the shipped preset rows were not recognized; the conservative defaults apply (sessionSandbox: true, so a missing systemd blocks) — see docs/CONFIGURATION.md");
1226
+
1227
+ phase("update-peers");
1228
+ // ---- profile-patch trap and deprecated keys ------------------------------
545
1229
  const dshHome = process.env.DSH_HOME !== undefined && process.env.DSH_HOME.length > 0 ? process.env.DSH_HOME : join(homedir(), ".dsh");
546
1230
  const profilesDir = join(dshHome, "profiles");
547
1231
  if (!existsSync(profilesDir)) {
548
1232
  check("config.profiles", "info", "Profile patches", `no profiles under ${profilesDir}`);
1233
+ check("config.deprecated", "info", "Deprecated keys", "no profile layers to scan");
549
1234
  } else {
550
1235
  /** @type {string[]} */
551
1236
  const trapped = [];
1237
+ /** @type {string[]} */
1238
+ const retired = [];
1239
+ /** @type {string[]} */
1240
+ const emptyDistro = [];
552
1241
  let seen = 0;
553
1242
  for (const entry of readdirSync(profilesDir, { withFileTypes: true })) {
554
1243
  if (!entry.isDirectory()) continue;
@@ -557,34 +1246,114 @@ async function main(options) {
557
1246
  seen += 1;
558
1247
  const text = readFileSync(patch, "utf8");
559
1248
  if (/^\s*-\s*id:\s*(wsl-shell|wsl-fs)\s*$/m.test(text)) trapped.push(entry.name);
1249
+ if (/substrate:\s*["']?share["']?/m.test(text)) retired.push(entry.name);
1250
+ if (/^\s*distro:\s*['"]['"]\s*$/m.test(text)) emptyDistro.push(entry.name);
560
1251
  }
561
1252
  if (trapped.length > 0) {
562
1253
  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
1254
  } else {
564
1255
  check("config.profiles", "ok", "Profile patches", `${seen} profile patch(es) scanned`);
565
1256
  }
1257
+ if (retired.length > 0) {
1258
+ 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");
1259
+ } else if (emptyDistro.length > 0) {
1260
+ 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`);
1261
+ } else {
1262
+ check("config.deprecated", "ok", "Deprecated keys", `${seen} profile patch(es) scanned, none carry retired keys`);
1263
+ }
566
1264
  }
567
1265
 
568
- // ---- fixes ---------------------------------------------------------------
1266
+ phase("config");
1267
+ // ---- fixes (the loop ends in a re-verified report) ------------------------
1268
+ // Safe actions only, per target: the sweep the session preflight runs, and
1269
+ // package installation behind --install plus an explicit confirmation. Every
1270
+ // fix is followed by a fresh probe of what it claims to have fixed — the
1271
+ // revised check carries the after state (so the verdict at the end is the
1272
+ // post-fix verdict, ready or the remaining blockers), and the fix.* row
1273
+ // narrates the before → after transition. A distro that never became
1274
+ // reachable has no state to fix.
569
1275
  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}"`);
1276
+ /** Replace one pushed check's verdict in place — the fix loop's "after".
1277
+ * @param {string} id - the check id.
1278
+ * @param {string | undefined} distro - the distro scope, for distro-scoped ids.
1279
+ * @param {Partial<Check>} patch - the fields to revise. */
1280
+ const reviseCheck = (/** @type {string} */ id, /** @type {string | undefined} */ distro, /** @type {Partial<Check>} */ patch, /** @type {string | undefined} */ title = undefined) => {
1281
+ const entry = checks.find((entry) => entry.id === id && (distro === undefined || entry.distro === distro));
1282
+ if (entry === undefined) {
1283
+ // A check the first pass never pushed (its prerequisite was missing)
1284
+ // still deserves an after-state row once the fix created it.
1285
+ if (title === undefined) return;
1286
+ const created = /** @type {Check} */ ({ id, status: "ok", title: title ?? id, detail: "", ...(distro === undefined ? {} : { distro }) });
1287
+ Object.assign(created, patch);
1288
+ checks.push(created);
1289
+ return;
1290
+ }
1291
+ Object.assign(entry, patch);
1292
+ };
1293
+ for (const [target, state] of states) {
1294
+ if (!state.reachable) continue;
1295
+ const fixCheck = (/** @type {string} */ id, /** @type {Check["status"]} */ status, /** @type {string} */ title, /** @type {string | undefined} */ detail = undefined, /** @type {string | undefined} */ remedy = undefined) => {
1296
+ checks.push({ id, status, title, ...(detail === undefined ? {} : { detail }), ...(remedy === undefined ? {} : { remedy }), distro: target });
1297
+ };
1298
+ if (state.stale > 0) {
1299
+ const swept = await inDistro(target, sessionScopeSweepScript());
1300
+ const afterReport = (await inDistro(target, STALE_SCOPE_REPORT)).stdout.trim();
1301
+ const afterLines = afterReport === "none" || afterReport.length === 0 ? [] : afterReport.split(/\r?\n/);
1302
+ const afterStale = afterLines.filter((line) => /\sstale(\s|$)/.test(line)).length;
1303
+ const fixed = swept.ok && afterStale === 0;
1304
+ 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}"`);
1305
+ reviseCheck("runtime.scopes", target, afterLines.length === 0
1306
+ ? { status: "info", detail: "none (the fix above swept them)", remedy: undefined }
1307
+ : { 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" });
1308
+ }
1309
+ if (state.bwrapPath.length === 0) {
1310
+ const install = installRemedy(target, state.family);
1311
+ if (!options.install) {
1312
+ fixCheck("fix.install", "info", "Package installation", "not attempted", "re-run with --fix --install (and --yes for a non-interactive run)");
1313
+ } else if (!(await confirm(`Install ${PACKAGES} in "${target}" as root?`, options.yes))) {
1314
+ fixCheck("fix.install", "info", "Package installation", "declined", install);
1315
+ } else {
1316
+ const command = INSTALL[state.family] ?? INSTALL["apt-get"] ?? `apt-get install -y ${PACKAGES}`;
1317
+ const installed = await run([WSL, "-d", target, "-u", "root", "--", "sh", "-c", command]);
1318
+ const bwrapAfter = (await inDistro(target, "command -v bwrap")).stdout.trim();
1319
+ const usableAfter = bwrapAfter.length > 0 ? (await inDistro(target, "bwrap --ro-bind / / -- true")).ok : false;
1320
+ const done = installed.ok && bwrapAfter.length > 0;
1321
+ fixCheck("fix.install", done ? "ok" : "warn", "Package installation", installed.ok
1322
+ ? `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"}`
1323
+ : "failed; see the output above", done ? undefined : install);
1324
+ reviseCheck("sandbox.bwrap", target, bwrapAfter.length > 0
1325
+ ? { status: "ok", detail: bwrapAfter, remedy: undefined }
1326
+ : { status: "fail", detail: "still missing after the install", remedy: install });
1327
+ reviseCheck("sandbox.bwrap-usable", target, bwrapAfter.length > 0
1328
+ ? { 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" }
1329
+ : {}, "bubblewrap usability");
1330
+ }
1331
+ }
573
1332
  }
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);
1333
+ // B3: the Windows git whitelist is user-scoped and reversible — the same
1334
+ // confirmation gate as a package install, then a fresh probe. Without a
1335
+ // TTY the fix declines loudly instead of silently doing nothing.
1336
+ if (winGitOk) {
1337
+ const gitEntry = checks.find((entry) => entry.id === "git.win-safe");
1338
+ if (gitEntry !== undefined && gitEntry.status === "warn") {
1339
+ if (await confirm('Add "//wsl.localhost/*" to the Windows git safe.directory whitelist?', options.yes)) {
1340
+ const added = await run(["git.exe", "config", "--global", "--add", "safe.directory", "//wsl.localhost/*"]);
1341
+ const entries = (await run(["git.exe", "config", "--global", "--get-all", "safe.directory"])).stdout.split(/\r?\n/).filter(Boolean);
1342
+ const whitelisted = entries.some((entry) => /wsl\.localhost/i.test(entry));
1343
+ reviseCheck("git.win-safe", undefined, whitelisted
1344
+ ? { 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 }
1345
+ : {});
1346
+ 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' });
1347
+ } else {
1348
+ 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/*"' });
1349
+ }
583
1350
  }
584
1351
  }
585
1352
  }
586
1353
 
587
- return report(checks, { json: options.json });
1354
+ phase("fix");
1355
+ timingsMs.total = Date.now() - runStart;
1356
+ return report(checks, { json: options.json }, runInfo);
588
1357
  }
589
1358
 
590
1359
  /**
@@ -632,13 +1401,187 @@ function probeResident(distro, scriptPath, wslExe = WSL) {
632
1401
  finish({ ok: true, pid: Number(pid), digestMatches: digest === expected });
633
1402
  });
634
1403
  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)})` });
1404
+ child.on("close", () => {
1405
+ if (settled) return;
1406
+ // 'exit' can fire before the stdio pipes are drained — the HELLO sits
1407
+ // in the pipe while the parent-side buffer looks empty (a loaded host
1408
+ // widens the window). 'close' fires after the streams flush, so the
1409
+ // harvest here sees everything the agent wrote.
1410
+ const first = buffered.split("\n")[0]?.trim() ?? "";
1411
+ if (first.startsWith("HELLO|")) {
1412
+ const [kind, name, version, digest, pid] = first.split("|");
1413
+ if (kind === "HELLO" && name === AGENT_NAME && Number(version) === PROTOCOL_VERSION) {
1414
+ const expected = createHash("sha256").update(readFileSync(scriptPath)).digest("hex");
1415
+ finish({ ok: true, pid: Number(pid), digestMatches: digest === expected });
1416
+ return;
1417
+ }
1418
+ }
1419
+ finish({ ok: false, detail: `agent exited before its HELLO (${buffered.trim().slice(0, 80)})` });
637
1420
  });
638
1421
  child.stdin.end();
639
1422
  });
640
1423
  }
641
1424
 
1425
+ /**
1426
+ * One smoke session against a fresh resident: spawn it, read the HELLO, run
1427
+ * one EXEC round trip (`uname -m`), create a temp dir over the same transport,
1428
+ * send one FSB batch (stat + list) against it, remove the dir, shut the
1429
+ * resident down. This is the chain the session actually rides — frame I/O and
1430
+ * the protocol v7 substrate — not a parallel probe path. Every failure names
1431
+ * its leg; a resident that dies mid-smoke fails fast instead of hanging.
1432
+ *
1433
+ * @param {string} distro - the distro.
1434
+ * @param {string} scriptPath - the agent script as a Linux path inside the distro.
1435
+ * @param {string} wslExe - the wsl.exe to spawn.
1436
+ * @returns {Promise<{ execOk: boolean, execDetail: string, fsOk: boolean, fsDetail: string }>} the two resident-leg verdicts.
1437
+ */
1438
+ function runSmokeLegs(distro, scriptPath, wslExe = WSL) {
1439
+ return new Promise((settle) => {
1440
+ const child = spawn(wslExe, ["-d", distro, "--exec", "sh", scriptPath], {
1441
+ stdio: ["pipe", "pipe", "pipe"],
1442
+ windowsHide: true,
1443
+ env: { ...process.env, WSL_UTF8: "1" },
1444
+ });
1445
+ let settled = false;
1446
+ let buffer = "";
1447
+ let helloSeen = false;
1448
+ /** @type {Map<string, (line: string) => void>} */
1449
+ const waiters = new Map();
1450
+ let helloResolve = /** @type {((value: boolean) => void) | undefined} */ (undefined);
1451
+ const helloPromise = new Promise((resolve) => { helloResolve = resolve; });
1452
+ const timer = setTimeout(() => finish({ execOk: false, execDetail: "the smoke session timed out", fsOk: false, fsDetail: "the smoke session timed out" }), 30_000);
1453
+ /** @param {{ execOk: boolean, execDetail: string, fsOk: boolean, fsDetail: string }} value - the leg verdicts. */
1454
+ const finish = (value) => {
1455
+ if (settled) return;
1456
+ settled = true;
1457
+ clearTimeout(timer);
1458
+ try { child.stdin.write("SHUTDOWN\n"); } catch { /* the resident may already be gone */ }
1459
+ setTimeout(() => {
1460
+ try { child.kill(); } catch { /* already gone */ }
1461
+ settle(value);
1462
+ }, 150);
1463
+ };
1464
+ child.stdout.on("data", (chunk) => {
1465
+ buffer += String(chunk);
1466
+ for (;;) {
1467
+ const newline = buffer.indexOf("\n");
1468
+ if (newline < 0) break;
1469
+ const line = buffer.slice(0, newline).trim();
1470
+ buffer = buffer.slice(newline + 1);
1471
+ if (line.length === 0) continue;
1472
+ const parsed = parseAgentLine(line);
1473
+ if (parsed.type === "hello") {
1474
+ helloSeen = true;
1475
+ helloResolve?.(true);
1476
+ continue;
1477
+ }
1478
+ if (parsed.type === "ack" || parsed.type === "pong" || parsed.type === "unknown") continue;
1479
+ const id = parsed.type === "result" || parsed.type === "agentError" || parsed.type === "fsError" ? parsed.id : "";
1480
+ const waiter = waiters.get(id);
1481
+ if (waiter !== undefined) {
1482
+ waiters.delete(id);
1483
+ waiter(line);
1484
+ }
1485
+ }
1486
+ });
1487
+ let childGone = false;
1488
+ child.on("error", (error) => finish({ execOk: false, execDetail: error.message, fsOk: false, fsDetail: error.message }));
1489
+ // A dead resident's pipe surfaces as EPIPE on the write side; the exit
1490
+ // handler names the cause, so the write-side error is swallowed.
1491
+ child.stdin.on("error", () => { /* named by the exit handler */ });
1492
+ child.on("close", () => {
1493
+ childGone = true;
1494
+ if (settled) return;
1495
+ // The same pipe-ordering race the handshake probe guards: a buffered
1496
+ // HELLO counts even when the data event has not fired yet.
1497
+ if (!helloSeen && buffer.includes("HELLO|")) {
1498
+ helloSeen = true;
1499
+ helloResolve?.(true);
1500
+ }
1501
+ if (!settled && waiters.size > 0) finish({ execOk: false, execDetail: "the resident exited mid-smoke", fsOk: false, fsDetail: "the resident exited mid-smoke" });
1502
+ });
1503
+ /** Send one request and resolve with the reply line that answers it.
1504
+ * @param {string} id - the request id.
1505
+ * @param {string[]} lines - the frame's lines. */
1506
+ const request = (id, lines) => new Promise((resolve) => {
1507
+ waiters.set(id, resolve);
1508
+ child.stdin.write(`${lines.join("\n")}\n`);
1509
+ });
1510
+ (async () => {
1511
+ // The race's losing timer must be cleared: a live timer keeps the
1512
+ // process lingering ~5 s past the report — per invocation.
1513
+ await new Promise((resolve) => {
1514
+ const wait = setTimeout(resolve, 5000);
1515
+ helloPromise.then(() => { clearTimeout(wait); resolve(true); });
1516
+ });
1517
+ if (!helloSeen) return finish({ execOk: false, execDetail: "no HELLO", fsOk: false, fsDetail: "no HELLO" });
1518
+ if (childGone) return finish({ execOk: false, execDetail: "the resident exited mid-smoke", fsOk: false, fsDetail: "the resident exited mid-smoke" });
1519
+ const execId = "smoke-exec";
1520
+ const execLine = await request(execId, encodeExecFrame({ id: execId, cwd: "/tmp", argv: ["uname", "-m"], timeoutMs: 15_000, maxOutputBytes: 4096 }));
1521
+ const execParsed = parseAgentLine(execLine);
1522
+ const execAnswer = execParsed.type === "result" ? execParsed.stdout.toString("utf8").trim() : "";
1523
+ const execOk = execParsed.type === "result" && execParsed.exitCode === 0 && execAnswer.length > 0;
1524
+ const execDetail = execOk
1525
+ ? `uname -m answered "${execAnswer}" over the frame round trip`
1526
+ : execParsed.type === "result"
1527
+ ? `exit ${execParsed.exitCode}: ${execParsed.stderr.toString("utf8").slice(0, 120)}`
1528
+ : execParsed.type === "agentError"
1529
+ ? `${execParsed.reason}: ${execParsed.message}`
1530
+ : `unexpected reply: ${execLine.slice(0, 80)}`;
1531
+ const mkId = "smoke-mktemp";
1532
+ const mkLine = await request(mkId, encodeExecFrame({ id: mkId, cwd: "/tmp", argv: ["mktemp", "-d", "/tmp/dsh-doctor-smoke-XXXXXXXX"], timeoutMs: 15_000, maxOutputBytes: 4096 }));
1533
+ const mkParsed = parseAgentLine(mkLine);
1534
+ const dir = mkParsed.type === "result" && mkParsed.exitCode === 0 ? mkParsed.stdout.toString("utf8").trim() : "";
1535
+ if (dir.length === 0) {
1536
+ return finish({ execOk, execDetail, fsOk: false, fsDetail: "the temp dir for the batch leg could not be created" });
1537
+ }
1538
+ const fsbId = "smoke-fsb";
1539
+ const fsbLine = await request(fsbId, encodeFsbFrame({ id: fsbId, timeoutMs: 15_000, ops: [{ op: "stat", args: [dir] }, { op: "list", args: [dir] }] }));
1540
+ const fsbParsed = parseAgentLine(fsbLine);
1541
+ const payload = fsbParsed.type === "result" ? fsbParsed.stdout.toString("utf8") : "";
1542
+ const fsOk = fsbParsed.type === "result" && fsbParsed.exitCode === 0 && payload.includes("OK 1") && payload.includes("OK 2");
1543
+ const rmId = "smoke-cleanup";
1544
+ const rmLine = await request(rmId, encodeExecFrame({ id: rmId, cwd: "/tmp", argv: ["rm", "-rf", dir], timeoutMs: 15_000, maxOutputBytes: 4096 }));
1545
+ const rmParsed = parseAgentLine(rmLine);
1546
+ const cleanupOk = rmParsed.type === "result" && rmParsed.exitCode === 0;
1547
+ const fsDetail = fsOk
1548
+ ? `stat + list over ${dir} answered one batch round trip${cleanupOk ? "; the dir is removed" : `; CLEANUP FAILED — ${dir} is left behind`}`
1549
+ : fsbParsed.type === "result"
1550
+ ? `exit ${fsbParsed.exitCode}: ${payload.slice(0, 120)}${cleanupOk ? "" : `; cleanup failed, ${dir} is left behind`}`
1551
+ : fsbParsed.type === "fsError"
1552
+ ? `${fsbParsed.reason}: ${fsbParsed.message}`
1553
+ : `unexpected reply: ${fsbLine.slice(0, 80)}`;
1554
+ return finish({ execOk, execDetail, fsOk, fsDetail });
1555
+ })().catch((error) => finish({ execOk: false, execDetail: /** @type {Error} */ (error).message, fsOk: false, fsDetail: /** @type {Error} */ (error).message }));
1556
+ });
1557
+ }
1558
+
1559
+ /**
1560
+ * The confined-profile smoke: the shipped bwrap builder's per-command shape,
1561
+ * run against a distro temp dir — a write inside the granted root must run,
1562
+ * a write outside it (into the read-only-bound /etc) must be refused. These
1563
+ * are the two assertions `probe:sandbox` makes, in miniature, so the doctor's
1564
+ * verdict covers the fence and not just the binary.
1565
+ * @param {string} distro - the distro.
1566
+ * @returns {Promise<{ ok: boolean, detail: string }>} the fence verdict.
1567
+ */
1568
+ async function runSandboxSmoke(distro) {
1569
+ const dirAnswer = await inDistro(distro, 'd=$(mktemp -d /tmp/dsh-doctor-smoke-XXXXXXXX) && printf %s "$d"');
1570
+ const dir = dirAnswer.stdout.trim();
1571
+ if (dir.length === 0) return { ok: false, detail: "the temp dir for the fence leg could not be created" };
1572
+ const prefix = bwrapArgvPrefix({ mode: "workspace-write", workspaceRoot: dir }, {});
1573
+ const inside = await run([WSL, "-d", distro, "--exec", ...prefix, "sh", "-c", 'printf ok > "$0" && cat "$0"', `${dir}/inside`]);
1574
+ const outside = await run([WSL, "-d", distro, "--exec", ...prefix, "sh", "-c", 'printf no > "$0" 2>/dev/null', "/etc/dsh-doctor-smoke-refuse"]);
1575
+ const cleanup = await inDistro(distro, `rm -rf "${dir}"`);
1576
+ const insideOk = inside.ok && inside.stdout.trim() === "ok";
1577
+ const outsideRefused = !outside.ok;
1578
+ const ok = insideOk && outsideRefused;
1579
+ return {
1580
+ ok,
1581
+ 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`}`,
1582
+ };
1583
+ }
1584
+
642
1585
  /**
643
1586
  * Ask one yes/no question on the terminal.
644
1587
  * @param {string} question - the prompt.
@@ -658,40 +1601,104 @@ async function confirm(question, yes) {
658
1601
  }
659
1602
 
660
1603
  /**
661
- * Print the report and return the exit status.
662
- * @param {Check[]} checks - the collected checks.
1604
+ * Assemble the report: stamp the blocking flag onto every check, compute the
1605
+ * per-distro and overall verdicts, print, and return the exit status.
1606
+ *
1607
+ * The blocking invariant is structural: a `fail` blocks, everything else does
1608
+ * not — config-awareness lives in the statuses (see the session checks), never
1609
+ * in a per-id exception here. A `skipped` check is a consequence of a blocker,
1610
+ * not a blocker itself.
1611
+ *
1612
+ * @param {Check[]} checks - the collected checks (distro-scoped ones carry their `distro`).
663
1613
  * @param {{ json: boolean }} options - the output mode.
664
- * @returns {number} 0 when nothing failed, 1 otherwise.
1614
+ * @param {{ distros?: string[], config?: EffectiveConfig, timingsMs?: Record<string, number>, bundle?: { path: string, redact: boolean, manifest: { name?: string, version?: string, peerDependencies?: Record<string, string> } } }} [runInfo] - the target distros, the effective configuration, the per-phase wall clock, and the bundle request.
1615
+ * @returns {number} 0 when the verdict is `ready`, 1 when `blocked`.
665
1616
  */
666
- function report(checks, options) {
1617
+ function report(checks, options, runInfo = {}) {
1618
+ const stamped = checks.map((entry) => ({
1619
+ ...entry,
1620
+ blocksFirstCommand: entry.status === "fail",
1621
+ }));
667
1622
  /** @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") };
1623
+ const count = (status) => stamped.filter((entry) => entry.status === status).length;
1624
+ const summary = { ok: count("ok"), warn: count("warn"), fail: count("fail"), info: count("info"), skipped: count("skipped") };
1625
+ const blockers = stamped.filter((entry) => entry.blocksFirstCommand).map((entry) => entry.id);
1626
+ const verdict = blockers.length === 0 ? "ready" : "blocked";
1627
+ /** The blockers a distro verdict owns: its own fails plus the host-level ones.
1628
+ * @param {string} name - the distro name.
1629
+ * @returns {string[]} the blocking ids. */
1630
+ const distroBlockers = (name) => stamped
1631
+ .filter((entry) => entry.blocksFirstCommand && (entry.distro === name || entry.distro === undefined))
1632
+ .map((entry) => entry.id);
1633
+ const targets = runInfo.distros ?? [];
1634
+ const distroVerdicts = targets.map((name) => ({
1635
+ name,
1636
+ verdict: distroBlockers(name).length === 0 ? "ready" : "blocked",
1637
+ blockers: distroBlockers(name),
1638
+ }));
670
1639
  if (options.json) {
671
- console.log(JSON.stringify({ schemaVersion: 1, generatedAt: new Date().toISOString(), checks, summary }, null, 2));
1640
+ console.log(JSON.stringify({
1641
+ schemaVersion: 2,
1642
+ generatedAt: new Date().toISOString(),
1643
+ ...(runInfo.config === undefined ? {} : { config: runInfo.config }),
1644
+ checks: stamped,
1645
+ summary,
1646
+ distroVerdicts,
1647
+ verdict,
1648
+ blockers,
1649
+ ...(runInfo.timingsMs === undefined ? {} : { timingsMs: runInfo.timingsMs }),
1650
+ }, null, 2));
672
1651
  } else {
673
1652
  console.log("dsh-plugin-wsl-env doctor");
674
1653
  let section = "";
675
- for (const entry of checks) {
1654
+ let lastDistro = /** @type {string | undefined} */ (undefined);
1655
+ for (const entry of stamped) {
1656
+ if (entry.distro !== undefined && entry.distro !== lastDistro && targets.length > 1) {
1657
+ console.log(`\n[${entry.distro}]`);
1658
+ section = "";
1659
+ lastDistro = entry.distro;
1660
+ }
676
1661
  const current = entry.id.split(".")[0] ?? "";
677
1662
  if (current !== section) {
678
1663
  section = current;
679
1664
  console.log(`\n${section}`);
680
1665
  }
681
- const mark = entry.status === "ok" ? "ok " : entry.status === "warn" ? "warn" : entry.status === "fail" ? "fail" : "info";
1666
+ const mark = entry.status === "ok" ? "ok " : entry.status === "warn" ? "warn" : entry.status === "fail" ? "fail" : entry.status === "skipped" ? "skip" : "info";
682
1667
  console.log(` ${mark} ${entry.title}${entry.detail === undefined ? "" : ` — ${entry.detail}`}`);
683
1668
  if (entry.remedy !== undefined) console.log(` fix: ${entry.remedy}`);
684
1669
  }
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");
1670
+ console.log(`\n${summary.ok} ok, ${summary.warn} warn, ${summary.fail} fail, ${summary.info} info${summary.skipped > 0 ? `, ${summary.skipped} skipped` : ""}`);
1671
+ const timingLine = Object.entries(runInfo.timingsMs ?? {}).filter(([key]) => key !== "total").map(([key, ms]) => `${key} ${ms}ms`).join(", ");
1672
+ if (timingLine.length > 0) console.log(`timings: ${timingLine}; total ${runInfo.timingsMs?.total ?? "?"}ms`);
1673
+ if (verdict === "ready") console.log(`verdict: READY — the first command should succeed${targets.length === 1 ? ` in ${targets[0]}` : targets.length > 1 ? ` in each of: ${targets.join(", ")}` : ""}`);
1674
+ else console.log(`verdict: BLOCKED by: ${blockers.join(", ")} — apply the fixes above, then rerun`);
1675
+ if (summary.fail > 0 || summary.skipped > 0) console.log("run with --fix to sweep stale scopes; --fix --install asks before installing packages");
1676
+ }
1677
+ if (runInfo.bundle !== undefined) {
1678
+ const bundle = {
1679
+ kind: "dsh-plugin-wsl-env doctor bundle",
1680
+ 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.",
1681
+ plugin: { name: runInfo.bundle.manifest.name ?? "dsh-plugin-wsl-env", version: runInfo.bundle.manifest.version ?? "", peers: runInfo.bundle.manifest.peerDependencies ?? {} },
1682
+ ...(runInfo.config === undefined ? {} : { config: runInfo.config }),
1683
+ report: { schemaVersion: 2, generatedAt: new Date().toISOString(), checks: stamped, summary, distroVerdicts, verdict, blockers, ...(runInfo.timingsMs === undefined ? {} : { timingsMs: runInfo.timingsMs }) },
1684
+ redacted: runInfo.bundle.redact ? "home and DSH paths replaced with <redacted-*>" : false,
1685
+ };
1686
+ let payload = `${JSON.stringify(bundle, null, 2)}\n`;
1687
+ if (runInfo.bundle.redact) {
1688
+ const homeReal = homedir();
1689
+ const dshReal = process.env.DSH_HOME !== undefined && process.env.DSH_HOME.length > 0 ? process.env.DSH_HOME : join(homeReal, ".dsh");
1690
+ payload = payload.split(homeReal).join("<redacted-home>").split(dshReal).join("<redacted-dsh-home>");
1691
+ }
1692
+ writeFileSync(runInfo.bundle.path, payload);
1693
+ console.log(`bundle: written to ${runInfo.bundle.path} (${payload.length} bytes${runInfo.bundle.redact ? ", redacted" : ""})`);
687
1694
  }
688
- return summary.fail > 0 ? 1 : 0;
1695
+ return verdict === "blocked" ? 1 : 0;
689
1696
  }
690
1697
 
691
1698
  if (process.argv[1] !== undefined && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
692
1699
  const options = parseArgs(process.argv.slice(2));
693
1700
  if (options.help) {
694
- console.log("node scripts/doctor.mjs [distro] [--json] [--fix] [--install] [--yes] [--read-only]");
1701
+ console.log("node scripts/doctor.mjs [distro] [--all] [--json] [--fix] [--install] [--yes] [--read-only] [--bundle <path>] [--redact]");
695
1702
  } else {
696
1703
  process.exitCode = await main(options);
697
1704
  }