@zhuxixi/pi-agent-board 0.13.1 → 0.14.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 (80) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/README.md +15 -8
  3. package/docs/SECTION_FOLDING.md +53 -0
  4. package/docs/superpowers/plans/2026-10-23-issue-222-attach-ready.md +290 -0
  5. package/docs/superpowers/plans/2026-10-28-issue-257-legacy-pty-runner-endpoint-cleanup.md +256 -0
  6. package/docs/superpowers/plans/2026-11-03-cwd-favorites-full-pool.md +266 -0
  7. package/docs/superpowers/plans/2026-11-03-issue-266-alt-h-detach.md +467 -0
  8. package/docs/superpowers/plans/2026-11-04-issue-270-scenario-stdout-flush.md +584 -0
  9. package/docs/superpowers/plans/2026-11-05-issue-278-ctrl-g-external-editor.md +381 -0
  10. package/docs/superpowers/plans/2026-11-06-issue-280-frame-witness-delivery.md +430 -0
  11. package/docs/superpowers/plans/2026-11-07-issue-284-attach-recovery.md +115 -0
  12. package/docs/superpowers/plans/2026-11-07-issue-284-u1-u2-trial-guide.md +39 -0
  13. package/docs/superpowers/plans/2026-11-08-host-restart-model-override.md +894 -0
  14. package/docs/superpowers/plans/2026-11-08-issue-288-cap-floor.md +51 -0
  15. package/docs/superpowers/plans/2026-11-09-dashboard-fold-flake.md +166 -0
  16. package/docs/superpowers/plans/2026-11-09-issue-273-harness-console-log-exit.md +369 -0
  17. package/docs/superpowers/plans/2026-11-10-issue-258-board-selection-settle.md +760 -0
  18. package/docs/superpowers/plans/2026-11-13-issue-294-snapshot-resize-intent.md +590 -0
  19. package/docs/superpowers/plans/2026-11-16-greeting-title-poll.md +838 -0
  20. package/docs/superpowers/plans/2026-11-22-issue-297-compaction-mirror.md +797 -0
  21. package/docs/superpowers/plans/2026-11-23-issue-254-cursor-keep-position.md +663 -0
  22. package/docs/superpowers/plans/2026-11-23-issue-95-legacy-quarantine.md +320 -0
  23. package/docs/superpowers/specs/2026-10-23-issue-222-attach-ready-design.md +204 -0
  24. package/docs/superpowers/specs/2026-10-28-issue-257-legacy-pty-runner-endpoint-cleanup-design.md +197 -0
  25. package/docs/superpowers/specs/2026-11-03-cwd-favorites-full-pool-design.md +106 -0
  26. package/docs/superpowers/specs/2026-11-03-issue-266-alt-h-detach-design.md +185 -0
  27. package/docs/superpowers/specs/2026-11-04-issue-270-scenario-stdout-flush-design.md +176 -0
  28. package/docs/superpowers/specs/2026-11-05-issue-278-ctrl-g-external-editor-design.md +185 -0
  29. package/docs/superpowers/specs/2026-11-07-issue-284-attach-recovery-design.md +166 -0
  30. package/docs/superpowers/specs/2026-11-08-host-restart-model-override-design.md +115 -0
  31. package/docs/superpowers/specs/2026-11-08-issue-288-cap-floor-design.md +86 -0
  32. package/docs/superpowers/specs/2026-11-09-dashboard-fold-flake-design.md +109 -0
  33. package/docs/superpowers/specs/2026-11-09-issue-273-harness-console-log-exit-design.md +182 -0
  34. package/docs/superpowers/specs/2026-11-10-issue-258-board-selection-settle-design.md +109 -0
  35. package/docs/superpowers/specs/2026-11-13-issue-294-snapshot-resize-intent-design.md +141 -0
  36. package/docs/superpowers/specs/2026-11-16-greeting-title-poll-design.md +174 -0
  37. package/docs/superpowers/specs/2026-11-22-issue-297-compaction-mirror-design.md +158 -0
  38. package/docs/superpowers/specs/2026-11-22-issue-95-legacy-quarantine-design.md +209 -0
  39. package/docs/superpowers/specs/2026-11-23-issue-254-cursor-keep-position-design.md +201 -0
  40. package/package.json +1 -1
  41. package/runner/pty-runner.mjs +526 -63
  42. package/runner/title-runner.mjs +33 -24
  43. package/src/commands/agent-board.ts +5 -1
  44. package/src/core/attach-detach.mjs +27 -0
  45. package/src/core/attach-frame-proof.mjs +897 -0
  46. package/src/core/attach-frame-reporter.mjs +738 -0
  47. package/src/core/attach-frame-stream.mjs +266 -0
  48. package/src/core/attach-pr-label.mjs +12 -0
  49. package/src/core/attach-recovery.mjs +239 -0
  50. package/src/core/attach-screen-owner.mjs +55 -0
  51. package/src/core/attach-view-proof.mjs +709 -0
  52. package/src/core/auto-state.mjs +6 -1
  53. package/src/core/cwd-stats.mjs +3 -1
  54. package/src/core/dashboard-prefs.mjs +31 -0
  55. package/src/core/derive.mjs +8 -1
  56. package/src/core/events.mjs +127 -1
  57. package/src/core/foreground-projection-cache.mjs +1 -0
  58. package/src/core/frame-witness-update.mjs +35 -0
  59. package/src/core/fullscreen-selection.mjs +60 -0
  60. package/src/core/host-protocol.mjs +13 -2
  61. package/src/core/hosted-frame-witness.mjs +60 -0
  62. package/src/core/paths.mjs +10 -3
  63. package/src/core/pty-attach-render.mjs +239 -0
  64. package/src/core/pty-kitty-images.mjs +237 -0
  65. package/src/core/rows.mjs +43 -7
  66. package/src/core/session-entries.mjs +82 -0
  67. package/src/core/session-launch-prefs.mjs +45 -0
  68. package/src/core/session-view.mjs +3 -63
  69. package/src/core/store.mjs +1 -0
  70. package/src/core/terminal-attach-client.mjs +199 -20
  71. package/src/core/terminal-attach-protocol.mjs +221 -7
  72. package/src/core/terminal-model.mjs +24 -3
  73. package/src/core/terminal-snapshot.mjs +10 -0
  74. package/src/core/title-flow.mjs +66 -0
  75. package/src/core/title.mjs +101 -0
  76. package/src/core/types.mjs +17 -0
  77. package/src/index.ts +85 -0
  78. package/src/runtime/service.mjs +87 -18
  79. package/src/ui/dashboard.ts +198 -44
  80. package/src/ui/pty-attach.ts +1462 -117
@@ -0,0 +1,584 @@
1
+ # Scenario stdout flush before exit — Implementation Plan
2
+
3
+ > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4
+
5
+ **Goal:** Make every `test-support` harness wait for stdout to drain before `process.exit`, so a large JSON result can no longer be truncated at the 64 KiB pipe buffer and turn every PR's CI red.
6
+
7
+ **Architecture:** One shared helper (`writeThenExit` + the `exitAfterStdout` binding) replaces 18 hand-written `write(); exit();` pairs. A static guard test parses `test-support/**` with the TypeScript compiler API and fails if the shape ever comes back; its detector is a pure function covered by synthetic positive/negative samples.
8
+
9
+ **Tech Stack:** Node 22/24 (ESM, `node:test`), TypeScript compiler API (`typescript@^5.9.3`, already a devDependency) for the guard, `node:child_process` for the slow-reader integration test.
10
+
11
+ **Spec:** `docs/superpowers/specs/2026-11-04-issue-270-scenario-stdout-flush-design.md` (issue #270)
12
+
13
+ ## Global Constraints
14
+
15
+ - Indentation is **tabs**; code comments and commit messages are **English** (repo `AGENTS.md`).
16
+ - Conventional commit subjects: `feat`/`fix`/`test`/`docs`/`chore`, with `(issue #270)` appended.
17
+ - **Never modify** `test-support/fake-pty-pi.mjs` or `test-support/fake-pty-generation-pi.mjs`: their sha256 is pinned by `S15_ACCEPTED_HASHES.fakePtyChild` / `ENTRY_ACCEPTED_HASHES.generationFixture` (`test/pty-attach-ready.test.mjs:1159,2594`).
18
+ - Stage files individually (`git add <path>`); never `git add -A`.
19
+ - Work only inside the worktree `/home/elling/work/git-repo/pi-agent-board/.pi/worktrees/issue-270-scenario-stdout-flush`.
20
+ - New test files must be named `*.test.mjs` under `test/` — `scripts/run-tests.mjs:348-349` discovers exactly that pattern.
21
+ - `test-support/**` is excluded from coverage (`.c8rc.json`), so the helper needs no coverage-driven contortions.
22
+
23
+ ## Review Focus
24
+
25
+ - **Broken pipe (EPIPE):** the reader closes stdout while the harness is still writing. Expected: exit with the caller's code, not an uncaught `error` event. Pinned by Task 1's error-branch test.
26
+ - **Write callback vs. timer/child handles:** several fixtures keep the event loop alive with `setInterval` or child processes, so natural drain-then-exit must stay an explicit `exit`. Pinned by Task 4/A4 running the existing suites.
27
+ - **Payloads just above 64 KiB:** the boundary is the kernel pipe buffer, not the payload size. Pinned by Task 2 (256 KiB through a deliberately stalled reader).
28
+ - **Guard false positives:** `.then` writing and `.catch` exiting are *not* adjacency, and `console.*` is out of scope. Pinned by Task 3's negative samples.
29
+ - **Guard false negatives after the sweep:** a new `write(); exit();` must fail the suite. Pinned by Task 3's positive samples plus the directory scan.
30
+
31
+ ---
32
+
33
+ ### Task 1: Shared flush helper + its unit tests
34
+
35
+ **Files:**
36
+ - Create: `test-support/stdout-flush.mjs`
37
+ - Test: `test/scenario-stdout-flush.test.mjs`
38
+
39
+ **Interfaces:**
40
+ - Produces:
41
+ - `writeThenExit(stream: Writable, text: string, code: number, exit: (code: number) => void): void`
42
+ - `exitAfterStdout(text: string, code?: number): void` (defaults to `0`)
43
+
44
+ - [ ] **Step 1: Write the failing test**
45
+
46
+ Create `test/scenario-stdout-flush.test.mjs`:
47
+
48
+ ```js
49
+ import assert from "node:assert/strict";
50
+ import { EventEmitter } from "node:events";
51
+ import test from "node:test";
52
+
53
+ import { writeThenExit } from "../test-support/stdout-flush.mjs";
54
+
55
+ /** Minimal stand-in for a writable: records bytes, then either calls back or fails. */
56
+ class FakeStream extends EventEmitter {
57
+ constructor({ failSync = false } = {}) {
58
+ super();
59
+ this.written = "";
60
+ this.failSync = failSync;
61
+ }
62
+
63
+ write(text, callback) {
64
+ if (this.failSync) throw new Error("write failed synchronously");
65
+ this.written += text;
66
+ this.callback = callback;
67
+ return true;
68
+ }
69
+ }
70
+
71
+ test("stdout-flush: exit runs once after the write callback fires", () => {
72
+ const stream = new FakeStream();
73
+ const exits = [];
74
+ writeThenExit(stream, "payload\n", 0, (code) => exits.push(code));
75
+ assert.equal(stream.written, "payload\n");
76
+ assert.deepEqual(exits, [], "exit must wait for the write callback");
77
+ stream.callback();
78
+ assert.deepEqual(exits, [0]);
79
+ });
80
+
81
+ test("stdout-flush: a broken pipe still exits with the caller's code, exactly once", () => {
82
+ const stream = new FakeStream();
83
+ const exits = [];
84
+ writeThenExit(stream, "payload\n", 3, (code) => exits.push(code));
85
+ stream.emit("error", new Error("EPIPE"));
86
+ stream.callback();
87
+ assert.deepEqual(exits, [3], "the error path exits once and the late callback is ignored");
88
+ });
89
+
90
+ test("stdout-flush: a synchronous write throw still exits with the caller's code", () => {
91
+ const stream = new FakeStream({ failSync: true });
92
+ const exits = [];
93
+ writeThenExit(stream, "payload\n", 1, (code) => exits.push(code));
94
+ assert.deepEqual(exits, [1]);
95
+ });
96
+ ```
97
+
98
+ - [ ] **Step 2: Run the test to verify it fails**
99
+
100
+ Run: `node --test test/scenario-stdout-flush.test.mjs`
101
+ Expected: FAIL — `Cannot find module '../test-support/stdout-flush.mjs'`.
102
+
103
+ - [ ] **Step 3: Write the helper**
104
+
105
+ Create `test-support/stdout-flush.mjs`:
106
+
107
+ ```js
108
+ /**
109
+ * Write `text` to `stream`, then call `exit(code)` once the write has drained.
110
+ *
111
+ * A bare `stream.write(text); exit(code)` tears the process down while the
112
+ * kernel pipe still holds a partial payload: everything past the 64 KiB pipe
113
+ * buffer is lost and the exit code still says 0. Issue #270 hit this with a
114
+ * ~143 KB battery result truncated at exactly 65536 bytes, which turned every
115
+ * PR's CI red while passing locally.
116
+ *
117
+ * `stream` and `exit` are injected so the three paths — flushed, broken pipe,
118
+ * synchronous write error — are unit-testable without spawning a child. Only
119
+ * statement-adjacent `process.stdout.write(...)` followed by `process.exit(...)`
120
+ * is guarded; a write inside `try` with the exit in `finally` is out of scope.
121
+ *
122
+ * @param {import("node:stream").Writable} stream
123
+ * @param {string} text
124
+ * @param {number} code exit status the caller already decided on
125
+ * @param {(code: number) => void} exit
126
+ */
127
+ export function writeThenExit(stream, text, code, exit) {
128
+ let settled = false;
129
+ const finish = () => {
130
+ if (settled) return;
131
+ settled = true;
132
+ exit(code);
133
+ };
134
+ stream.once("error", finish);
135
+ try {
136
+ stream.write(text, finish);
137
+ } catch {
138
+ finish();
139
+ }
140
+ }
141
+
142
+ /**
143
+ * Bind {@link writeThenExit} to the real process. Use this instead of
144
+ * `process.stdout.write(...); process.exit(...)` in every test-support harness.
145
+ *
146
+ * @param {string} text
147
+ * @param {number} [code]
148
+ */
149
+ export function exitAfterStdout(text, code = 0) {
150
+ writeThenExit(process.stdout, text, code, (status) => process.exit(status));
151
+ }
152
+ ```
153
+
154
+ - [ ] **Step 4: Run the test to verify it passes**
155
+
156
+ Run: `node --test test/scenario-stdout-flush.test.mjs`
157
+ Expected: PASS — 3 tests, 0 failures.
158
+
159
+ - [ ] **Step 5: Commit**
160
+
161
+ ```bash
162
+ git add test-support/stdout-flush.mjs test/scenario-stdout-flush.test.mjs
163
+ git commit -F - <<'EOF'
164
+ feat(test): flush stdout before exiting a test-support harness (issue #270)
165
+ EOF
166
+ ```
167
+
168
+ ---
169
+
170
+ ### Task 2: Probe fixture + slow-reader integration test
171
+
172
+ **Files:**
173
+ - Create: `test-support/stdout-flush-probe.mjs`
174
+ - Modify: `test/scenario-stdout-flush.test.mjs` (append one test)
175
+
176
+ **Interfaces:**
177
+ - Consumes: `exitAfterStdout` from Task 1.
178
+ - Produces: `test-support/stdout-flush-probe.mjs` accepting `--bytes N` (default `262144`), writing `{"payload":"x"*N}\n` and exiting through the helper.
179
+
180
+ - [ ] **Step 1: Write the failing test**
181
+
182
+ Append to `test/scenario-stdout-flush.test.mjs` (add the imports at the top of the file):
183
+
184
+ ```js
185
+ import { spawn } from "node:child_process";
186
+ import { fileURLToPath } from "node:url";
187
+ ```
188
+
189
+ ```js
190
+ const PROBE = fileURLToPath(new URL("../test-support/stdout-flush-probe.mjs", import.meta.url));
191
+
192
+ /**
193
+ * Spawn the probe with stdout on a pipe and attach the reader only after
194
+ * `delayMs`. While nobody reads, the kernel pipe buffer (64 KiB) fills and the
195
+ * child's write goes pending — the exact condition that truncated issue #270.
196
+ * The delay is not a timing assertion: the 256 KiB payload cannot fit either way.
197
+ */
198
+ function runProbeWithSlowReader(bytes, delayMs = 250) {
199
+ return new Promise((settle, fail) => {
200
+ const child = spawn(process.execPath, [PROBE, "--bytes", String(bytes)], { stdio: ["ignore", "pipe", "pipe"] });
201
+ const chunks = [];
202
+ let stderr = "";
203
+ // No stdout listener yet: the stream stays paused, nobody reads the pipe, and
204
+ // the kernel buffer (64 KiB) fills — the issue #270 condition. Do NOT add
205
+ // `child.stdout.pause()` here: an explicit pause() sets flowing = false and the
206
+ // delayed `.on("data")` below would never resume the stream (the test hangs).
207
+ child.stderr.on("data", (chunk) => { stderr += chunk; });
208
+ child.on("error", fail);
209
+ child.on("close", (code) => settle({ code, stdout: Buffer.concat(chunks).toString("utf8"), stderr }));
210
+ setTimeout(() => child.stdout.on("data", (chunk) => chunks.push(chunk)), delayMs).unref();
211
+ });
212
+ }
213
+
214
+ test("stdout-flush: a 256 KiB result survives a reader that starts late", async () => {
215
+ const result = await runProbeWithSlowReader(262144);
216
+ assert.equal(result.code, 0, `probe must exit 0; stderr:\n${result.stderr}`);
217
+ const parsed = JSON.parse(result.stdout);
218
+ assert.equal(parsed.payload.length, 262144, "every byte of the payload must reach the reader");
219
+ });
220
+ ```
221
+
222
+ - [ ] **Step 2: Run the test to verify it fails**
223
+
224
+ Run: `node --test test/scenario-stdout-flush.test.mjs`
225
+ Expected: FAIL — the probe file does not exist (`Cannot find module .../stdout-flush-probe.mjs`, exit code 1).
226
+
227
+ - [ ] **Step 3: Write the probe**
228
+
229
+ Create `test-support/stdout-flush-probe.mjs`:
230
+
231
+ ```js
232
+ #!/usr/bin/env node
233
+ /**
234
+ * Executable fixture for the stdout-flush integration test (issue #270).
235
+ * Writes a JSON result comfortably past the 64 KiB pipe buffer, then exits
236
+ * through the shared helper so the payload is fully drained first.
237
+ */
238
+ import { exitAfterStdout } from "./stdout-flush.mjs";
239
+
240
+ const index = process.argv.indexOf("--bytes");
241
+ const bytes = index === -1 ? 262144 : Number(process.argv[index + 1]);
242
+ exitAfterStdout(`${JSON.stringify({ payload: "x".repeat(bytes) })}\n`, 0);
243
+ ```
244
+
245
+ - [ ] **Step 4: Run the test to verify it passes**
246
+
247
+ Run: `node --test test/scenario-stdout-flush.test.mjs`
248
+ Expected: PASS — 4 tests, 0 failures.
249
+
250
+ - [ ] **Step 5: Prove the test has teeth (manual, no committed change)**
251
+
252
+ Back up the probe, swap in the old shape, confirm the new test fails, then restore:
253
+
254
+ ```bash
255
+ cp test-support/stdout-flush-probe.mjs /tmp/stdout-flush-probe.bak
256
+ # edit the last line of test-support/stdout-flush-probe.mjs to:
257
+ # process.stdout.write(`${JSON.stringify({ payload: "x".repeat(bytes) })}\n`);
258
+ # process.exit(0);
259
+ node --test test/scenario-stdout-flush.test.mjs
260
+ ```
261
+ Expected: FAIL with `Unexpected end of JSON input` (empty stdout) or a payload shorter than 262144. Then:
262
+
263
+ ```bash
264
+ cp /tmp/stdout-flush-probe.bak test-support/stdout-flush-probe.mjs
265
+ node --test test/scenario-stdout-flush.test.mjs
266
+ ```
267
+ Expected: PASS again. Leave no backup file inside the worktree.
268
+
269
+ - [ ] **Step 6: Commit**
270
+
271
+ ```bash
272
+ git add test-support/stdout-flush-probe.mjs test/scenario-stdout-flush.test.mjs
273
+ git commit -F - <<'EOF'
274
+ test: prove a slow reader no longer truncates harness results (issue #270)
275
+ EOF
276
+ ```
277
+
278
+ ---
279
+
280
+ ### Task 3: Static guard (red first) + detector self-tests
281
+
282
+ **Files:**
283
+ - Modify: `test/scenario-stdout-flush.test.mjs` (append detector + 2 tests)
284
+
285
+ **Interfaces:**
286
+ - Produces: `findUnguardedStdoutExits(sourceText: string, fileName: string): {file: string, line: number}[]` inside the test file.
287
+
288
+ - [ ] **Step 1: Write the failing guard**
289
+
290
+ Append to `test/scenario-stdout-flush.test.mjs` (add these imports at the top):
291
+
292
+ ```js
293
+ import { readdirSync, readFileSync } from "node:fs";
294
+ import { join, relative } from "node:path";
295
+ import ts from "typescript";
296
+ ```
297
+
298
+ ```js
299
+ const TEST_SUPPORT_ROOT = fileURLToPath(new URL("../test-support/", import.meta.url));
300
+
301
+ const isPropertyAccessOn = (node, name, receiver) =>
302
+ ts.isPropertyAccessExpression(node) && node.name.text === name && receiver(node.expression);
303
+ const isProcessIdentifier = (node) => ts.isIdentifier(node) && node.text === "process";
304
+ const isStdoutReceiver = (node) => isPropertyAccessOn(node, "stdout", isProcessIdentifier);
305
+ const isCallStatement = (statement, property, receiver) =>
306
+ ts.isExpressionStatement(statement) &&
307
+ ts.isCallExpression(statement.expression) &&
308
+ isPropertyAccessOn(statement.expression.expression, property, receiver);
309
+ const writesStdout = (statement) => isCallStatement(statement, "write", isStdoutReceiver);
310
+ const exitsProcess = (statement) => isCallStatement(statement, "exit", isProcessIdentifier);
311
+
312
+ /** Unwrap `if`/block so `if (ready) process.stdout.write(x)` counts as a write. */
313
+ function containsStatement(statement, predicate) {
314
+ if (predicate(statement)) return true;
315
+ if (ts.isIfStatement(statement)) {
316
+ return containsStatement(statement.thenStatement, predicate) ||
317
+ (statement.elseStatement !== undefined && containsStatement(statement.elseStatement, predicate));
318
+ }
319
+ if (ts.isBlock(statement)) return statement.statements.some((child) => containsStatement(child, predicate));
320
+ return false;
321
+ }
322
+
323
+ /**
324
+ * List every statement pair where one writes `process.stdout` and the next one
325
+ * calls `process.exit`. `console.*` is deliberately not matched: those payloads
326
+ * are short human-readable lines, and the spec keeps them out of scope.
327
+ * A write inside `try` with the exit in `finally` is not covered.
328
+ */
329
+ export function findUnguardedStdoutExits(sourceText, fileName) {
330
+ const file = ts.createSourceFile(fileName, sourceText, ts.ScriptTarget.Latest, true, fileName.endsWith(".ts") ? ts.ScriptKind.TS : ts.ScriptKind.JS);
331
+ const found = [];
332
+ const visit = (node) => {
333
+ if (node.statements !== undefined) {
334
+ for (let index = 0; index + 1 < node.statements.length; index += 1) {
335
+ const previous = node.statements[index];
336
+ const next = node.statements[index + 1];
337
+ // Two sibling conditionals are independent paths, never one drain-then-exit
338
+ // sequence: `if (dryRun) { write; exit; } if (guard) { …; exit(2); }` would
339
+ // otherwise pair the two outer ifs. A real pair inside their blocks is found
340
+ // by the recursion into each block.
341
+ if (ts.isIfStatement(previous) && ts.isIfStatement(next)) continue;
342
+ if (containsStatement(previous, writesStdout) && containsStatement(next, exitsProcess)) {
343
+ const { line } = file.getLineAndCharacterOfPosition(previous.getStart(file));
344
+ found.push({ file: fileName, line: line + 1 });
345
+ }
346
+ }
347
+ }
348
+ ts.forEachChild(node, visit);
349
+ };
350
+ visit(file);
351
+ return found;
352
+ }
353
+
354
+ function testSupportFiles(directory) {
355
+ const files = [];
356
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
357
+ const path = join(directory, entry.name);
358
+ if (entry.isDirectory()) files.push(...testSupportFiles(path));
359
+ else if (/\.(ts|mjs|js)$/.test(entry.name)) files.push(path);
360
+ }
361
+ return files;
362
+ }
363
+
364
+ test("stdout-flush: the detector flags the shape and accepts the guards", () => {
365
+ const violations = [
366
+ ["plain write then exit", `process.stdout.write("x");\nprocess.exit(0);`],
367
+ ["conditional write then exit", `if (ready) process.stdout.write(carry);\nprocess.exit(1);`],
368
+ ["block-wrapped write then exit", `if (ready) { process.stdout.write(token); }\nprocess.exit(0);`],
369
+ ];
370
+ for (const [label, source] of violations) {
371
+ assert.equal(findUnguardedStdoutExits(source, "sample.mjs").length, 1, `must flag: ${label}`);
372
+ }
373
+ const accepted = [
374
+ ["write with an exit callback", `process.stdout.write("x", () => process.exit(0));`],
375
+ ["shared helper", `exitAfterStdout("x", 0);`],
376
+ ["console.log then exit", `console.log("x");\nprocess.exit(0);`],
377
+ ["then writes, catch exits", `run().then((r) => { process.stdout.write(JSON.stringify(r)); }).catch(() => { process.exit(1); });`],
378
+ ["flush, then conditional helper exit", `process.stdout.write("echo:hi\\n");\nif (exiting) exitAfterStdout("", 0);`],
379
+ ["sibling conditionals never pair", `if (dryRun) { process.stdout.write("x"); }\nif (approved !== "1") { process.exit(2); }`],
380
+ ];
381
+ for (const [label, source] of accepted) {
382
+ assert.deepEqual(findUnguardedStdoutExits(source, "sample.mjs"), [], `must accept: ${label}`);
383
+ }
384
+ });
385
+
386
+ test("stdout-flush: no test-support file writes stdout immediately before process.exit", () => {
387
+ const offenders = [];
388
+ for (const path of testSupportFiles(TEST_SUPPORT_ROOT)) {
389
+ offenders.push(...findUnguardedStdoutExits(readFileSync(path, "utf8"), relative(TEST_SUPPORT_ROOT, path)));
390
+ }
391
+ assert.deepEqual(
392
+ offenders,
393
+ [],
394
+ `write-then-exit must go through exitAfterStdout():\n${offenders.map((entry) => `${entry.file}:${entry.line}`).join("\n")}`,
395
+ );
396
+ });
397
+ ```
398
+
399
+ - [ ] **Step 2: Run the guard to verify it fails on the real tree**
400
+
401
+ Run: `node --test test/scenario-stdout-flush.test.mjs`
402
+ Expected: detector self-test PASSES; the directory scan FAILS listing exactly these 18 locations:
403
+
404
+ ```
405
+ attach-entry-22-scenario.ts:1382 attach-ready-catchup-scenario.ts:368
406
+ attach-ready-entry-scenario.ts:1070 attach-ready-interactions-scenario.ts:656
407
+ ensure-host-helper.mjs:44 fake-pty-frame-wrapper.mjs:137 fake-pty-frame-wrapper.mjs:143
408
+ fake-slow-start-pi.mjs:34 formal-measurement/formal-runner.mjs:24
409
+ formal-measurement/preflight.mjs:135 pi23a-production-smoke-runner.mjs:317
410
+ pi23a-smoke-runner.mjs:452 pty-attach-20b-scenario.ts:4010
411
+ pty-attach-21b-scenario.ts:1389 pty-attach-matrix-scenario.ts:1222
412
+ pty-attach-parser-replacement-scenario.ts:808 pty-attach-ready-scenario.ts:4452
413
+ pty-attach-timing-scenario.ts:1653
414
+ ```
415
+
416
+ If the list differs, stop and reconcile the detector with `research/01-reproduction-and-inventory.md` §3 — do **not** weaken the detector to make it pass.
417
+
418
+ - [ ] **Step 3: Commit the red guard**
419
+
420
+ ```bash
421
+ git add test/scenario-stdout-flush.test.mjs
422
+ git commit -F - <<'EOF'
423
+ test: guard test-support against write-then-exit truncation (issue #270)
424
+ EOF
425
+ ```
426
+
427
+ ---
428
+
429
+ ### Task 4: Replace all 18 write-then-exit sites
430
+
431
+ **Files (modify):**
432
+ - 10 scenarios: `pty-attach-ready-scenario.ts:4452`, `attach-entry-22-scenario.ts:1382`, `attach-ready-catchup-scenario.ts:368`, `attach-ready-entry-scenario.ts:1070`, `attach-ready-interactions-scenario.ts:656`, `pty-attach-20b-scenario.ts:4010`, `pty-attach-21b-scenario.ts:1389`, `pty-attach-matrix-scenario.ts:1222`, `pty-attach-timing-scenario.ts:1653`, `pty-attach-parser-replacement-scenario.ts:808`
433
+ - `ensure-host-helper.mjs:44`, `pi23a-smoke-runner.mjs:452`, `pi23a-production-smoke-runner.mjs:317`, `formal-measurement/formal-runner.mjs:24`, `formal-measurement/preflight.mjs:135`
434
+ - Special recipes: `fake-pty-frame-wrapper.mjs:137,143`, `fake-slow-start-pi.mjs:34-35`
435
+
436
+ **Interfaces:**
437
+ - Consumes: `exitAfterStdout(text, code?)` from Task 1.
438
+ - Produces: nothing new; the guard from Task 3 goes green.
439
+
440
+ - [ ] **Step 1: Mechanical replacement (15 sites)**
441
+
442
+ In each of the files listed above (except the three special-recipe lines), replace the two-statement pair with one call, keeping the payload expression and the exit code expression **verbatim**:
443
+
444
+ ```diff
445
+ - process.stdout.write(JSON.stringify(result) + "\n");
446
+ - process.exit(0);
447
+ + exitAfterStdout(JSON.stringify(result) + "\n", 0);
448
+ ```
449
+
450
+ Variants keep their own code expression, e.g. `pty-attach-20b-scenario.ts`:
451
+
452
+ ```diff
453
+ - process.stdout.write(JSON.stringify(result) + "\n");
454
+ - process.exit(typeof result.exitCode === "number" ? result.exitCode : 0);
455
+ + exitAfterStdout(JSON.stringify(result) + "\n", typeof result.exitCode === "number" ? result.exitCode : 0);
456
+ ```
457
+
458
+ and `pty-attach-parser-replacement-scenario.ts`, which uses a template literal:
459
+
460
+ ```diff
461
+ - process.stdout.write(`${JSON.stringify(result)}\n`);
462
+ - process.exit(result.ok ? 0 : 1);
463
+ + exitAfterStdout(`${JSON.stringify(result)}\n`, result.ok ? 0 : 1);
464
+ ```
465
+
466
+ Add the import next to the other relative imports in each file:
467
+
468
+ ```js
469
+ import { exitAfterStdout } from "./stdout-flush.mjs";
470
+ ```
471
+
472
+ For `formal-measurement/formal-runner.mjs` and `formal-measurement/preflight.mjs` the import path is `"../stdout-flush.mjs"`.
473
+
474
+ - [ ] **Step 2: Special recipe — `fake-pty-frame-wrapper.mjs` (2 sites)**
475
+
476
+ ```diff
477
+ inner.onExit(({ exitCode }) => {
478
+ - if (tokenReady && carry.length > 0) process.stdout.write(carry);
479
+ - process.exit(exitCode ?? 0);
480
+ + exitAfterStdout(tokenReady && carry.length > 0 ? carry : "", exitCode ?? 0);
481
+ });
482
+ } else {
483
+ inner.stdout.on("data", onInnerData);
484
+ inner.on("exit", (code) => {
485
+ - if (tokenReady && carry.length > 0) process.stdout.write(carry);
486
+ - process.exit(code ?? 0);
487
+ + exitAfterStdout(tokenReady && carry.length > 0 ? carry : "", code ?? 0);
488
+ });
489
+ ```
490
+
491
+ - [ ] **Step 3: Special recipe — `fake-slow-start-pi.mjs` (1 site)**
492
+
493
+ Keep the write where it is; only the conditional exit changes. This fixture must keep echoing non-exit input (the resize-before-ready test waits for `echo:still-alive` before sending `exit\r`):
494
+
495
+ ```diff
496
+ process.stdout.write(`echo:${visible}\n`);
497
+ - if (text.includes("exit")) process.exit(0);
498
+ + if (text.includes("exit")) exitAfterStdout("", 0);
499
+ ```
500
+
501
+ - [ ] **Step 4: Run the guard and the new tests**
502
+
503
+ Run: `node --test test/scenario-stdout-flush.test.mjs`
504
+ Expected: PASS — 6 tests (3 unit + 1 integration + 2 guard), 0 failures, no offenders listed.
505
+
506
+ - [ ] **Step 5: Run the s15 battery suite**
507
+
508
+ Run: `node --test test/pty-attach-ready.test.mjs`
509
+ Expected: PASS — 88 tests, 0 failures, including `step 15 integration: case S real-runner battery …`.
510
+
511
+ - [ ] **Step 6: Commit**
512
+
513
+ ```bash
514
+ git add test-support/pty-attach-ready-scenario.ts test-support/attach-entry-22-scenario.ts \
515
+ test-support/attach-ready-catchup-scenario.ts test-support/attach-ready-entry-scenario.ts \
516
+ test-support/attach-ready-interactions-scenario.ts test-support/pty-attach-20b-scenario.ts \
517
+ test-support/pty-attach-21b-scenario.ts test-support/pty-attach-matrix-scenario.ts \
518
+ test-support/pty-attach-timing-scenario.ts test-support/pty-attach-parser-replacement-scenario.ts \
519
+ test-support/ensure-host-helper.mjs test-support/pi23a-smoke-runner.mjs \
520
+ test-support/pi23a-production-smoke-runner.mjs test-support/formal-measurement/formal-runner.mjs \
521
+ test-support/formal-measurement/preflight.mjs test-support/fake-pty-frame-wrapper.mjs \
522
+ test-support/fake-slow-start-pi.mjs
523
+ git commit -F - <<'EOF'
524
+ fix(test): drain stdout before exiting every test-support harness (issue #270)
525
+ EOF
526
+ ```
527
+
528
+ ---
529
+
530
+ ### Task 5: Full verification gate
531
+
532
+ **Files:** none (verification only).
533
+
534
+ - [ ] **Step 1: Run the repository gate**
535
+
536
+ Run: `npm run verify`
537
+ Expected: PASS — typecheck, perf gate, full test suite, coverage (lines 85 / funcs 80 / branches 70), `pack:dry`.
538
+
539
+ - [ ] **Step 2: Record the evidence**
540
+
541
+ Save the command output summary (test counts, coverage numbers) for the PR description and the issue comment. If the perf gate or a real-process suite is flaky, re-run that suite once in isolation before treating it as a regression; if it fails twice, stop and report.
542
+
543
+ - [ ] **Step 3: Commit only if the gate required a fix**
544
+
545
+ If `npm run verify` failed for a real reason, fix it, re-run the gate, and commit exactly the touched files with a subject naming the failure (for example `fix(test): keep the fixture alive until the child exits (issue #270)`). Stage each path explicitly; no `git add -A`.
546
+
547
+ ---
548
+
549
+ ### Task 6: PR, Zima CR, and CI
550
+
551
+ **Files:** none.
552
+
553
+ - [ ] **Step 1: Push the branch**
554
+
555
+ ```bash
556
+ git push -u origin issue-270-scenario-stdout-flush
557
+ ```
558
+
559
+ - [ ] **Step 2: Open the PR**
560
+
561
+ The body must state the scope expansion from spec §4 (issue acceptance named `test-support/*-scenario.ts`; this PR clears all `test-support/**`), the root cause with the 65536-byte evidence, and the verification evidence from Task 5. No `## Testing` placeholders.
562
+
563
+ ```bash
564
+ gh pr create --repo zhuxixi/pi-agent-board --base main --head issue-270-scenario-stdout-flush \
565
+ --title "fix(test): drain stdout before exiting test-support harnesses (issue #270)" --body-file <path>
566
+ ```
567
+
568
+ - [ ] **Step 3: Trigger Zima CR and wait for convergence**
569
+
570
+ ```bash
571
+ gh pr edit <N> --add-label zima:needs-review
572
+ ```
573
+ Then follow `zima-pr-monitor`: read `pi-cr-meta` / `cc-cr-meta`, fix blocking findings in the worktree, re-push, re-label, converge. On this machine the CR job is picked up by the 7700K host via the label — do **not** run `zima pjob run` or `zima pjob ps` here.
574
+
575
+ - [ ] **Step 4: Watch CI**
576
+
577
+ ```bash
578
+ gh pr checks <N> --watch
579
+ ```
580
+ Expected: `Test (Node 22)` and `Test (Node 24)` both pass — this is acceptance A6 and the whole point of the issue.
581
+
582
+ - [ ] **Step 5: Stop before merge**
583
+
584
+ Merge requires explicit user approval (`authorization.md` → `Merge: requires-explicit-user-approval`). Report CR convergence + CI status and wait.