@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
@@ -6,14 +6,21 @@ import { createConnection, type Socket } from "node:net";
6
6
  import type { Component, KeybindingsManager, RgbColor, TUI, TerminalColorScheme, TuiMouseEvent, TuiMouseEventResult } from "@earendil-works/pi-tui";
7
7
  import { CURSOR_MARKER, Key, matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
8
8
  import { resolveAttachDeleteKey } from "../core/attach-delete.mjs";
9
+ import { classifyProofInvalidFamily, classifyProofStatus, sanitizeViewProofEnumPair } from "../core/attach-recovery.mjs";
10
+ import { resolveAttachDetachChord } from "../core/attach-detach.mjs";
11
+ import { createAttachScreenOwnerState, installAttachScreenOwnerObservers } from "../core/attach-screen-owner.mjs";
12
+ import { createPtyKittyImages } from "../core/pty-kitty-images.mjs";
9
13
  import { findHttpUrlAtCells, findWordRangeAtCells } from "../core/pty-links.mjs";
10
- import { createAttachOutputRenderScheduler, detectCursorDesync, isPtyCursorHidden, nextAttachRender, projectPtyCursor, shouldScheduleAttachRenderForMessage } from "../core/pty-attach-render.mjs";
14
+ import { canPublishAttachView, createAttachOutputRenderScheduler, decideAttachPresentation, detectCursorDesync, isPtyCursorHidden, nextAttachRender, projectPtyCursor, resizeIntentEvidenceFromRecords, shouldScheduleAttachRenderForMessage } from "../core/pty-attach-render.mjs";
11
15
  import { evaluateAttachReconnect, shouldEscapeAttach } from "../core/pty-attach-reconnect.mjs";
12
16
  import { installImeCursorCoalesce } from "../core/ime-cursor-coalesce.mjs";
13
17
  import { createJiggleRetryController } from "../core/pty-attach-jiggle-controller.mjs";
14
18
  import { createTerminalAttachClient } from "../core/terminal-attach-client.mjs";
19
+ import { MAX_VIEW_PROOF_RECORDS } from "../core/terminal-attach-protocol.mjs";
20
+ import { createSafeTrailingClassifier } from "../core/attach-view-proof.mjs";
15
21
  import { backgroundRgbFromTerminalColors, buildSettleSchemePatch, colorSchemeForBackgroundRgb, extractOscQuerySequences, resolveProbeApi, toColorSchemeReport } from "../core/terminal-query-sequences.mjs";
16
22
  import { REPLY_GUARD_WINDOW_MS, createReplyGuard, isReplyGuardEnabled } from "../core/terminal-reply-guard.mjs";
23
+ import { createFullscreenSelectionSettler } from "../core/fullscreen-selection.mjs";
17
24
  import { clampInt, encodeWheelReport, fullscreenMouseEnableSequence, historyFloorAfterHydrate, isFullscreenSelectionEnd, resolveAttachMouseAction, resolveAttachWheelRoute, resolvePasteSelectionSource, resolveWheelLines, sameMousePoint, scrollableHistoryLines, scrollViewportTop, selectionDragScrollLines, selectionReleaseIsDrag, shouldOwnOuterMouseMode, splitAttachInput, wheelScrollLinesUp } from "../core/pty-scroll.mjs";
18
25
 
19
26
  export type PtyAttachResult = { action: "detached" } | { action: "closed"; exitCode?: number | null } | { action: "delete" };
@@ -27,7 +34,7 @@ type ThemeLike = {
27
34
  * getActiveSelectionText / clearTextSelection are private in TuiAltScreen's d.ts
28
35
  * (runtime-reachable plain methods), getCopyOnSelect is public. Every access is
29
36
  * feature-detected so an older or newer pi-tui degrades instead of throwing. */
30
- interface FullscreenSelectionHost {
37
+ export interface FullscreenSelectionHost {
31
38
  getActiveSelectionText?: () => string | undefined;
32
39
  getCopyOnSelect?: () => boolean;
33
40
  clearTextSelection?: () => void;
@@ -42,14 +49,96 @@ export interface AttachSettleDiagnosticPatch {
42
49
  details: { probeApi?: string; outcome: string; report?: string; late?: boolean };
43
50
  }
44
51
 
52
+ /** Issue #284 §3.4: which path settled this attach (recorded as readyReason). */
53
+ export type AttachReadyReason = "complete" | "committed-degraded" | "legacy-settle" | "legacy-cap";
54
+
55
+ /** Issue #284 §3.4/D5: recovery facts recorded at attach settle (and, from
56
+ * issue #288 D2, at each attach WAIT phase expiry). Numbers and finite
57
+ * enums only — never tokens, screen text, keys, or raw terminal data.
58
+ * The committedView identity records only numeric facts: the local parser
59
+ * generation (epoch) and the geometry revision; the connection/baseline
60
+ * tokens stay out of the diagnostic payload, and the wire generation id and
61
+ * the parser object remain excluded as non-numeric identity axes.
62
+ * latestViewProof carries the whitelisted (status, reason) pair — unrecognized
63
+ * wire strings map to "unrecognized" (sanitizeViewProofEnumPair). */
64
+ export interface AttachRecoveryFacts {
65
+ notReadyReason: string | null;
66
+ publishabilityState: string;
67
+ deadlineState: string;
68
+ witnessLatched: boolean;
69
+ budgetDeadline: number;
70
+ budgetElapsed: boolean;
71
+ proofStatus: string | null;
72
+ proofStickyInvalid: boolean;
73
+ committedView: {
74
+ generation: number;
75
+ geometryRevision: number;
76
+ source: string;
77
+ sourceCols: number;
78
+ sourceRows: number;
79
+ contentKind: string;
80
+ } | null;
81
+ latestViewProof: { status: string; reason: string } | null;
82
+ }
83
+
84
+ /** Diagnostic patch emitted at attach settle with the #284 recovery facts. */
85
+ export interface AttachRecoveryDiagnosticPatch {
86
+ source: string;
87
+ level: "info";
88
+ code: "attach_settle_ready";
89
+ message: string;
90
+ details: AttachRecoveryFacts & { readyReason: AttachReadyReason };
91
+ }
92
+
93
+ /** Issue #288 D2: which attach deadline expired while the attach was still
94
+ * waiting — the 250ms recovery budget or the 2500ms hard cap. */
95
+ export type AttachWaitExpiredPhase = "budget" | "cap";
96
+
97
+ /** Diagnostic patch emitted when an attach wait phase expires and the attach
98
+ * keeps waiting (issue #288 D2). Same recovery facts as the settle record;
99
+ * no readyReason — a waiting attach has none. */
100
+ export interface AttachWaitExpiredDiagnosticPatch {
101
+ source: string;
102
+ level: "info";
103
+ code: "attach_wait_expired";
104
+ message: string;
105
+ details: AttachRecoveryFacts & { phase: AttachWaitExpiredPhase };
106
+ }
107
+
45
108
  export interface PtyAttachOptions {
46
109
  socketPath: string;
47
110
  screenLogPath?: string;
48
111
  title: string;
112
+ /** Persisted winning PR/MR reference shown beside the session name. */
113
+ prLabel?: string;
49
114
  /** Issue #161: receives settle-scheme diagnostic patches. Default: no-op. */
50
- onDiagnostic?: (event: AttachSettleDiagnosticPatch) => void;
115
+ onDiagnostic?: (event: AttachSettleDiagnosticPatch | AttachRecoveryDiagnosticPatch | AttachWaitExpiredDiagnosticPatch) => void;
116
+ /** Issue #284: injectable clock for attach-lifecycle deadlines. The default
117
+ * (host clock + global timers) keeps the existing behavior untouched; the
118
+ * component harness injects a virtual time source and timer queue so the
119
+ * 250ms settle / 2500ms cap / 250ms recovery budget boundaries are asserted
120
+ * deterministically instead of on wall clock. */
121
+ clock?: AttachClock;
122
+ }
123
+
124
+ /** Issue #284 attach-lifecycle clock seam: `now` plus a scheduler pair. The
125
+ * scheduled handle is opaque (the injected scheduler may return any id). */
126
+ export interface AttachClock {
127
+ now(): number;
128
+ schedule(fn: () => void, ms: number): unknown;
129
+ clear(handle: unknown): void;
51
130
  }
52
131
 
132
+ const hostAttachClock: AttachClock = {
133
+ now: () => Date.now(),
134
+ schedule: (fn, ms) => {
135
+ const timer = setTimeout(fn, ms);
136
+ timer.unref?.();
137
+ return timer;
138
+ },
139
+ clear: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
140
+ };
141
+
53
142
  const require = createRequire(import.meta.url);
54
143
  const { Terminal } = require("@xterm/headless") as { Terminal: new (opts: Record<string, unknown>) => XtermLike };
55
144
 
@@ -62,8 +151,17 @@ const SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇",
62
151
  const LOADING_TICK_MS = 120;
63
152
  /** How long to keep the loading banner after the last resize-jiggle during attach. */
64
153
  const ATTACH_SETTLE_MS = 250;
65
- /** Hard cap on the attach transition so a silent session can't stall the banner. */
66
- const ATTACH_HARD_TIMEOUT_MS = 2500;
154
+ /** Hard cap on the attach transition so a silent session can't stall the banner.
155
+ * Issue #288: the cap doubles as the trailing-only downgrade floor (spec §2
156
+ * D1); exported for the integration driver's wall-clock readouts. */
157
+ export const ATTACH_HARD_TIMEOUT_MS = 2500;
158
+ /** Issue #284 recovery budget: one 250ms window per attach lifetime. Once it
159
+ * elapses, a protocol attach with a safely committed view but no covering F
160
+ * proof may publish degraded (spec §3.2; the policy wiring lands with T6 —
161
+ * this constant only owns the timer fact). Ordinary output and reconnect
162
+ * re-entry never reset or extend it (invariant I5). Exported for the
163
+ * component harness's diagnostic readouts. */
164
+ export const ATTACH_RECOVERY_BUDGET_MS = 250;
67
165
  /** Protocol-race guard for legacy jiggle arming (issue #91 phase 4): the
68
166
  * undecided window must not pulse the child before the snapshot probe
69
167
  * resolves — a resize-free attach is the protocol-mode contract. Invisible
@@ -102,9 +200,15 @@ const TERMINAL_PASSTHROUGH_CARRY_MAX_BYTES = TERMINAL_PASSTHROUGH_MAX_BYTES + 40
102
200
  const KITTY_IMAGE_PREFIX = "\x1b_G";
103
201
  const ITERM2_FILE_PREFIX = "\x1b]1337;File=";
104
202
 
203
+ interface XtermParserLike {
204
+ registerCsiHandler(opts: { prefix: string; final: string }, cb: (params: (number | number[])[]) => boolean): { dispose(): void };
205
+ }
206
+
105
207
  interface XtermLike {
106
208
  write(data: string, cb?: () => void): void;
107
209
  resize(cols: number, rows: number): void;
210
+ parser?: XtermParserLike;
211
+ dispose?(): void;
108
212
  // Full buffer wipe (@xterm/headless Terminal.reset): the attach client's
109
213
  // "empty/resnapshot → UI resets its buffer" contract (phase 4, F3).
110
214
  reset(): void;
@@ -161,8 +265,110 @@ interface BufferCellLike {
161
265
  isOverline(): number;
162
266
  }
163
267
 
268
+ interface CommittedRow { cells: SnapshotLine; kittyPrefix: string; }
269
+
270
+ interface CommittedView {
271
+ identity: {
272
+ connectionToken: number;
273
+ baselineToken: number;
274
+ generation: string;
275
+ parser: XtermLike;
276
+ geometryRevision: number;
277
+ targetCols: number;
278
+ targetRows: number;
279
+ closed: boolean;
280
+ };
281
+ start: number;
282
+ end: number;
283
+ rows: CommittedRow[];
284
+ cursor: { row: number; col: number } | null;
285
+ cursorHidden: boolean;
286
+ viewportTop: number | null;
287
+ proofSeq: number | null;
288
+ /** Issue #284 §3.1 predicate 7 facts, recorded at commit: which path
289
+ * captured the grid, the grid's ACTUAL dimensions (the parser size at
290
+ * commit — the readiness assembly must never re-read the current target
291
+ * here), and the locally closed completeness classification. */
292
+ source: "snapshot" | "sync-close";
293
+ sourceCols: number;
294
+ sourceRows: number;
295
+ contentKind: "complete" | "unknown";
296
+ }
297
+
298
+ /** Primitive cell snapshot used by committed rendering and interactions. */
299
+ class SnapshotCell implements BufferCellLike {
300
+ private constructor(
301
+ private readonly charsValue: string,
302
+ private readonly widthValue: number,
303
+ private readonly attrs: {
304
+ bold: number; dim: number; italic: number; underline: number; blink: number; inverse: number;
305
+ invisible: number; strikethrough: number; overline: number;
306
+ fgRGB: boolean; fgPalette: boolean; fg: number;
307
+ bgRGB: boolean; bgPalette: boolean; bg: number;
308
+ },
309
+ private readonly uriValue: string,
310
+ ) {
311
+ this.extended = this.uriValue ? { urlId: 1, _urlId: 1 } : undefined;
312
+ }
313
+ static empty(): SnapshotCell {
314
+ return new SnapshotCell("", 0, {
315
+ bold: 0, dim: 0, italic: 0, underline: 0, blink: 0, inverse: 0,
316
+ invisible: 0, strikethrough: 0, overline: 0,
317
+ fgRGB: false, fgPalette: false, fg: -1, bgRGB: false, bgPalette: false, bg: -1,
318
+ }, "");
319
+ }
320
+ static fromBufferCell(cell: BufferCellLike, uri: string): SnapshotCell {
321
+ return new SnapshotCell(cell.getChars(), cell.getWidth(), {
322
+ bold: cell.isBold(), dim: cell.isDim(), italic: cell.isItalic(), underline: cell.isUnderline(),
323
+ blink: cell.isBlink(), inverse: cell.isInverse(), invisible: cell.isInvisible(),
324
+ strikethrough: cell.isStrikethrough(), overline: cell.isOverline(),
325
+ fgRGB: cell.isFgRGB(), fgPalette: cell.isFgPalette(), fg: cell.getFgColor(),
326
+ bgRGB: cell.isBgRGB(), bgPalette: cell.isBgPalette(), bg: cell.getBgColor(),
327
+ }, uri);
328
+ }
329
+ getWidth(): number { return this.widthValue; }
330
+ getChars(): string { return this.charsValue; }
331
+ hasExtendedAttrs(): number { return this.uriValue ? 1 : 0; }
332
+ extended?: { urlId?: number; _urlId?: number };
333
+ getFgColor(): number { return this.attrs.fg; }
334
+ getBgColor(): number { return this.attrs.bg; }
335
+ isFgRGB(): boolean { return this.attrs.fgRGB; }
336
+ isBgRGB(): boolean { return this.attrs.bgRGB; }
337
+ isFgPalette(): boolean { return this.attrs.fgPalette; }
338
+ isBgPalette(): boolean { return this.attrs.bgPalette; }
339
+ isFgDefault(): boolean { return !this.attrs.fgRGB && !this.attrs.fgPalette; }
340
+ isBgDefault(): boolean { return !this.attrs.bgRGB && !this.attrs.bgPalette; }
341
+ isBold(): number { return this.attrs.bold; }
342
+ isItalic(): number { return this.attrs.italic; }
343
+ isDim(): number { return this.attrs.dim; }
344
+ isUnderline(): number { return this.attrs.underline; }
345
+ isBlink(): number { return this.attrs.blink; }
346
+ isInverse(): number { return this.attrs.inverse; }
347
+ isInvisible(): number { return this.attrs.invisible; }
348
+ isStrikethrough(): number { return this.attrs.strikethrough; }
349
+ isOverline(): number { return this.attrs.overline; }
350
+ osc8Uri(): string { return this.uriValue; }
351
+ }
352
+
353
+ class SnapshotLine implements BufferLineLike {
354
+ constructor(readonly cells: SnapshotCell[]) {}
355
+ get length(): number { return this.cells.length; }
356
+ getCell(x: number): BufferCellLike | undefined { return this.cells[x]; }
357
+ translateToString(trimRight = false): string {
358
+ const text = this.cells.map((cell) => cell.getChars() || " ").join("");
359
+ return trimRight ? text.replace(/\s+$/u, "") : text;
360
+ }
361
+ }
362
+
164
363
  type MousePoint = { line: number; col: number };
165
364
  type ScreenCell = { row: number; col: number };
365
+ /** Issue #278: one ownership-adapter transition (attach-screen-owner.mjs). */
366
+ type AttachScreenOwnerTransition = {
367
+ previous: { syncOpen: boolean; externalOutputActive: boolean };
368
+ current: { syncOpen: boolean; externalOutputActive: boolean };
369
+ syncOpenMarker: boolean;
370
+ syncCloseMarker: boolean;
371
+ };
166
372
  /** Issue #187: `screenAnchor` is the RAW reported cell of the press; the drag/click
167
373
  * decision compares it against the release cell, because buffer coordinates drift
168
374
  * while the session streams. Absent on word selections (they are created on release). */
@@ -232,7 +438,106 @@ export class PtyAttachComponent implements Component {
232
438
  // configurable via $AGENT_BOARD_WHEEL_LINES. The fullscreen handleMouse path uses
233
439
  // the TUI's wheelDelta instead, which is already accelerated and line-quantified.
234
440
  private readonly mouseWheelLines = resolveWheelLines();
235
- private readonly term: XtermLike;
441
+ /** Current local parser. Replaced atomically at an accepted snapshotReady. */
442
+ private term: XtermLike;
443
+ private kittyImages: ReturnType<typeof createPtyKittyImages> | null;
444
+ /** Monotonic identity axes: one per accepted socket / authoritative baseline / parser. */
445
+ private connectionToken = 0;
446
+ private baselineToken = 0;
447
+ private parserEpoch = 1;
448
+ private parserObservers: Array<{ dispose(): void }> = [];
449
+ private parserObservationSupported = true;
450
+ private replacementFailureCount = 0;
451
+ private parserSyncOpen = false;
452
+ private parserObserverEvents = 0;
453
+ /** Issue #278: true while an external editor (Ctrl+G Nvim) owns the child screen. */
454
+ private externalOutputActive = false;
455
+ /** Set when an ownership transition arrived while an authoritative frame was
456
+ * hydrating: the frame's own wrapper sync window must not clear external
457
+ * ownership, so the adapter is re-synced from component state once the
458
+ * hydration write completes (design D7: suspend, then preserve). */
459
+ private screenOwnerResyncPending = false;
460
+ private collectingConnectionToken = 0;
461
+ private collectingBaselineToken = 0;
462
+ private collectingParserEpoch = 0;
463
+ /** Distinct facts; none of these is presentation truth in this stage. */
464
+ private protocolBaselineState: "unverified" | "valid-empty" | "valid-content" = "unverified";
465
+ private localHydrationState: "idle" | "hydrating" | "complete" | "failed" = "idle";
466
+ private publishabilityState: "wait" | "unknown" | "ready" = "wait";
467
+ private firstAttachSideEffectsApplied = false;
468
+ private latestViewProof: unknown = null;
469
+ private viewProofRecords: unknown[] = [];
470
+ private viewProofRecordCount = 0;
471
+ /** Identity captured when the current proof/coverage was received. */
472
+ private viewProofIdentity: ReturnType<PtyAttachComponent["currentViewIdentity"]> | null = null;
473
+ /** Local geometry revision: incremented once per real differing-size transition. */
474
+ private geometryRevision = 0;
475
+ private resizeIntentRequired = false;
476
+ private resizeIntentSatisfied = false;
477
+ /** Issue #294: seq of the F record that proved the current intent (gate
478
+ * freshness fact: the evidence must not postdate the covered window). */
479
+ private resizeIntentProofSeq: number | null = null;
480
+ private resizeIntentId = 0;
481
+ private pendingEarlySyncTarget: string | null = null;
482
+ /** Protocol transition facts; timers may mark expiry but never publish. */
483
+ private deadlineState: "pending" | "expired" = "pending";
484
+ private notReadyReason: string | null = null;
485
+ private parserWritesInFlight = 0;
486
+ private readonly attachStartedAt: number;
487
+ private readonly viewProofTrailing = createSafeTrailingClassifier();
488
+ private recentProtocolOutput: Array<{ seq: number; data: string }> = [];
489
+ private proofResyncRequested = false;
490
+ /** Runner-reported reporter capability. Without it the attach keeps the
491
+ * accepted legacy deadline path (old/no-reporter hosts are not stranded). */
492
+ private frameWitnessAvailable = false;
493
+ /** Issue #284 latch layer (spec §3.3/I6): set once when frameWitnessAvailable
494
+ * first becomes true during THIS attach. Capability loss never clears it —
495
+ * the attach stays on the committed presentation path (no legacy deadline
496
+ * restore) until detach/dispose; same-component reconnects and view-layer
497
+ * invalidations (resnapshot/reset/baseline change) leave it alone. */
498
+ private witnessLatched = false;
499
+ /** Issue #284 failure-fact layer (spec §3.1.1/I6): the baseline token an
500
+ * unrecovered invalid proof classification was recorded on. The effective
501
+ * sticky state is (token === baselineToken). Recovery is PUBLISH-ONLY: a
502
+ * covered classification alone never clears it, because coverage is
503
+ * established before the full-view policy validates
504
+ * sequence/metadata/geometry/intent/identity — a wrong-geometry F would
505
+ * otherwise wash the sticky fact and re-open the degraded path. Only
506
+ * evaluateAttachReady's policy "publish" on the current baseline/identity
507
+ * (or a new baseline identity via replaceParser at an accepted
508
+ * snapshotReady, which rebinds it) clears/rebinds it. Capability loss —
509
+ * which nulls latestViewProof — deliberately keeps it. */
510
+ private proofInvalidatedBaselineToken: number | null = null;
511
+ /** Issue #288 D1/I8 hard-dominance latch: the baseline token a HARD invalid
512
+ * family classification (classifyProofInvalidFamily === "hard") latched
513
+ * on; the effective state is (token === baselineToken), exactly like the
514
+ * sticky failure fact. Hard dominance: once latched, later trailing
515
+ * shapes, other non-covered shapes, capability loss, S records, and
516
+ * missing proofs NEVER clear it — the cap floor stays closed for this
517
+ * baseline. Cleared only where the sticky fact clears: the policy PUBLISH
518
+ * branch (a fully valid F) or a baseline identity change (replaceParser
519
+ * increments baselineToken, so the stale binding goes inactive). The
520
+ * cap-floor publish-degraded deliberately does NOT clear it (I7). */
521
+ private proofHardInvalidatedThisBaseline: number | null = null;
522
+ /** Last §3.1.1 classification assembled for the policy (diagnostics/readout). */
523
+ private lastProofStatus: "none" | "missing" | "invalid" | "covered" | null = null;
524
+ /** Sticky-state twin of the classification (diagnostics/readout): mirrors
525
+ * the POST-update sticky state — (proofInvalidatedBaselineToken ===
526
+ * baselineToken) AFTER the classification applied its binding change, so
527
+ * the invalidation (false→true) and publish recovery (true→false)
528
+ * transitions are both visible to settle readouts. */
529
+ private lastProofStickyInvalid = false;
530
+ /** Issue #284 §3.4: which path settled this attach; null while still
531
+ * waiting (the wait reason stays in notReadyReason, semantics unchanged). */
532
+ private readyReason: AttachReadyReason | null = null;
533
+ /** Last complete modern projection installed at a real ?2026l boundary. */
534
+ private committedView: CommittedView | null = null;
535
+ /** Display-only same-generation/geometry recovery view; never readiness. */
536
+ private recoveryView: CommittedView | null = null;
537
+ private recoveryGeneration: string | null = null;
538
+ private currentWireGeneration: string | null = null;
539
+ private emptyResetPending = false;
540
+ private attachWaitToken = 0;
236
541
  private cols = 120;
237
542
  private rows = 24;
238
543
  // Absolute buffer line shown at the top of the viewport. null means follow bottom.
@@ -248,10 +553,12 @@ export class PtyAttachComponent implements Component {
248
553
  private desyncProbeTimer: ReturnType<typeof setInterval> | null = null;
249
554
  /** Injectable clock for desync gating (tests override this). */
250
555
  private nowFn: () => number = () => Date.now();
556
+ /** Issue #284: attach-lifecycle clock (deadlines + attach timers). */
557
+ private readonly clock: AttachClock;
251
558
  private selection: MouseSelection | null = null;
252
- /** Issue #172: bumped on every left press so a settle still queued for the previous
253
- * gesture cannot read or clear a selection the next press has already started. */
254
- private selectionGestureSerial = 0;
559
+ /** Issue #172/#174/#258: the shared settle core owns the gesture serial, the
560
+ * deferral and the closed gate; attach supplies only the X11 PRIMARY mirror. */
561
+ private readonly selectionSettler: ReturnType<typeof createFullscreenSelectionSettler>;
255
562
  private selectionDragging = false;
256
563
  private selectionAutoScrollTimer: ReturnType<typeof setInterval> | null = null;
257
564
  private selectionAutoScrollLines = 0;
@@ -271,8 +578,25 @@ export class PtyAttachComponent implements Component {
271
578
  // initial resize-jiggle redraws settle, so attach never visibly scrolls/flashes the
272
579
  // buffer. `receivedOutput` tracks buffer content; `attaching` gates whether we paint it.
273
580
  private attaching = true;
274
- private attachSettleTimer: ReturnType<typeof setTimeout> | null = null;
275
- private attachHardTimeout: ReturnType<typeof setTimeout> | null = null;
581
+ private attachSettleTimer: unknown = null;
582
+ private attachHardTimeout: unknown = null;
583
+ // Issue #284 recovery budget: armed ONCE per attach lifetime at the first
584
+ // startAttachSettle entry (deadline = attachStartedAt + 250ms). Reconnect
585
+ // re-entry must never re-arm or extend it (I5). The callback is fenced by
586
+ // the attach lifetime itself — attaching && !closed && budgetArmed — NOT by
587
+ // attachWaitToken: that token increments on every startAttachSettle re-entry
588
+ // and would permanently invalidate the armed callback after a reconnect
589
+ // (spec §3.2 fence lifecycle). Stale-connection views stay blocked by the
590
+ // identity fence (I3) instead.
591
+ private attachRecoveryBudgetTimer: unknown = null;
592
+ private budgetArmed = false;
593
+ /** Issue #288 D2: which wait phases already recorded their wait diagnostic
594
+ * — single-shot per phase per attach (the budgetArmed fence pattern). */
595
+ private attachWaitDiagnosticEmitted: { budget: boolean; cap: boolean } = { budget: false, cap: false };
596
+ /** Timer fact only: the budget deadline passed while this attach was still
597
+ * waiting. Publishing on it is the policy's decision (T6 wiring), never the
598
+ * timer's. */
599
+ private budgetElapsed = false;
276
600
  // Last scheme delivered to the child at settle (issue #161). Starts null:
277
601
  // null never matches the duplicate check, so a timeout-then-late sequence
278
602
  // still delivers. Single-shot per attach — settle runs at most once.
@@ -308,6 +632,20 @@ export class PtyAttachComponent implements Component {
308
632
  private readonly done: (result: PtyAttachResult) => void,
309
633
  private readonly opts: PtyAttachOptions,
310
634
  ) {
635
+ // Issue #284 clock seam: assigned from the constructor parameter (not a
636
+ // field initializer) so it is set regardless of the loader's field-init
637
+ // semantics, before any attach-lifecycle deadline is computed. Output
638
+ // timestamps (nowFn) follow the injected clock too, so legacy deadline
639
+ // math never mixes virtual and wall time.
640
+ this.clock = opts.clock ?? hostAttachClock;
641
+ this.attachStartedAt = this.clock.now();
642
+ if (opts.clock) this.nowFn = opts.clock.now;
643
+ this.selectionSettler = createFullscreenSelectionSettler({
644
+ host: this.tui as FullscreenSelectionHost,
645
+ mirror: (text) => this.writePrimarySelection(text),
646
+ repaint: () => this.scheduleRender(),
647
+ shouldSettle: () => !this.closed,
648
+ });
311
649
  const size = this.currentSize();
312
650
  this.cols = size.cols;
313
651
  this.rows = size.rows;
@@ -315,6 +653,12 @@ export class PtyAttachComponent implements Component {
315
653
  // parameter property is set regardless of the TS loader's field-init semantics.
316
654
  this.imeCoalesceUninstall = installImeCursorCoalesce(this.tui);
317
655
  this.term = new Terminal({ cols: this.cols, rows: this.rows, scrollback: 2000, allowProposedApi: true });
656
+ this.kittyImages = process.env.AGENT_BOARD_FORWARD_IMAGES !== "0"
657
+ ? createPtyKittyImages(this.term, () => { this.historyFloor = 0; })
658
+ : null;
659
+ this.parserObservers = this.installParserObservers(this.term, this.parserEpoch);
660
+ this.parserObservationSupported = this.parserObservers.length > 0;
661
+ if (!this.parserObservationSupported) this.attachClient.forceLegacy("parser_observation_unavailable");
318
662
  // Keep mouse reporting enabled by default so wheel scrolling and local drag-to-copy
319
663
  // selection can coexist inside the attach surface. Set AGENT_BOARD_ATTACH_MOUSE=0
320
664
  // to fall back to terminal-native selection only.
@@ -431,25 +775,11 @@ export class PtyAttachComponent implements Component {
431
775
  this.send({ type: "input", data });
432
776
  return;
433
777
  }
434
- if (matchesKey(data, "ctrl+\\")) {
435
- // Unconditional, terminal-independent escape (issue #126): 0x1c is a
436
- // single raw ASCII byte every terminal forwards unchanged in raw
437
- // mode — no modifier-encoding dependency like Ctrl+Left (macOS
438
- // Terminal.app never emits it, WezTerm consumes it for tab
439
- // switching). Only caveat (documented in README): layouts where
440
- // `\` sits on AltGr may never produce this byte; the escape ladder
441
- // still covers those. matchesKey also covers the kitty CSI-u and
442
- // modifyOtherKeys encodings of the same chord.
443
- this.detach();
444
- return;
445
- }
446
- if (matchesKey(data, Key.ctrl("left"))) {
447
- // Explicit detach chord (issue #89): single ← is gated on editor state
448
- // (it doubles as cursor-left inside a non-empty draft), so a user with
449
- // a draft had no way out short of Ctrl+C/D, which kills the child Pi.
450
- // Ctrl+← is unambiguous intent — detach unconditionally, regardless of
451
- // editor state or socket liveness (same always-exitable guarantee as
452
- // the disconnected-← escape, issue #48).
778
+ if (resolveAttachDetachChord(data)) {
779
+ // Issue #266: unconditional detach chords — Ctrl+\ (raw 0x1c, #126),
780
+ // Ctrl+← (#89) and Alt+H (vim h = left). Bare ← stays gated on the
781
+ // pushed editor_state; a chord needs no gate. Rationale and the
782
+ // encoding matrix live in src/core/attach-detach.mjs.
453
783
  this.detach();
454
784
  return;
455
785
  }
@@ -533,21 +863,10 @@ export class PtyAttachComponent implements Component {
533
863
  return { handled: true, render: false };
534
864
  }
535
865
  const nativePasteEnabled = process.env.AGENT_BOARD_ATTACH_NATIVE_PASTE !== "0";
536
- // Issue #172: a press starts a new gesture. Two reports can share one stdin chunk
537
- // (pi-tui emits them synchronously in a loop), so the settle queued by the previous
538
- // release must not consume the selection this press just started.
539
- if (event.type === "press" && event.button === "left") this.selectionGestureSerial += 1;
540
- if (isFullscreenSelectionEnd(event)) {
541
- // Observe only — pi's fullscreen selection keeps the event. Overlays are
542
- // dispatched before TuiAltScreen finalizes (and copies) the selection for this
543
- // event, so settling must run deferred (issue #174).
544
- const serial = this.selectionGestureSerial;
545
- process.nextTick(() => {
546
- if (serial !== this.selectionGestureSerial) return;
547
- this.settleFullscreenSelection(nativePasteEnabled);
548
- });
549
- return undefined;
550
- }
866
+ // Issue #172 + #258: observe the gesture; the shared settler owns the
867
+ // serial guard, the deferral and the lifecycle gate.
868
+ this.selectionSettler.observeMouse(event);
869
+ if (isFullscreenSelectionEnd(event)) return undefined;
551
870
  const action = resolveAttachMouseAction(event, { nativePasteEnabled });
552
871
  if (action !== "paste-primary") return undefined;
553
872
  this.clearPendingClick();
@@ -557,22 +876,26 @@ export class PtyAttachComponent implements Component {
557
876
  }
558
877
 
559
878
  render(width: number): string[] {
879
+ if (this.closed) return [];
560
880
  this.resizeIfNeeded(width);
561
881
  const height = this.tui.terminal?.rows ?? 24;
562
882
  const bodyHeight = Math.max(1, height - 2);
563
883
  let body: string[];
564
- if (!this.attaching && this.receivedOutput) {
884
+ if (this.modernCommittedMode() && this.emptyResetPending) {
885
+ body = Array.from({ length: bodyHeight }, () => "");
886
+ } else if (!this.attaching && this.receivedOutput) {
565
887
  const projected = this.project(bodyHeight);
566
888
  body = projected.lines;
567
889
  while (body.length < bodyHeight) body.unshift("");
568
890
  } else {
569
891
  body = this.renderLoading(bodyHeight, width);
570
892
  }
893
+ const headerTitle = this.opts.prLabel ? `${this.opts.title} · ${this.opts.prLabel}` : this.opts.title;
571
894
  const header = this.confirmArmed
572
895
  ? this.theme.fg("accent", this.theme.bold(` Delete "${truncateToWidth(this.opts.title, 24, "")}"? `)) +
573
896
  this.theme.fg("muted", "y confirms · any other key cancels")
574
- : this.theme.fg("accent", this.theme.bold(` ${this.opts.title} `)) +
575
- this.theme.fg("muted", `${this.status} · opens links · drag selects+copies · Ctrl+←/Ctrl+\\ detach`);
897
+ : this.theme.fg("accent", this.theme.bold(` ${headerTitle} `)) +
898
+ this.theme.fg("muted", `${this.status} · links · select+copy · Ctrl+←/Ctrl+\\/Alt+H detach`);
576
899
  return [clip(header, width), ...body.map((l) => clipTerminalLine(l, width)), this.theme.fg("dim", "─".repeat(width))];
577
900
  }
578
901
 
@@ -588,7 +911,7 @@ export class PtyAttachComponent implements Component {
588
911
  out.push(center(this.theme.fg("accent", this.theme.bold(title)), width));
589
912
  out.push(center(this.theme.fg("muted", detail), width));
590
913
  out.push("");
591
- out.push(center(this.theme.fg("dim", "Ctrl+←/Ctrl+\\ to detach"), width));
914
+ out.push(center(this.theme.fg("dim", "Ctrl+←/Ctrl+\\/Alt+H to detach"), width));
592
915
  while (out.length < height) out.push("");
593
916
  return out.slice(0, height);
594
917
  }
@@ -626,6 +949,154 @@ export class PtyAttachComponent implements Component {
626
949
  this.done({ action: "detached" });
627
950
  }
628
951
 
952
+ /** Install the component's public ?2026 observers; false return keeps xterm defaults.
953
+ * Issue #278: the ownership adapter tracks ?2026 sync windows around ?1049
954
+ * alt-screen exits so external editor output can be projected live. */
955
+ private installParserObservers(term: XtermLike, epoch: number): Array<{ dispose(): void }> {
956
+ try {
957
+ return installAttachScreenOwnerObservers(term, {
958
+ initialState: createAttachScreenOwnerState(this.externalOutputActive),
959
+ // The .mjs adapter infers an untyped default callback; the transition
960
+ // handler below carries the exact shape (cast at this assignment only).
961
+ onTransition: ((info: AttachScreenOwnerTransition) => {
962
+ this.handleScreenOwnerTransition(term, epoch, info);
963
+ }) as () => void,
964
+ });
965
+ } catch {
966
+ return [];
967
+ }
968
+ }
969
+
970
+ /** Apply one ownership-adapter transition to the component: sync-window
971
+ * bookkeeping, interaction cleanup on an external-flag change, and the
972
+ * committed-view commit at a real sync close. */
973
+ private handleScreenOwnerTransition(term: XtermLike, epoch: number, { previous, current, syncOpenMarker, syncCloseMarker }: AttachScreenOwnerTransition): void {
974
+ if (this.closed || this.term !== term || this.parserEpoch !== epoch) return;
975
+ this.parserSyncOpen = current.syncOpen;
976
+ if (syncOpenMarker || syncCloseMarker) this.parserObserverEvents += 1;
977
+ if (current.externalOutputActive !== previous.externalOutputActive) {
978
+ if (this.localHydrationState === "hydrating") {
979
+ // Runner-synthesized hydration frames wrap their content in their own
980
+ // ?2026 window; that wrapper clear is not a real ownership return.
981
+ this.screenOwnerResyncPending = true;
982
+ } else if (this.attachMode !== "legacy") {
983
+ this.externalOutputActive = current.externalOutputActive;
984
+ this.resetExternalProjectionInteraction();
985
+ }
986
+ // Legacy mode: no adoption and no interaction cleanup — a Ctrl+G handoff
987
+ // must not destroy selection/scroll state on the raw-buffer surface.
988
+ }
989
+ if (syncCloseMarker) this.commitCommittedView(term, epoch, "sync-close");
990
+ }
991
+
992
+ /** Reinstall the ownership observers on the current parser after a hydration
993
+ * window that suppressed frame-wrapper ownership transitions: the adapter
994
+ * re-initializes from the component's preserved external ownership. The
995
+ * observed sync-window position is kept; failure keeps the old observers. */
996
+ private resyncScreenOwnerAdapter(term: XtermLike, epoch: number): void {
997
+ const syncOpen = this.parserSyncOpen;
998
+ const observers = this.installParserObservers(term, epoch);
999
+ if (observers.length === 0) return;
1000
+ for (const observer of this.parserObservers) {
1001
+ try { observer.dispose(); } catch { /* best effort */ }
1002
+ }
1003
+ this.parserObservers = observers;
1004
+ this.parserSyncOpen = syncOpen;
1005
+ }
1006
+
1007
+ /** Side-effect boundary for an external-ownership change: stale Pi interaction
1008
+ * geometry (viewport/selection/clicks) must not leak onto the external or
1009
+ * restored surface. Never sends input and never forces a parser read. */
1010
+ private resetExternalProjectionInteraction(): void {
1011
+ this.clearSelectionAutoScroll();
1012
+ this.clearPendingClick();
1013
+ this.selection = null;
1014
+ this.selectionDragging = false;
1015
+ this.lastClickPoint = null;
1016
+ this.lastClickAt = 0;
1017
+ this.viewportTop = null;
1018
+ }
1019
+
1020
+ /**
1021
+ * Replace the local parser exactly at an accepted authoritative snapshotReady:
1022
+ * same constructor options, observers installed before the first frame write.
1023
+ * Creation/observer failure is fail-closed (old parser retained, no write).
1024
+ */
1025
+ private replaceParser(): boolean {
1026
+ // Preserve the last complete same-generation view before a nonempty
1027
+ // resnapshot replaces the parser. An empty baseline clears it later in
1028
+ // the same snapshotReady event.
1029
+ this.captureRecoveryView();
1030
+ let next: XtermLike;
1031
+ try {
1032
+ next = new Terminal({ cols: this.cols, rows: this.rows, scrollback: 2000, allowProposedApi: true });
1033
+ } catch {
1034
+ return false;
1035
+ }
1036
+ const nextEpoch = this.parserEpoch + 1;
1037
+ const observers = this.installParserObservers(next, nextEpoch);
1038
+ let nextImages: ReturnType<typeof createPtyKittyImages> | null = null;
1039
+ try {
1040
+ if (this.kittyImages) nextImages = createPtyKittyImages(next, () => { this.historyFloor = 0; });
1041
+ } catch {
1042
+ for (const observer of observers) observer.dispose();
1043
+ try { next.dispose?.(); } catch { /* best effort */ }
1044
+ return false;
1045
+ }
1046
+ if (observers.length === 0) {
1047
+ nextImages?.dispose();
1048
+ try { next.dispose?.(); } catch { /* best effort */ }
1049
+ return false;
1050
+ }
1051
+ const previous = this.term;
1052
+ const previousObservers = this.parserObservers;
1053
+ const previousImages = this.kittyImages;
1054
+ this.term = next;
1055
+ this.kittyImages = nextImages;
1056
+ this.parserObservers = observers;
1057
+ this.parserEpoch = nextEpoch;
1058
+ this.baselineToken += 1;
1059
+ this.replacementFailureCount = 0;
1060
+ this.parserObservationSupported = true;
1061
+ this.parserSyncOpen = false;
1062
+ this.parserWritesInFlight = 0;
1063
+ this.committedView = null;
1064
+ this.historyFloor = 0;
1065
+ this.viewportTop = null;
1066
+ this.selection = null;
1067
+ this.selectionDragging = false;
1068
+ this.localHydrationState = "idle";
1069
+ for (const observer of previousObservers) {
1070
+ try { observer.dispose(); } catch { /* best effort */ }
1071
+ }
1072
+ previousImages?.dispose();
1073
+ try { previous.dispose?.(); } catch { /* best effort */ }
1074
+ return true;
1075
+ }
1076
+
1077
+ private disposeCurrentParser(): void {
1078
+ for (const observer of this.parserObservers) {
1079
+ try { observer.dispose(); } catch { /* best effort */ }
1080
+ }
1081
+ this.parserObservers = [];
1082
+ this.kittyImages?.dispose();
1083
+ this.kittyImages = null;
1084
+ try { this.term.dispose?.(); } catch { /* best effort */ }
1085
+ }
1086
+
1087
+ /** Bounded fail-closed policy for a failed authoritative parser replacement. */
1088
+ private handleParserReplacementFailure(): void {
1089
+ this.protocolBaselineState = "unverified";
1090
+ this.localHydrationState = "failed";
1091
+ this.publishabilityState = "wait";
1092
+ this.latestViewProof = null;
1093
+ this.viewProofRecords = [];
1094
+ this.viewProofRecordCount = 0;
1095
+ this.replacementFailureCount += 1;
1096
+ if (this.replacementFailureCount <= 3) this.attachClient.requestResync("parser_replacement_failed");
1097
+ else this.attachClient.forceLegacy("parser_replacement_failed");
1098
+ }
1099
+
629
1100
  private connect(): void {
630
1101
  if (this.closed || this.connected || this.socket) return;
631
1102
  // On Windows the control socket is a named pipe — it never exists as a
@@ -647,10 +1118,25 @@ export class PtyAttachComponent implements Component {
647
1118
  return;
648
1119
  }
649
1120
  this.clearRetry();
1121
+ this.outputRenderScheduler.cancel();
1122
+ this.captureRecoveryView();
650
1123
  this.connected = true;
651
1124
  this.everConnected = true;
1125
+ this.connectionToken += 1;
1126
+ this.committedView = null;
1127
+ // Issue #284 view layer (I6): a connection-generation change also
1128
+ // invalidates the old proof facts — only the new connection's
1129
+ // snapshot/records may re-establish them. The latch survives: it is
1130
+ // attach-scoped, not connection-scoped.
1131
+ this.latestViewProof = null;
1132
+ this.viewProofIdentity = null;
1133
+ this.viewProofTrailing.reset();
1134
+ this.currentWireGeneration = null;
1135
+ // Do not paint the previous generation between reconnect and its
1136
+ // confirming hello/status; same-generation status clears this gate.
1137
+ this.emptyResetPending = true;
652
1138
  this.disconnectedAt = null;
653
- this.status = "attached";
1139
+ this.status = this.recoveryView !== null ? "reconnecting…" : "attached";
654
1140
  this.send({ type: "hello", clientId: `ui-${Date.now()}`, wantOutput: true });
655
1141
  // Snapshot+subscribe attach (issue #91 phase 4): the first connect
656
1142
  // probes with subscribe_terminal (old runners stay silent → probe
@@ -665,7 +1151,7 @@ export class PtyAttachComponent implements Component {
665
1151
  // so the jiggle never runs there (armLegacyJiggle guards the race).
666
1152
  this.armLegacyJiggle();
667
1153
  this.enableMouseScroll();
668
- this.scheduleRender();
1154
+ if (!this.emptyResetPending) this.scheduleRender();
669
1155
  this.startAttachSettle();
670
1156
  });
671
1157
  socket.on("data", (chunk) => {
@@ -676,6 +1162,7 @@ export class PtyAttachComponent implements Component {
676
1162
  // A failed socket can close after a replacement connection has already
677
1163
  // succeeded. Never let that stale event clear the replacement state.
678
1164
  if (this.socket !== socket) return;
1165
+ this.captureRecoveryView();
679
1166
  this.socket = null;
680
1167
  this.connected = false;
681
1168
  this.disconnectedAt ??= Date.now();
@@ -697,6 +1184,7 @@ export class PtyAttachComponent implements Component {
697
1184
  try { socket.destroy(); } catch { /* best-effort stale-socket cleanup */ }
698
1185
  return;
699
1186
  }
1187
+ this.captureRecoveryView();
700
1188
  this.socket = null;
701
1189
  this.connected = false;
702
1190
  // Notify before nulling: the close event that follows will hit the
@@ -767,22 +1255,547 @@ export class PtyAttachComponent implements Component {
767
1255
  */
768
1256
  private startAttachSettle(): void {
769
1257
  if (!this.attaching) return;
1258
+ this.armAttachRecoveryBudget();
1259
+ this.attachWaitToken += 1;
1260
+ const waitToken = this.attachWaitToken;
770
1261
  this.deferAttachSettle();
771
- if (!this.attachHardTimeout) {
772
- this.attachHardTimeout = setTimeout(() => this.finishAttachTransition(), ATTACH_HARD_TIMEOUT_MS);
773
- this.attachHardTimeout.unref?.();
1262
+ if (this.attachHardTimeout !== null) this.clock.clear(this.attachHardTimeout);
1263
+ const remainingHard = Math.max(0, ATTACH_HARD_TIMEOUT_MS - (this.clock.now() - this.attachStartedAt));
1264
+ this.attachHardTimeout = this.clock.schedule(() => this.handleAttachHardTimeout(waitToken), remainingHard);
1265
+ }
1266
+
1267
+ /** Arm the recovery budget once per attach lifetime; every later
1268
+ * startAttachSettle re-entry (reconnect) is a no-op so the deadline never
1269
+ * moves (I5). */
1270
+ private armAttachRecoveryBudget(): void {
1271
+ if (this.budgetArmed || this.closed || !this.attaching) return;
1272
+ this.budgetArmed = true;
1273
+ const remaining = Math.max(0, ATTACH_RECOVERY_BUDGET_MS - (this.clock.now() - this.attachStartedAt));
1274
+ this.attachRecoveryBudgetTimer = this.clock.schedule(() => this.handleAttachRecoveryBudgetTimeout(), remaining);
1275
+ }
1276
+
1277
+ /** Budget expiry records the timer fact and re-evaluates readiness at the
1278
+ * shared convergence point. The fence is the attach lifetime only (spec
1279
+ * §3.2): a settled or closed component records nothing. */
1280
+ private handleAttachRecoveryBudgetTimeout(): void {
1281
+ this.attachRecoveryBudgetTimer = null;
1282
+ if (!this.budgetArmed || !this.attaching || this.closed) return;
1283
+ this.budgetElapsed = true;
1284
+ // Issue #288 D2: the budget expiry leaves on-disk wait evidence — emitted
1285
+ // BEFORE the policy re-evaluation so a settle it triggers always follows
1286
+ // the budget record (A4 ordering).
1287
+ this.emitAttachWaitExpiredDiagnostic("budget");
1288
+ this.evaluateAttachReady();
1289
+ }
1290
+
1291
+ private clearAttachRecoveryBudget(): void {
1292
+ if (this.attachRecoveryBudgetTimer !== null) {
1293
+ this.clock.clear(this.attachRecoveryBudgetTimer);
1294
+ this.attachRecoveryBudgetTimer = null;
774
1295
  }
775
1296
  }
776
1297
 
777
1298
  private deferAttachSettle(): void {
778
- if (!this.attaching) return;
779
- if (this.attachSettleTimer) clearTimeout(this.attachSettleTimer);
780
- this.attachSettleTimer = setTimeout(() => this.finishAttachTransition(), ATTACH_SETTLE_MS);
781
- this.attachSettleTimer.unref?.();
1299
+ // Protocol sessions never defer the legacy settle; a LATCHED session
1300
+ // stays on that path even after capability loss (issue #284 I6) — a
1301
+ // post-loss reconnect/output must not resurrect the legacy settle.
1302
+ if (!this.attaching || this.modernCommittedMode()) return;
1303
+ if (this.attachSettleTimer !== null) this.clock.clear(this.attachSettleTimer);
1304
+ const waitToken = this.attachWaitToken;
1305
+ this.attachSettleTimer = this.clock.schedule(() => this.handleAttachSettleTimeout(waitToken), ATTACH_SETTLE_MS);
1306
+ }
1307
+
1308
+ /** Legacy settle callback. In protocol mode the timer is cancelled; an
1309
+ * undecided timer may not consume the first transition either. */
1310
+ private handleAttachSettleTimeout(waitToken = this.attachWaitToken): void {
1311
+ if (waitToken !== this.attachWaitToken) return;
1312
+ this.attachSettleTimer = null;
1313
+ if (!this.attaching || this.closed) return;
1314
+ // A latched protocol attach is never legacy-compatible: capability loss
1315
+ // keeps the committed path (issue #284 I6), so this timer may not consume
1316
+ // the transition for it.
1317
+ const legacyCompatible = this.attachMode === "legacy" || (this.attachMode === "protocol" && !this.modernCommittedMode());
1318
+ if (legacyCompatible) this.finishAttachTransition("legacy-settle");
1319
+ }
1320
+
1321
+ /** The 2500 ms cap never forces a modern publish of an UNFINISHED frame. It
1322
+ * records an explicit expired wait and hands the decision to the readiness
1323
+ * policy: the 250 ms recovery budget (armed once at attach start) has long
1324
+ * elapsed by then, so the degraded chain alone decides whether a safely
1325
+ * committed view may be revealed — the #265 idle-downgrade special case is
1326
+ * deleted (issue #284 §3.2); the policy owns every reveal. Legacy keeps its
1327
+ * old reveal. */
1328
+ private handleAttachHardTimeout(waitToken = this.attachWaitToken): void {
1329
+ if (waitToken !== this.attachWaitToken) return;
1330
+ this.attachHardTimeout = null;
1331
+ if (!this.attaching || this.closed) return;
1332
+ // Same latch rule as the settle timeout: a latched attach never falls
1333
+ // back to the legacy reveal branch (issue #284 I6).
1334
+ const legacyCompatible = this.attachMode === "legacy" || (this.attachMode === "protocol" && !this.modernCommittedMode());
1335
+ if (legacyCompatible) {
1336
+ this.finishAttachTransition("legacy-cap");
1337
+ return;
1338
+ }
1339
+ this.deadlineState = "expired";
1340
+ this.notReadyReason = this.attachMode === "protocol" ? "deadline-expired:waiting-for-complete-frame" : "deadline-expired:mode-undecided";
1341
+ this.publishabilityState = "unknown";
1342
+ // Issue #288 D2: the cap expiry is the second wait phase — recorded after
1343
+ // the deadline state flip (and after the budget record, which fired at
1344
+ // 250ms) and before the policy re-evaluation, so a cap-floor settle it
1345
+ // triggers still lands after both wait records (A4 ordering).
1346
+ this.emitAttachWaitExpiredDiagnostic("cap");
1347
+ this.evaluateAttachReady();
1348
+ this.scheduleRender();
782
1349
  }
783
1350
 
784
- private finishAttachTransition(): void {
785
- if (!this.attaching) return;
1351
+ /** A late legacy decision restores the ORIGINAL deadlines (remaining time),
1352
+ * not a fresh extended window. */
1353
+ private restoreLegacyDeadlines(): void {
1354
+ if (!this.attaching || this.closed) return;
1355
+ const now = this.clock.now();
1356
+ if (now - this.attachStartedAt >= ATTACH_HARD_TIMEOUT_MS) {
1357
+ this.finishAttachTransition("legacy-cap");
1358
+ return;
1359
+ }
1360
+ const settleBase = this.lastOutputAt > 0 ? this.lastOutputAt : this.attachStartedAt;
1361
+ const remaining = Math.max(0, ATTACH_SETTLE_MS - (now - settleBase));
1362
+ if (this.attachSettleTimer !== null) this.clock.clear(this.attachSettleTimer);
1363
+ const waitToken = this.attachWaitToken;
1364
+ this.attachSettleTimer = this.clock.schedule(() => this.handleAttachSettleTimeout(waitToken), remaining);
1365
+ if (this.attachHardTimeout === null) {
1366
+ this.attachHardTimeout = this.clock.schedule(() => this.handleAttachHardTimeout(waitToken), Math.max(0, ATTACH_HARD_TIMEOUT_MS - (now - this.attachStartedAt)));
1367
+ }
1368
+ }
1369
+
1370
+ private currentViewIdentity() {
1371
+ return {
1372
+ connectionToken: this.connectionToken,
1373
+ baselineToken: this.baselineToken,
1374
+ generation: this.attachClient.getIdentity().generation ?? "local",
1375
+ parser: this.term,
1376
+ geometryRevision: this.geometryRevision,
1377
+ targetCols: this.cols,
1378
+ targetRows: this.rows,
1379
+ closed: this.closed,
1380
+ };
1381
+ }
1382
+
1383
+ /** Snapshot the visible complete grid at a real close boundary. Only
1384
+ * primitives are copied; no xterm BufferLine/Cell survives this call.
1385
+ * `source` records which path captured the grid (spec §3.1 predicate 7):
1386
+ * "snapshot" — the authoritative hydration write of a validated non-empty
1387
+ * snapshot frame; "sync-close" — a locally parsed closed ?2026 sync frame. */
1388
+ private commitCommittedView(term: XtermLike, epoch: number, source: "snapshot" | "sync-close"): void {
1389
+ if (this.closed || this.term !== term || this.parserEpoch !== epoch) return;
1390
+ if (!this.modernCommittedMode() || this.localHydrationState === "hydrating") return;
1391
+ const height = this.bodyHeight();
1392
+ const buf = term.buffer.active;
1393
+ const start = Math.max(0, Math.min(this.viewportTop ?? this.liveBottomViewportTop(height), Math.max(0, buf.length - height)));
1394
+ const end = Math.min(buf.length, start + height);
1395
+ const rows: CommittedRow[] = [];
1396
+ // Capture image APCs with the committed grid so recovery can outlive
1397
+ // the parser and its Kitty markers during an authoritative resnapshot.
1398
+ const kittyLines = this.kittyImages?.hasPlacements() ? this.kittyImages.project(Array(end - start).fill(""), start, end - start) : undefined;
1399
+ for (let lineIndex = start; lineIndex < end; lineIndex += 1) {
1400
+ const line = buf.getLine(lineIndex);
1401
+ const cells: SnapshotCell[] = [];
1402
+ if (line) {
1403
+ for (let x = 0; x < line.length; x += 1) {
1404
+ const cell = line.getCell(x);
1405
+ if (!cell || cell.getWidth() === 0) {
1406
+ cells.push(SnapshotCell.empty());
1407
+ continue;
1408
+ }
1409
+ cells.push(SnapshotCell.fromBufferCell(cell, osc8UriForCell(term, cell)));
1410
+ }
1411
+ }
1412
+ rows.push({ cells: new SnapshotLine(cells), kittyPrefix: kittyLines?.[lineIndex - start] ?? "" });
1413
+ }
1414
+ const cursor = projectPtyCursor(buf, start, height);
1415
+ // The grid's actual dimensions at commit (duck-typed xterm read; the
1416
+ // parser is kept at this.cols/this.rows, but the fact must come from the
1417
+ // captured grid itself, never be re-derived from the current target at
1418
+ // assembly time — spec §3.1 predicate 4).
1419
+ const dims = term as { cols?: unknown; rows?: unknown };
1420
+ const sourceCols = typeof dims.cols === "number" && dims.cols > 0 ? dims.cols : this.cols;
1421
+ const sourceRows = typeof dims.rows === "number" && dims.rows > 0 ? dims.rows : this.rows;
1422
+ // §3.1 predicate 7 (locally closed completeness only — no semantic
1423
+ // boot/raw claim without an F): a snapshot commit is complete when the
1424
+ // validated non-empty frame finished hydrating (this method early-returns
1425
+ // while hydrating, and empty baselines never write a frame); a sync-close
1426
+ // commit is closed by definition. Anything else fails closed to "unknown".
1427
+ const contentKind: "complete" | "unknown" =
1428
+ source === "snapshot"
1429
+ ? this.protocolBaselineState === "valid-content" && this.localHydrationState === "complete" ? "complete" : "unknown"
1430
+ : source === "sync-close"
1431
+ ? "complete"
1432
+ : "unknown";
1433
+ this.committedView = {
1434
+ identity: this.currentViewIdentity(),
1435
+ start,
1436
+ end,
1437
+ rows,
1438
+ cursor,
1439
+ cursorHidden: isPtyCursorHidden(term),
1440
+ viewportTop: this.viewportTop,
1441
+ proofSeq: null,
1442
+ source,
1443
+ sourceCols,
1444
+ sourceRows,
1445
+ contentKind,
1446
+ };
1447
+ this.recoveryView = null;
1448
+ this.recoveryGeneration = null;
1449
+ this.emptyResetPending = false;
1450
+ if (this.connected) this.status = "attached";
1451
+ // Issue #284 D4 rendezvous: a successful commit is a convergence point.
1452
+ // A late snapshot arriving after the budget expired re-evaluates
1453
+ // immediately instead of waiting for the next cap (spec D4).
1454
+ this.evaluateAttachReady();
1455
+ }
1456
+
1457
+ private captureRecoveryView(): void {
1458
+ if (!this.modernCommittedMode() || this.committedView === null || this.closed) return;
1459
+ if (!canPublishAttachView(this.committedView.identity, this.currentViewIdentity())) return;
1460
+ this.recoveryView = this.committedView;
1461
+ this.recoveryGeneration = this.committedView.identity.generation;
1462
+ }
1463
+
1464
+ private invalidateRecoveryView(): void {
1465
+ this.recoveryView = null;
1466
+ this.recoveryGeneration = null;
1467
+ }
1468
+
1469
+ private recoveryViewValid(): boolean {
1470
+ if (!this.modernCommittedMode() || this.recoveryView === null || this.closed) return false;
1471
+ if (this.recoveryView.identity.closed === true) return false;
1472
+ if (this.recoveryView.identity.targetCols !== this.cols || this.recoveryView.identity.targetRows !== this.rows) return false;
1473
+ if (this.recoveryView.identity.geometryRevision !== this.geometryRevision) return false;
1474
+ if (typeof this.currentWireGeneration !== "string" || this.currentWireGeneration.length === 0) return false;
1475
+ if (this.currentWireGeneration !== this.recoveryGeneration) return false;
1476
+ return true;
1477
+ }
1478
+
1479
+ private activeCommittedView(): CommittedView | null {
1480
+ if (this.committedViewValid()) return this.committedView;
1481
+ if (this.recoveryViewValid()) return this.recoveryView;
1482
+ return null;
1483
+ }
1484
+
1485
+ /** Committed-path membership (projection, commits, recovery, selection
1486
+ * source): protocol mode with the reporter capability OR the #284 latch —
1487
+ * capability loss after a latched attach keeps this path alive (spec §3.3). */
1488
+ private modernCommittedMode(): boolean {
1489
+ return this.attachMode === "protocol" && (this.frameWitnessAvailable || this.witnessLatched);
1490
+ }
1491
+
1492
+ /** Visible/interaction fork (issue #278): the committed projection is used in
1493
+ * modern mode except while an external editor owns the screen — then the live
1494
+ * buffer is projected/addressed. Hydration keeps committed blank protection
1495
+ * even under external ownership, so an open frame never leaks partial rows. */
1496
+ private usesCommittedProjection(): boolean {
1497
+ return this.modernCommittedMode() &&
1498
+ (!this.externalOutputActive || this.localHydrationState === "hydrating");
1499
+ }
1500
+
1501
+ private committedViewValid(): boolean {
1502
+ if (this.committedView === null) return false;
1503
+ return canPublishAttachView(this.committedView.identity, this.currentViewIdentity());
1504
+ }
1505
+
1506
+ private liveBottomViewportTop(height: number): number {
1507
+ const buf = this.term.buffer.active;
1508
+ const bottom = Math.min(buf.length, buf.baseY + this.rows);
1509
+ return Math.max(0, bottom - height);
1510
+ }
1511
+
1512
+ private committedLineAt(lineIndex: number): BufferLineLike | null {
1513
+ if (!this.modernCommittedMode()) return null;
1514
+ const view = this.activeCommittedView();
1515
+ if (view === null || lineIndex < view.start || lineIndex >= view.end) return null;
1516
+ return view.rows[lineIndex - view.start]?.cells ?? null;
1517
+ }
1518
+
1519
+ private captureViewProofIdentity(): void {
1520
+ this.viewProofIdentity = this.currentViewIdentity();
1521
+ }
1522
+
1523
+ private invalidateViewProof(reason: string): void {
1524
+ this.latestViewProof = { status: "unknown", reason, proof: null, throughSeq: null, cursorVisible: null };
1525
+ this.viewProofIdentity = null;
1526
+ this.viewProofTrailing.reset();
1527
+ // Issue #294: intent evidence is sticky — see noteGeometryIntent/snapshotReady/viewProofRecord.
1528
+ }
1529
+
1530
+ /** Feed ordinary output after the last F proof through the safe-trailing
1531
+ * classifier. Only a completely safe window may extend coverage. */
1532
+ private noteViewProofOutput(data: string): void {
1533
+ const coverage = this.latestViewProof as { status?: string; proof?: unknown } | null;
1534
+ if (this.attachMode !== "protocol" || coverage === null || coverage.status !== "covered" || coverage.proof === null) return;
1535
+ const localSeq = this.attachClient.getLastSeq();
1536
+ const state = this.viewProofTrailing.push(data);
1537
+ if (state.status === "safe") {
1538
+ this.latestViewProof = {
1539
+ status: "covered",
1540
+ reason: "safe-trailing",
1541
+ proof: (coverage as { proof: unknown }).proof,
1542
+ throughSeq: localSeq,
1543
+ cursorVisible: state.cursorVisible,
1544
+ };
1545
+ this.captureViewProofIdentity();
1546
+ } else {
1547
+ this.invalidateViewProof(state.status === "pending" ? "view-proof-trailing-pending" : `view-proof-trailing-${state.reason ?? "unsafe"}`);
1548
+ }
1549
+ }
1550
+
1551
+ private noteViewProofRecord(record: Record<string, unknown>): void {
1552
+ if (record.marker === "S") {
1553
+ this.viewProofRecords.push(record);
1554
+ if (this.viewProofRecords.length > MAX_VIEW_PROOF_RECORDS) this.viewProofRecords.shift();
1555
+ this.viewProofRecordCount += 1;
1556
+ this.invalidateViewProof("candidate-open");
1557
+ return;
1558
+ }
1559
+ if (record.marker === "A") {
1560
+ this.viewProofRecords.push(record);
1561
+ if (this.viewProofRecords.length > MAX_VIEW_PROOF_RECORDS) this.viewProofRecords.shift();
1562
+ this.viewProofRecordCount += 1;
1563
+ this.invalidateViewProof("candidate-aborted");
1564
+ return;
1565
+ }
1566
+ if (record.marker !== "F") return;
1567
+ this.viewProofRecords.push(record);
1568
+ if (this.viewProofRecords.length > MAX_VIEW_PROOF_RECORDS) this.viewProofRecords.shift();
1569
+ this.viewProofRecordCount += 1;
1570
+ this.latestViewProof = {
1571
+ status: "covered",
1572
+ reason: "safe-trailing",
1573
+ proof: record,
1574
+ throughSeq: record.seq,
1575
+ cursorVisible: typeof record.cursorVisible === "boolean" ? record.cursorVisible : null,
1576
+ };
1577
+ this.captureViewProofIdentity();
1578
+ this.viewProofTrailing.reset(typeof record.cursorVisible === "boolean" ? { cursorVisible: record.cursorVisible } : {});
1579
+ const proofSeq = Number(record.seq);
1580
+ const following = this.recentProtocolOutput.filter((chunk) => chunk.seq > proofSeq).sort((a, b) => a.seq - b.seq);
1581
+ let expectedSeq = proofSeq + 1;
1582
+ for (const chunk of following) {
1583
+ if (chunk.seq !== expectedSeq) {
1584
+ this.invalidateViewProof("view-proof-replay-gap");
1585
+ return;
1586
+ }
1587
+ expectedSeq = chunk.seq + 1;
1588
+ const state = this.viewProofTrailing.push(chunk.data);
1589
+ if (state.status !== "safe") {
1590
+ this.invalidateViewProof(state.status === "pending" ? "view-proof-trailing-pending" : `view-proof-trailing-${state.reason ?? "unsafe"}`);
1591
+ return;
1592
+ }
1593
+ this.latestViewProof = {
1594
+ status: "covered",
1595
+ reason: "safe-trailing",
1596
+ proof: record,
1597
+ throughSeq: chunk.seq,
1598
+ cursorVisible: state.cursorVisible,
1599
+ };
1600
+ this.captureViewProofIdentity();
1601
+ }
1602
+ if (this.attachClient.getLastSeq() >= expectedSeq) {
1603
+ this.invalidateViewProof("view-proof-replay-gap");
1604
+ }
1605
+ }
1606
+
1607
+ /** Derive proofStatus through the §3.1.1 pure classifier and manage the
1608
+ * sticky failure fact (the component-side duty of spec §3.1.1): any
1609
+ * invalid classification binds to the CURRENT baseline. The classifier
1610
+ * NEVER clears the binding here — recovery is publish-only (see
1611
+ * evaluateAttachReady's publish branch): noteViewProofRecord(F) builds
1612
+ * covered/safe-trailing coverage BEFORE the full-view policy validates
1613
+ * sequence/metadata/geometry/intent/identity, so a covered classification
1614
+ * on a non-publishable F must keep the degraded path blocked. A new
1615
+ * baseline identity (replaceParser at an accepted snapshotReady) rebinds
1616
+ * it. Capability loss (latestViewProof = null) keeps the recorded fact. */
1617
+ private classifyLatestProof(): "none" | "missing" | "invalid" | "covered" {
1618
+ const stickyInvalid = this.proofInvalidatedBaselineToken === this.baselineToken;
1619
+ const proofStatus = classifyProofStatus(this.latestViewProof as Record<string, unknown> | null, stickyInvalid);
1620
+ this.lastProofStatus = proofStatus;
1621
+ if (proofStatus === "invalid") this.proofInvalidatedBaselineToken = this.baselineToken;
1622
+ // Issue #288 D1: latch the HARD invalid family on the current baseline.
1623
+ // The family is a property of the ARRIVAL shape (never of the sticky
1624
+ // fact), so a trailing arrival under an existing sticky binding latches
1625
+ // nothing, while a hard arrival latches even when the sticky fact was
1626
+ // first set by a trailing shape — hard dominates (I8). Never cleared
1627
+ // here: same publish-only/baseline-rebind lifecycle as the sticky fact.
1628
+ if (proofStatus === "invalid" && classifyProofInvalidFamily(this.latestViewProof as Record<string, unknown> | null) === "hard") {
1629
+ this.proofHardInvalidatedThisBaseline = this.baselineToken;
1630
+ }
1631
+ // The diagnostic field mirrors the POST-update sticky state (review fix):
1632
+ // recording the pre-update value hid the invalidation transition
1633
+ // (false→true) from every settle readout built from it.
1634
+ this.lastProofStickyInvalid = this.proofInvalidatedBaselineToken === this.baselineToken;
1635
+ return proofStatus;
1636
+ }
1637
+
1638
+ /** Fact assembly for the accepted decideAttachPresentation gate. Issue #284
1639
+ * extends the assembly with the recovery facts (spec §3.1): the policy —
1640
+ * and only the policy — decides the committed-degraded publish; a timer
1641
+ * fact alone never publishes. */
1642
+ private evaluateAttachReady(): void {
1643
+ if (!this.attaching || this.closed || this.attachMode !== "protocol") return;
1644
+ // A latched attach keeps evaluating after capability loss (I6): the
1645
+ // committed presentation path — and with it the recovery facts — stays
1646
+ // alive until detach/dispose. Never-latched/legacy sessions keep the
1647
+ // legacy deadline path untouched.
1648
+ if (!this.modernCommittedMode()) return;
1649
+ const proofStatus = this.classifyLatestProof();
1650
+ if (this.parserWritesInFlight > 0) return;
1651
+ if (this.committedView === null) {
1652
+ this.notReadyReason = "committed-view-missing";
1653
+ return;
1654
+ }
1655
+ const coverage = this.latestViewProof as { status?: string; proof?: { metadata?: unknown } | null } | null;
1656
+ const proof = coverage?.status === "covered" && coverage.proof !== null ? coverage.proof : null;
1657
+ const localSeq = this.attachClient.getLastSeq();
1658
+ const baselineState =
1659
+ this.protocolBaselineState === "valid-empty" || this.protocolBaselineState === "valid-content"
1660
+ ? this.protocolBaselineState
1661
+ : this.localHydrationState === "hydrating"
1662
+ ? "hydrating"
1663
+ : this.protocolBaselineState;
1664
+ const committedView = this.committedView;
1665
+ const decision = decideAttachPresentation({
1666
+ closed: this.closed,
1667
+ mode: this.attachMode,
1668
+ baselineState,
1669
+ localParseComplete: this.parserWritesInFlight === 0 && this.localHydrationState !== "hydrating",
1670
+ frameState: this.parserSyncOpen ? "open" : this.parserWritesInFlight > 0 ? "unknown" : "complete",
1671
+ contentAvailable: this.receivedOutput === true && proof !== null,
1672
+ contentKind: proof === null ? "unknown" : "complete",
1673
+ localSeq,
1674
+ viewProof: coverage,
1675
+ viewIdentity: this.viewProofIdentity,
1676
+ currentIdentity: this.currentViewIdentity(),
1677
+ targetCols: this.cols,
1678
+ targetRows: this.rows,
1679
+ geometryRevision: this.geometryRevision,
1680
+ requiredGeometryRevision: this.resizeIntentRequired ? this.geometryRevision : undefined,
1681
+ resizeIntentRequired: this.resizeIntentRequired,
1682
+ resizeIntentSatisfied: this.resizeIntentSatisfied,
1683
+ resizeIntentProofSeq: this.resizeIntentProofSeq,
1684
+ intentId: this.resizeIntentId,
1685
+ deadlineState: this.deadlineState,
1686
+ // Issue #284 recovery facts (spec §3.1): plain facts recorded on the
1687
+ // committed view and by the §3.1.1 classifier. Supplying them opts the
1688
+ // protocol call into the degraded chain inside the policy.
1689
+ witnessLatched: this.witnessLatched,
1690
+ committedViewValid: this.committedViewValid(),
1691
+ committedViewSource: committedView.source,
1692
+ committedViewCols: committedView.sourceCols,
1693
+ committedViewRows: committedView.sourceRows,
1694
+ committedContentKind: committedView.contentKind,
1695
+ proofStatus,
1696
+ // Issue #288 D1 cap floor: the hard-latch absence is the policy's
1697
+ // recoverability fact — a trailing-only invalidation may pass
1698
+ // predicate 5 once the cap expires; a hard one never may.
1699
+ capRecoverable: this.proofHardInvalidatedThisBaseline !== this.baselineToken,
1700
+ budgetElapsed: this.budgetElapsed,
1701
+ });
1702
+ this.notReadyReason = decision.action === "wait" ? decision.reason : null;
1703
+ if (decision.action === "publish") {
1704
+ // Issue #284 §3.1.1 recovery is publish-only: the covered
1705
+ // classification precedes the full-view gates, so ONLY a policy
1706
+ // "publish" — a fully valid F for the current baseline/identity —
1707
+ // may clear the sticky failure fact. A wrong-geometry/intent F that
1708
+ // merely covers the proof channel must keep the degraded path
1709
+ // blocked (a covered-but-unpublishable F is exactly the shape the
1710
+ // degraded chain refuses via proof-status-covered).
1711
+ this.proofInvalidatedBaselineToken = null;
1712
+ this.proofHardInvalidatedThisBaseline = null;
1713
+ this.lastProofStickyInvalid = false;
1714
+ this.publishabilityState = "ready";
1715
+ this.finishAttachTransition("complete");
1716
+ } else if (decision.action === "publish-degraded") {
1717
+ this.publishabilityState = "ready";
1718
+ this.finishAttachTransition("committed-degraded");
1719
+ } else if (decision.action === "wait") {
1720
+ this.publishabilityState = this.deadlineState === "expired" ? "unknown" : "wait";
1721
+ }
1722
+ }
1723
+
1724
+ /** Issue #288 D2: the SHARED recovery-facts snapshot behind the settle and
1725
+ * wait diagnostic records — the #284 settle-diagnostic assembly (enum
1726
+ * whitelisting via sanitizeViewProofEnumPair, numeric-only committedView
1727
+ * identity, token exclusion) moved here verbatim; the two event wrappers
1728
+ * below add only their outcome field, so the whitelist logic is never
1729
+ * duplicated. Numbers and finite enums only — never tokens, screen text,
1730
+ * keys, or raw terminal data. */
1731
+ private buildAttachRecoveryFacts(): AttachRecoveryFacts {
1732
+ const committedView = this.committedView;
1733
+ const proof = sanitizeViewProofEnumPair(this.latestViewProof as Record<string, unknown> | null);
1734
+ return {
1735
+ notReadyReason: this.notReadyReason,
1736
+ publishabilityState: this.publishabilityState,
1737
+ deadlineState: this.deadlineState,
1738
+ witnessLatched: this.witnessLatched,
1739
+ budgetDeadline: this.attachStartedAt + ATTACH_RECOVERY_BUDGET_MS,
1740
+ budgetElapsed: this.budgetElapsed,
1741
+ proofStatus: this.lastProofStatus,
1742
+ proofStickyInvalid: this.lastProofStickyInvalid,
1743
+ committedView: committedView === null ? null : {
1744
+ // Numeric identity facts only: the local parser generation
1745
+ // (the committed view's epoch — identity.parser is the current
1746
+ // parser at every publish settle) and the geometry revision.
1747
+ // The connection/baseline tokens are deliberately omitted.
1748
+ generation: this.parserEpoch,
1749
+ geometryRevision: committedView.identity.geometryRevision,
1750
+ source: committedView.source,
1751
+ sourceCols: committedView.sourceCols,
1752
+ sourceRows: committedView.sourceRows,
1753
+ contentKind: committedView.contentKind,
1754
+ },
1755
+ latestViewProof: proof,
1756
+ };
1757
+ }
1758
+
1759
+ /** Issue #284 §3.4/D5: the settle record. Captured inside
1760
+ * finishAttachTransition before the wait state resets, so it keeps the
1761
+ * LAST wait reason. Byte-identical to the pre-#288 settle payload (the
1762
+ * readyReason field still leads the details object). */
1763
+ private buildSettleDiagnostic(source: AttachReadyReason): AttachRecoveryDiagnosticPatch {
1764
+ return {
1765
+ source: "attach",
1766
+ level: "info",
1767
+ code: "attach_settle_ready",
1768
+ message: `attach settle ready via ${source}`,
1769
+ details: { readyReason: source, ...this.buildAttachRecoveryFacts() },
1770
+ };
1771
+ }
1772
+
1773
+ /** Issue #288 D2: the wait record — the same recovery facts plus the
1774
+ * expired phase, and NO readyReason (a waiting attach has none). */
1775
+ private buildWaitExpiredDiagnostic(phase: AttachWaitExpiredPhase): AttachWaitExpiredDiagnosticPatch {
1776
+ return {
1777
+ source: "attach",
1778
+ level: "info",
1779
+ code: "attach_wait_expired",
1780
+ message: `attach wait expired at ${phase} deadline`,
1781
+ details: { phase, ...this.buildAttachRecoveryFacts() },
1782
+ };
1783
+ }
1784
+
1785
+ /** Issue #288 D2: record a wait-phase expiry on the onDiagnostic channel.
1786
+ * Emitted only while the attach is still waiting and at most once per
1787
+ * phase per attach — a settled or closed component records nothing, and a
1788
+ * re-scheduled deadline (reconnect re-entry of startAttachSettle) cannot
1789
+ * duplicate the event. */
1790
+ private emitAttachWaitExpiredDiagnostic(phase: AttachWaitExpiredPhase): void {
1791
+ if (this.closed || !this.attaching) return;
1792
+ if (this.attachWaitDiagnosticEmitted[phase]) return;
1793
+ this.attachWaitDiagnosticEmitted[phase] = true;
1794
+ this.opts.onDiagnostic?.(this.buildWaitExpiredDiagnostic(phase));
1795
+ }
1796
+
1797
+ private finishAttachTransition(source: AttachReadyReason): void {
1798
+ if (!this.attaching || this.closed) return;
786
1799
  // Note: jiggle retry chain is NOT cancelled here — it survives the settle
787
1800
  // transition because any successful jiggle triggers a fullRender which emits
788
1801
  // \x1b[2J, self-cancelling the chain. Post-settle jiggles only occur when the
@@ -792,15 +1805,25 @@ export class PtyAttachComponent implements Component {
792
1805
  // selection) is acceptable in exchange for self-healing. When the child is
793
1806
  // healthy, the very first jiggle's fullRender is detected and the chain
794
1807
  // stops before settle ends, so no post-settle jiggle fires at all.
1808
+ // Issue #284 §3.4: record which path settled BEFORE the wait state resets
1809
+ // (the diagnostic keeps the last wait reason; notReadyReason semantics are
1810
+ // unchanged — null once settled).
1811
+ const settleDiagnostic = this.buildSettleDiagnostic(source);
795
1812
  this.attaching = false;
796
- if (this.attachSettleTimer) {
797
- clearTimeout(this.attachSettleTimer);
1813
+ this.publishabilityState = "ready";
1814
+ this.readyReason = source;
1815
+ this.notReadyReason = null;
1816
+ this.opts.onDiagnostic?.(settleDiagnostic);
1817
+ this.firstAttachSideEffectsApplied = true;
1818
+ if (this.attachSettleTimer !== null) {
1819
+ this.clock.clear(this.attachSettleTimer);
798
1820
  this.attachSettleTimer = null;
799
1821
  }
800
- if (this.attachHardTimeout) {
801
- clearTimeout(this.attachHardTimeout);
1822
+ if (this.attachHardTimeout !== null) {
1823
+ this.clock.clear(this.attachHardTimeout);
802
1824
  this.attachHardTimeout = null;
803
1825
  }
1826
+ this.clearAttachRecoveryBudget();
804
1827
  this.stopLoadingTicker();
805
1828
  // Force a full clear so the loading banner is replaced atomically by the settled
806
1829
  // buffer, instead of diffing banner lines into buffer lines.
@@ -1263,11 +2286,26 @@ export class PtyAttachComponent implements Component {
1263
2286
  }
1264
2287
  }
1265
2288
 
2289
+ private interactionLine(lineIndex: number): BufferLineLike | null {
2290
+ if (this.usesCommittedProjection()) return this.committedLineAt(lineIndex);
2291
+ return this.term.buffer.active.getLine(lineIndex) ?? null;
2292
+ }
2293
+
2294
+ private interactionNullCell(): BufferCellLike {
2295
+ return this.usesCommittedProjection() ? SnapshotCell.empty() : this.term.buffer.active.getNullCell();
2296
+ }
2297
+
1266
2298
  private mousePointForEvent(row: number, col: number, clampToBody: boolean): MousePoint | null {
1267
2299
  const height = this.bodyHeight();
1268
2300
  const bodyRow = row - 2;
1269
2301
  if (!clampToBody && (bodyRow < 0 || bodyRow >= height)) return null;
1270
2302
  const clampedRow = clampInt(bodyRow, 0, Math.max(0, height - 1));
2303
+ if (this.usesCommittedProjection()) {
2304
+ const view = this.activeCommittedView();
2305
+ if (view === null) return null;
2306
+ const line = clampInt(view.start + clampedRow, view.start, Math.max(view.start, view.end - 1));
2307
+ return { line, col: clampInt(col - 1, 0, Math.max(0, this.cols - 1)) };
2308
+ }
1271
2309
  this.clampViewportTop(height);
1272
2310
  const start = this.viewportTop ?? this.bottomViewportTop(height);
1273
2311
  const line = clampInt(start + clampedRow, 0, Math.max(0, this.term.buffer.active.length - 1));
@@ -1301,10 +2339,9 @@ export class PtyAttachComponent implements Component {
1301
2339
  }
1302
2340
 
1303
2341
  private selectWordAtPoint(point: MousePoint): boolean {
1304
- const buf = this.term.buffer.active;
1305
- const line = buf.getLine(point.line);
2342
+ const line = this.interactionLine(point.line);
1306
2343
  if (!line) return false;
1307
- const reusable = buf.getNullCell();
2344
+ const reusable = this.interactionNullCell();
1308
2345
  const range = findWordRangeAtCells(asciiCellsForBufferLine(line, reusable), point.col);
1309
2346
  if (!range) return false;
1310
2347
  this.selection = {
@@ -1322,10 +2359,9 @@ export class PtyAttachComponent implements Component {
1322
2359
  }
1323
2360
 
1324
2361
  private linkAtPoint(point: MousePoint): string | null {
1325
- const buf = this.term.buffer.active;
1326
- const line = buf.getLine(point.line);
2362
+ const line = this.interactionLine(point.line);
1327
2363
  if (!line) return null;
1328
- const reusable = buf.getNullCell();
2364
+ const reusable = this.interactionNullCell();
1329
2365
  const cell = line.getCell(point.col, reusable);
1330
2366
  const osc8 = cell ? osc8UriForCell(this.term, cell) : "";
1331
2367
  if (osc8) return osc8;
@@ -1388,26 +2424,6 @@ export class PtyAttachComponent implements Component {
1388
2424
  }
1389
2425
  }
1390
2426
 
1391
- /** Issue #174 (B2) + #172: a selection gesture ended inside this overlay and pi has
1392
- * finalized (and copied) its selection. Mirror the text into X11 PRIMARY so
1393
- * middle-click paste closes the loop, then drop pi's selection so the inverse-video
1394
- * highlight does not outlive the copy. Clearing is skipped when copy-on-select is
1395
- * off (the user copies later with pi's Ctrl+X) and when the pi-tui method is absent
1396
- * (older/newer runtime) — both degrade to the previous behaviour instead of throwing.
1397
- * clearTextSelection preserves pi's multi-click history; resetTextSelection would
1398
- * clear lastClick and break double-click word / triple-click line selection. */
1399
- private settleFullscreenSelection(nativePasteEnabled: boolean): void {
1400
- if (this.closed) return;
1401
- const alt = this.tui as FullscreenSelectionHost;
1402
- const text = alt.getActiveSelectionText?.();
1403
- if (typeof text !== "string" || text.length === 0) return;
1404
- if (nativePasteEnabled) this.writePrimarySelection(text);
1405
- if (alt.getCopyOnSelect?.() === false) return;
1406
- if (typeof alt.clearTextSelection !== "function") return;
1407
- alt.clearTextSelection();
1408
- this.scheduleRender();
1409
- }
1410
-
1411
2427
  /** Write `text` to the X11 PRIMARY selection so other apps can middle-click-paste it. */
1412
2428
  private writePrimarySelection(text: string): void {
1413
2429
  if (process.env.AGENT_BOARD_ATTACH_NATIVE_PASTE === "0") return;
@@ -1424,11 +2440,10 @@ export class PtyAttachComponent implements Component {
1424
2440
  private selectionText(): string {
1425
2441
  const range = normalizeSelection(this.selection);
1426
2442
  if (!range) return "";
1427
- const buf = this.term.buffer.active;
1428
- const reusable = buf.getNullCell();
2443
+ const reusable = this.interactionNullCell();
1429
2444
  const parts: string[] = [];
1430
2445
  for (let lineIndex = range.start.line; lineIndex <= range.end.line; lineIndex++) {
1431
- const line = buf.getLine(lineIndex);
2446
+ const line = this.interactionLine(lineIndex);
1432
2447
  if (!line) {
1433
2448
  parts.push("");
1434
2449
  continue;
@@ -1462,9 +2477,15 @@ export class PtyAttachComponent implements Component {
1462
2477
  // Render width is authoritative inside ctx.ui.custom; terminal.cols is not
1463
2478
  // consistently exposed by all Pi TUI versions.
1464
2479
  size.cols = Math.max(20, width);
1465
- if (size.cols === this.cols && size.rows === this.rows) return;
2480
+ if (size.cols === this.cols && size.rows === this.rows) {
2481
+ // A same-size render after the early protocol size-sync consumes that
2482
+ // one-shot pair; it must not mint another intent.
2483
+ if (this.pendingEarlySyncTarget === `${size.cols}x${size.rows}`) this.pendingEarlySyncTarget = null;
2484
+ return;
2485
+ }
1466
2486
  this.cols = size.cols;
1467
2487
  this.rows = size.rows;
2488
+ this.noteGeometryIntent(size.cols, size.rows);
1468
2489
  // A real terminal resize supersedes the hold protocol: cancel any armed
1469
2490
  // hold and adopt the new size as the baseline (guard G4, issue #25).
1470
2491
  this.jiggleRetry.notifyExternalResize(size.cols, size.rows);
@@ -1479,6 +2500,33 @@ export class PtyAttachComponent implements Component {
1479
2500
  this.enableMouseScroll();
1480
2501
  }
1481
2502
 
2503
+ /** A differing resize is exactly one local geometry revision/intent; an
2504
+ * applied ack is not completion, only a matching proof is. */
2505
+ private noteGeometryIntent(cols = this.cols, rows = this.rows, options: { early?: boolean } = {}): void {
2506
+ const target = `${cols}x${rows}`;
2507
+ if (options.early === true) {
2508
+ // Every actual early size-sync/mismatch advances once. De-dup is
2509
+ // ONLY early→next render; early→early is never collapsed. The latest
2510
+ // pending target is consumed by the next render of that target.
2511
+ this.pendingEarlySyncTarget = target;
2512
+ } else if (this.pendingEarlySyncTarget === target) {
2513
+ // The next render of the same target consumes the early pair.
2514
+ this.pendingEarlySyncTarget = null;
2515
+ return;
2516
+ } else {
2517
+ this.pendingEarlySyncTarget = null;
2518
+ }
2519
+ this.geometryRevision += 1;
2520
+ this.resizeIntentId = this.geometryRevision;
2521
+ this.resizeIntentRequired = true;
2522
+ this.resizeIntentSatisfied = false;
2523
+ this.resizeIntentProofSeq = null;
2524
+ this.committedView = null;
2525
+ this.recoveryView = null;
2526
+ this.recoveryGeneration = null;
2527
+ this.invalidateViewProof("geometry-resize");
2528
+ }
2529
+
1482
2530
  private sendResize(cols = this.cols, rows = this.rows): void {
1483
2531
  // Phase 5 (D4): enveloped resize when the host has an instance fence
1484
2532
  // (correlated applied/superseded acks; starting-window host_starting is
@@ -1517,6 +2565,14 @@ export class PtyAttachComponent implements Component {
1517
2565
 
1518
2566
  private tryScrollBy(linesUp: number): boolean {
1519
2567
  const height = this.bodyHeight();
2568
+ if (this.usesCommittedProjection()) {
2569
+ // The committed view is the only visible cache. Record the requested
2570
+ // viewport intent but let the child own history: the display stays on
2571
+ // the current complete range until a later verified boundary.
2572
+ const intent = scrollViewportTop(this.viewportTop, this.bottomViewportTop(height), linesUp, this.scrollFloorStart(height));
2573
+ this.viewportTop = intent.viewportTop;
2574
+ return false;
2575
+ }
1520
2576
  const result = scrollViewportTop(this.viewportTop, this.bottomViewportTop(height), linesUp, this.scrollFloorStart(height));
1521
2577
  this.viewportTop = result.viewportTop;
1522
2578
  if (result.changed) this.requestScrollRender();
@@ -1610,6 +2666,7 @@ export class PtyAttachComponent implements Component {
1610
2666
  const lines = this.parserBuffer.split("\n");
1611
2667
  this.parserBuffer = lines.pop() ?? "";
1612
2668
  let needsRender = false;
2669
+ let suppressGenerationRender = false;
1613
2670
  for (const line of lines) {
1614
2671
  if (!line.trim()) continue;
1615
2672
  try {
@@ -1626,7 +2683,58 @@ export class PtyAttachComponent implements Component {
1626
2683
  continue;
1627
2684
  }
1628
2685
  if (msg.type === "hello" || msg.type === "status") {
2686
+ const wireGeneration = typeof msg.generation === "string" ? msg.generation : typeof msg.status?.generation === "string" ? msg.status.generation : null;
2687
+ if (wireGeneration !== null) {
2688
+ this.currentWireGeneration = wireGeneration;
2689
+ this.emptyResetPending = this.recoveryGeneration !== null && wireGeneration !== this.recoveryGeneration;
2690
+ if (
2691
+ (this.committedView !== null && wireGeneration !== this.committedView.identity.generation) ||
2692
+ (this.recoveryGeneration !== null && wireGeneration !== this.recoveryGeneration)
2693
+ ) {
2694
+ this.outputRenderScheduler.cancel();
2695
+ this.committedView = null;
2696
+ this.invalidateRecoveryView();
2697
+ this.invalidateViewProof("generation-change");
2698
+ // Do not paint the previous generation from a status render
2699
+ // before the new empty/snapshot arrives.
2700
+ suppressGenerationRender = true;
2701
+ }
2702
+ }
1629
2703
  this.status = "attached";
2704
+ const status = (msg.status ?? msg) as { frameWitness?: { enabled?: unknown } };
2705
+ if (status.frameWitness?.enabled === true) {
2706
+ const wasAvailable = this.frameWitnessAvailable;
2707
+ this.frameWitnessAvailable = true;
2708
+ // Latch on the first observation of this attach (idempotent):
2709
+ // later losses may not strand the attach on the legacy path.
2710
+ this.witnessLatched = true;
2711
+ if (!wasAvailable && this.attaching && this.attachMode === "protocol") {
2712
+ if (this.attachSettleTimer !== null) {
2713
+ this.clock.clear(this.attachSettleTimer);
2714
+ this.attachSettleTimer = null;
2715
+ }
2716
+ this.deadlineState = "pending";
2717
+ this.evaluateAttachReady();
2718
+ }
2719
+ } else if (status.frameWitness?.enabled === false && this.frameWitnessAvailable) {
2720
+ this.frameWitnessAvailable = false;
2721
+ this.latestViewProof = null;
2722
+ this.viewProofIdentity = null;
2723
+ if (this.attaching && this.attachMode === "protocol") {
2724
+ if (this.witnessLatched) {
2725
+ // Issue #284 latch layer (I6/§3.3): a latched attach keeps the
2726
+ // committed presentation path — no restoreLegacyDeadlines, no
2727
+ // latch clear. Record the loss and keep waiting for safe facts;
2728
+ // the view layer rebuilds on the next new-identity snapshot or
2729
+ // closed frame.
2730
+ this.notReadyReason = "witness-capability-lost";
2731
+ } else {
2732
+ this.deadlineState = "pending";
2733
+ this.notReadyReason = "legacy-deadlines-without-reporter";
2734
+ this.restoreLegacyDeadlines();
2735
+ }
2736
+ }
2737
+ }
1630
2738
  if (msg.type === "hello") this.editorEmpty = typeof msg.editorEmpty === "boolean" ? msg.editorEmpty : null;
1631
2739
  } else if (msg.type === "editor_state") {
1632
2740
  this.editorEmpty = typeof msg.empty === "boolean" ? msg.empty : null;
@@ -1645,7 +2753,7 @@ export class PtyAttachComponent implements Component {
1645
2753
  // Ignore malformed protocol lines; raw PTY data is only legal inside output.data.
1646
2754
  }
1647
2755
  }
1648
- if (needsRender) this.scheduleRender();
2756
+ if (needsRender && !suppressGenerationRender) this.scheduleRender();
1649
2757
  }
1650
2758
 
1651
2759
  /**
@@ -1654,7 +2762,7 @@ export class PtyAttachComponent implements Component {
1654
2762
  * hydrates frames.
1655
2763
  */
1656
2764
  private handleAttachEvent(
1657
- event: "mode" | "snapshotBegin" | "snapshotReady" | "output" | "resubscribing" | "protocolError" | "cmdAck" | "reconciled" | "epochReset",
2765
+ event: "mode" | "snapshotBegin" | "snapshotReady" | "output" | "viewProof" | "viewProofRecord" | "resubscribing" | "protocolError" | "cmdAck" | "reconciled" | "epochReset",
1658
2766
  payload: any,
1659
2767
  ): void {
1660
2768
  if (event === "mode") {
@@ -1663,9 +2771,22 @@ export class PtyAttachComponent implements Component {
1663
2771
  if (this.attachMode === "protocol") {
1664
2772
  // Snapshot mode owns screen correctness: cancel any pending legacy
1665
2773
  // jiggle arming and unwind anything already armed (restores a held
1666
- // resize; no-ops otherwise).
2774
+ // resize; no-ops otherwise). The legacy 250 ms settle is cancelled
2775
+ // permanently for this attach; the hard deadline only marks an
2776
+ // explicit expired wait, never a forced publish.
1667
2777
  this.clearJiggleStartTimer();
1668
2778
  this.jiggleRetry.restoreAndStop();
2779
+ if (this.modernCommittedMode() && this.attachSettleTimer !== null) {
2780
+ this.clock.clear(this.attachSettleTimer);
2781
+ this.attachSettleTimer = null;
2782
+ }
2783
+ this.deadlineState = "pending";
2784
+ this.notReadyReason = this.frameWitnessAvailable
2785
+ ? "awaiting-complete-frame"
2786
+ : this.witnessLatched
2787
+ ? "witness-capability-lost"
2788
+ : "legacy-deadlines-without-reporter";
2789
+ this.evaluateAttachReady();
1669
2790
  } else if (prev === "protocol") {
1670
2791
  // Downgrade after a protocol session (recovery budget exhausted):
1671
2792
  // re-arm the legacy screen-healing machinery. This must run whenever
@@ -1676,11 +2797,50 @@ export class PtyAttachComponent implements Component {
1676
2797
  this.clearJiggleStartTimer();
1677
2798
  if (this.connected) this.jiggleRetry.start(this.cols, this.rows);
1678
2799
  }
2800
+ if (this.attachMode === "legacy") {
2801
+ this.externalOutputActive = false;
2802
+ this.restoreLegacyDeadlines();
2803
+ }
1679
2804
  // Legacy decided during the undecided window: the race-guard timer
1680
2805
  // already fired at 100ms (≪ the 1500ms probe timeout) — nothing to do.
1681
2806
  return;
1682
2807
  }
1683
2808
  if (event === "snapshotBegin") {
2809
+ // Collecting identity only: replacement happens at snapshotReady.
2810
+ const beginGeneration = (payload ?? {}) as { generation?: unknown; empty?: unknown; externalOutputActive?: unknown };
2811
+ if (beginGeneration.empty === true) {
2812
+ // Empty baseline invalidates old views/proof AT THE BEGIN, before
2813
+ // any status/hello render can present the dead generation again.
2814
+ this.outputRenderScheduler.cancel();
2815
+ this.committedView = null;
2816
+ this.invalidateRecoveryView();
2817
+ this.invalidateViewProof("new-empty-baseline");
2818
+ this.emptyResetPending = true;
2819
+ this.scheduleRender();
2820
+ }
2821
+ if (typeof beginGeneration.generation === "string") {
2822
+ const generationChanged =
2823
+ (this.committedView !== null && beginGeneration.generation !== this.committedView.identity.generation) ||
2824
+ (this.recoveryGeneration !== null && beginGeneration.generation !== this.recoveryGeneration);
2825
+ if (generationChanged) {
2826
+ this.committedView = null;
2827
+ this.invalidateRecoveryView();
2828
+ this.invalidateViewProof("generation-change");
2829
+ // New-generation state starts unowned; only a validated snapshot
2830
+ // boolean below may adopt external ownership for this generation.
2831
+ this.externalOutputActive = false;
2832
+ }
2833
+ }
2834
+ // Issue #278: the runner samples external ownership at capture end into
2835
+ // snapshot_begin. A validated boolean adopts it (running the interaction
2836
+ // cleanup on change); an absent field preserves same-generation local state.
2837
+ if (typeof beginGeneration.externalOutputActive === "boolean" && beginGeneration.externalOutputActive !== this.externalOutputActive) {
2838
+ this.externalOutputActive = beginGeneration.externalOutputActive;
2839
+ this.resetExternalProjectionInteraction();
2840
+ }
2841
+ this.collectingConnectionToken = this.connectionToken;
2842
+ this.collectingBaselineToken = this.baselineToken;
2843
+ this.collectingParserEpoch = this.parserEpoch;
1684
2844
  // Protocol attach size-sync (CR R1 blocking): the legacy attach resized
1685
2845
  // the child at every connect (jiggle start); subscribe_terminal carries
1686
2846
  // no size, so without this the child keeps its host-creation geometry
@@ -1695,12 +2855,16 @@ export class PtyAttachComponent implements Component {
1695
2855
  typeof beginSize.rows === "number" &&
1696
2856
  (beginSize.cols !== this.cols || beginSize.rows !== this.rows)
1697
2857
  ) {
2858
+ // One early size-sync pairs with the next render of the same target.
2859
+ // Later independent size-syncs to an already-seen target still advance.
2860
+ this.noteGeometryIntent(this.cols, this.rows, { early: true });
1698
2861
  this.sendResize();
1699
2862
  }
1700
2863
  return;
1701
2864
  }
1702
2865
  if (event === "snapshotReady") {
1703
- const snap = (payload ?? {}) as { frame?: string; empty?: boolean; resnapshot?: boolean; scrollbackLines?: number };
2866
+ const snap = (payload ?? {}) as { frame?: string; empty?: boolean; resnapshot?: boolean; scrollbackLines?: number; viewProof?: unknown; viewProofRecords?: unknown[] };
2867
+ if (this.collectingConnectionToken !== this.connectionToken) return;
1704
2868
  // The synthesized frame is self-contained on dirty terminals (phase 3
1705
2869
  // torture-proven: DECSTR + clear preamble wipes the constructor
1706
2870
  // screen.log replay and any pre-probe broadcast bytes), so hydrating is
@@ -1715,29 +2879,124 @@ export class PtyAttachComponent implements Component {
1715
2879
  // constructor's screen.log warm-start must not outlive the protocol
1716
2880
  // answer — a gated reset let the dead session's tail render as a
1717
2881
  // cold-start ghost once the banner lifted (final-review F1).
2882
+ if (!this.replaceParser()) {
2883
+ this.handleParserReplacementFailure();
2884
+ return; // fail-closed: no write to the old parser
2885
+ }
2886
+ const records = Array.isArray(snap.viewProofRecords) ? snap.viewProofRecords.slice(0, MAX_VIEW_PROOF_RECORDS) : [];
2887
+ this.viewProofRecords = records;
2888
+ this.viewProofRecordCount = records.length;
2889
+ if (
2890
+ !this.proofResyncRequested &&
2891
+ records.some((record) => (record as { marker?: unknown } | null)?.marker === "F") &&
2892
+ (snap.viewProof as { status?: string } | null | undefined)?.status !== "covered"
2893
+ ) {
2894
+ this.proofResyncRequested = true;
2895
+ this.attachClient.requestResync("view-proof-records-without-coverage");
2896
+ }
2897
+ this.viewProofTrailing.reset();
2898
+ this.recentProtocolOutput = [];
2899
+ const evidence = resizeIntentEvidenceFromRecords(
2900
+ { required: this.resizeIntentRequired, geometryRevision: this.geometryRevision, intentId: this.resizeIntentId, cols: this.cols, rows: this.rows },
2901
+ records,
2902
+ );
2903
+ this.resizeIntentSatisfied = evidence.satisfied;
2904
+ this.resizeIntentProofSeq = evidence.proofSeq;
2905
+ if (snap.viewProof !== undefined) {
2906
+ this.latestViewProof = snap.viewProof;
2907
+ this.viewProofIdentity = (snap.viewProof as { status?: string } | null)?.status === "covered" ? this.currentViewIdentity() : null;
2908
+ if ((snap.viewProof as { status?: string } | null)?.status === "covered") this.proofResyncRequested = false;
2909
+ } else if (snap.empty === true) {
2910
+ this.latestViewProof = { status: "unknown", reason: "empty-baseline", proof: null, throughSeq: null, cursorVisible: null };
2911
+ this.viewProofIdentity = null;
2912
+ } else {
2913
+ this.latestViewProof = null;
2914
+ this.viewProofIdentity = null;
2915
+ }
1718
2916
  if (typeof snap.frame === "string") {
2917
+ this.protocolBaselineState = "valid-content";
2918
+ this.localHydrationState = "hydrating";
1719
2919
  this.pushOutput(snap.frame, { authoritative: true, scrollbackLines: snap.scrollbackLines });
1720
2920
  } else if (snap.empty || snap.resnapshot) {
2921
+ if (snap.empty === true) {
2922
+ this.committedView = null;
2923
+ this.invalidateRecoveryView();
2924
+ this.invalidateViewProof("new-empty-baseline");
2925
+ this.emptyResetPending = true;
2926
+ }
2927
+ this.protocolBaselineState = "valid-empty";
1721
2928
  this.childInputReady = false;
1722
2929
  this.childInputModeCarry = "";
1723
- this.term.reset();
1724
- // Issue #205: the buffer is empty again, so a stale floor would make the
1725
- // first `floor` lines of the restarted host unscrollable.
2930
+ // Issue #205: the replacement parser is empty, so no stale floor/poison
2931
+ // survives. Empty/resnapshot never triggers the first-attach hooks.
1726
2932
  this.historyFloor = 0;
2933
+ this.scheduleRender();
2934
+ this.evaluateAttachReady();
1727
2935
  }
1728
2936
  return;
1729
2937
  }
1730
2938
  if (event === "output") {
2939
+ // Replacement failure is a hard fence: protocol bytes cannot be mixed into
2940
+ // the old parser while waiting for a bounded fresh resync/legacy decision.
2941
+ if (this.localHydrationState === "failed") return;
1731
2942
  // Live/replay protocol output: no jiggle clear-detection — that feed
1732
2943
  // exists to cancel the shrink-and-hold chain, which never runs in
1733
2944
  // protocol mode.
1734
- if (typeof payload === "string") this.pushOutput(payload, { forwardProtocols: true });
2945
+ if (typeof payload === "string") {
2946
+ this.recentProtocolOutput.push({ seq: this.attachClient.getLastSeq(), data: payload });
2947
+ if (this.recentProtocolOutput.length > 16) this.recentProtocolOutput.shift();
2948
+ this.noteViewProofOutput(payload);
2949
+ this.pushOutput(payload, { forwardProtocols: true });
2950
+ }
2951
+ return;
2952
+ }
2953
+ if (event === "viewProof") {
2954
+ this.latestViewProof = payload ?? null;
2955
+ if ((payload as { status?: string } | null)?.status === "covered") {
2956
+ this.viewProofIdentity = this.currentViewIdentity();
2957
+ this.viewProofTrailing.reset({ cursorVisible: typeof (payload as { cursorVisible?: unknown }).cursorVisible === "boolean" ? (payload as { cursorVisible: boolean }).cursorVisible : undefined });
2958
+ } else {
2959
+ this.viewProofIdentity = null;
2960
+ this.viewProofTrailing.reset();
2961
+ if (String((payload as { reason?: string } | null)?.reason ?? "").includes("reporter-replaced")) {
2962
+ this.viewProofRecords = [];
2963
+ this.viewProofRecordCount = 0;
2964
+ }
2965
+ }
2966
+ this.evaluateAttachReady();
2967
+ return;
2968
+ }
2969
+ if (event === "viewProofRecord") {
2970
+ if (payload !== null && typeof payload === "object") {
2971
+ const record = payload as Record<string, unknown>;
2972
+ this.noteViewProofRecord(record);
2973
+ if (record.marker === "F") {
2974
+ // Issue #294: one matcher for every evidence source — a live F
2975
+ // re-evaluates through the same pure predicate (full validation
2976
+ // incl. target dims); a non-match leaves the evidence untouched.
2977
+ const evidence = resizeIntentEvidenceFromRecords(
2978
+ { required: this.resizeIntentRequired, geometryRevision: this.geometryRevision, intentId: this.resizeIntentId, cols: this.cols, rows: this.rows },
2979
+ [record],
2980
+ );
2981
+ if (evidence.satisfied) {
2982
+ this.resizeIntentSatisfied = true;
2983
+ this.resizeIntentProofSeq = evidence.proofSeq;
2984
+ }
2985
+ }
2986
+ this.evaluateAttachReady();
2987
+ }
1735
2988
  return;
1736
2989
  }
1737
2990
  if (event === "epochReset") {
1738
2991
  this.childInputReady = false;
1739
2992
  this.childInputModeCarry = "";
2993
+ this.committedView = null;
2994
+ this.invalidateRecoveryView();
2995
+ this.invalidateViewProof("epoch-reset");
2996
+ this.externalOutputActive = false;
1740
2997
  }
2998
+ // "viewProof"/"viewProofRecord": independent protocol facts in this stage;
2999
+ // the component has no readiness/publish hook for them yet.
1741
3000
  // "resubscribing": recovery is client-internal (informational only).
1742
3001
  // "protocolError": observability only — recovery is automatic until the
1743
3002
  // legacy fallback, whose mode event the UI acts on above.
@@ -1759,7 +3018,8 @@ export class PtyAttachComponent implements Component {
1759
3018
  if (process.env.AGENT_BOARD_FORWARD_IMAGES !== "0") {
1760
3019
  const { sequences, carry } = extractTerminalPassthroughSequences(this.passthroughCarry + data);
1761
3020
  this.passthroughCarry = carry;
1762
- toWrite.push(...sequences);
3021
+ // Kitty placements belong to projected grid rows, not the host's parked cursor.
3022
+ toWrite.push(...sequences.filter((seq) => !seq.startsWith(KITTY_IMAGE_PREFIX)));
1763
3023
  }
1764
3024
  if (process.env.AGENT_BOARD_FORWARD_TERMINAL_QUERIES !== "0") {
1765
3025
  // Issue #128 D1: forward the child's terminal capability queries
@@ -1830,25 +3090,79 @@ export class PtyAttachComponent implements Component {
1830
3090
  }
1831
3091
  if (opts.forwardProtocols || opts.authoritative) this.updateChildInputReadiness(data);
1832
3092
  if (opts.forwardProtocols) this.forwardTerminalProtocols(data);
3093
+ const term = this.term;
3094
+ const connectionToken = this.connectionToken;
3095
+ const baselineToken = this.baselineToken;
3096
+ const parserEpoch = this.parserEpoch;
3097
+ const generation = this.attachClient.getIdentity().generation ?? "local";
3098
+ const capturedIdentity = { connectionToken, baselineToken, generation, parser: term, geometryRevision: this.geometryRevision, targetCols: this.cols, targetRows: this.rows, closed: false };
1833
3099
  // @xterm/headless parses asynchronously; the buffer is only populated once this
1834
3100
  // callback fires. Mark the buffer as ready (so the project path can paint it), but
1835
3101
  // stay on the loading banner while `attaching` — otherwise the screen-log replay and
1836
3102
  // the initial resize-jiggle redraws would flash through the viewport. Each parsed
1837
- // chunk also defers the settle window, so the banner holds until output actually
3103
+ // chunk defers the settle window, so the banner holds until output actually
1838
3104
  // stops arriving (i.e. the redraw finished), not just until the resize jiggle ends.
1839
- this.term.write(data, () => {
3105
+ // Current-epoch invariant: replaceParser() resets this counter to 0 when it
3106
+ // advances parserEpoch. A stale callback returns below WITHOUT decrementing;
3107
+ // decrementing it would cancel a new-epoch write and allow premature publish.
3108
+ this.parserWritesInFlight += 1;
3109
+ try {
3110
+ // snapshotReady already replaced the parser and Kitty bridge; injecting an
3111
+ // extra reset OSC into its frame would disturb complete-frame observation.
3112
+ term.write(this.kittyImages?.transform(data) ?? data, () => {
3113
+ if (this.parserEpoch !== parserEpoch) return;
3114
+ if (this.parserWritesInFlight > 0) this.parserWritesInFlight -= 1;
3115
+ const currentIdentity = {
3116
+ connectionToken: this.connectionToken,
3117
+ baselineToken: this.baselineToken,
3118
+ generation: this.attachClient.getIdentity().generation ?? "local",
3119
+ parser: this.term,
3120
+ geometryRevision: this.geometryRevision,
3121
+ targetCols: this.cols,
3122
+ targetRows: this.rows,
3123
+ closed: this.closed,
3124
+ };
3125
+ if (!canPublishAttachView(capturedIdentity, currentIdentity)) return;
1840
3126
  if (opts.forwardProtocols || opts.authoritative) this.flushPendingSchemeReport();
1841
3127
  // Issue #205: baseY is only final once this chunk parsed, and the callback
1842
3128
  // has no buffer binding — re-read it. Rows past the runner-vouched
1843
3129
  // scrollback are overflow the hydration itself scrolled out.
1844
- if (opts.authoritative) this.historyFloor = historyFloorAfterHydrate(this.term.buffer.active.baseY, opts.scrollbackLines);
3130
+ if (opts.authoritative) {
3131
+ this.historyFloor = historyFloorAfterHydrate(term.buffer.active.baseY, opts.scrollbackLines);
3132
+ this.localHydrationState = "complete";
3133
+ if (this.screenOwnerResyncPending) {
3134
+ // The hydrating frame's wrapper sync window is fully parsed now;
3135
+ // restore adapter/component ownership agreement before committing.
3136
+ this.screenOwnerResyncPending = false;
3137
+ this.resyncScreenOwnerAdapter(term, parserEpoch);
3138
+ }
3139
+ if (!this.parserSyncOpen) this.commitCommittedView(term, parserEpoch, "snapshot");
3140
+ }
1845
3141
  this.receivedOutput = true;
1846
- this.deferAttachSettle();
1847
- this.outputRenderScheduler.request();
1848
- });
3142
+ this.deferAttachSettle();
3143
+ this.outputRenderScheduler.request();
3144
+ this.evaluateAttachReady();
3145
+ });
3146
+ } catch {
3147
+ if (this.parserEpoch === parserEpoch && this.parserWritesInFlight > 0) this.parserWritesInFlight -= 1;
3148
+ }
3149
+ }
3150
+
3151
+ private projectCommitted(height: number): { lines: string[]; cursor: { row: number; col: number } | null } {
3152
+ const view = this.activeCommittedView();
3153
+ if (view === null) return { lines: [], cursor: null };
3154
+ const selection = normalizeSelection(this.selection);
3155
+ const out: string[] = [];
3156
+ for (let index = 0; index < view.rows.length && out.length < height; index += 1) {
3157
+ const lineIndex = view.start + index;
3158
+ out.push(view.rows[index].kittyPrefix + lineToAnsi(view.rows[index].cells, SnapshotCell.empty(), this.term, lineIndex, selection, view.cursor, view.cursorHidden));
3159
+ }
3160
+ return { lines: out, cursor: view.cursor };
1849
3161
  }
1850
3162
 
1851
3163
  private project(height: number): { lines: string[]; cursor: { row: number; col: number } | null } {
3164
+ if (this.closed) return { lines: [], cursor: null };
3165
+ if (this.usesCommittedProjection()) return this.projectCommitted(height);
1852
3166
  const out: string[] = [];
1853
3167
  const buf = this.term.buffer.active;
1854
3168
  const selection = normalizeSelection(this.selection);
@@ -1865,7 +3179,7 @@ export class PtyAttachComponent implements Component {
1865
3179
  out.push(lineToAnsi(buf.getLine(i), reusable, this.term, i, selection, cursor, cursorHidden));
1866
3180
  }
1867
3181
  if (out.length === 0) out.push("Waiting for PTY output…");
1868
- return { lines: out.slice(-height), cursor };
3182
+ return { lines: this.kittyImages?.project(out.slice(-height), start, height) ?? out.slice(-height), cursor };
1869
3183
  }
1870
3184
 
1871
3185
  private close(gracefulSocket = false): void {
@@ -1876,6 +3190,12 @@ export class PtyAttachComponent implements Component {
1876
3190
  return;
1877
3191
  }
1878
3192
  this.closed = true;
3193
+ this.attachWaitToken += 1;
3194
+ this.committedView = null;
3195
+ this.externalOutputActive = false;
3196
+ this.recoveryView = null;
3197
+ this.recoveryGeneration = null;
3198
+ this.disposeCurrentParser();
1879
3199
  this.imeCoalesceUninstall?.();
1880
3200
  this.detachColorSchemeBridge();
1881
3201
  this.clearReplyGuardTimer();
@@ -1889,15 +3209,38 @@ export class PtyAttachComponent implements Component {
1889
3209
  this.clearRetry();
1890
3210
  this.stopLoadingTicker();
1891
3211
  this.outputRenderScheduler.dispose();
3212
+ // Narrow feature-detected host seam (repo pi-tui 1.1.0, host pi 1.4.0):
3213
+ // cancel the already-queued TUI frame without stopping the TUI. A closed
3214
+ // flag inside render cannot cancel a render queued before dispose.
3215
+ const renderSeam = this.tui as unknown as {
3216
+ cancelRenderTimer?: () => void;
3217
+ renderRequested?: boolean;
3218
+ };
3219
+ if (typeof renderSeam.cancelRenderTimer === "function") {
3220
+ try { renderSeam.cancelRenderTimer(); } catch { /* host seam is best-effort */ }
3221
+ }
3222
+ // TuiBase.requestImmediateRender() queues a process.nextTick that checks
3223
+ // renderRequested; clearing it cancels an already queued immediate paint
3224
+ // without stopping the TUI. Verified host pi 1.4.0 shape.
3225
+ if (typeof renderSeam.renderRequested === "boolean") renderSeam.renderRequested = false;
1892
3226
  this.stopDesyncProbe();
1893
- if (this.attachSettleTimer) {
1894
- clearTimeout(this.attachSettleTimer);
3227
+ if (this.attachSettleTimer !== null) {
3228
+ this.clock.clear(this.attachSettleTimer);
1895
3229
  this.attachSettleTimer = null;
1896
3230
  }
1897
- if (this.attachHardTimeout) {
1898
- clearTimeout(this.attachHardTimeout);
3231
+ if (this.attachHardTimeout !== null) {
3232
+ this.clock.clear(this.attachHardTimeout);
1899
3233
  this.attachHardTimeout = null;
1900
3234
  }
3235
+ this.clearAttachRecoveryBudget();
3236
+ this.budgetArmed = false;
3237
+ // Issue #284 latch layer: the latch is attach-scoped — detach/dispose
3238
+ // ends this attach; a new component re-observes the capability fresh.
3239
+ this.witnessLatched = false;
3240
+ // Same attach scope for the sticky failure fact (spec §3.1.1/I6) and the
3241
+ // #288 hard-dominance latch (spec §3 I8).
3242
+ this.proofInvalidatedBaselineToken = null;
3243
+ this.proofHardInvalidatedThisBaseline = null;
1901
3244
  this.clearGracefulSocketCloseTimer();
1902
3245
  const socket = this.socket;
1903
3246
  this.socket = null;
@@ -2119,12 +3462,14 @@ function clip(line: string, width: number): string {
2119
3462
 
2120
3463
  function clipTerminalLine(line: string, width: number): string {
2121
3464
  // pi-tui's width helpers are ANSI-aware, but OSC sequences are terminal
2122
- // protocols rather than SGR styling. Avoid truncating inside OSC 8 hyperlinks;
2123
- // these lines are already projected from an xterm buffer sized to the viewport.
2124
- return line.includes("\x1b]") ? line : clip(line, width);
3465
+ // protocols rather than SGR styling. Preserve complete OSC 8 links and Kitty
3466
+ // APCs; these lines are projected from a buffer already sized to the viewport.
3467
+ return line.includes("\x1b]") || line.includes(KITTY_IMAGE_PREFIX) ? line : clip(line, width);
2125
3468
  }
2126
3469
 
2127
3470
  function osc8UriForCell(term: XtermLike, cell: BufferCellLike): string {
3471
+ const committed = (cell as { osc8Uri?: () => string }).osc8Uri?.();
3472
+ if (typeof committed === "string" && committed.length > 0) return committed;
2128
3473
  // xterm leaves cached extended data on reused cells when this flag is unset.
2129
3474
  if (!cell.hasExtendedAttrs()) return "";
2130
3475
  const id = cell.extended?.urlId ?? cell.extended?._urlId ?? 0;