@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,266 @@
1
+ /**
2
+ * Runner-side DCS frame-marker stream parser (issue #222, step 23b1, FW-03).
3
+ *
4
+ * The child reporter writes FROZEN DCS markers into the same ordered stdout stream as
5
+ * the TUI output (`src/core/attach-frame-proof.mjs` owns the literals and validation).
6
+ * This module splits that stream at exact marker boundaries so marker bytes never reach
7
+ * the canonical xterm model, the screen log, the outer Terminal, user input or legacy
8
+ * replay output.
9
+ *
10
+ * ## Contract
11
+ *
12
+ * - Chunks are arbitrary: a marker may be split across PTY reads or coalesced with
13
+ * ordinary output. A bounded pending tail (<= `MAX_PENDING_MARKER_TAIL` code units)
14
+ * carries an incomplete DCS tail into the next chunk.
15
+ * - A complete marker is validated by `decodeFrameMarker` and additionally against the
16
+ * reporter instance: token match, S -> F/A order, strictly increasing frameId,
17
+ * one open candidate at a time, no duplicate F/A, no F/A without S. Any violation is a
18
+ * `protocol-error` — never a proof. Marker bytes are dropped in every case.
19
+ * - Unknown non-marker DCS (`ESC P …`) is ordinary output and keeps legacy behaviour.
20
+ * A DCS that starts like the marker family but never validates is dropped with a
21
+ * bounded diagnostic and can never enable modern proof.
22
+ * - `proof.seq` is assigned by the CALLER to the sequence of the preceding ordinary
23
+ * output SEGMENT (not a child frameId, not socket timing). Multiple proofs at the same
24
+ * seq keep production order.
25
+ * - A pending partial marker at `finish()` is invalid, never a proof.
26
+ *
27
+ * `seq` values here are placeholders (`seq: null`); `runner/pty-runner.mjs` fills them
28
+ * with the real output sequence of the preceding segment.
29
+ */
30
+
31
+ import { decodeFrameMarker } from "./attach-frame-proof.mjs";
32
+
33
+ export const FRAME_STREAM_PROTOCOL = 1;
34
+ export const MAX_PENDING_MARKER_TAIL = 4096;
35
+ export const MAX_STREAM_DIAGNOSTICS = 64;
36
+ export const MAX_PROOF_HISTORY = 256;
37
+ export const MAX_FINISHED_FRAME_IDS = 4096;
38
+
39
+ const DCS_INTRO = "\u001bP";
40
+ const MARKER_PREFIX = "\u001bP> agent-board-frame/1 ; ";
41
+
42
+ function bytes(text) {
43
+ return Buffer.byteLength(text, "utf8");
44
+ }
45
+
46
+ /**
47
+ * @param {{token: string, instanceId: string, sessionEpoch?: number, maxPending?: number}} options
48
+ */
49
+ export function createFrameStreamParser({ token, instanceId, sessionEpoch = 0, maxPending = MAX_PENDING_MARKER_TAIL }) {
50
+ if (typeof token !== "string" || token.length === 0) throw new Error("frame stream parser requires a reporter token");
51
+ const state = {
52
+ token,
53
+ instanceId,
54
+ sessionEpoch,
55
+ pending: "",
56
+ pendingBytes: 0,
57
+ lastFrameId: 0,
58
+ openFrameId: null,
59
+ finishedFrameIds: new Set(),
60
+ proofs: [],
61
+ diagnostics: [],
62
+ segments: 0,
63
+ markers: 0,
64
+ droppedProofs: 0,
65
+ droppedFinishedIds: 0,
66
+ };
67
+ const diagnostic = (reason, extra = {}) => {
68
+ state.diagnostics.push({ reason, ...extra });
69
+ if (state.diagnostics.length > MAX_STREAM_DIAGNOSTICS) state.diagnostics.splice(0, state.diagnostics.length - MAX_STREAM_DIAGNOSTICS);
70
+ };
71
+
72
+ /** Accept one marker literal; returns a proof part or null (with a diagnostic). */
73
+ function acceptMarker(literal) {
74
+ if (bytes(literal) > maxPending) {
75
+ diagnostic("marker-oversize", { bytes: bytes(literal) });
76
+ return null;
77
+ }
78
+ let decoded = null;
79
+ try {
80
+ decoded = decodeFrameMarker(literal);
81
+ } catch {
82
+ decoded = null;
83
+ }
84
+ if (decoded === null) {
85
+ diagnostic("marker-invalid");
86
+ return null;
87
+ }
88
+ if (decoded.token !== state.token) {
89
+ diagnostic("marker-wrong-token");
90
+ return null;
91
+ }
92
+ if (decoded.kind === "S") {
93
+ if (state.openFrameId !== null) {
94
+ diagnostic("marker-s-with-open-candidate", { openFrameId: state.openFrameId, frameId: decoded.frameId });
95
+ return null;
96
+ }
97
+ if (state.finishedFrameIds.has(decoded.frameId)) {
98
+ diagnostic("marker-duplicate-s", { frameId: decoded.frameId });
99
+ return null;
100
+ }
101
+ if (decoded.frameId <= state.lastFrameId) {
102
+ diagnostic("marker-frameid-regression", { frameId: decoded.frameId, lastFrameId: state.lastFrameId });
103
+ return null;
104
+ }
105
+ state.lastFrameId = decoded.frameId;
106
+ state.openFrameId = decoded.frameId;
107
+ state.markers += 1;
108
+ // Additive S/candidate part: F/A proofs and `state.proofs` semantics stay
109
+ // unchanged; the runner routes this record separately.
110
+ return {
111
+ kind: "candidate",
112
+ candidate: {
113
+ marker: "S",
114
+ frameId: decoded.frameId,
115
+ seq: null,
116
+ sessionEpoch: state.sessionEpoch,
117
+ intentId: decoded.intentId,
118
+ sampledCols: decoded.sampledCols,
119
+ },
120
+ };
121
+ }
122
+ if (state.openFrameId === null || state.openFrameId !== decoded.frameId) {
123
+ diagnostic("marker-close-without-open-s", { frameId: decoded.frameId, openFrameId: state.openFrameId });
124
+ return null;
125
+ }
126
+ state.openFrameId = null;
127
+ state.finishedFrameIds.add(decoded.frameId);
128
+ if (state.finishedFrameIds.size > MAX_FINISHED_FRAME_IDS) {
129
+ const oldest = state.finishedFrameIds.values().next().value;
130
+ state.finishedFrameIds.delete(oldest);
131
+ state.droppedFinishedIds += 1;
132
+ }
133
+ state.markers += 1;
134
+ // F5/F8: the ACCEPTED proof is stored here and the SAME object is returned, so the
135
+ // runner can assign `proof.seq` and snapshot/finish report the real proofs (no
136
+ // second divergent list).
137
+ const proof = {
138
+ marker: decoded.kind,
139
+ frameId: decoded.frameId,
140
+ seq: null,
141
+ sessionEpoch: state.sessionEpoch,
142
+ ...(decoded.kind === "F" ? { metadata: decoded.metadata } : { reason: decoded.reason }),
143
+ };
144
+ state.proofs.push(proof);
145
+ if (state.proofs.length > MAX_PROOF_HISTORY) {
146
+ state.proofs.shift();
147
+ state.droppedProofs += 1;
148
+ }
149
+ return { kind: "proof", proof };
150
+ }
151
+
152
+ /**
153
+ * Feed one arbitrary chunk. Returns ordered parts:
154
+ * `{kind:"output", data}` for ordinary bytes, `{kind:"candidate", candidate}` for an
155
+ * accepted S boundary, and `{kind:"proof", proof}` for a completed F/A witness.
156
+ * S/F/A `seq` is filled by the caller.
157
+ */
158
+ function push(chunk) {
159
+ const parts = [];
160
+ if (typeof chunk !== "string" || chunk.length === 0) return parts;
161
+ let text = state.pending + chunk;
162
+ state.pending = "";
163
+ state.pendingBytes = 0;
164
+ let index = 0;
165
+ const emitOutput = (data) => {
166
+ if (data.length === 0) return;
167
+ state.segments += 1;
168
+ parts.push({ kind: "output", data });
169
+ };
170
+ while (index < text.length) {
171
+ const intro = text.indexOf(DCS_INTRO, index);
172
+ if (intro < 0) {
173
+ // A trailing lone ESC may be the first byte of a split introducer: carry it.
174
+ if (text.endsWith("\u001b")) {
175
+ emitOutput(text.slice(index, text.length - 1));
176
+ state.pending = "\u001b";
177
+ state.pendingBytes = 1;
178
+ } else {
179
+ emitOutput(text.slice(index));
180
+ }
181
+ index = text.length;
182
+ break;
183
+ }
184
+ if (intro > index) emitOutput(text.slice(index, intro));
185
+ const terminator = text.indexOf("\u001b\\", intro + 2);
186
+ const prefixLookalike = text.startsWith(MARKER_PREFIX, intro);
187
+ if (terminator < 0) {
188
+ // Incomplete DCS tail: ALWAYS carry it into the next chunk (bounded), so a
189
+ // marker split character-by-character never leaks bytes. Only a tail that
190
+ // exceeds the bound is resolved here: a marker-family tail is dropped with a
191
+ // diagnostic, any other DCS keeps legacy behaviour and is emitted as output.
192
+ const tail = text.slice(intro);
193
+ if (bytes(tail) > maxPending) {
194
+ if (prefixLookalike || tail.startsWith(MARKER_PREFIX.slice(0, Math.min(tail.length, MARKER_PREFIX.length)))) {
195
+ diagnostic("marker-tail-oversize", { bytes: bytes(tail) });
196
+ } else {
197
+ emitOutput(tail);
198
+ }
199
+ index = text.length;
200
+ break;
201
+ }
202
+ state.pending = tail;
203
+ state.pendingBytes = bytes(tail);
204
+ index = text.length;
205
+ break;
206
+ }
207
+ const literal = text.slice(intro, terminator + 2);
208
+ if (prefixLookalike) {
209
+ const accepted = acceptMarker(literal);
210
+ if (accepted !== null) parts.push(accepted);
211
+ } else {
212
+ // Unknown DCS is ordinary output (legacy behaviour).
213
+ emitOutput(literal);
214
+ }
215
+ index = terminator + 2;
216
+ }
217
+ text = "";
218
+ return parts;
219
+ }
220
+
221
+ /**
222
+ * End of stream. A pending marker-family tail or an open candidate is invalid (never a
223
+ * proof); a trailing ORDINARY byte (e.g. a lone ESC or a non-marker partial DCS) is
224
+ * returned as `trailing` so the caller can forward it to the normal output path
225
+ * instead of dropping legitimate child output.
226
+ */
227
+ function finish(reason = "stream-end") {
228
+ let trailing = "";
229
+ if (state.pending.length > 0) {
230
+ // Only an actual marker-family prefix is invalid at end; a lone ESC or any
231
+ // other partial DCS is ordinary child output and must be forwarded.
232
+ const markerFamily = state.pending.startsWith(MARKER_PREFIX) || (state.pending.startsWith("\u001bP") && MARKER_PREFIX.startsWith(state.pending));
233
+ if (markerFamily) {
234
+ diagnostic("pending-marker-at-end", { at: reason, bytes: state.pendingBytes });
235
+ } else {
236
+ trailing = state.pending;
237
+ }
238
+ state.pending = "";
239
+ state.pendingBytes = 0;
240
+ }
241
+ if (state.openFrameId !== null) {
242
+ diagnostic("open-candidate-at-end", { frameId: state.openFrameId, at: reason });
243
+ state.openFrameId = null;
244
+ }
245
+ return { diagnostics: state.diagnostics.slice(), proofs: state.proofs.slice(), trailing };
246
+ }
247
+
248
+ function snapshot() {
249
+ return {
250
+ protocol: FRAME_STREAM_PROTOCOL,
251
+ instanceId: state.instanceId,
252
+ sessionEpoch: state.sessionEpoch,
253
+ segments: state.segments,
254
+ markers: state.markers,
255
+ lastFrameId: state.lastFrameId,
256
+ openFrameId: state.openFrameId,
257
+ pendingBytes: state.pendingBytes,
258
+ proofs: state.proofs.slice(),
259
+ diagnostics: state.diagnostics.slice(),
260
+ droppedProofs: state.droppedProofs,
261
+ droppedFinishedIds: state.droppedFinishedIds,
262
+ };
263
+ }
264
+
265
+ return { push, finish, snapshot, state };
266
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Label the winning persisted PR/MR reference for the attach header. Issue-only
3
+ * references and malformed numbers never become a session title badge.
4
+ * @param {import("./types.mjs").CodeRefsSummary|null|undefined} summary
5
+ * @returns {string}
6
+ */
7
+ export function attachPrLabel(summary) {
8
+ const pr = summary?.pr;
9
+ if (pr?.kind !== "pr" || !Number.isSafeInteger(pr.number) || pr.number <= 0) return "";
10
+ const isMr = summary.provider === "gitlab" || summary.prPrefix === "!";
11
+ return `${isMr ? "MR !" : "PR #"}${pr.number}`;
12
+ }
@@ -0,0 +1,239 @@
1
+ /**
2
+ * Issue #284 attach recovery: pure proof-status classification (spec §3.1.1).
3
+ *
4
+ * classifyProofStatus is the single implementation source for the four
5
+ * proofStatus buckets consumed by decideAttachPresentation's committed-degraded
6
+ * chain. The reason enums are anchored to their producers:
7
+ *
8
+ * - src/core/attach-view-proof.mjs `coverageFor`: `covered` (exact-proof /
9
+ * safe-trailing), `unavailable` (candidate-open, candidate-aborted,
10
+ * trailing-pending, trailing-unsafe), `unknown` (no-output, no-proof,
11
+ * output-gap, journal-gap, journal-evicted, proof-evicted,
12
+ * snapshot-seq-future, snapshot-before-window, invalid-snapshot-seq).
13
+ * - src/core/terminal-attach-client.mjs `unknownViewProof`: `unknown` +
14
+ * invalid-view-proof, view-proof-future, records-dropped, proof-output-gap.
15
+ * - src/ui/pty-attach.ts `invalidateViewProof` call sites: `unknown` +
16
+ * candidate-open (:1319), candidate-aborted (:1326), view-proof-replay-gap,
17
+ * view-proof-trailing-pending / view-proof-trailing-<reason>.
18
+ * Other UI-side invalidation reasons reaching the coverage object
19
+ * (new-empty-baseline, empty-baseline, generation-change, epoch-reset,
20
+ * geometry-resize) fail closed as invalid; geometry-resize is also
21
+ * whitelisted for the diagnostic readout.
22
+ *
23
+ * Matching uses exact string tables; any unrecognized status/reason classifies
24
+ * as "invalid" (fail closed — prefer waiting over displaying).
25
+ */
26
+
27
+ const COVERED_REASONS = new Set(["exact-proof", "safe-trailing"]);
28
+
29
+ // Runner-protocol candidate states are recoverable "missing evidence": the
30
+ // candidate may still end covered, so the degraded path may publish.
31
+ const CANDIDATE_REASONS = new Set(["candidate-open", "candidate-aborted"]);
32
+
33
+ // Coverage-for shapes that mean "output exists but was never proven" — missing
34
+ // evidence, degradable like the candidate shapes.
35
+ const UNKNOWN_MISSING_REASONS = new Set(["no-proof", "no-output"]);
36
+
37
+ // Continuity/window/protocol-validation failures: the view was proven once and
38
+ // then degraded, or the journal cannot vouch for the window. Never degradable.
39
+ const UNKNOWN_INVALID_REASONS = new Set([
40
+ "output-gap",
41
+ "journal-gap",
42
+ "journal-evicted",
43
+ "proof-evicted",
44
+ "snapshot-seq-future",
45
+ "snapshot-before-window",
46
+ "invalid-snapshot-seq",
47
+ "invalid-view-proof",
48
+ "view-proof-future",
49
+ "records-dropped",
50
+ "proof-output-gap",
51
+ "view-proof-replay-gap",
52
+ ]);
53
+
54
+ function isCoveredShape(viewProof) {
55
+ return (
56
+ viewProof !== null &&
57
+ typeof viewProof === "object" &&
58
+ !Array.isArray(viewProof) &&
59
+ viewProof.status === "covered" &&
60
+ COVERED_REASONS.has(viewProof.reason)
61
+ );
62
+ }
63
+
64
+ /**
65
+ * Classify the latest view proof for the attach recovery policy.
66
+ *
67
+ * The sticky priority rule runs FIRST: when `stickyInvalid` is true, every
68
+ * input except a recognized covered shape returns "invalid" — a live S/A
69
+ * record, no-proof, a null proof after capability loss, and unrecognized
70
+ * values included. The sticky fact is only cleared by the caller (component
71
+ * layer) when the full-view policy PUBLISHES on the current baseline — a
72
+ * covered shape alone is not recovery, because coverage is established before
73
+ * the policy validates sequence/metadata/geometry/intent/identity — or when
74
+ * the baseline identity changes; this function reports "covered" for exactly
75
+ * the publishable-recovery shape.
76
+ *
77
+ * @param {object|null} latestViewProof coverage object as produced by
78
+ * coverageFor / unknownViewProof / invalidateViewProof (null = capability
79
+ * revoked or never received).
80
+ * @param {boolean} stickyInvalid whether the current baseline already recorded
81
+ * an unrecovered invalid classification.
82
+ * @returns {"none" | "missing" | "invalid" | "covered"}
83
+ */
84
+ export function classifyProofStatus(latestViewProof, stickyInvalid) {
85
+ if (stickyInvalid === true) {
86
+ return isCoveredShape(latestViewProof) ? "covered" : "invalid";
87
+ }
88
+ const viewProof = latestViewProof;
89
+ if (viewProof === null || viewProof === undefined) return "none";
90
+ if (typeof viewProof !== "object" || Array.isArray(viewProof)) return "invalid";
91
+ if (viewProof.status === "covered") {
92
+ return COVERED_REASONS.has(viewProof.reason) ? "covered" : "invalid";
93
+ }
94
+ if (viewProof.status === "unavailable") {
95
+ // trailing-pending/trailing-unsafe extend a prior covered proof with
96
+ // unsafe trailing bytes: covered-then-degraded, never degradable.
97
+ return CANDIDATE_REASONS.has(viewProof.reason) ? "missing" : "invalid";
98
+ }
99
+ if (viewProof.status === "unknown") {
100
+ if (CANDIDATE_REASONS.has(viewProof.reason) || UNKNOWN_MISSING_REASONS.has(viewProof.reason)) return "missing";
101
+ if (UNKNOWN_INVALID_REASONS.has(viewProof.reason)) return "invalid";
102
+ if (typeof viewProof.reason === "string" && viewProof.reason.startsWith("view-proof-trailing-")) return "invalid";
103
+ return "invalid";
104
+ }
105
+ return "invalid";
106
+ }
107
+
108
+ /** Issue #284 review hardening (settle-diagnostics hygiene): recognized
109
+ * (status, reason) pairs for the diagnostic layer's latestViewProof readout.
110
+ * The attach client's sanitizer accepts arbitrary reason strings from the
111
+ * wire, so anything exposed to onDiagnostic consumers must pass a whitelist
112
+ * first: recognized producer pairs pass through verbatim, everything else
113
+ * maps to "unrecognized" (finite enums only — never raw wire strings).
114
+ * Mirrors the classifier's tables plus the runner's reporter lifecycle
115
+ * reasons and the snapshot/baseline invalidation reasons that reach the
116
+ * component's coverage object. */
117
+ const DIAGNOSTIC_STATUS_REASONS = {
118
+ covered: new Set(["exact-proof", "safe-trailing"]),
119
+ unavailable: new Set(["candidate-open", "candidate-aborted", "trailing-pending", "trailing-unsafe"]),
120
+ unknown: new Set([
121
+ // coverageFor missing-evidence shapes.
122
+ "candidate-open",
123
+ "candidate-aborted",
124
+ "no-proof",
125
+ "no-output",
126
+ // coverageFor window/continuity failures.
127
+ "output-gap",
128
+ "journal-gap",
129
+ "journal-evicted",
130
+ "proof-evicted",
131
+ "snapshot-seq-future",
132
+ "snapshot-before-window",
133
+ "invalid-snapshot-seq",
134
+ // terminal-attach-client unknownViewProof reasons.
135
+ "invalid-view-proof",
136
+ "view-proof-future",
137
+ "records-dropped",
138
+ "proof-output-gap",
139
+ // pty-attach invalidateViewProof call sites.
140
+ "view-proof-replay-gap",
141
+ "new-empty-baseline",
142
+ "empty-baseline",
143
+ "generation-change",
144
+ "epoch-reset",
145
+ "geometry-resize",
146
+ // runner resetViewProofSubscribers reasons (reporter close/replacement).
147
+ "reporter-replaced",
148
+ "reporter-close",
149
+ ]),
150
+ };
151
+
152
+ /** The dynamic noteViewProofOutput family: view-proof-trailing-<reason>, where
153
+ * <reason> is a trailing-classifier/scanner identifier. Accept it only in its
154
+ * lowercase-identifier form so arbitrary bytes can never ride the prefix. */
155
+ const TRAILING_REASON_PREFIX = "view-proof-trailing-";
156
+ const LOWERCASE_IDENTIFIER = /^[a-z][a-z0-9-]*$/;
157
+
158
+ /**
159
+ * Whitelist a coverage object's (status, reason) pair for diagnostic records.
160
+ *
161
+ * @param {object|null} latestViewProof coverage object as produced by
162
+ * coverageFor / unknownViewProof / invalidateViewProof (null = capability
163
+ * revoked or never received).
164
+ * @returns {{status: string, reason: string} | null} the recognized pair
165
+ * verbatim, {status: "unrecognized", reason: "unrecognized"} for any
166
+ * non-producer shape, or null when there is no proof object at all.
167
+ */
168
+ export function sanitizeViewProofEnumPair(latestViewProof) {
169
+ if (latestViewProof === null || latestViewProof === undefined) return null;
170
+ if (typeof latestViewProof !== "object" || Array.isArray(latestViewProof)) {
171
+ return { status: "unrecognized", reason: "unrecognized" };
172
+ }
173
+ const status = latestViewProof.status;
174
+ const reason = latestViewProof.reason;
175
+ if (typeof status !== "string" || typeof reason !== "string") {
176
+ return { status: "unrecognized", reason: "unrecognized" };
177
+ }
178
+ const known = DIAGNOSTIC_STATUS_REASONS[status];
179
+ if (known === undefined) return { status: "unrecognized", reason: "unrecognized" };
180
+ if (known.has(reason)) return { status, reason };
181
+ if (status === "unknown" && reason.startsWith(TRAILING_REASON_PREFIX) && LOWERCASE_IDENTIFIER.test(reason)) {
182
+ return { status, reason };
183
+ }
184
+ return { status: "unrecognized", reason: "unrecognized" };
185
+ }
186
+
187
+ // --- Issue #288 D1: invalid-family classification for the cap floor ---
188
+
189
+ // Runner-snapshot trailing shapes (coverageFor): a prior covered proof
190
+ // extended by unsafe trailing bytes — the trailing family's snapshot arrival
191
+ // shape, distinct from the UI's unknown + view-proof-trailing-* shapes.
192
+ const UNAVAILABLE_TRAILING_REASONS = new Set(["trailing-pending", "trailing-unsafe"]);
193
+
194
+ /** Trailing-family identifier form for the UI arrival shape: the suffix
195
+ * after view-proof-trailing- accepts lowercase alphanumerics and hyphens
196
+ * only (spec I9 — malformed/empty/uppercase/special-character suffixes
197
+ * classify as hard, never trailing). */
198
+ const TRAILING_FAMILY_IDENTIFIER = /^[a-z0-9-]+$/;
199
+
200
+ function isTrailingFamilyReason(reason) {
201
+ return (
202
+ typeof reason === "string" &&
203
+ reason.startsWith(TRAILING_REASON_PREFIX) &&
204
+ TRAILING_FAMILY_IDENTIFIER.test(reason.slice(TRAILING_REASON_PREFIX.length))
205
+ );
206
+ }
207
+
208
+ /**
209
+ * Classify an invalid proof classification into its recovery family (issue
210
+ * #288 D1): "trailing" shapes may still be admitted by the attach cap floor
211
+ * once the deadline expires; "hard" shapes never can.
212
+ *
213
+ * The family is a property of the arrival shape, so the sticky fact is not
214
+ * consulted: null is returned exactly when classifyProofStatus (without
215
+ * sticky) would NOT classify the shape as "invalid" — covered shapes, the
216
+ * missing-evidence candidate/no-proof/no-output shapes, and a null/absent
217
+ * proof object. The trailing family covers the two real arrival shapes of
218
+ * issue #288:
219
+ * - runner snapshot `coverageFor`: unavailable + trailing-pending /
220
+ * trailing-unsafe;
221
+ * - UI local paths (`noteViewProofOutput` live output and post-F replay via
222
+ * `invalidateViewProof`): unknown + view-proof-trailing-pending and
223
+ * unknown + view-proof-trailing-<identifier> in strict identifier form.
224
+ * Every other invalid classification — the window/continuity/validation
225
+ * reasons, non-object payloads, and any unrecognized status/reason — is
226
+ * "hard" (fail closed: the cap floor must not unlock it).
227
+ *
228
+ * @param {object|null} viewProof coverage object as produced by
229
+ * coverageFor / unknownViewProof / invalidateViewProof (null = capability
230
+ * revoked or never received).
231
+ * @returns {"trailing" | "hard" | null}
232
+ */
233
+ export function classifyProofInvalidFamily(viewProof) {
234
+ if (classifyProofStatus(viewProof, false) !== "invalid") return null;
235
+ if (typeof viewProof !== "object" || Array.isArray(viewProof)) return "hard";
236
+ if (viewProof.status === "unavailable" && UNAVAILABLE_TRAILING_REASONS.has(viewProof.reason)) return "trailing";
237
+ if (viewProof.status === "unknown" && isTrailingFamilyReason(viewProof.reason)) return "trailing";
238
+ return "hard";
239
+ }
@@ -0,0 +1,55 @@
1
+ // Issue #278: Ctrl+G opens an external editor that temporarily exits Pi's
2
+ // alt screen. This module tracks synchronized-output ownership (?2026) around
3
+ // alt-screen exits (?1049l) so the attach view can tell Pi-owned frames from
4
+ // external editor output. The reducer is pure; the adapter only registers
5
+ // xterm CSI handlers and always returns false so normal parsing continues.
6
+
7
+ function hasParam(params, wanted) {
8
+ return params.some((value) => value === wanted || (Array.isArray(value) && value.includes(wanted)));
9
+ }
10
+
11
+ export function createAttachScreenOwnerState(externalOutputActive = false) {
12
+ return { syncOpen: false, externalOutputActive };
13
+ }
14
+
15
+ export function transitionAttachScreenOwner(state, event) {
16
+ if (event.type === "reset") return createAttachScreenOwnerState();
17
+ if (event.type === "adopt") return { ...state, externalOutputActive: event.active };
18
+ if (event.type !== "csi") return state;
19
+ const has2026 = hasParam(event.params, 2026);
20
+ const has1049 = hasParam(event.params, 1049);
21
+ if (event.final === "h" && has2026) return { syncOpen: true, externalOutputActive: false };
22
+ if (event.final === "l") {
23
+ return {
24
+ syncOpen: has2026 ? false : state.syncOpen,
25
+ externalOutputActive: has1049 && state.syncOpen ? true : state.externalOutputActive,
26
+ };
27
+ }
28
+ return state;
29
+ }
30
+
31
+ export function installAttachScreenOwnerObservers(term, { initialState = createAttachScreenOwnerState(), onTransition = () => {} } = {}) {
32
+ if (!term?.parser || typeof term.parser.registerCsiHandler !== "function") return [];
33
+ let state = initialState;
34
+ const observers = [];
35
+ try {
36
+ for (const final of ["h", "l"]) {
37
+ observers.push(term.parser.registerCsiHandler({ prefix: "?", final }, (params) => {
38
+ const previous = state;
39
+ const event = { type: "csi", final, params };
40
+ const current = transitionAttachScreenOwner(state, event);
41
+ state = current;
42
+ onTransition({
43
+ previous, current, event,
44
+ syncOpenMarker: final === "h" && hasParam(params, 2026),
45
+ syncCloseMarker: final === "l" && hasParam(params, 2026),
46
+ });
47
+ return false;
48
+ }));
49
+ }
50
+ return observers;
51
+ } catch (error) {
52
+ for (const observer of observers) observer.dispose();
53
+ throw error;
54
+ }
55
+ }