@zhuxixi/pi-agent-board 0.13.0 → 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 (91) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/README.md +37 -12
  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-26-issue-245-key-hints-doc-sync.md +244 -0
  6. package/docs/superpowers/plans/2026-10-27-issue-172-fullscreen-selection-clear.md +344 -0
  7. package/docs/superpowers/plans/2026-10-27-issue-252-select-key-hints.md +209 -0
  8. package/docs/superpowers/plans/2026-10-28-issue-255-coordinator-endpoint-zombie.md +442 -0
  9. package/docs/superpowers/plans/2026-10-28-issue-257-legacy-pty-runner-endpoint-cleanup.md +256 -0
  10. package/docs/superpowers/plans/2026-11-03-cwd-favorites-full-pool.md +266 -0
  11. package/docs/superpowers/plans/2026-11-03-issue-266-alt-h-detach.md +467 -0
  12. package/docs/superpowers/plans/2026-11-04-issue-270-scenario-stdout-flush.md +584 -0
  13. package/docs/superpowers/plans/2026-11-05-issue-278-ctrl-g-external-editor.md +381 -0
  14. package/docs/superpowers/plans/2026-11-06-issue-280-frame-witness-delivery.md +430 -0
  15. package/docs/superpowers/plans/2026-11-07-issue-284-attach-recovery.md +115 -0
  16. package/docs/superpowers/plans/2026-11-07-issue-284-u1-u2-trial-guide.md +39 -0
  17. package/docs/superpowers/plans/2026-11-08-host-restart-model-override.md +894 -0
  18. package/docs/superpowers/plans/2026-11-08-issue-288-cap-floor.md +51 -0
  19. package/docs/superpowers/plans/2026-11-09-dashboard-fold-flake.md +166 -0
  20. package/docs/superpowers/plans/2026-11-09-issue-273-harness-console-log-exit.md +369 -0
  21. package/docs/superpowers/plans/2026-11-10-issue-258-board-selection-settle.md +760 -0
  22. package/docs/superpowers/plans/2026-11-13-issue-294-snapshot-resize-intent.md +590 -0
  23. package/docs/superpowers/plans/2026-11-16-greeting-title-poll.md +838 -0
  24. package/docs/superpowers/plans/2026-11-22-issue-297-compaction-mirror.md +797 -0
  25. package/docs/superpowers/plans/2026-11-23-issue-254-cursor-keep-position.md +663 -0
  26. package/docs/superpowers/plans/2026-11-23-issue-95-legacy-quarantine.md +320 -0
  27. package/docs/superpowers/specs/2026-10-23-issue-222-attach-ready-design.md +204 -0
  28. package/docs/superpowers/specs/2026-10-26-issue-245-key-hints-doc-sync-design.md +72 -0
  29. package/docs/superpowers/specs/2026-10-27-issue-172-fullscreen-selection-clear-design.md +248 -0
  30. package/docs/superpowers/specs/2026-10-27-issue-252-select-key-hints-design.md +95 -0
  31. package/docs/superpowers/specs/2026-10-28-issue-255-coordinator-endpoint-zombie-design.md +380 -0
  32. package/docs/superpowers/specs/2026-10-28-issue-257-legacy-pty-runner-endpoint-cleanup-design.md +197 -0
  33. package/docs/superpowers/specs/2026-11-03-cwd-favorites-full-pool-design.md +106 -0
  34. package/docs/superpowers/specs/2026-11-03-issue-266-alt-h-detach-design.md +185 -0
  35. package/docs/superpowers/specs/2026-11-04-issue-270-scenario-stdout-flush-design.md +176 -0
  36. package/docs/superpowers/specs/2026-11-05-issue-278-ctrl-g-external-editor-design.md +185 -0
  37. package/docs/superpowers/specs/2026-11-07-issue-284-attach-recovery-design.md +166 -0
  38. package/docs/superpowers/specs/2026-11-08-host-restart-model-override-design.md +115 -0
  39. package/docs/superpowers/specs/2026-11-08-issue-288-cap-floor-design.md +86 -0
  40. package/docs/superpowers/specs/2026-11-09-dashboard-fold-flake-design.md +109 -0
  41. package/docs/superpowers/specs/2026-11-09-issue-273-harness-console-log-exit-design.md +182 -0
  42. package/docs/superpowers/specs/2026-11-10-issue-258-board-selection-settle-design.md +109 -0
  43. package/docs/superpowers/specs/2026-11-13-issue-294-snapshot-resize-intent-design.md +141 -0
  44. package/docs/superpowers/specs/2026-11-16-greeting-title-poll-design.md +174 -0
  45. package/docs/superpowers/specs/2026-11-22-issue-297-compaction-mirror-design.md +158 -0
  46. package/docs/superpowers/specs/2026-11-22-issue-95-legacy-quarantine-design.md +209 -0
  47. package/docs/superpowers/specs/2026-11-23-issue-254-cursor-keep-position-design.md +201 -0
  48. package/package.json +1 -1
  49. package/runner/pty-runner.mjs +526 -63
  50. package/runner/state-coordinator.mjs +62 -5
  51. package/runner/title-runner.mjs +33 -24
  52. package/src/commands/agent-board.ts +5 -1
  53. package/src/core/attach-detach.mjs +27 -0
  54. package/src/core/attach-frame-proof.mjs +897 -0
  55. package/src/core/attach-frame-reporter.mjs +738 -0
  56. package/src/core/attach-frame-stream.mjs +266 -0
  57. package/src/core/attach-pr-label.mjs +12 -0
  58. package/src/core/attach-recovery.mjs +239 -0
  59. package/src/core/attach-screen-owner.mjs +55 -0
  60. package/src/core/attach-view-proof.mjs +709 -0
  61. package/src/core/auto-state.mjs +6 -1
  62. package/src/core/cwd-stats.mjs +3 -1
  63. package/src/core/dashboard-prefs.mjs +31 -0
  64. package/src/core/derive.mjs +8 -1
  65. package/src/core/events.mjs +127 -1
  66. package/src/core/foreground-projection-cache.mjs +1 -0
  67. package/src/core/frame-witness-update.mjs +35 -0
  68. package/src/core/fullscreen-selection.mjs +60 -0
  69. package/src/core/host-coordination.mjs +48 -0
  70. package/src/core/host-protocol.mjs +13 -2
  71. package/src/core/hosted-frame-witness.mjs +60 -0
  72. package/src/core/paths.mjs +10 -3
  73. package/src/core/pty-attach-render.mjs +239 -0
  74. package/src/core/pty-kitty-images.mjs +237 -0
  75. package/src/core/pty-scroll.mjs +8 -8
  76. package/src/core/rows.mjs +43 -7
  77. package/src/core/session-entries.mjs +82 -0
  78. package/src/core/session-launch-prefs.mjs +45 -0
  79. package/src/core/session-view.mjs +3 -63
  80. package/src/core/store.mjs +1 -0
  81. package/src/core/terminal-attach-client.mjs +199 -20
  82. package/src/core/terminal-attach-protocol.mjs +221 -7
  83. package/src/core/terminal-model.mjs +24 -3
  84. package/src/core/terminal-snapshot.mjs +10 -0
  85. package/src/core/title-flow.mjs +66 -0
  86. package/src/core/title.mjs +101 -0
  87. package/src/core/types.mjs +17 -0
  88. package/src/index.ts +85 -0
  89. package/src/runtime/service.mjs +87 -18
  90. package/src/ui/dashboard.ts +206 -49
  91. package/src/ui/pty-attach.ts +1472 -99
@@ -0,0 +1,797 @@
1
+ # Compaction Mirror Implementation Plan (issue #297)
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:** Mirror pi's compaction window into the board row so `/compact` shows `working` instead of the stale pre-compaction state.
6
+
7
+ **Architecture:** One persisted `compaction` window field (`{phase, reason, startedAt, previous, error}`) carried on `RunStatus`/`ViewState`. Two pure helpers in `src/core/events.mjs` (`beginCompaction`/`endCompaction`) own every transition and are the only summary producer while a window is open. The extension hook path (`syncRowEvent`) and the JSON stream path (`reduceEvent`) both call the same helpers; `isAgentBusy` is untouched and picks the row up from `semanticState === "working"`.
8
+
9
+ **Tech Stack:** Node ESM `.mjs` core, TypeScript extension entry (`src/index.ts`), `node:test` + `assert/strict`, fake-pi harness for runner integration.
10
+
11
+ **Spec:** `docs/superpowers/specs/2026-11-22-issue-297-compaction-mirror-design.md` (issue #297 spec v2-final)
12
+
13
+ ## Global Constraints
14
+
15
+ - Tabs for indentation; English comments and commit subjects (`feat:` / `fix:` / `test:` / `docs:`).
16
+ - Never edit `CHANGELOG.md` by hand; never touch `src/core/state-commands.mjs` (`PATCHABLE_FIELDS` and the decision layer stay as-is).
17
+ - `isAgentBusy()` semantics must not change: the fix works only by setting `semanticState: "working"`.
18
+ - `compaction` must be nullable and tolerated when absent on legacy rows (`?? null`); no migration, no version bump.
19
+ - Legacy rows and rows with `compaction === null` must keep byte-identical behavior outside the window.
20
+ - Commits are staged per file (`git add <path>`), never `git add -A`.
21
+ - Existing test files keep passing unmodified except where a task explicitly adds cases.
22
+
23
+ ## Review Focus
24
+
25
+ - A `/compact` that fails in milliseconds ("Nothing to compact", "Already compacted") must never leave the row stuck at `working` + `Compacting context…` — the begin write may still be in flight when the end hook lands.
26
+ - An idle row must come back byte-for-byte to its pre-compaction shape after a successful compaction, including `processState: "exited"` and the old `summary`.
27
+ - A compaction that happens mid-run (threshold/overflow) must not drop the row out of `working` before the run actually ends.
28
+ - A failed compaction must surface pi's `errorMessage` on the row without fabricating `semanticState: "failed"`.
29
+ - The JSON runner path (`compaction_start`/`compaction_end`) must behave identically to the interactive path, including summary ownership.
30
+
31
+ ---
32
+
33
+ ### Task 1: Core window model (helpers, derive, types, projection)
34
+
35
+ **Files:**
36
+ - Modify: `src/core/types.mjs` (CompactionWindow typedef; `ViewState.compaction`; `RunStatus.compaction`)
37
+ - Modify: `src/core/derive.mjs:100-130` (`deriveSummary` compaction branch)
38
+ - Modify: `src/core/events.mjs:70-110` (`createRunStatus`), `:144-215` (`reduceEvent`), `:225-260` (`finalizeRun`), `:262-300` (`projectViewState`), plus new helpers
39
+ - Test: `test/derive.test.mjs`, `test/events.test.mjs`
40
+
41
+ **Interfaces:**
42
+ - Produces: `beginCompaction(status, facts, now)`, `endCompaction(status, facts, now)` exported from `src/core/events.mjs`; `facts = { reason?, willRetry?, aborted?, errorMessage? }`.
43
+ - Produces: `RunStatus.compaction` / `ViewState.compaction` shape `{ phase: "running"|"failed", reason, startedAt, previous, error }`.
44
+
45
+ - [ ] **Step 1: Write the failing derive test**
46
+
47
+ Append to `test/derive.test.mjs` (import already includes `deriveSummary`):
48
+
49
+ ```js
50
+ test("deriveSummary renders the compaction window (issue #297)", () => {
51
+ const base = {
52
+ semanticState: "working",
53
+ processState: "alive",
54
+ currentTool: { name: "bash", summary: "bash: npm test" },
55
+ latestAssistantPreview: "Old preview text that must not win.",
56
+ };
57
+ assert.equal(deriveSummary({ ...base, compaction: { phase: "running" } }), "Compacting context…");
58
+ assert.equal(
59
+ deriveSummary({ ...base, compaction: { phase: "failed", error: "Compaction failed: Nothing to compact (session too small)" } }),
60
+ "Compaction failed: Nothing to compact (session too small)",
61
+ );
62
+ assert.equal(deriveSummary({ ...base, compaction: null }), "bash: npm test");
63
+ });
64
+ ```
65
+
66
+ - [ ] **Step 2: Run it and watch it fail**
67
+
68
+ Run: `node --test test/derive.test.mjs`
69
+ Expected: FAIL — the first assertion returns `bash: npm test`.
70
+
71
+ - [ ] **Step 3: Implement the derive branch**
72
+
73
+ In `src/core/derive.mjs`, at the top of `deriveSummary` (before the active-tool branch):
74
+
75
+ ```js
76
+ // 0. A compaction window owns the summary (issue #297, invariant I8).
77
+ if (s.compaction) {
78
+ if (s.compaction.phase === "failed" && s.compaction.error) return truncate(s.compaction.error, max);
79
+ return "Compacting context…";
80
+ }
81
+ ```
82
+
83
+ - [ ] **Step 4: Run the derive test**
84
+
85
+ Run: `node --test test/derive.test.mjs`
86
+ Expected: PASS (new test + all existing ones).
87
+
88
+ - [ ] **Step 5: Write the failing reducer tests**
89
+
90
+ Append to `test/events.test.mjs` (imports `createRunStatus, finalizeRun, projectViewState, reduceEvent` already exist — add `beginCompaction, endCompaction`):
91
+
92
+ ```js
93
+ test("beginCompaction snapshots the pre-compaction state once and opens the window", () => {
94
+ const s = createRunStatus(cfg(), 1, 1000);
95
+ s.semanticState = "idle";
96
+ s.processState = "exited";
97
+ s.summary = "Needs instructions";
98
+ s.question = null;
99
+ beginCompaction(s, { reason: "manual" }, 2000);
100
+ assert.equal(s.semanticState, "working");
101
+ assert.equal(s.processState, "alive");
102
+ assert.equal(s.summary, "Compacting context…");
103
+ assert.equal(s.compaction.phase, "running");
104
+ assert.equal(s.compaction.reason, "manual");
105
+ assert.equal(s.compaction.startedAt, 2000);
106
+ assert.deepEqual(s.compaction.previous, {
107
+ semanticState: "idle",
108
+ processState: "exited",
109
+ summary: "Needs instructions",
110
+ question: null,
111
+ error: null,
112
+ });
113
+ // Idempotent while running: the original snapshot survives.
114
+ beginCompaction(s, { reason: "threshold" }, 2500);
115
+ assert.equal(s.compaction.reason, "manual");
116
+ assert.equal(s.compaction.startedAt, 2000);
117
+ assert.equal(s.compaction.previous.semanticState, "idle");
118
+ });
119
+
120
+ test("beginCompaction treats a leftover failed marker as a fresh window", () => {
121
+ const s = createRunStatus(cfg(), 1, 1000);
122
+ s.semanticState = "idle";
123
+ s.processState = "exited";
124
+ s.compaction = { phase: "failed", reason: "manual", startedAt: 1500, previous: null, error: "Compaction failed: x" };
125
+ beginCompaction(s, { reason: "manual" }, 2000);
126
+ assert.equal(s.compaction.phase, "running");
127
+ assert.equal(s.compaction.previous.semanticState, "idle");
128
+ assert.equal(s.compaction.previous.processState, "exited");
129
+ });
130
+
131
+ test("endCompaction restores a resting pre-state verbatim", () => {
132
+ const s = createRunStatus(cfg(), 1, 1000);
133
+ s.semanticState = "idle";
134
+ s.processState = "exited";
135
+ s.summary = "Needs instructions";
136
+ s.question = null;
137
+ beginCompaction(s, {}, 2000);
138
+ endCompaction(s, { willRetry: false, aborted: false, errorMessage: null }, 3000);
139
+ assert.equal(s.semanticState, "idle");
140
+ assert.equal(s.processState, "exited", "processState must come back to the snapshot value");
141
+ assert.equal(s.summary, "Needs instructions");
142
+ assert.equal(s.compaction, null);
143
+ });
144
+
145
+ test("endCompaction keeps a mid-run row working", () => {
146
+ const s = createRunStatus(cfg(), 1, 1000);
147
+ s.semanticState = "working";
148
+ s.processState = "alive";
149
+ beginCompaction(s, { reason: "threshold" }, 2000);
150
+ endCompaction(s, { willRetry: false }, 3000);
151
+ assert.equal(s.semanticState, "working");
152
+ assert.equal(s.processState, "alive");
153
+ assert.equal(s.compaction, null);
154
+ });
155
+
156
+ test("endCompaction keeps willRetry rows working and drops the error", () => {
157
+ const s = createRunStatus(cfg(), 1, 1000);
158
+ s.semanticState = "idle";
159
+ s.processState = "exited";
160
+ s.summary = "Needs instructions";
161
+ beginCompaction(s, { reason: "overflow" }, 2000);
162
+ endCompaction(s, { willRetry: true, aborted: false, errorMessage: "Compaction failed: boom" }, 3000);
163
+ assert.equal(s.semanticState, "working");
164
+ assert.equal(s.error, null, "a retry supersedes its error");
165
+ assert.equal(s.compaction, null);
166
+ });
167
+
168
+ test("endCompaction restores on abort without an error", () => {
169
+ const s = createRunStatus(cfg(), 1, 1000);
170
+ s.semanticState = "needs_input";
171
+ s.processState = "exited";
172
+ s.summary = "Approve this plan?";
173
+ s.question = "Approve this plan?";
174
+ beginCompaction(s, { reason: "manual" }, 2000);
175
+ endCompaction(s, { aborted: true, errorMessage: "Compaction failed: ignored" }, 3000);
176
+ assert.equal(s.semanticState, "needs_input");
177
+ assert.equal(s.question, "Approve this plan?");
178
+ assert.equal(s.error, null);
179
+ assert.equal(s.compaction, null);
180
+ });
181
+
182
+ test("endCompaction surfaces a real failure without faking a failed run", () => {
183
+ const s = createRunStatus(cfg(), 1, 1000);
184
+ s.semanticState = "idle";
185
+ s.processState = "exited";
186
+ s.summary = "Needs instructions";
187
+ beginCompaction(s, { reason: "manual" }, 2000);
188
+ endCompaction(s, { aborted: false, errorMessage: "Compaction failed: Nothing to compact (session too small)" }, 3000);
189
+ assert.equal(s.semanticState, "idle", "the session itself is still usable");
190
+ assert.equal(s.error, "Compaction failed: Nothing to compact (session too small)");
191
+ assert.equal(s.compaction.phase, "failed");
192
+ assert.equal(s.compaction.previous, null);
193
+ assert.equal(s.summary, "Compaction failed: Nothing to compact (session too small)");
194
+ });
195
+
196
+ test("endCompaction without a snapshot stays working instead of throwing", () => {
197
+ const s = createRunStatus(cfg(), 1, 1000);
198
+ s.semanticState = "working";
199
+ s.compaction = null;
200
+ endCompaction(s, { willRetry: false }, 3000);
201
+ assert.equal(s.semanticState, "working");
202
+ assert.equal(s.compaction, null);
203
+ });
204
+
205
+ test("reduceEvent mirrors compaction_start/compaction_end and owns the summary", () => {
206
+ const s = createRunStatus(cfg(), 1, 1000);
207
+ assert.equal(reduceEvent(s, { type: "compaction_start", reason: "threshold" }, 2000), true);
208
+ assert.equal(s.semanticState, "working");
209
+ assert.equal(s.processState, "alive");
210
+ assert.equal(s.summary, "Compacting context…");
211
+ assert.equal(reduceEvent(s, { type: "compaction_end", reason: "threshold", result: { summary: "x" }, aborted: false, willRetry: false }, 3000), true);
212
+ assert.equal(s.compaction, null);
213
+ assert.equal(s.semanticState, "working", "was mid-run");
214
+ });
215
+
216
+ test("a failed compaction notice survives until the next real event", () => {
217
+ const s = createRunStatus(cfg(), 1, 1000);
218
+ s.semanticState = "idle";
219
+ s.processState = "exited";
220
+ s.summary = "Needs instructions";
221
+ reduceEvent(s, { type: "compaction_start", reason: "manual" }, 2000);
222
+ reduceEvent(s, { type: "compaction_end", reason: "manual", result: undefined, aborted: false, willRetry: false, errorMessage: "Compaction failed: boom" }, 3000);
223
+ assert.equal(s.compaction.phase, "failed");
224
+ assert.equal(s.summary, "Compaction failed: boom");
225
+ reduceEvent(s, { type: "tool_execution_start", toolCallId: "t1", toolName: "bash", args: { command: "ls" } }, 4000);
226
+ assert.equal(s.compaction, null, "the next real event drops the failure notice");
227
+ });
228
+
229
+ test("finalizeRun and projectViewState handle the window field", () => {
230
+ const s = createRunStatus(cfg(), 1, 1000);
231
+ beginCompaction(s, { reason: "manual" }, 2000);
232
+ const projected = projectViewState(s, 2000);
233
+ assert.equal(projected.compaction.phase, "running");
234
+ assert.equal(projected.compaction.previous.semanticState, "queued");
235
+ finalizeRun(s, { exitCode: 0 }, 3000);
236
+ assert.equal(s.compaction, null);
237
+ assert.equal(projectViewState(s, 3000).compaction, null);
238
+ const legacy = { ...s };
239
+ delete legacy.compaction;
240
+ assert.equal(projectViewState(legacy, 4000).compaction, null);
241
+ });
242
+ ```
243
+
244
+ - [ ] **Step 6: Run the reducer tests and watch them fail**
245
+
246
+ Run: `node --test test/events.test.mjs`
247
+ Expected: FAIL — `beginCompaction is not a function`.
248
+
249
+ - [ ] **Step 7: Implement the helpers, reduceEvent cases and field plumbing**
250
+
251
+ `src/core/events.mjs` — add after the `QUESTION_TOOL_NAMES` block:
252
+
253
+ ```js
254
+ /** Compaction event types whose summary is owned by begin/endCompaction (I8). */
255
+ const COMPACTION_EVENT_TYPES = new Set(["compaction_start", "compaction_end"]);
256
+
257
+ /**
258
+ * Open (or refresh) a compaction window on a status (issue #297).
259
+ * The pre-compaction snapshot is taken once per window: a repeated
260
+ * before_compact/compaction_start keeps the original, while a leftover
261
+ * `failed` marker counts as a new window (the user retried).
262
+ * @param {any} status @param {{reason?: "manual"|"threshold"|"overflow"}} facts @param {number} now
263
+ */
264
+ export function beginCompaction(status, facts = {}, now) {
265
+ const existing = status.compaction;
266
+ if (!existing || existing.phase === "failed") {
267
+ status.compaction = {
268
+ phase: "running",
269
+ reason: facts.reason ?? "manual",
270
+ startedAt: now,
271
+ previous: {
272
+ semanticState: status.semanticState,
273
+ processState: status.processState,
274
+ summary: status.summary,
275
+ question: status.question ?? null,
276
+ error: status.error ?? null,
277
+ },
278
+ error: null,
279
+ };
280
+ }
281
+ status.semanticState = "working";
282
+ status.processState = "alive";
283
+ status.lastActivityAt = now;
284
+ status.summary = deriveSummary(status);
285
+ }
286
+
287
+ /**
288
+ * Close a compaction window and restore what it replaced (issue #297).
289
+ * Resting pre-states restore verbatim (including processState, R1-G3); a
290
+ * mid-run pre-state or willRetry stays working so the continuing run owns the
291
+ * row until agent_end. A genuine failure restores the row and leaves a
292
+ * `failed` marker so the summary keeps showing pi's message (R1-G1).
293
+ * @param {any} status @param {{willRetry?: boolean, aborted?: boolean, errorMessage?: string|null}} facts @param {number} now
294
+ */
295
+ export function endCompaction(status, facts = {}, now) {
296
+ const marker = status.compaction ?? null;
297
+ const previous = marker?.previous ?? null;
298
+ status.compaction = null;
299
+ status.lastActivityAt = now;
300
+ if (!previous) {
301
+ // No snapshot survived (late/duplicate end): stay working; agent_end or
302
+ // reconcile converges the row.
303
+ status.semanticState = "working";
304
+ status.summary = deriveSummary(status);
305
+ return;
306
+ }
307
+ if (facts.willRetry || previous.semanticState === "queued" || previous.semanticState === "working") {
308
+ // The run continues (threshold/overflow) or is retried; a retry
309
+ // supersedes its own error, so dropping errorMessage here is deliberate.
310
+ status.semanticState = "working";
311
+ status.processState = "alive";
312
+ status.summary = deriveSummary(status);
313
+ return;
314
+ }
315
+ status.semanticState = previous.semanticState;
316
+ status.processState = previous.processState;
317
+ status.question = previous.question;
318
+ status.error = previous.error;
319
+ if (!facts.aborted && facts.errorMessage) {
320
+ status.error = facts.errorMessage;
321
+ status.compaction = {
322
+ phase: "failed",
323
+ reason: marker?.reason ?? "manual",
324
+ startedAt: marker?.startedAt ?? now,
325
+ previous: null,
326
+ error: facts.errorMessage,
327
+ };
328
+ status.summary = deriveSummary(status);
329
+ return;
330
+ }
331
+ status.summary = previous.summary || deriveSummary(status);
332
+ }
333
+ ```
334
+
335
+ In `createRunStatus`, add `compaction: null,` after `currentTool: null,`.
336
+
337
+ In `reduceEvent`, add `let summaryPinned = false;` beside `let meaningful = false;`, add the two cases before `default:`:
338
+
339
+ ```js
340
+ case "compaction_start": {
341
+ beginCompaction(status, { reason: event.reason }, now);
342
+ summaryPinned = true;
343
+ meaningful = true;
344
+ break;
345
+ }
346
+ case "compaction_end": {
347
+ endCompaction(status, {
348
+ willRetry: Boolean(event.willRetry),
349
+ aborted: Boolean(event.aborted),
350
+ errorMessage: event.errorMessage ?? null,
351
+ }, now);
352
+ summaryPinned = true;
353
+ meaningful = true;
354
+ break;
355
+ }
356
+ ```
357
+
358
+ and replace the tail `if (meaningful) status.summary = deriveSummary(status);` with:
359
+
360
+ ```js
361
+ if (meaningful) {
362
+ // A leftover failure notice belongs to the compaction that produced it;
363
+ // the next real activity supersedes it (invariant I6).
364
+ if (status.compaction?.phase === "failed" && !COMPACTION_EVENT_TYPES.has(event.type)) status.compaction = null;
365
+ if (!summaryPinned) status.summary = deriveSummary(status);
366
+ }
367
+ ```
368
+
369
+ In `finalizeRun`, add `status.compaction = null;` after `status.currentTool = null;`.
370
+
371
+ In `projectViewState`, add `compaction: status.compaction ?? null,` after `latestTool`.
372
+
373
+ `src/core/types.mjs` — add before the `ViewState` typedef:
374
+
375
+ ```js
376
+ /**
377
+ * Compaction window mirrored from pi (issue #297).
378
+ * @typedef {Object} CompactionWindow
379
+ * @property {"running"|"failed"} phase
380
+ * @property {"manual"|"threshold"|"overflow"} reason
381
+ * @property {number} startedAt
382
+ * @property {{semanticState:SemanticState, processState:ProcessState, summary:string, question:string|null, error:string|null}|null} previous
383
+ * Pre-compaction snapshot; non-null only while running.
384
+ * @property {string|null} error pi's errorMessage, only on phase "failed".
385
+ */
386
+ ```
387
+
388
+ and add `@property {CompactionWindow|null} [compaction] Compaction window mirrored from pi (issue #297).` to both `ViewState` and `RunStatus`.
389
+
390
+ - [ ] **Step 8: Run the reducer + derive tests**
391
+
392
+ Run: `node --test test/derive.test.mjs test/events.test.mjs`
393
+ Expected: PASS.
394
+
395
+ - [ ] **Step 9: Run the whole suite to catch projection regressions**
396
+
397
+ Run: `npm test`
398
+ Expected: PASS (the coordinator leak gate included).
399
+
400
+ - [ ] **Step 10: Commit**
401
+
402
+ ```bash
403
+ git add src/core/types.mjs src/core/derive.mjs src/core/events.mjs test/derive.test.mjs test/events.test.mjs
404
+ git commit -m "fix: model the compaction window in the row reducer (issue #297)"
405
+ ```
406
+
407
+ ---
408
+
409
+ ### Task 2: Foreground/hosted mirror (extension hooks, cache whitelist, static guard)
410
+
411
+ **Files:**
412
+ - Modify: `src/index.ts:238-244` (three hook registrations)
413
+ - Modify: `src/runtime/service.mjs:874-895` (`blankState`), `:906-937` (`statusFromRow`), `:1834-1930` (`syncRowEvent`)
414
+ - Modify: `src/core/foreground-projection-cache.mjs:22-33` (`CACHED_FIELDS`)
415
+ - Test: `test/service.test.mjs`, new `test/index-compaction-events.test.mjs`
416
+
417
+ **Interfaces:**
418
+ - Consumes: `beginCompaction`, `endCompaction` from Task 1.
419
+ - Produces: `syncHostedEvent(viewId, event)` / `syncForegroundEvent(sessionFile, event)` accept the three compaction hook events; `state.json.compaction` mirrors the window.
420
+
421
+ - [ ] **Step 1: Write the failing service tests**
422
+
423
+ Append to `test/service.test.mjs` (helpers `service`, `freshRoot`, `readState`, `writeState`, `setEnv`, `waitFor`, `delayedMaterializingSendStateCommand` already exist in that file):
424
+
425
+ ```js
426
+ test("syncHostedEvent mirrors a compaction window end to end (issue #297)", async () => {
427
+ const root = freshRoot();
428
+ const prevCoordinator = setEnv("AGENT_BOARD_COORDINATOR", "off");
429
+ try {
430
+ createView(root, { id: "v1", name: "a", cwd: "/r" });
431
+ const svc = service(root);
432
+ const s = readState(root, "v1");
433
+ s.semanticState = "idle";
434
+ s.processState = "exited";
435
+ s.summary = "Needs instructions";
436
+ writeState(root, s);
437
+
438
+ assert.equal(await svc.syncHostedEvent("v1", { type: "session_before_compact", reason: "manual", willRetry: false }), true);
439
+ const compacting = readState(root, "v1");
440
+ assert.equal(compacting.semanticState, "working");
441
+ assert.equal(compacting.processState, "alive");
442
+ assert.equal(compacting.summary, "Compacting context…");
443
+ assert.equal(compacting.compaction.phase, "running");
444
+ assert.equal(compacting.compaction.previous.semanticState, "idle");
445
+ assert.equal(service(root).row("v1").alive, true);
446
+ // The busy guards now see the row (they key on semanticState only).
447
+ assert.equal((await service(root).markCompleted("v1")).ok, false);
448
+ assert.equal((await service(root).holdView("v1")).ok, false);
449
+
450
+ assert.equal(await svc.syncHostedEvent("v1", { type: "session_compact", reason: "manual", willRetry: false, fromExtension: false }), true);
451
+ const restored = readState(root, "v1");
452
+ assert.equal(restored.semanticState, "idle");
453
+ assert.equal(restored.processState, "exited");
454
+ assert.equal(restored.summary, "Needs instructions");
455
+ assert.equal(restored.compaction, null);
456
+ assert.equal(service(root).row("v1").alive, false);
457
+ } finally {
458
+ setEnv("AGENT_BOARD_COORDINATOR", prevCoordinator);
459
+ rmSync(root, { recursive: true, force: true });
460
+ }
461
+ });
462
+
463
+ test("a failed compaction surfaces pi's message and never fakes a failed run (issue #297)", async () => {
464
+ const root = freshRoot();
465
+ const prevCoordinator = setEnv("AGENT_BOARD_COORDINATOR", "off");
466
+ try {
467
+ createView(root, { id: "v1", name: "a", cwd: "/r" });
468
+ const svc = service(root);
469
+ const s = readState(root, "v1");
470
+ s.semanticState = "idle";
471
+ s.processState = "exited";
472
+ s.summary = "Needs instructions";
473
+ writeState(root, s);
474
+
475
+ await svc.syncHostedEvent("v1", { type: "session_before_compact", reason: "manual", willRetry: false });
476
+ await svc.syncHostedEvent("v1", {
477
+ type: "session_compact_failed",
478
+ reason: "manual",
479
+ aborted: false,
480
+ willRetry: false,
481
+ errorMessage: "Compaction failed: Nothing to compact (session too small)",
482
+ fromExtension: false,
483
+ });
484
+ const failed = readState(root, "v1");
485
+ assert.equal(failed.semanticState, "idle");
486
+ assert.equal(failed.processState, "exited");
487
+ assert.equal(failed.error, "Compaction failed: Nothing to compact (session too small)");
488
+ assert.equal(failed.compaction.phase, "failed");
489
+ assert.match(failed.summary, /^Compaction failed: /);
490
+
491
+ // The next real activity drops the notice (invariant I6).
492
+ await svc.syncHostedEvent("v1", { type: "input", text: "try again" });
493
+ const resumed = readState(root, "v1");
494
+ assert.equal(resumed.compaction, null);
495
+ assert.equal(resumed.semanticState, "working");
496
+ assert.equal(resumed.summary, "Running…");
497
+ } finally {
498
+ setEnv("AGENT_BOARD_COORDINATOR", prevCoordinator);
499
+ rmSync(root, { recursive: true, force: true });
500
+ }
501
+ });
502
+
503
+ test("an aborted compaction restores the pre-compaction row silently (issue #297)", async () => {
504
+ const root = freshRoot();
505
+ const prevCoordinator = setEnv("AGENT_BOARD_COORDINATOR", "off");
506
+ try {
507
+ createView(root, { id: "v1", name: "a", cwd: "/r" });
508
+ const svc = service(root);
509
+ const s = readState(root, "v1");
510
+ s.semanticState = "needs_input";
511
+ s.processState = "exited";
512
+ s.summary = "Approve this plan?";
513
+ s.question = "Approve this plan?";
514
+ s.pendingQuestions = [{ toolCallId: "q1", question: "Approve this plan?" }];
515
+ writeState(root, s);
516
+
517
+ await svc.syncHostedEvent("v1", { type: "session_before_compact", reason: "manual", willRetry: false });
518
+ await svc.syncHostedEvent("v1", { type: "session_compact_failed", reason: "manual", aborted: true, willRetry: false, errorMessage: undefined });
519
+ const restored = readState(root, "v1");
520
+ assert.equal(restored.semanticState, "needs_input");
521
+ assert.equal(restored.question, "Approve this plan?");
522
+ assert.equal(restored.error, null);
523
+ assert.equal(restored.compaction, null);
524
+ } finally {
525
+ setEnv("AGENT_BOARD_COORDINATOR", prevCoordinator);
526
+ rmSync(root, { recursive: true, force: true });
527
+ }
528
+ });
529
+
530
+ test("a fast-failing compaction cannot strand an idle row in working (issue #297, R1-G2)", async () => {
531
+ const root = freshRoot();
532
+ const prevCoordinator = setEnv("AGENT_BOARD_COORDINATOR", "off");
533
+ const fake = delayedMaterializingSendStateCommand(root, { delayMs: 20 });
534
+ try {
535
+ const meta = createView(root, { id: "v1", name: "a", cwd: "/r" });
536
+ const st = readState(root, "v1");
537
+ st.semanticState = "idle";
538
+ st.processState = "exited";
539
+ st.summary = "Needs instructions";
540
+ writeState(root, st);
541
+
542
+ // Back-to-back hooks while the begin projection is still in flight.
543
+ await service(root, { sendStateCommand: fake.send }).syncForegroundEvent(meta.sessionFile, { type: "session_before_compact", reason: "manual" });
544
+ await service(root, { sendStateCommand: fake.send }).syncForegroundEvent(meta.sessionFile, {
545
+ type: "session_compact_failed",
546
+ reason: "manual",
547
+ aborted: false,
548
+ willRetry: false,
549
+ errorMessage: "Compaction failed: Nothing to compact (session too small)",
550
+ });
551
+
552
+ const settled = await waitFor(() => {
553
+ const s = readState(root, "v1");
554
+ return s.compaction?.phase === "failed" ? s : null;
555
+ });
556
+ assert.ok(settled, "the failure notice materialized");
557
+ assert.equal(settled.semanticState, "idle", "never stranded on working");
558
+ assert.equal(settled.processState, "exited");
559
+ } finally {
560
+ setEnv("AGENT_BOARD_COORDINATOR", prevCoordinator);
561
+ rmSync(root, { recursive: true, force: true });
562
+ }
563
+ });
564
+ ```
565
+
566
+ - [ ] **Step 2: Add the static registration guard test**
567
+
568
+ Create `test/index-compaction-events.test.mjs`:
569
+
570
+ ```js
571
+ import assert from "node:assert/strict";
572
+ import { readFileSync } from "node:fs";
573
+ import { fileURLToPath } from "node:url";
574
+ import { test } from "node:test";
575
+
576
+ const ENTRY = fileURLToPath(new URL("../src/index.ts", import.meta.url));
577
+
578
+ /** Issue #297: the compaction hooks live in the extension registration layer,
579
+ * which the service harness never exercises — a typo there would only surface
580
+ * in a manual run, so pin the three names as static text. */
581
+ test("the extension registers every compaction hook (issue #297)", () => {
582
+ const source = readFileSync(ENTRY, "utf8");
583
+ for (const hook of ["session_before_compact", "session_compact", "session_compact_failed"]) {
584
+ assert.match(source, new RegExp(`pi\\.on\\("${hook}"`), `missing pi.on("${hook}") registration`);
585
+ }
586
+ });
587
+ ```
588
+
589
+ - [ ] **Step 3: Run the new tests and watch them fail**
590
+
591
+ Run: `node --test test/service.test.mjs test/index-compaction-events.test.mjs`
592
+ Expected: FAIL — the row stays `idle` after `session_before_compact`, and the extension registration is missing.
593
+
594
+ - [ ] **Step 4: Implement the foreground mirror**
595
+
596
+ `src/core/foreground-projection-cache.mjs` — add `"compaction",` to `CACHED_FIELDS` (after `"lastAgentActivityAt",` or alphabetically near `"currentTool"`; keep the list's existing style).
597
+
598
+ `src/runtime/service.mjs` — add the import (near the existing `events.mjs` import): `beginCompaction, endCompaction`; add a module-level `const COMPACTION_EVENTS = new Set(["session_before_compact", "session_compact", "session_compact_failed"]);`
599
+
600
+ In `blankState`, add `compaction: null,` after `latestTool: null,`.
601
+ In `statusFromRow`, add `compaction: s.compaction ?? null,` after `latestTool`.
602
+
603
+ In `syncRowEvent`, right after the `foregroundProjectionCache.adopt(...)` call, add:
604
+
605
+ ```js
606
+ // Issue #297: only the three compaction hooks keep the window marker; any
607
+ // other event supersedes a leftover failure notice.
608
+ if (status.compaction && !COMPACTION_EVENTS.has(event.type)) status.compaction = null;
609
+ ```
610
+
611
+ and after the existing `input | before_agent_start | agent_start` branch, before the `agent_end` branch:
612
+
613
+ ```js
614
+ if (event.type === "session_before_compact") {
615
+ beginCompaction(status, { reason: event.reason }, now);
616
+ // Throughput path: periodic self-healing mirror, fire-and-forget.
617
+ void writeForegroundState(row, status);
618
+ return true;
619
+ }
620
+
621
+ if (event.type === "session_compact" || event.type === "session_compact_failed") {
622
+ endCompaction(status, {
623
+ willRetry: Boolean(event.willRetry),
624
+ aborted: Boolean(event.aborted),
625
+ errorMessage: event.errorMessage ?? null,
626
+ }, now);
627
+ void writeForegroundState(row, status);
628
+ return true;
629
+ }
630
+ ```
631
+
632
+ `src/index.ts` — after the `agent_end` registration:
633
+
634
+ ```ts
635
+ // Issue #297: compaction is work in progress. Registered separately from the
636
+ // AgentSessionEvent stream because these three hooks are what a live pi
637
+ // session actually emits to extensions.
638
+ pi.on("session_before_compact", async (event, ctx) => syncForeground(event, ctx));
639
+ pi.on("session_compact", async (event, ctx) => syncForeground(event, ctx));
640
+ pi.on("session_compact_failed", async (event, ctx) => syncForeground(event, ctx));
641
+ ```
642
+
643
+ - [ ] **Step 5: Run the service + static tests**
644
+
645
+ Run: `node --test test/service.test.mjs test/index-compaction-events.test.mjs`
646
+ Expected: PASS.
647
+
648
+ - [ ] **Step 6: Run the full suite**
649
+
650
+ Run: `npm test`
651
+ Expected: PASS.
652
+
653
+ - [ ] **Step 7: Commit**
654
+
655
+ ```bash
656
+ git add src/index.ts src/runtime/service.mjs src/core/foreground-projection-cache.mjs test/service.test.mjs test/index-compaction-events.test.mjs
657
+ git commit -m "fix: mirror the compaction window from live pi sessions (issue #297)"
658
+ ```
659
+
660
+ ---
661
+
662
+ ### Task 3: JSON runner path (fake-pi mode + end-to-end assertion)
663
+
664
+ **Files:**
665
+ - Modify: `test-support/fake-pi.mjs` (new `compact` mode)
666
+ - Test: `test/runner.integration.test.mjs`
667
+
668
+ **Interfaces:**
669
+ - Consumes: `beginCompaction`/`endCompaction` wired into `reduceEvent` by Task 1 (no runner code change needed: the progress beat ships the whole in-memory status).
670
+ - Produces: `FAKE_PI_MODE=compact` fixture; `FAKE_PI_COMPACT_MS` overrides the window length (default 1200).
671
+
672
+ - [ ] **Step 1: Add the fake-pi mode**
673
+
674
+ In `test-support/fake-pi.mjs`, after the first `message_end` block and before the `if (mode === "abort")` block:
675
+
676
+ ```js
677
+ if (mode === "compact") {
678
+ // Mid-run threshold compaction: the run continues afterwards, so the row
679
+ // must stay working across the window (issue #297, A4).
680
+ emit({ type: "compaction_start", reason: "threshold" });
681
+ await sleep(Number(process.env.FAKE_PI_COMPACT_MS || 1200));
682
+ emit({
683
+ type: "compaction_end",
684
+ reason: "threshold",
685
+ result: { summary: "older context compacted", tokensBefore: 4096, firstKeptEntryId: "u0000001" },
686
+ aborted: false,
687
+ willRetry: false,
688
+ });
689
+ }
690
+ ```
691
+
692
+ - [ ] **Step 2: Write the failing integration test**
693
+
694
+ Append to `test/runner.integration.test.mjs`, following the completed-run fixture (tracked coordinator, `makeConfig`, `launchRun`, `killDetached`):
695
+
696
+ ```js
697
+ test("runner mirrors a mid-run compaction window into the row (issue #297)", { timeout: 30000 }, async () => {
698
+ const root = mkdtempSync(join(tmpdir(), "agentview-run-compact-"));
699
+ process.env.FAKE_PI_MODE = "compact";
700
+ process.env.FAKE_PI_COMPACT_MS = "1500";
701
+ process.env.AGENT_BOARD_SUMMARY_MODEL = "off";
702
+ let runnerPid = null;
703
+ const coord = await startCoordinator(root);
704
+ try {
705
+ const meta = createView(root, { id: "view_1", name: "compact", cwd: root });
706
+ const config = makeConfig(root, "view_1", "run_1", meta.sessionFile, root, "compact the context");
707
+ const st = readState(root, "view_1");
708
+ st.currentRunId = "run_1";
709
+ const { writeState } = await import("../src/core/store.mjs");
710
+ writeState(root, st);
711
+
712
+ runnerPid = launchRun(root, config, { runnerScript: RUNNER }).pid;
713
+ assert.ok(runnerPid && runnerPid > 0, "runner spawned");
714
+
715
+ const during = await waitFor(() => {
716
+ const state = readState(root, "view_1");
717
+ const status = readStatus(root, "view_1", "run_1");
718
+ return state?.compaction?.phase === "running" && status?.compaction?.phase === "running" ? { state, status } : null;
719
+ });
720
+ assert.equal(during.state.semanticState, "working");
721
+ assert.equal(during.state.processState, "alive");
722
+ assert.equal(during.state.summary, "Compacting context…");
723
+ assert.equal(during.status.semanticState, "working");
724
+
725
+ const done = await waitFor(() => {
726
+ const status = readStatus(root, "view_1", "run_1");
727
+ return status && status.endedAt ? status : null;
728
+ });
729
+ assert.equal(done.compaction, null, "the window is cleared once the run finishes");
730
+ await waitFor(() => (isAlive(runnerPid) ? null : true), 15000);
731
+ const finalState = readState(root, "view_1");
732
+ assert.equal(finalState.compaction, null);
733
+ assert.notEqual(finalState.semanticState, "working");
734
+ } finally {
735
+ await killDetached(runnerPid);
736
+ await coord.kill();
737
+ delete process.env.FAKE_PI_MODE;
738
+ delete process.env.FAKE_PI_COMPACT_MS;
739
+ delete process.env.AGENT_BOARD_SUMMARY_MODEL;
740
+ rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 });
741
+ }
742
+ });
743
+ ```
744
+
745
+ - [ ] **Step 3: Run it and watch it fail**
746
+
747
+ Run: `node --test test/runner.integration.test.mjs`
748
+ Expected: FAIL — `during` never becomes truthy (no `compaction` field is written by the runner path before Task 1 is wired; with Task 1 done this passes, so if it fails now the failure proves the fixture/wiring gap).
749
+
750
+ - [ ] **Step 4: Fix whatever the failure names**
751
+
752
+ The only expected causes are: the fake mode not emitting (step 1 missed), or `reduceEvent` not receiving the events (Task 1's cases missing). Do not add runner-specific code — the beat ships the whole status by design.
753
+
754
+ - [ ] **Step 5: Run the integration test again**
755
+
756
+ Run: `node --test test/runner.integration.test.mjs`
757
+ Expected: PASS.
758
+
759
+ - [ ] **Step 6: Commit**
760
+
761
+ ```bash
762
+ git add test-support/fake-pi.mjs test/runner.integration.test.mjs
763
+ git commit -m "test: cover the JSON runner compaction window (issue #297)"
764
+ ```
765
+
766
+ ---
767
+
768
+ ### Task 4: Full verification and acceptance reconciliation
769
+
770
+ **Files:**
771
+ - No source changes expected. If `npm run verify` reports a genuine defect, fix it inside the owning task's files and re-commit.
772
+
773
+ **Interfaces:**
774
+ - Consumes: Tasks 1–3.
775
+ - Produces: the A1–A6 evidence table for the PR body and the issue comment.
776
+
777
+ - [ ] **Step 1: Run the full gate**
778
+
779
+ Run: `npm run verify`
780
+ Expected: typecheck + perf gate + tests + coverage thresholds + pack:dry all pass.
781
+
782
+ - [ ] **Step 2: Run the coverage-only command if verify failed on thresholds**
783
+
784
+ Run: `npm run test:coverage`
785
+ Expected: lines ≥ 85 / functions ≥ 80 / branches ≥ 70.
786
+
787
+ - [ ] **Step 3: Record the acceptance evidence**
788
+
789
+ Write the A1–A6 rows with the exact commands run and their outcomes into the PR body draft (`docs/superpowers/plans/2026-11-22-issue-297-compaction-mirror.md` is the plan; the evidence goes into the PR description and the issue comment). U1 stays `pending` until a human runs a real `/compact`.
790
+
791
+ - [ ] **Step 4: Commit any fixes, then hand off**
792
+
793
+ ```bash
794
+ git status --short
795
+ ```
796
+
797
+ Expected: clean. Then post the implementation summary comment to the issue and open the PR in `github-issue-driven` step 9.