dsh-plugin-wsl-env 0.29.0 → 0.29.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/CHANGELOG.md +342 -0
  2. package/CONTRIBUTING.md +68 -12
  3. package/CONTRIBUTING.zh.md +34 -4
  4. package/README.md +1 -1
  5. package/agent/native/linux-aarch64/dsh-wsl-agent +0 -0
  6. package/agent/native/linux-x86_64/dsh-wsl-agent +0 -0
  7. package/agent/wsl-agent.sh +15 -4
  8. package/client.js +454 -110
  9. package/cordis.patch.yml +28 -7
  10. package/docs/AGENT-PROTOCOL-V7.md +4 -2
  11. package/docs/ARCHITECTURE.md +3 -1
  12. package/docs/ARCHITECTURE.zh.md +3 -1
  13. package/docs/COMPATIBILITY.md +1 -1
  14. package/docs/COMPATIBILITY.zh.md +1 -1
  15. package/docs/CONFIGURATION.md +19 -7
  16. package/docs/CONFIGURATION.zh.md +13 -5
  17. package/docs/DIAGNOSTICS.md +31 -5
  18. package/docs/DIAGNOSTICS.zh.md +22 -5
  19. package/docs/LIMITATIONS.md +65 -6
  20. package/docs/LIMITATIONS.zh.md +51 -6
  21. package/docs/PERFORMANCE.md +29 -1
  22. package/docs/PERFORMANCE.zh.md +23 -1
  23. package/docs/QUICKSTART.md +1 -1
  24. package/docs/QUICKSTART.zh.md +1 -1
  25. package/docs/README.zh.md +1 -1
  26. package/docs/RELEASING.md +29 -6
  27. package/docs/RELEASING.zh.md +9 -0
  28. package/docs/adr/0002-native-agent.md +50 -2
  29. package/lib/agent-confined.js +15 -4
  30. package/lib/agent-errors.d.ts +16 -0
  31. package/lib/agent-errors.js +19 -0
  32. package/lib/agent-exec.d.ts +8 -1
  33. package/lib/agent-exec.js +2 -1
  34. package/lib/agent-shared.d.ts +85 -2
  35. package/lib/agent-shared.js +167 -38
  36. package/lib/agent.d.ts +60 -6
  37. package/lib/agent.js +177 -28
  38. package/lib/auto-preset.js +7 -2
  39. package/lib/doctor-live.d.ts +36 -7
  40. package/lib/doctor-live.js +61 -12
  41. package/lib/doctor-process.d.ts +68 -0
  42. package/lib/doctor-process.js +139 -0
  43. package/lib/doctor-report.js +11 -109
  44. package/lib/fs-substrate.js +3 -3
  45. package/lib/fsio-agent.d.ts +57 -6
  46. package/lib/fsio-agent.js +168 -75
  47. package/lib/git-exec.d.ts +7 -1
  48. package/lib/git-exec.js +14 -2
  49. package/lib/native-agent.d.ts +25 -4
  50. package/lib/native-agent.js +52 -9
  51. package/lib/picker.d.ts +2 -1
  52. package/lib/picker.js +30 -13
  53. package/lib/plugin-update.js +18 -14
  54. package/lib/provider-common.d.ts +112 -0
  55. package/lib/provider-common.js +171 -0
  56. package/lib/sandbox-core.js +52 -13
  57. package/lib/search-exec.d.ts +6 -0
  58. package/lib/search-exec.js +10 -2
  59. package/lib/session-runtime.d.ts +46 -1
  60. package/lib/session-runtime.js +57 -7
  61. package/lib/session-scope.d.ts +22 -1
  62. package/lib/session-scope.js +33 -7
  63. package/lib/shell-env.js +125 -12
  64. package/lib/socket-isolation.d.ts +12 -4
  65. package/lib/socket-isolation.js +27 -10
  66. package/lib/status.js +53 -4
  67. package/lib/subprocess.js +3 -3
  68. package/lib/terminal-activity.js +6 -9
  69. package/lib/wsl-doctor-command.js +36 -80
  70. package/lib/wsl-filesystem.d.ts +9 -4
  71. package/lib/wsl-filesystem.js +26 -10
  72. package/lib/wsl-shell.d.ts +27 -17
  73. package/lib/wsl-shell.js +83 -24
  74. package/lib/wsl.d.ts +3 -1
  75. package/lib/wsl.js +82 -7
  76. package/package.json +5 -4
  77. package/scripts/bootstrap.sh +36 -12
  78. package/scripts/doctor.mjs +514 -201
package/lib/agent.js CHANGED
@@ -17,6 +17,13 @@
17
17
  * dead, calls reject with {@link AgentUnavailableError} — the executor's cue
18
18
  * to fall back to the one-shot `wsl.exe` path it shipped with, so the worst
19
19
  * case of the agent is "today's behaviour, plus one failed round trip".
20
+ * The cue is exact: a request the resident provably never took rejects with
21
+ * the plain class, while one that was with the resident when it was lost
22
+ * rejects with {@link AgentRequestStateUnknownError} — still unavailable,
23
+ * never safe to replay for a caller whose request has effects.
24
+ * `lastError` is the failure not yet recovered from: an accepted handshake
25
+ * clears it, so a resident that came back is diagnosed by what it is now,
26
+ * not by the crash it survived.
20
27
  * 2. **The in-distro timeout is the real one.** The EXEC frame carries the
21
28
  * timeout in whole seconds and the agent SIGTERMs the child itself, so a
22
29
  * timed-out command dies where it lives instead of leaving an orphan
@@ -43,7 +50,7 @@
43
50
  * @module dsh-plugin-wsl-env/agent
44
51
  */
45
52
  import { spawn } from "node:child_process";
46
- import { AgentUnavailableError, BASH_TIMEOUT_REASON, CwdError, SpawnError } from "./agent-errors.js";
53
+ import { AgentRequestStateUnknownError, AgentUnavailableError, BASH_TIMEOUT_REASON, CwdError, SpawnError } from "./agent-errors.js";
47
54
  import { AGENT_NAME, MAX_FRAME_BYTES, MIN_PROTOCOL_VERSION, PROTOCOL_VERSION, encodeExecFrame, encodeFsbFrame, encodeFsFrame, encodeKill, parseAgentLine } from "./agent-protocol.js";
48
55
  /**
49
56
  * A zeroed per-kind metrics record.
@@ -86,6 +93,84 @@ const DEFAULT_REVIVAL_BACKOFF_MS = 2000;
86
93
  * dies promptly.
87
94
  */
88
95
  const CANCEL_SIGNAL_GRACE_MS = 60;
96
+ /**
97
+ * How a frame reaches the resident's stdin (#86).
98
+ *
99
+ * One `write()` of a frame larger than a Windows pipe's buffer (64 KiB) costs
100
+ * a fixed ~100 ms before the resident has the rest of it. Measured on the
101
+ * production path — Windows host, `wsl.exe`, the native agent — a 68 KiB
102
+ * stdin payload answered in 14 ms with the same binary spawned directly in
103
+ * the distro and in 114 ms through `wsl.exe`, and the resident's `ACK` was
104
+ * what came late: the frame, not the request, was slow to arrive. The piece
105
+ * size is not the cause — the same bytes as several pieces written back to
106
+ * back pay it too — and neither reader nor agent is: a plain line reader and
107
+ * `cat` see 68 KiB in under 5 ms. What removes the cost is a timer turn
108
+ * between the pieces, which lets the relay drain the pipe before more of the
109
+ * frame arrives.
110
+ *
111
+ * A timer turn costs about 10 ms on a Windows host, so the schedule pays it
112
+ * only where the measurement says it wins. A payload of 64–384 KiB takes
113
+ * 30–98 ms pieced against 115–120 ms as one write; at 512 KiB one write is
114
+ * faster (123 ms against 144), and at 1 MiB far more so (36 against 264).
115
+ * So frames above one pipe buffer and up to half a mebibyte go out in pieces
116
+ * with a turn between them, and every other frame stays the single write it
117
+ * always was.
118
+ */
119
+ const PIECED_WRITE_ABOVE_BYTES = 64 * 1024;
120
+ const PIECED_WRITE_UNTIL_BYTES = 512 * 1024;
121
+ const WRITE_PIECE_BYTES = 60 * 1024;
122
+ /**
123
+ * Whether a frame goes out in pieces.
124
+ * @param frame - the frame, terminator included.
125
+ * @returns true for a frame in the band where piecing wins.
126
+ */
127
+ function isPieced(frame) {
128
+ const bytes = Buffer.byteLength(frame);
129
+ return bytes > PIECED_WRITE_ABOVE_BYTES && bytes <= PIECED_WRITE_UNTIL_BYTES;
130
+ }
131
+ /**
132
+ * Put one frame on a stream: in pieces with a timer turn between them when
133
+ * {@link isPieced} says so, otherwise as one write.
134
+ * @param stdin - the resident's stdin.
135
+ * @param frame - the frame, terminator included.
136
+ */
137
+ async function writeFrame(stdin, frame) {
138
+ if (!isPieced(frame)) {
139
+ stdin.write(frame);
140
+ return;
141
+ }
142
+ const buffer = Buffer.from(frame);
143
+ for (let offset = 0; offset < buffer.length; offset += WRITE_PIECE_BYTES) {
144
+ // The timer turn: the relay drains what is in the pipe before more arrives.
145
+ if (offset > 0)
146
+ await new Promise((resolve) => setTimeout(resolve, 0));
147
+ const piece = buffer.subarray(offset, Math.min(buffer.length, offset + WRITE_PIECE_BYTES));
148
+ // Each piece is awaited: one that fits the pipe answers at once, and a
149
+ // slow relay holds the next piece back instead of piling bytes up here.
150
+ await new Promise((resolve, reject) => {
151
+ stdin.write(piece, (error) => (error == null ? resolve() : reject(error)));
152
+ });
153
+ }
154
+ }
155
+ /**
156
+ * Write the queued frames one at a time, so the pieces of one never interleave
157
+ * with the next. A dead pipe empties the queue: the stream's error listener
158
+ * has already absorbed the event, and nothing after a failed piece is worth
159
+ * sending.
160
+ * @param {PendingWrites} writes - the record to drain.
161
+ */
162
+ async function drainWrites(writes) {
163
+ try {
164
+ for (let frame = writes.frames.shift(); frame !== undefined; frame = writes.frames.shift())
165
+ await writeFrame(writes.stdin, frame);
166
+ }
167
+ catch {
168
+ writes.frames.length = 0;
169
+ }
170
+ finally {
171
+ writes.draining = false;
172
+ }
173
+ }
89
174
  /**
90
175
  * How many requests one resident may hold in flight before refusing more. The
91
176
  * agent is serial, so a large queue only delays every entry; the cap keeps a
@@ -176,6 +261,8 @@ function spawnDefault({ wslPath, distro, scriptPath, argvPrefix = [], leaseMs =
176
261
  }
177
262
  /** The resident agent for one distro. */
178
263
  export class WslAgent {
264
+ /** The frames waiting for the current resident's stdin; see {@link writeLines}. */
265
+ writes;
179
266
  /**
180
267
  * @param config - the agent configuration.
181
268
  */
@@ -207,11 +294,13 @@ export class WslAgent {
207
294
  this.deadUntil = 0;
208
295
  this.revivalBackoffMs = config.revivalBackoffMs ?? DEFAULT_REVIVAL_BACKOFF_MS;
209
296
  this.idleTimer = null;
297
+ this.lastActivityAt = Date.now();
210
298
  this.lastError = "";
211
299
  this.protocolVersion = 0;
212
300
  this.caps = new Set();
213
301
  this.requestMetrics = emptyAgentMetrics();
214
302
  this.prepare = config.prepare;
303
+ this.onStart = config.onStart;
215
304
  }
216
305
  /**
217
306
  * Whether the agent is permanently out — the executor's fallback cue.
@@ -289,14 +378,15 @@ export class WslAgent {
289
378
  return this.startPromise;
290
379
  const prepared = this.prepare?.();
291
380
  if (prepared === undefined) {
292
- const started = this.beginStart();
381
+ const started = this.beginStart(false);
293
382
  this.startPromise = started;
294
383
  return started;
295
384
  }
296
385
  const started = prepared.then((entry) => {
297
- if (entry !== undefined)
298
- this.applyPrepared(entry);
299
- return this.beginStart();
386
+ if (entry === undefined)
387
+ return this.beginStart(false);
388
+ this.applyPrepared(entry);
389
+ return this.beginStart(true);
300
390
  });
301
391
  this.startPromise = started;
302
392
  return started;
@@ -319,9 +409,11 @@ export class WslAgent {
319
409
  /**
320
410
  * Spawn the process and run the handshake.
321
411
  *
412
+ * @param native - whether this start runs the prepared entry rather than
413
+ * the instance's default one.
322
414
  * @returns resolved once the state is `ready`.
323
415
  */
324
- beginStart() {
416
+ beginStart(native) {
325
417
  this.state = "starting";
326
418
  this.agentPid = undefined;
327
419
  return new Promise((resolve, reject) => {
@@ -352,10 +444,12 @@ export class WslAgent {
352
444
  this.state = this.rebuildUsed ? "dead" : "idle";
353
445
  if (this.rebuildUsed)
354
446
  this.lastError = this.lastError || String(error);
447
+ this.onStart?.({ ok: false, native });
355
448
  reject(error instanceof AgentUnavailableError ? error : new AgentUnavailableError(String(error)));
356
449
  }
357
450
  else {
358
451
  this.state = "ready";
452
+ this.onStart?.({ ok: true, native });
359
453
  resolve();
360
454
  }
361
455
  };
@@ -415,10 +509,18 @@ export class WslAgent {
415
509
  });
416
510
  }
417
511
  /**
418
- * The stdout line splitter: a bounded buffer instead of readline, which
419
- * accumulates an over-long line whole before anyone can object — exactly the
420
- * unbounded-capture hole. Protocol lines are ASCII by construction (ids,
421
- * numbers, base64), so chunk-boundary decoding is not a concern.
512
+ * The stdout line splitter: a list of the chunks of the line still
513
+ * arriving, instead of readline, which accumulates an over-long line whole
514
+ * before anyone can object — exactly the unbounded-capture hole. Protocol
515
+ * lines are ASCII by construction (ids, numbers, base64), so chunk-boundary
516
+ * decoding is not a concern.
517
+ *
518
+ * The chunks are searched, never a joined string. One growing string made
519
+ * this quadratic — every chunk copied the whole frame so far and scanned
520
+ * it again for the newline — and since this runs on the host's event loop,
521
+ * a 16 MiB read frame arriving in 64 KiB chunks held that loop for about
522
+ * 2.6 seconds. Now a chunk is searched once, and a line is joined once,
523
+ * when its newline has arrived.
422
524
  *
423
525
  * @param child - the transport to read.
424
526
  * @param current - whether this child is still the current generation.
@@ -426,30 +528,40 @@ export class WslAgent {
426
528
  * @param handshakeTimer - the handshake watchdog.
427
529
  */
428
530
  readAgentOutput(child, current, settleStart, handshakeTimer) {
429
- let buffered = "";
531
+ /** The chunks of the line still arriving, in arrival order. */
532
+ let chunks = [];
533
+ /** How many bytes {@link chunks} hold. */
534
+ let held = 0;
430
535
  child.stdout.on("data", (chunk) => {
431
536
  if (!current())
432
537
  return;
433
- buffered += chunk.toString("utf8");
538
+ let rest = chunk;
434
539
  for (;;) {
435
- const newline = buffered.indexOf("\n");
540
+ const newline = rest.indexOf(0x0a);
436
541
  if (newline === -1) {
437
- if (buffered.length > this.frameCapBytes) {
438
- this.lastError = `agent frame of ${buffered.length} bytes exceeded the ${this.frameCapBytes}-byte protocol cap`;
439
- buffered = "";
542
+ if (held + rest.length > this.frameCapBytes) {
543
+ this.lastError = `agent frame of ${held + rest.length} bytes exceeded the ${this.frameCapBytes}-byte protocol cap`;
544
+ chunks = [];
545
+ held = 0;
440
546
  child.kill();
441
547
  }
548
+ else if (rest.length > 0) {
549
+ chunks.push(rest);
550
+ held += rest.length;
551
+ }
442
552
  return;
443
553
  }
444
- const line = buffered.slice(0, newline);
445
- buffered = buffered.slice(newline + 1);
554
+ const head = rest.subarray(0, newline);
555
+ const line = chunks.length === 0 ? head : Buffer.concat([...chunks, head], held + head.length);
556
+ chunks = [];
557
+ held = 0;
558
+ rest = rest.subarray(newline + 1);
446
559
  if (line.length > this.frameCapBytes) {
447
560
  this.lastError = `agent frame of ${line.length} bytes exceeded the ${this.frameCapBytes}-byte protocol cap`;
448
- buffered = "";
449
561
  child.kill();
450
562
  return;
451
563
  }
452
- this.handleLine(line, settleStart, handshakeTimer);
564
+ this.handleLine(line.toString("utf8"), settleStart, handshakeTimer);
453
565
  }
454
566
  });
455
567
  }
@@ -506,6 +618,9 @@ export class WslAgent {
506
618
  this.agentPid = message.pid;
507
619
  this.protocolVersion = message.version;
508
620
  this.caps = new Set(message.caps ?? []);
621
+ // The resident is up, so whatever failed last is over. Kept, the old
622
+ // failure warned in every later diagnosis until the app restarted.
623
+ this.lastError = "";
509
624
  settleStart();
510
625
  }
511
626
  /**
@@ -680,7 +795,7 @@ export class WslAgent {
680
795
  if (pending.settled)
681
796
  continue;
682
797
  pending.settled = true;
683
- pending.reject(new AgentUnavailableError(`agent exited before request ${pending.id} was sent; it never ran`));
798
+ pending.reject(this.refusalFor(pending, "the agent exited before the request was dispatched"));
684
799
  }
685
800
  else if (isReplayableFrame(pending.lines)) {
686
801
  if (pending.watchdog) {
@@ -697,7 +812,7 @@ export class WslAgent {
697
812
  if (pending.settled)
698
813
  continue;
699
814
  pending.settled = true;
700
- pending.reject(new AgentUnavailableError(`agent exited while request ${pending.id} was in flight; its state is unknown — inspect the distro before retrying`));
815
+ pending.reject(this.refusalFor(pending, "the agent exited while the request was in flight"));
701
816
  }
702
817
  }
703
818
  return relayable;
@@ -730,7 +845,7 @@ export class WslAgent {
730
845
  if (pending.settled)
731
846
  continue;
732
847
  pending.settled = true;
733
- pending.reject(new AgentUnavailableError(`agent exited before request ${id} could be re-sent; its state is unknown`));
848
+ pending.reject(this.refusalFor(pending, "the agent exited before the request could be re-sent"));
734
849
  }
735
850
  }
736
851
  this.dispatchQueued();
@@ -757,10 +872,26 @@ export class WslAgent {
757
872
  if (pending.settled)
758
873
  continue;
759
874
  pending.settled = true;
760
- pending.reject(new AgentUnavailableError(message));
875
+ pending.reject(this.refusalFor(pending, message));
761
876
  }
762
877
  this.pending.clear();
763
878
  }
879
+ /**
880
+ * The refusal an abandoned entry rejects with. An entry whose frame reached
881
+ * the resident may have run, and its refusal says so — that is what keeps a
882
+ * caller with a non-idempotent request from replaying it. An entry that was
883
+ * never written provably never ran, which is the plain out-of-service cue
884
+ * such a caller may act on.
885
+ *
886
+ * @param pending - the abandoned entry.
887
+ * @param reason - what happened to the resident.
888
+ * @returns the refusal.
889
+ */
890
+ refusalFor(pending, reason) {
891
+ return pending.sent
892
+ ? new AgentRequestStateUnknownError(`${reason}; request ${pending.id} was in flight and its state is unknown — inspect the distro before retrying`)
893
+ : new AgentUnavailableError(`${reason}; request ${pending.id} was never sent, so it never ran`);
894
+ }
764
895
  /**
765
896
  * Register one request's pending entry and write its frame: the shared
766
897
  * request machinery (abort, submission, the ACK-armed watchdog). The
@@ -1178,13 +1309,12 @@ export class WslAgent {
1178
1309
  this.process = null;
1179
1310
  this.agentPid = undefined;
1180
1311
  if (this.pending.size > 0) {
1181
- const reason = new AgentUnavailableError("the agent was closed before this request answered");
1182
1312
  for (const pending of this.pending.values()) {
1183
1313
  this.clearPending(pending);
1184
1314
  if (pending.settled)
1185
1315
  continue;
1186
1316
  pending.settled = true;
1187
- pending.reject(reason);
1317
+ pending.reject(this.refusalFor(pending, "the agent was closed before this request answered"));
1188
1318
  }
1189
1319
  this.pending.clear();
1190
1320
  }
@@ -1230,7 +1360,25 @@ export class WslAgent {
1230
1360
  const child = this.process;
1231
1361
  if (!child || !child.stdin || !child.stdin.writable)
1232
1362
  return false;
1233
- child.stdin.write(`${lines.join("\n")}\n`);
1363
+ const stdin = child.stdin;
1364
+ const frame = `${lines.join("\n")}\n`;
1365
+ let writes = this.writes;
1366
+ if (writes === undefined || writes.stdin !== stdin) {
1367
+ // A new resident. Its predecessor's record keeps its own queue and ends
1368
+ // against a dead pipe on its own.
1369
+ writes = { stdin, frames: [], draining: false };
1370
+ this.writes = writes;
1371
+ }
1372
+ if (!writes.draining && !isPieced(frame)) {
1373
+ stdin.write(frame);
1374
+ }
1375
+ else {
1376
+ writes.frames.push(frame);
1377
+ if (!writes.draining) {
1378
+ writes.draining = true;
1379
+ void drainWrites(writes);
1380
+ }
1381
+ }
1234
1382
  this.rearmIdleTimer();
1235
1383
  return true;
1236
1384
  }
@@ -1253,8 +1401,9 @@ export class WslAgent {
1253
1401
  // A dead pipe is what close() is cleaning up after.
1254
1402
  }
1255
1403
  }
1256
- /** Restart the idle-shutdown countdown. */
1404
+ /** Note the exchange, then restart the idle-shutdown countdown. */
1257
1405
  rearmIdleTimer() {
1406
+ this.lastActivityAt = Date.now();
1258
1407
  if (!this.idleMs)
1259
1408
  return;
1260
1409
  if (this.idleTimer)
@@ -304,7 +304,7 @@ export async function apply(ctx, config = {}) {
304
304
  return;
305
305
  }
306
306
  const original = facade.createSession;
307
- facade.createSession = async function (request) {
307
+ const wrapped = async function (request) {
308
308
  // A non-default preset id always wins; the default id (or no id) is
309
309
  // automatic. Only a distro workspace is affected. A workspace the operator
310
310
  // opened for Windows access keeps the host preset even here: this is the
@@ -334,10 +334,15 @@ export async function apply(ctx, config = {}) {
334
334
  return original.call(this, request);
335
335
  }
336
336
  };
337
+ facade.createSession = wrapped;
337
338
  publishAutoPresetSeam("active", "agents.createSession is wrapped; distro sessions mount the WSL preset first", "createSession");
338
339
  trace("creation-time preset fix installed");
339
340
  controllerCtx.effect(() => () => {
340
- facade.createSession = original;
341
+ // Restore only what is still ours: with two wrappers live (a hot reload
342
+ // that outlived its predecessor), the late disposer used to clobber the
343
+ // newer wrapper and silently disable the fix.
344
+ if (facade.createSession === wrapped)
345
+ facade.createSession = original;
341
346
  publishAutoPresetSeam("inactive", "the auto-preset row was disposed");
342
347
  });
343
348
  });
@@ -9,7 +9,7 @@
9
9
  * the plugin's context (the app process itself, through
10
10
  * {@link doctorReport}) merge the resident's own `status()` snapshot into a
11
11
  * collected report — no transport is invented, and a status that answers for
12
- * no resident (pid unknown) changes nothing.
12
+ * no resident (never started: no pid, no death, no failure) changes nothing.
13
13
  *
14
14
  * @module dsh-plugin-wsl-env/doctor-live
15
15
  */
@@ -37,24 +37,53 @@ export interface DoctorReport {
37
37
  checks: DoctorCheck[];
38
38
  /** Per-status tally. */
39
39
  summary: Record<string, number>;
40
+ /** The ids of the blocking (`fail`) checks, when the report derives them. */
41
+ blockers?: string[];
42
+ /** `ready` or `blocked`, when the report derives it from {@link blockers}. */
43
+ verdict?: string;
44
+ /** Per-distro `verdict` and `blockers`, when the report derives them. */
45
+ distroVerdicts?: Array<{
46
+ name: string;
47
+ verdict: string;
48
+ blockers: string[];
49
+ }>;
50
+ }
51
+ /** What a diagnosis knows about a resident beyond its lifecycle snapshot. */
52
+ export interface LiveResidentNotes {
53
+ /**
54
+ * Why the resident is not on the native entry though the backend asks for
55
+ * it — the entry is demoted, or its preparation failed.
56
+ */
57
+ nativeNote?: string;
40
58
  }
41
59
  /**
42
60
  * Fold an in-process resident's lifecycle snapshot into a doctor report's
43
61
  * `agent.handshake` check.
44
62
  *
45
63
  * The merge fires only when the status answers for a resident this process
46
- * actually holds (`pid` known) — a never-started singleton's snapshot says
47
- * nothing about the app's resident and is ignored, keeping the fresh-probe
48
- * report honest. A `dead` resident fails the check; a `lastError` on a
49
- * running resident surfaces as `warn` (the revival budget may already have
50
- * recovered it); the digest facts the fresh probe established are kept.
64
+ * actually held — a pid, a death, or a failure not yet recovered from (see
65
+ * {@link isHeld}). A never-started singleton's snapshot says nothing about
66
+ * the app's resident and is ignored, keeping the fresh-probe report honest.
67
+ * A `dead` resident FAILS the check: every path into `dead` clears the pid,
68
+ * so a pid-only test used to skip exactly the resident that was down, and
69
+ * file operations failing closed behind it read as `ready`. A `lastError` on
70
+ * a running resident surfaces as `warn`; it is the failure not yet recovered
71
+ * from, because an accepted handshake clears it. The digest facts the fresh
72
+ * probe established are kept.
73
+ *
74
+ * A verdict the collector derived from its own checks — `blockers`,
75
+ * `verdict`, `distroVerdicts` — is derived again when the merge changes a
76
+ * check's status: a digest trusts those fields over the checks when the
77
+ * report carries them, so a failure that stops reaching them stops existing.
51
78
  *
79
+ * @template T - the report's own type, preserved so richer shapes pass through.
52
80
  * @param report - the collected doctor report (not mutated).
53
81
  * @param status - the in-process `status()` snapshot, when reachable.
82
+ * @param notes - what the caller knows beyond the snapshot.
54
83
  * @returns the report with the merged handshake check; the input object when
55
84
  * there is nothing to merge.
56
85
  */
57
- export declare function mergeLiveResidentStatus(report: DoctorReport, status: AgentStatus | undefined): DoctorReport;
86
+ export declare function mergeLiveResidentStatus<T extends DoctorReport>(report: T, status: AgentStatus | undefined, notes?: LiveResidentNotes): T;
58
87
  /** The report fields {@link mergeAutoPresetSeam} needs; the strict and loose report types both fit. */
59
88
  interface SeamMergeReport {
60
89
  /** The report's check rows. */
@@ -1,33 +1,63 @@
1
1
  import { autoPresetSeam } from "./auto-preset-seam.js";
2
+ /**
3
+ * Whether a status answers for a resident this process holds. Entering `dead`
4
+ * clears the pid, so the pid alone cannot be the test: a resident that died
5
+ * has a death to its name or a failure not yet recovered from, and either
6
+ * makes its state this process's business. A never-started singleton — idle,
7
+ * no pid, nothing ever failed — says nothing about the app's resident.
8
+ *
9
+ * @param status - the in-process snapshot.
10
+ * @returns true when the snapshot describes a resident that was held.
11
+ */
12
+ function isHeld(status) {
13
+ return status.pid != null || status.deaths > 0 || status.lastError.length > 0;
14
+ }
2
15
  /**
3
16
  * Fold an in-process resident's lifecycle snapshot into a doctor report's
4
17
  * `agent.handshake` check.
5
18
  *
6
19
  * The merge fires only when the status answers for a resident this process
7
- * actually holds (`pid` known) — a never-started singleton's snapshot says
8
- * nothing about the app's resident and is ignored, keeping the fresh-probe
9
- * report honest. A `dead` resident fails the check; a `lastError` on a
10
- * running resident surfaces as `warn` (the revival budget may already have
11
- * recovered it); the digest facts the fresh probe established are kept.
20
+ * actually held — a pid, a death, or a failure not yet recovered from (see
21
+ * {@link isHeld}). A never-started singleton's snapshot says nothing about
22
+ * the app's resident and is ignored, keeping the fresh-probe report honest.
23
+ * A `dead` resident FAILS the check: every path into `dead` clears the pid,
24
+ * so a pid-only test used to skip exactly the resident that was down, and
25
+ * file operations failing closed behind it read as `ready`. A `lastError` on
26
+ * a running resident surfaces as `warn`; it is the failure not yet recovered
27
+ * from, because an accepted handshake clears it. The digest facts the fresh
28
+ * probe established are kept.
12
29
  *
30
+ * A verdict the collector derived from its own checks — `blockers`,
31
+ * `verdict`, `distroVerdicts` — is derived again when the merge changes a
32
+ * check's status: a digest trusts those fields over the checks when the
33
+ * report carries them, so a failure that stops reaching them stops existing.
34
+ *
35
+ * @template T - the report's own type, preserved so richer shapes pass through.
13
36
  * @param report - the collected doctor report (not mutated).
14
37
  * @param status - the in-process `status()` snapshot, when reachable.
38
+ * @param notes - what the caller knows beyond the snapshot.
15
39
  * @returns the report with the merged handshake check; the input object when
16
40
  * there is nothing to merge.
17
41
  */
18
- export function mergeLiveResidentStatus(report, status) {
19
- if (!status || status.pid == null)
42
+ export function mergeLiveResidentStatus(report, status, notes = {}) {
43
+ if (!status || !isHeld(status))
20
44
  return report;
21
45
  const fresh = report.checks.find((check) => check.id === "agent.handshake");
22
46
  if (!fresh)
23
47
  return report;
24
48
  const errorLine = status.lastError.length > 0 ? `; lastError: ${status.lastError}` : "";
25
- // The fresh check's shape fields (distro, blocksFirstCommand) ride through:
26
- // the merge rewrites the verdict and the evidence, never the schema.
49
+ const verdict = status.state === "dead" ? "fail" : status.lastError.length > 0 ? "warn" : fresh.status;
50
+ // The fresh check's shape fields (distro) ride through: the merge rewrites
51
+ // the verdict and the evidence, never the schema. `blocksFirstCommand` is
52
+ // the collector's own stamp of "this check fails", so it follows the
53
+ // verdict wherever the report carries it.
27
54
  const merged = {
28
55
  ...fresh,
29
- status: status.state === "dead" ? "fail" : status.lastError.length > 0 ? "warn" : fresh.status,
30
- detail: `probed: the live resident (pid ${status.pid}, state ${status.state}, deaths ${status.deaths}, pending ${status.pending})${errorLine}; fresh-probe facts: ${fresh.detail ?? ""}`,
56
+ status: verdict,
57
+ ...(fresh.blocksFirstCommand === undefined ? {} : { blocksFirstCommand: verdict === "fail" }),
58
+ detail: `probed: the live resident (pid ${status.pid ?? "none"}, state ${status.state}, deaths ${status.deaths}, pending ${status.pending})${errorLine}`
59
+ + `; fresh-probe facts: ${fresh.detail ?? ""}`
60
+ + (notes.nativeNote === undefined ? "" : `; native agent: ${notes.nativeNote}`),
31
61
  };
32
62
  const checks = report.checks.map((check) => (check === fresh ? merged : check));
33
63
  const summary = { ...report.summary };
@@ -35,7 +65,26 @@ export function mergeLiveResidentStatus(report, status) {
35
65
  summary[fresh.status] = Math.max(0, (summary[fresh.status] ?? 0) - 1);
36
66
  summary[merged.status] = (summary[merged.status] ?? 0) + 1;
37
67
  }
38
- return { ...report, checks, summary };
68
+ if (merged.status === fresh.status)
69
+ return { ...report, checks, summary };
70
+ // The collector derives its verdict fields as every `fail` blocks, a
71
+ // distro's blockers being its own fails plus the host-level ones.
72
+ const blocking = checks.filter((check) => check.status === "fail").map((check) => check.id);
73
+ const distroBlockers = (name) => checks.filter((check) => check.status === "fail" && (check.distro === name || check.distro === undefined)).map((check) => check.id);
74
+ // The derived fields keep the report's own type: each is rewritten only
75
+ // where the report carried it, so nothing is added to a shape that lacked it.
76
+ const derived = {
77
+ ...(report.blockers === undefined && report.verdict === undefined ? {} : { blockers: blocking, verdict: blocking.length === 0 ? "ready" : "blocked" }),
78
+ ...(report.distroVerdicts === undefined
79
+ ? {}
80
+ : {
81
+ distroVerdicts: report.distroVerdicts.map((row) => {
82
+ const own = distroBlockers(row.name);
83
+ return { ...row, blockers: own, verdict: own.length === 0 ? "ready" : "blocked" };
84
+ }),
85
+ }),
86
+ };
87
+ return { ...report, checks, summary, ...derived };
39
88
  }
40
89
  /**
41
90
  * Fold auto-preset's creation-time seam state into a doctor report.
@@ -0,0 +1,68 @@
1
+ /**
2
+ * The bounded `doctor.mjs` subprocess collector shared by the two doctor
3
+ * runners: the in-app report (`doctor-report.ts`, the `wsl_doctor` tool) and
4
+ * the `/wsl-doctor` command. Both used to carry their own spawn, deadline and
5
+ * stream handling; the command's copy concatenated per-chunk
6
+ * `toString("utf8")` (splitting a multi-byte character at a chunk boundary),
7
+ * had no output cap, and checked the JSON prefix before the deadline. One
8
+ * collector now owns all three rules:
9
+ *
10
+ * - the deadline kills the child and settles the run as timed out;
11
+ * - stdout + stderr are capped, and crossing the cap kills the run;
12
+ * - streams are decoded with a `StringDecoder` (`setEncoding("utf8")`), so a
13
+ * chunk boundary never splits a code point;
14
+ * - a grandchild that inherited the pipes cannot hold the collector past the
15
+ * bounded drain window after the doctor itself exits.
16
+ *
17
+ * This is a TypeScript source built to `lib/doctor-process.js`; edit THIS file
18
+ * and run `pnpm run build` — the artifact under `lib/` is generated, and
19
+ * `pnpm test` fails when it drifts.
20
+ *
21
+ * @module dsh-plugin-wsl-env/doctor-process
22
+ */
23
+ /**
24
+ * How much of one doctor stream the collector retains. The `--json` report is
25
+ * a few dozen KiB; the cap exists so a runaway child cannot grow the Host's
26
+ * memory without bound.
27
+ */
28
+ export declare const DOCTOR_OUTPUT_LIMIT_BYTES: number;
29
+ /**
30
+ * How long after the doctor exits the collector waits for its pipes. A
31
+ * grandchild that inherited the pipes can keep them open forever; the report
32
+ * on stdout is complete once the doctor itself has exited, so the wait is
33
+ * bounded instead of following the pipes to EOF.
34
+ */
35
+ export declare const DOCTOR_DRAIN_GRACE_MS = 500;
36
+ /** One finished doctor subprocess, as the collector hands it to the parser. */
37
+ export interface DoctorRun {
38
+ stdout: string;
39
+ stderr: string;
40
+ /** The exit status; null when a signal ended the run. */
41
+ status: number | null;
42
+ /** The terminating signal name, when one ended the run. */
43
+ signal: string | null;
44
+ /** The run outlived its deadline and was killed. */
45
+ timedOut: boolean;
46
+ /** Stream capture crossed {@link DOCTOR_OUTPUT_LIMIT_BYTES} and the run was killed. */
47
+ overLimit: boolean;
48
+ /** The transport failure: a spawn error (ENOENT, EACCES) or an abort. */
49
+ spawnError?: Error;
50
+ }
51
+ /**
52
+ * Run the doctor CLI asynchronously and collect its streams.
53
+ *
54
+ * `spawnSync` would block the Host's event loop for the whole run — up to the
55
+ * deadline, with no way to cancel and every other tool stalled behind it — so
56
+ * the collector spawns, arms a deadline and the caller's abort signal, and
57
+ * settles on the child's exit plus a bounded drain window. A grandchild that
58
+ * inherits the pipes cannot hold the collector past that window.
59
+ *
60
+ * @param argv - the node argv (script path first).
61
+ * @param options - the child env, the deadline, and the caller's signal.
62
+ * @returns the finished run, including the spawn failure when it never started.
63
+ */
64
+ export declare function runDoctorProcess(argv: string[], options: {
65
+ env?: NodeJS.ProcessEnv;
66
+ timeoutMs: number;
67
+ signal?: AbortSignal;
68
+ }): Promise<DoctorRun>;