@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
@@ -39,7 +39,11 @@ import {
39
39
  } from "../src/core/control-protocol.mjs";
40
40
  import { readHost, readState, updateOwnedHost, writeHost } from "../src/core/store.mjs";
41
41
  import { sendStateCommand } from "../src/core/coordinator-client.mjs";
42
- import { classifyClientHello, helloBookkeeping } from "../src/core/host-protocol.mjs";
42
+ import { classifyClientHello, helloBookkeeping, CLIENT_ID_FRAME_REPORTER } from "../src/core/host-protocol.mjs";
43
+ import { createFrameStreamParser } from "../src/core/attach-frame-stream.mjs";
44
+ import { createViewProofTracker } from "../src/core/attach-view-proof.mjs";
45
+ import { createFrameWitnessSummaryScheduler } from "../src/core/frame-witness-update.mjs";
46
+ import { createHash, randomBytes } from "node:crypto";
43
47
  import { markRowFailedDirect } from "./pty-runner-legacy.mjs";
44
48
  import { ensureNodePtySpawnHelperExecutable } from "../src/core/pty-support.mjs";
45
49
 
@@ -99,6 +103,218 @@ function readScreenLogTail(path, maxBytes) {
99
103
  * @param {string} screenLogPath
100
104
  * @returns {{} | { error: string }}
101
105
  */
106
+ /**
107
+ * Issue #222 FW-03/FW-04 runner-side frame-witness plumbing.
108
+ *
109
+ * A frame reporter socket (`hello` with `clientId:"frame-reporter"` and
110
+ * `frameWitness:{protocol:1}`) receives a per-instance random >=128-bit base64url token and
111
+ * the owned DCS parser is installed for that child. Old/no hello keeps byte-identical
112
+ * behaviour: `splitFrameChunk` passes the chunk through untouched.
113
+ */
114
+ function enableFrameReporter(socket, msg, send) {
115
+ const protocol = msg && msg.frameWitness && Number(msg.frameWitness.protocol);
116
+ if (msg?.clientId !== CLIENT_ID_FRAME_REPORTER || protocol !== 1) return null;
117
+ const token = randomBytes(32).toString("base64url");
118
+ // F4: the identity is the runner's ACTUAL generation (one per runner process), not a
119
+ // per-connection UUID. A reporter replacement gets a new token but the same generation.
120
+ const instanceId = GENERATION;
121
+ // The reporter reports its actual extension session epoch (1, then 2+ after a real
122
+ // /new). Absence keeps the legacy epoch-1 compatibility default; present values must
123
+ // be positive integers or the enable is rejected without installing proof.
124
+ const reportedEpoch = msg.frameWitness?.sessionEpoch;
125
+ let sessionEpoch = 1;
126
+ if (reportedEpoch !== undefined) {
127
+ if (!Number.isInteger(reportedEpoch) || reportedEpoch < 1) return null;
128
+ sessionEpoch = reportedEpoch;
129
+ }
130
+ const state = {
131
+ socket,
132
+ token,
133
+ instanceId,
134
+ sessionEpoch,
135
+ parser: createFrameStreamParser({ token, instanceId, sessionEpoch }),
136
+ viewProof: createViewProofTracker(),
137
+ viewProofBaselineSeeded: false,
138
+ viewProofFailures: 0,
139
+ viewProofLastFailure: null,
140
+ geometryRevision: 0,
141
+ requestSeq: 0,
142
+ intents: [],
143
+ };
144
+ send(socket, { type: "frame_witness_enable", protocol: 1, token, instanceId, sessionEpoch });
145
+ return state;
146
+ }
147
+
148
+ /** Split one child chunk into ordinary segments + proofs (marker bytes are stripped). */
149
+ function splitFrameChunk(data, frameReporter) {
150
+ if (!frameReporter) return [{ kind: "output", data }];
151
+ const parts = frameReporter.parser.push(data);
152
+ return parts.length > 0 ? parts : [];
153
+ }
154
+
155
+ /**
156
+ * Announce a frame-witness intent after an ACTUAL differing-size resize reached applied.
157
+ * Same-size requests do not call this at all (zero resize, no new revision). Each intent
158
+ * carries the current instance, a unique requestId, a monotonically increasing
159
+ * geometryRevision and the exact target cols/rows.
160
+ */
161
+ function announceFrameIntent(frameReporter, send, cols, rows) {
162
+ if (!frameReporter) return null;
163
+ frameReporter.geometryRevision += 1;
164
+ frameReporter.requestSeq += 1;
165
+ const intent = {
166
+ type: "frame_witness_intent",
167
+ protocol: 1,
168
+ instanceId: frameReporter.instanceId,
169
+ requestId: `fw-${frameReporter.requestSeq}`,
170
+ geometryRevision: frameReporter.geometryRevision,
171
+ cols,
172
+ rows,
173
+ };
174
+ frameReporter.intents.push({ requestId: intent.requestId, geometryRevision: intent.geometryRevision, cols, rows });
175
+ send(frameReporter.socket, intent);
176
+ return intent;
177
+ }
178
+
179
+ /**
180
+ * F7: ONE cleanup path for every lifecycle end (socket close/error, child exit, reporter
181
+ * replacement). Finishes the parser, forwards any trailing ORDINARY byte to the normal
182
+ * output path, and clears the state so no stale enabled reporter survives.
183
+ */
184
+ function cleanupFrameReporter(frameReporter, reason, forward) {
185
+ if (!frameReporter) return null;
186
+ const finished = frameReporter.parser.finish(reason);
187
+ if (typeof forward === "function" && typeof finished.trailing === "string" && finished.trailing.length > 0) forward(finished.trailing);
188
+ return finished;
189
+ }
190
+
191
+ /** Bounded host-facing summary (never the token). */
192
+ function frameWitnessSummary(frameReporter) {
193
+ if (!frameReporter) return { enabled: false };
194
+ const snapshot = frameReporter.parser.snapshot();
195
+ return {
196
+ enabled: true,
197
+ instanceId: frameReporter.instanceId,
198
+ sessionEpoch: frameReporter.sessionEpoch,
199
+ tokenFingerprint: createHash("sha256").update(frameReporter.token).digest("hex").slice(0, 16),
200
+ proofs: snapshot.proofs.length,
201
+ droppedProofs: snapshot.droppedProofs,
202
+ droppedFinishedIds: snapshot.droppedFinishedIds,
203
+ diagnostics: snapshot.diagnostics.length,
204
+ lastFrameId: snapshot.lastFrameId,
205
+ openFrameId: snapshot.openFrameId,
206
+ pendingBytes: snapshot.pendingBytes,
207
+ geometryRevision: frameReporter.geometryRevision,
208
+ intents: frameReporter.intents.length,
209
+ viewProofFailures: frameReporter.viewProofFailures ?? 0,
210
+ ...(frameReporter.viewProofLastFailure === null ? {} : { viewProofLastFailure: frameReporter.viewProofLastFailure }),
211
+ // Bounded, user-text-free view of the newest proof so a real-topology test can
212
+ // assert target geometry/mode/seq without parsing host-private internals.
213
+ lastProof: (() => {
214
+ const proofs = snapshot.proofs;
215
+ const last = proofs.length === 0 ? null : proofs[proofs.length - 1];
216
+ if (last === null) return null;
217
+ return {
218
+ marker: last.marker,
219
+ frameId: last.frameId,
220
+ seq: last.seq,
221
+ sessionEpoch: last.sessionEpoch,
222
+ ...(last.metadata === undefined
223
+ ? { reason: last.reason }
224
+ : {
225
+ cols: last.metadata.cols,
226
+ rows: last.metadata.rows,
227
+ mode: last.metadata.mode,
228
+ rendererEpoch: last.metadata.rendererEpoch,
229
+ intentId: last.metadata.intentId,
230
+ geometryRevision: last.metadata.geometryRevision,
231
+ }),
232
+ };
233
+ })(),
234
+ };
235
+ }
236
+
237
+ /** One per-enabled-reporter tracker source; reads the CURRENT reporter on every call. */
238
+ function createViewProofSource(getReporter) {
239
+ return {
240
+ coverage(seq) {
241
+ try {
242
+ return getReporter()?.viewProof?.coverageFor(seq) ?? null;
243
+ } catch {
244
+ return null;
245
+ }
246
+ },
247
+ replay(fromSeq, throughSeq) {
248
+ try {
249
+ return getReporter()?.viewProof?.replay(fromSeq, throughSeq) ?? null;
250
+ } catch {
251
+ return null;
252
+ }
253
+ },
254
+ };
255
+ }
256
+
257
+ function noteViewProofFailure(frameReporter, reason) {
258
+ if (!frameReporter) return;
259
+ frameReporter.viewProofFailures = (frameReporter.viewProofFailures ?? 0) + 1;
260
+ frameReporter.viewProofLastFailure = String(reason).slice(0, 64);
261
+ }
262
+
263
+ /** Feed the canonical segment seq into the tracker BEFORE subscriptions see it. */
264
+ function feedViewProofOutput(frameReporter, seq, data) {
265
+ if (!frameReporter?.viewProof) return;
266
+ try {
267
+ const result = frameReporter.viewProof.feedOutput(seq, data);
268
+ if (result.status === "protocol-error") noteViewProofFailure(frameReporter, result.reason);
269
+ else frameReporter.viewProofBaselineSeeded = true;
270
+ } catch (err) {
271
+ noteViewProofFailure(frameReporter, err instanceof Error ? err.message : String(err));
272
+ }
273
+ }
274
+
275
+ /**
276
+ * Route one additive S candidate or F/A proof into the accepted tracker. Returns the
277
+ * accepted wire record (seq already assigned) or null. Never calls completeProof for an
278
+ * S/A record.
279
+ */
280
+ function applyViewProofPart(frameReporter, part, seq) {
281
+ if (!frameReporter?.viewProof) return null;
282
+ const record = part.kind === "candidate" ? part.candidate : part.kind === "proof" ? part.proof : null;
283
+ if (record === null) return null;
284
+ record.seq = seq;
285
+ // A tracker created at reporter-enable time may see its first S before any ordinary
286
+ // segment was fed after enable. Adopt the runner's existing output seq as the baseline
287
+ // (zero bytes retained) so the real first frame is not dropped.
288
+ if (record.marker === "S" && frameReporter.viewProofBaselineSeeded === false && seq >= 1) {
289
+ try {
290
+ const baseline = frameReporter.viewProof.feedOutput(seq, "");
291
+ if (baseline.status === "protocol-error") noteViewProofFailure(frameReporter, baseline.reason);
292
+ else frameReporter.viewProofBaselineSeeded = true;
293
+ } catch (err) {
294
+ noteViewProofFailure(frameReporter, err instanceof Error ? err.message : String(err));
295
+ }
296
+ }
297
+ let result;
298
+ try {
299
+ if (record.marker === "S") result = frameReporter.viewProof.openCandidate(record);
300
+ else if (record.marker === "F") result = frameReporter.viewProof.completeProof(record);
301
+ else if (record.marker === "A") result = frameReporter.viewProof.abortCandidate(record);
302
+ else result = { status: "protocol-error", reason: "unknown-record-marker" };
303
+ } catch (err) {
304
+ noteViewProofFailure(frameReporter, err instanceof Error ? err.message : String(err));
305
+ return null;
306
+ }
307
+ if (result.status !== "ok") {
308
+ noteViewProofFailure(frameReporter, result.reason);
309
+ return null;
310
+ }
311
+ return record;
312
+ }
313
+
314
+ function resetViewProofSubscribers(terminalSubscriptions, reason) {
315
+ for (const sub of terminalSubscriptions.values()) sub.onViewProofReset?.(reason);
316
+ }
317
+
102
318
  function attributedExitError(exitCode, screenLogPath) {
103
319
  if (exitCode === 0) return {};
104
320
  try {
@@ -145,12 +361,16 @@ function legacyMain(config) {
145
361
  const clients = new Set();
146
362
  /** Resident editor-state reporters: connected but never "attached" (#103). */
147
363
  const editorReporters = new Set();
364
+ let frameReporter = null;
365
+ let lastOutputSeq = 0;
148
366
  let childPid = null;
149
367
  let child = null;
150
368
  let exitCode = null;
151
369
  let shutdownStarted = false;
152
370
  let shutdownExitCode = null;
153
371
  let childExited = false;
372
+ /** {dev,ino} recorded at bind time; cleanup unlinks only this exact inode. */
373
+ let boundSocketIdentity = null;
154
374
  let resolveChildExit;
155
375
  const childExitPromise = new Promise((resolve) => {
156
376
  resolveChildExit = resolve;
@@ -193,6 +413,18 @@ function legacyMain(config) {
193
413
  // legacy-mode main: no instance fence exists, so EVERY envelope claims a
194
414
  // foreign instance and is rejected with `instance_mismatch` (documented
195
415
  // contract — legacy-mode hosts serve only envelope-less clients).
416
+ // Shared by the control runtime and the plain resize message. Only an ACTUAL
417
+ // model geometry change announces an intent; same-size/no-op stays silent.
418
+ const applyResize = (cols, rows) => {
419
+ const before = { cols: terminalModel.cols, rows: terminalModel.rows };
420
+ resizeChildAndModel(child, terminalModel, cols, rows);
421
+ update({ cols, rows });
422
+ const after = { cols: terminalModel.cols, rows: terminalModel.rows };
423
+ if (frameReporter !== null && (after.cols !== before.cols || after.rows !== before.rows)) {
424
+ announceFrameIntent(frameReporter, send, after.cols, after.rows);
425
+ frameWitnessSummaryUpdates.flush();
426
+ }
427
+ };
196
428
  const control = createControlRuntime({
197
429
  viewId: config.viewId,
198
430
  root: config.root,
@@ -212,10 +444,7 @@ function legacyMain(config) {
212
444
  },
213
445
  hostCols: () => host.cols,
214
446
  hostRows: () => host.rows,
215
- applyResize: (cols, rows) => {
216
- resizeChildAndModel(child, terminalModel, cols, rows);
217
- update({ cols, rows });
218
- },
447
+ applyResize,
219
448
  currentDims: () => ({ cols: terminalModel.cols, rows: terminalModel.rows }),
220
449
  applyInterrupt: () => {
221
450
  if (child) child.write("\x1b");
@@ -259,6 +488,11 @@ function legacyMain(config) {
259
488
  persist();
260
489
  broadcast({ type: "status", status: host, generation: GENERATION });
261
490
  };
491
+ const frameWitnessSummaryUpdates = createFrameWitnessSummaryScheduler({
492
+ publish: () => {
493
+ if (frameReporter !== null) update({ frameWitness: frameWitnessSummary(frameReporter) });
494
+ },
495
+ });
262
496
  persist();
263
497
 
264
498
  // Last-resort crash path (registered early, before spawnInteractive, so any
@@ -332,25 +566,64 @@ function legacyMain(config) {
332
566
  update({ childPid });
333
567
 
334
568
  child.onData((data) => {
335
- screenLogBytes = appendBoundedScreenLog(screenLog, data, screenLogBytes, screenLogLimits);
336
- const outputSeq = feedOutput(terminalModel, data);
337
- // Per-socket output delivery (issue #91 phase 3): sockets that speak the
338
- // subscribe_terminal protocol get exactly-once, gap-checked chunks from
339
- // their subscription state machine; every other client keeps the legacy
340
- // fire-and-forget broadcast (additive seq). Both streams to one socket
341
- // would duplicate every chunk.
342
- const outputLine = JSON.stringify({ type: "output", seq: outputSeq, data }) + "\n";
343
- for (const [socket, sub] of terminalSubscriptions) {
344
- if (sub.subscribed()) sub.onOutput(outputSeq, data);
345
- // Per-socket guard: a synchronous throw from a dead socket must never
346
- // escape into the uncaughtException crash path (whole-branch review).
347
- else { try { socket.write(outputLine); } catch { /* 'error' handler cleans up */ } }
569
+ // Issue #222 FW-03: split the ordered stream at exact DCS marker boundaries. With
570
+ // no frame reporter this is the byte-identical legacy path (one output part).
571
+ // Marker bytes never reach screenLog, the canonical model, subscribers or the
572
+ // legacy broadcast.
573
+ for (const part of splitFrameChunk(data, frameReporter)) {
574
+ if (part.kind !== "output") {
575
+ // S opens; F completes; A aborts. Never call completeProof for every record.
576
+ const record = applyViewProofPart(frameReporter, part, lastOutputSeq);
577
+ if (record !== null) {
578
+ for (const sub of terminalSubscriptions.values()) sub.onViewProofRecord?.(record);
579
+ }
580
+ if (frameReporter !== null) frameWitnessSummaryUpdates.schedule();
581
+ continue;
582
+ }
583
+ const chunk = part.data;
584
+ screenLogBytes = appendBoundedScreenLog(screenLog, chunk, screenLogBytes, screenLogLimits);
585
+ const outputSeq = feedOutput(terminalModel, chunk);
586
+ lastOutputSeq = outputSeq;
587
+ feedViewProofOutput(frameReporter, outputSeq, chunk);
588
+ // Per-socket output delivery (issue #91 phase 3): sockets that speak the
589
+ // subscribe_terminal protocol get exactly-once, gap-checked chunks from
590
+ // their subscription state machine; every other client keeps the legacy
591
+ // fire-and-forget broadcast (additive seq). Both streams to one socket
592
+ // would duplicate every chunk.
593
+ const outputLine = JSON.stringify({ type: "output", seq: outputSeq, data: chunk }) + "\n";
594
+ for (const [socket, sub] of terminalSubscriptions) {
595
+ if (sub.subscribed()) sub.onOutput(outputSeq, chunk);
596
+ // Per-socket guard: a synchronous throw from a dead socket must never
597
+ // escape into the uncaughtException crash path (whole-branch review).
598
+ else { try { socket.write(outputLine); } catch { /* 'error' handler cleans up */ } }
599
+ }
348
600
  }
349
601
  });
350
602
  child.onExit((code) => {
351
603
  childExited = true;
352
604
  resolveChildExit?.();
353
605
  exitCode = code ?? 0;
606
+ if (frameReporter !== null) {
607
+ // F9: a trailing ordinary byte is forwarded through the normal output path.
608
+ cleanupFrameReporter(frameReporter, "child-exit", (trailing) => {
609
+ try {
610
+ screenLogBytes = appendBoundedScreenLog(screenLog, trailing, screenLogBytes, screenLogLimits);
611
+ const seq = feedOutput(terminalModel, trailing);
612
+ feedViewProofOutput(frameReporter, seq, trailing);
613
+ for (const [socket, sub] of terminalSubscriptions) {
614
+ if (sub.subscribed()) sub.onOutput(seq, trailing);
615
+ }
616
+ } catch {
617
+ /* best effort during exit */
618
+ }
619
+ });
620
+ resetViewProofSubscribers(terminalSubscriptions, "child-exit");
621
+ try {
622
+ frameWitnessSummaryUpdates.flush();
623
+ } catch {
624
+ /* row may already be finalised */
625
+ }
626
+ }
354
627
  // Terminate lifecycle (spec D4): a confirmed child exit is the observed
355
628
  // evidence for any enveloped terminate still pending on a live socket.
356
629
  control.flushTerminateObservations(exitCode, false);
@@ -377,7 +650,7 @@ function legacyMain(config) {
377
650
  clients.add(socket);
378
651
  terminalSubscriptions.set(
379
652
  socket,
380
- createTerminalSubscription({ model: terminalModel, send: (msg) => send(socket, msg), generation: GENERATION }),
653
+ createTerminalSubscription({ model: terminalModel, send: (msg) => send(socket, msg), generation: GENERATION, viewProof: createViewProofSource(() => frameReporter) }),
381
654
  );
382
655
  socket.write(JSON.stringify({ type: "hello", status: host, editorEmpty, generation: GENERATION }) + "\n");
383
656
  let buffer = "";
@@ -392,21 +665,66 @@ function legacyMain(config) {
392
665
  editorReporters.delete(socket);
393
666
  terminalSubscriptions.delete(socket);
394
667
  control.closeSocket(socket);
395
- update();
668
+ const reporterLost = frameReporter !== null && frameReporter.socket === socket;
669
+ if (reporterLost) {
670
+ frameWitnessSummaryUpdates.cancel();
671
+ // P2: a trailing ORDINARY byte must not be lost when the reporter goes away.
672
+ cleanupFrameReporter(frameReporter, "reporter-close", (trailing) => {
673
+ try {
674
+ screenLogBytes = appendBoundedScreenLog(screenLog, trailing, screenLogBytes, screenLogLimits);
675
+ const seq = feedOutput(terminalModel, trailing);
676
+ lastOutputSeq = seq;
677
+ feedViewProofOutput(frameReporter, seq, trailing);
678
+ for (const [peer, sub] of terminalSubscriptions) if (sub.subscribed()) sub.onOutput(seq, trailing);
679
+ } catch {
680
+ /* best effort */
681
+ }
682
+ });
683
+ frameReporter = null;
684
+ resetViewProofSubscribers(terminalSubscriptions, "reporter-close");
685
+ }
686
+ update(reporterLost ? { frameWitness: { enabled: false } } : {});
396
687
  });
397
688
  socket.on("error", () => {
398
689
  clients.delete(socket);
399
690
  editorReporters.delete(socket);
400
691
  terminalSubscriptions.delete(socket);
401
692
  control.closeSocket(socket);
402
- update();
693
+ const reporterLost = frameReporter !== null && frameReporter.socket === socket;
694
+ if (reporterLost) {
695
+ frameWitnessSummaryUpdates.cancel();
696
+ cleanupFrameReporter(frameReporter, "reporter-error", (trailing) => {
697
+ try {
698
+ screenLogBytes = appendBoundedScreenLog(screenLog, trailing, screenLogBytes, screenLogLimits);
699
+ const seq = feedOutput(terminalModel, trailing);
700
+ lastOutputSeq = seq;
701
+ feedViewProofOutput(frameReporter, seq, trailing);
702
+ for (const [peer, sub] of terminalSubscriptions) if (sub.subscribed()) sub.onOutput(seq, trailing);
703
+ } catch {
704
+ /* best effort */
705
+ }
706
+ });
707
+ frameReporter = null;
708
+ resetViewProofSubscribers(terminalSubscriptions, "reporter-error");
709
+ }
710
+ update(reporterLost ? { frameWitness: { enabled: false } } : {});
403
711
  });
404
712
  });
405
713
  server.on("error", (err) => {
406
714
  update({ state: "failed", endedAt: Date.now(), error: err instanceof Error ? err.message : String(err), exitCode: 1 });
407
715
  void shutdown(1);
408
716
  });
409
- server.listen(socketPath, () => update({ socketPath, state: "alive" }));
717
+ server.listen(socketPath, () => {
718
+ // Capture the identity BEFORE publishing readiness: "host ready" must imply
719
+ // "identity recorded", or a shutdown could run with a stale/null identity.
720
+ if (process.platform !== "win32") {
721
+ try {
722
+ const st = statSync(socketPath);
723
+ boundSocketIdentity = { dev: st.dev, ino: st.ino };
724
+ } catch { /* without the identity, cleanup degrades to a no-op */ }
725
+ }
726
+ update({ socketPath, state: "alive" });
727
+ });
410
728
 
411
729
  function handleClientLine(line, socket) {
412
730
  if (!line.trim()) return;
@@ -434,6 +752,33 @@ function legacyMain(config) {
434
752
  terminalSubscriptions.delete(socket);
435
753
  }
436
754
  if (book.registerReporter) editorReporters.add(socket);
755
+ // Issue #222 FW-04: a frame reporter gets a per-instance random token; only a
756
+ // valid hello + frameWitness protocol 1 enables anything. Old/no hello is
757
+ // unchanged (no new messages).
758
+ {
759
+ const enabled = enableFrameReporter(socket, msg, send);
760
+ if (enabled !== null) {
761
+ const replacingReporter = frameReporter !== null && frameReporter.socket !== socket;
762
+ if (replacingReporter) {
763
+ // Same ordinary-trailing forwarding path as close/error/child-exit: a
764
+ // pending ordinary tail must not be lost when the reporter is replaced.
765
+ cleanupFrameReporter(frameReporter, "reporter-replaced", (trailing) => {
766
+ try {
767
+ screenLogBytes = appendBoundedScreenLog(screenLog, trailing, screenLogBytes, screenLogLimits);
768
+ const seq = feedOutput(terminalModel, trailing);
769
+ lastOutputSeq = seq;
770
+ feedViewProofOutput(frameReporter, seq, trailing);
771
+ for (const [peer, sub] of terminalSubscriptions) if (sub.subscribed()) sub.onOutput(seq, trailing);
772
+ } catch {
773
+ /* best effort during replacement */
774
+ }
775
+ });
776
+ }
777
+ frameReporter = enabled;
778
+ if (replacingReporter) resetViewProofSubscribers(terminalSubscriptions, "reporter-replaced");
779
+ try { frameWitnessSummaryUpdates.flush(); } catch { /* row may be finalised */ }
780
+ }
781
+ }
437
782
  // A real client writes via flipAttachedEver alone (hence the `else
438
783
  // if`); `persist` is the write flag for rows that write as-is (reporter).
439
784
  if (book.flipAttachedEver) update({ attachedEver: true });
@@ -447,11 +792,7 @@ function legacyMain(config) {
447
792
  case "resize": {
448
793
  const cols = clampInt(msg.cols, 20, 300, host.cols);
449
794
  const rows = clampInt(msg.rows, 5, 120, host.rows);
450
- // Paired step (CR R1 advisory): model reflows only when the real PTY
451
- // resize succeeded. host.cols/rows keep recording the intended size
452
- // (new-client clamp baseline), deliberately outside the guard.
453
- resizeChildAndModel(child, terminalModel, cols, rows);
454
- update({ cols, rows });
795
+ applyResize(cols, rows);
455
796
  break;
456
797
  }
457
798
  case "interrupt":
@@ -508,8 +849,24 @@ function legacyMain(config) {
508
849
  // runner-finalizing evidence before sockets end (exit-confirm flush in
509
850
  // child.onExit covers the natural path; this covers deliberate shutdown).
510
851
  control.flushTerminateObservations(null, true);
511
- try { server?.close(); } catch {}
512
- try { if (existsSync(socketPath)) unlinkSync(socketPath); } catch {}
852
+ // Do NOT call server.close() (issue #257, nodejs/node#19729): libuv unlinks the
853
+ // unix-socket bind path when the listening handle closes, so a shutdown after a
854
+ // successor bound would delete the successor's endpoint. With no close there is
855
+ // no implicit unlink. Cleanup is explicit and identity-gated below — the legacy
856
+ // path has no lease, so dev+ino is its only ownership proof.
857
+ // Windows has no close-time unlink (named pipes are kernel objects), so keep the
858
+ // historical prompt refusal of new connections there.
859
+ if (process.platform === "win32") {
860
+ try { server?.close(); } catch { /* already closed */ }
861
+ }
862
+ if (process.platform !== "win32" && boundSocketIdentity) {
863
+ try {
864
+ const st = statSync(socketPath);
865
+ if (ownsEndpoint(boundSocketIdentity, { dev: st.dev, ino: st.ino })) {
866
+ try { unlinkSync(socketPath); } catch { /* best effort */ }
867
+ }
868
+ } catch { /* path gone — nothing to clean */ }
869
+ }
513
870
  for (const client of clients) {
514
871
  try { client.end(); } catch {}
515
872
  }
@@ -563,6 +920,8 @@ async function ownedMain(config) {
563
920
  const clients = new Set();
564
921
  /** Resident editor-state reporters: connected but never "attached" (#103). */
565
922
  const editorReporters = new Set();
923
+ let frameReporter = null;
924
+ let lastOutputSeq = 0;
566
925
  let childPid = null;
567
926
  let child = null;
568
927
  let exitCode = null;
@@ -623,6 +982,11 @@ async function ownedMain(config) {
623
982
  if (result.updated && result.host) host = result.host;
624
983
  return result;
625
984
  };
985
+ const frameWitnessSummaryUpdates = createFrameWitnessSummaryScheduler({
986
+ publish: () => {
987
+ if (frameReporter !== null) ownedUpdate((cur) => ({ ...cur, frameWitness: frameWitnessSummary(frameReporter) }));
988
+ },
989
+ });
626
990
  const isOwnerNow = () => {
627
991
  const h = readHost(config.root, config.viewId);
628
992
  return Boolean(h && h.instanceId === config.instanceId);
@@ -823,6 +1187,20 @@ async function ownedMain(config) {
823
1187
  // model (actions close over it) and BEFORE the endpoint binds, so the durable
824
1188
  // journal is loaded from disk before any client can reconcile. The action
825
1189
  // closures read `child`/`host` at call time (both are let-bound above).
1190
+ // Shared by the control runtime and the plain resize message against a live
1191
+ // child. The raw no-child branch below retains its cachedResize behavior.
1192
+ const applyResize = (cols, rows) => {
1193
+ const before = { cols: terminalModel.cols, rows: terminalModel.rows };
1194
+ resizeChildAndModel(child, terminalModel, cols, rows);
1195
+ notifyChildResize(childPid);
1196
+ cachedResize = null;
1197
+ ownedUpdate((cur) => ({ ...cur, cols, rows }));
1198
+ const after = { cols: terminalModel.cols, rows: terminalModel.rows };
1199
+ if (frameReporter !== null && (after.cols !== before.cols || after.rows !== before.rows)) {
1200
+ announceFrameIntent(frameReporter, send, after.cols, after.rows);
1201
+ frameWitnessSummaryUpdates.flush();
1202
+ }
1203
+ };
826
1204
  const control = createControlRuntime({
827
1205
  viewId: config.viewId,
828
1206
  root: config.root,
@@ -836,18 +1214,7 @@ async function ownedMain(config) {
836
1214
  },
837
1215
  hostCols: () => host.cols,
838
1216
  hostRows: () => host.rows,
839
- applyResize: (cols, rows) => {
840
- // The runtime pre-checks childReady (host_starting reply otherwise),
841
- // so this only runs against a live child — the starting window's
842
- // cachedResize path belongs exclusively to the legacy switch below.
843
- // Paired step (CR R1 advisory): model reflows only when the real
844
- // PTY resize succeeded; cachedResize cleared either way — a failed
845
- // resize is not retried against a exiting child.
846
- resizeChildAndModel(child, terminalModel, cols, rows);
847
- notifyChildResize(childPid);
848
- cachedResize = null;
849
- ownedUpdate((cur) => ({ ...cur, cols, rows }));
850
- },
1217
+ applyResize,
851
1218
  currentDims: () => ({ cols: terminalModel.cols, rows: terminalModel.rows }),
852
1219
  applyInterrupt: () => {
853
1220
  if (child) child.write("\x1b");
@@ -881,7 +1248,7 @@ async function ownedMain(config) {
881
1248
  clients.add(socket);
882
1249
  terminalSubscriptions.set(
883
1250
  socket,
884
- createTerminalSubscription({ model: terminalModel, send: (msg) => send(socket, msg), generation: GENERATION }),
1251
+ createTerminalSubscription({ model: terminalModel, send: (msg) => send(socket, msg), generation: GENERATION, viewProof: createViewProofSource(() => frameReporter) }),
885
1252
  );
886
1253
  socket.write(JSON.stringify({ type: "hello", status: host, editorEmpty, generation: GENERATION }) + "\n");
887
1254
  broadcast({ type: "status", status: host, generation: GENERATION });
@@ -897,18 +1264,54 @@ async function ownedMain(config) {
897
1264
  editorReporters.delete(socket);
898
1265
  terminalSubscriptions.delete(socket);
899
1266
  control.closeSocket(socket);
1267
+ const reporterLost = frameReporter !== null && frameReporter.socket === socket;
1268
+ if (reporterLost) {
1269
+ frameWitnessSummaryUpdates.cancel();
1270
+ cleanupFrameReporter(frameReporter, "reporter-close", (trailing) => {
1271
+ try {
1272
+ screenLogBytes = appendBoundedScreenLog(screenLog, trailing, screenLogBytes, screenLogLimits);
1273
+ const seq = feedOutput(terminalModel, trailing);
1274
+ lastOutputSeq = seq;
1275
+ feedViewProofOutput(frameReporter, seq, trailing);
1276
+ for (const [peer, sub] of terminalSubscriptions) if (sub.subscribed()) sub.onOutput(seq, trailing);
1277
+ } catch {
1278
+ /* best effort */
1279
+ }
1280
+ });
1281
+ frameReporter = null;
1282
+ resetViewProofSubscribers(terminalSubscriptions, "reporter-close");
1283
+ }
900
1284
  if (probeSockets.has(socket)) return;
901
1285
  // Merge into the live record (a stale closure spread here erases a
902
1286
  // concurrent revoke — final review finding 2).
903
- ownedUpdate((cur) => ({ ...cur }));
1287
+ const closeUpdate = ownedUpdate((cur) => (reporterLost ? { ...cur, frameWitness: { enabled: false } } : { ...cur }));
1288
+ if (reporterLost && closeUpdate.updated) broadcast({ type: "status", status: host, generation: GENERATION });
904
1289
  });
905
1290
  socket.on("error", () => {
906
1291
  clients.delete(socket);
907
1292
  editorReporters.delete(socket);
908
1293
  terminalSubscriptions.delete(socket);
909
1294
  control.closeSocket(socket);
1295
+ const reporterLost = frameReporter !== null && frameReporter.socket === socket;
1296
+ if (reporterLost) {
1297
+ frameWitnessSummaryUpdates.cancel();
1298
+ cleanupFrameReporter(frameReporter, "reporter-error", (trailing) => {
1299
+ try {
1300
+ screenLogBytes = appendBoundedScreenLog(screenLog, trailing, screenLogBytes, screenLogLimits);
1301
+ const seq = feedOutput(terminalModel, trailing);
1302
+ lastOutputSeq = seq;
1303
+ feedViewProofOutput(frameReporter, seq, trailing);
1304
+ for (const [peer, sub] of terminalSubscriptions) if (sub.subscribed()) sub.onOutput(seq, trailing);
1305
+ } catch {
1306
+ /* best effort */
1307
+ }
1308
+ });
1309
+ frameReporter = null;
1310
+ resetViewProofSubscribers(terminalSubscriptions, "reporter-error");
1311
+ }
910
1312
  if (probeSockets.has(socket)) return;
911
- ownedUpdate((cur) => ({ ...cur }));
1313
+ const errorUpdate = ownedUpdate((cur) => (reporterLost ? { ...cur, frameWitness: { enabled: false } } : { ...cur }));
1314
+ if (reporterLost && errorUpdate.updated) broadcast({ type: "status", status: host, generation: GENERATION });
912
1315
  });
913
1316
  socket.markProbe = () => probeSockets.add(socket);
914
1317
  });
@@ -997,22 +1400,61 @@ async function ownedMain(config) {
997
1400
  }
998
1401
  childPid = child.pid ?? null;
999
1402
  child.onData((data) => {
1000
- screenLogBytes = appendBoundedScreenLog(screenLog, data, screenLogBytes, screenLogLimits);
1001
- const outputSeq = feedOutput(terminalModel, data);
1002
- // Per-socket output delivery — same contract as legacyMain above.
1003
- const outputLine = JSON.stringify({ type: "output", seq: outputSeq, data }) + "\n";
1004
- for (const [socket, sub] of terminalSubscriptions) {
1005
- if (sub.subscribed()) sub.onOutput(outputSeq, data);
1006
- // Same per-socket guard the legacy broadcast had: a synchronous throw
1007
- // from a dead socket must never escape into the uncaughtException
1008
- // crash path (whole-branch review finding).
1009
- else { try { socket.write(outputLine); } catch { /* socket 'error' handler cleans up */ } }
1403
+ // Issue #222 FW-03 (owned host path): marker bytes are stripped before every
1404
+ // consumer and each ordinary segment gets its own output sequence; a proof takes
1405
+ // the sequence of the preceding ordinary segment (never a child frameId, never
1406
+ // socket timing) and several proofs at one seq keep production order.
1407
+ for (const part of splitFrameChunk(data, frameReporter)) {
1408
+ if (part.kind !== "output") {
1409
+ // S opens; F completes; A aborts. Never call completeProof for every record.
1410
+ const record = applyViewProofPart(frameReporter, part, lastOutputSeq);
1411
+ if (record !== null) {
1412
+ for (const sub of terminalSubscriptions.values()) sub.onViewProofRecord?.(record);
1413
+ }
1414
+ frameWitnessSummaryUpdates.schedule();
1415
+ continue;
1416
+ }
1417
+ const chunk = part.data;
1418
+ screenLogBytes = appendBoundedScreenLog(screenLog, chunk, screenLogBytes, screenLogLimits);
1419
+ const outputSeq = feedOutput(terminalModel, chunk);
1420
+ lastOutputSeq = outputSeq;
1421
+ feedViewProofOutput(frameReporter, outputSeq, chunk);
1422
+ // Per-socket output delivery — same contract as legacyMain above.
1423
+ const outputLine = JSON.stringify({ type: "output", seq: outputSeq, data: chunk }) + "\n";
1424
+ for (const [socket, sub] of terminalSubscriptions) {
1425
+ if (sub.subscribed()) sub.onOutput(outputSeq, chunk);
1426
+ // Same per-socket guard the legacy broadcast had: a synchronous throw
1427
+ // from a dead socket must never escape into the uncaughtException
1428
+ // crash path (whole-branch review finding).
1429
+ else { try { socket.write(outputLine); } catch { /* socket 'error' handler cleans up */ } }
1430
+ }
1010
1431
  }
1011
1432
  });
1012
1433
  child.onExit((code) => {
1013
1434
  childExited = true;
1014
1435
  resolveChildExit?.();
1015
1436
  exitCode = code ?? 0;
1437
+ if (frameReporter !== null) {
1438
+ // F9: a trailing ordinary byte is forwarded through the normal output path.
1439
+ cleanupFrameReporter(frameReporter, "child-exit", (trailing) => {
1440
+ try {
1441
+ screenLogBytes = appendBoundedScreenLog(screenLog, trailing, screenLogBytes, screenLogLimits);
1442
+ const seq = feedOutput(terminalModel, trailing);
1443
+ feedViewProofOutput(frameReporter, seq, trailing);
1444
+ for (const [socket, sub] of terminalSubscriptions) {
1445
+ if (sub.subscribed()) sub.onOutput(seq, trailing);
1446
+ }
1447
+ } catch {
1448
+ /* best effort during exit */
1449
+ }
1450
+ });
1451
+ resetViewProofSubscribers(terminalSubscriptions, "child-exit");
1452
+ try {
1453
+ frameWitnessSummaryUpdates.flush();
1454
+ } catch {
1455
+ /* row may already be finalised */
1456
+ }
1457
+ }
1016
1458
  // Terminate lifecycle (spec D4): a confirmed child exit is the observed
1017
1459
  // evidence for any enveloped terminate still pending — flush before the
1018
1460
  // finish teardown ends the client sockets.
@@ -1122,6 +1564,33 @@ async function ownedMain(config) {
1122
1564
  terminalSubscriptions.delete(socket);
1123
1565
  }
1124
1566
  if (book.registerReporter) editorReporters.add(socket);
1567
+ // Issue #222 FW-04: a frame reporter gets a per-instance random token; only a
1568
+ // valid hello + frameWitness protocol 1 enables anything. Old/no hello is
1569
+ // unchanged (no new messages).
1570
+ {
1571
+ const enabled = enableFrameReporter(socket, msg, send);
1572
+ if (enabled !== null) {
1573
+ const replacingReporter = frameReporter !== null && frameReporter.socket !== socket;
1574
+ if (replacingReporter) {
1575
+ // Same ordinary-trailing forwarding path as close/error/child-exit: a
1576
+ // pending ordinary tail must not be lost when the reporter is replaced.
1577
+ cleanupFrameReporter(frameReporter, "reporter-replaced", (trailing) => {
1578
+ try {
1579
+ screenLogBytes = appendBoundedScreenLog(screenLog, trailing, screenLogBytes, screenLogLimits);
1580
+ const seq = feedOutput(terminalModel, trailing);
1581
+ lastOutputSeq = seq;
1582
+ feedViewProofOutput(frameReporter, seq, trailing);
1583
+ for (const [peer, sub] of terminalSubscriptions) if (sub.subscribed()) sub.onOutput(seq, trailing);
1584
+ } catch {
1585
+ /* best effort during replacement */
1586
+ }
1587
+ });
1588
+ }
1589
+ frameReporter = enabled;
1590
+ if (replacingReporter) resetViewProofSubscribers(terminalSubscriptions, "reporter-replaced");
1591
+ try { frameWitnessSummaryUpdates.flush(); } catch { /* row may be finalised */ }
1592
+ }
1593
+ }
1125
1594
  // The probe's close-time host.json refresh stays suppressed: the
1126
1595
  // resolver probes every HOST_PROBE_RETRY_MS, so flushing there
1127
1596
  // would amplify fenced writes (see the probeSockets comment at the
@@ -1161,17 +1630,11 @@ async function ownedMain(config) {
1161
1630
  case "resize": {
1162
1631
  const cols = clampInt(msg.cols, 20, 300, host.cols);
1163
1632
  const rows = clampInt(msg.rows, 5, 120, host.rows);
1164
- if (child) {
1165
- // Paired step (CR R1 advisory): model reflows only when the real
1166
- // PTY resize succeeded; cachedResize cleared either way — a failed
1167
- // resize is not retried against a exiting child.
1168
- resizeChildAndModel(child, terminalModel, cols, rows);
1169
- notifyChildResize(childPid);
1170
- cachedResize = null;
1171
- } else {
1633
+ if (child) applyResize(cols, rows);
1634
+ else {
1172
1635
  cachedResize = { cols, rows };
1636
+ ownedUpdate((cur) => ({ ...cur, cols, rows }));
1173
1637
  }
1174
- ownedUpdate((cur) => ({ ...cur, cols, rows }));
1175
1638
  break;
1176
1639
  }
1177
1640
  case "interrupt":