Skip to content

fix(#647): AC-3 — route retry/fallback messages through renderer's appendNotice - #667

Merged
admarble merged 4 commits into
mainfrom
feature/647-ac3-bracketed-notice-helper
May 20, 2026
Merged

admarble merged 4 commits into
mainfrom
feature/647-ac3-bracketed-notice-helper

Conversation

@admarble

@admarble admarble commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Closes #647 AC-3 by routing the 6 unbracketed console.log calls in phase-executor.ts (MCP fallback, spec retry, verbose-mode retry messages) through a new PhasePauseHandle.appendNotice(message) method that mirrors appendEventLine's clear → write → redraw flow. log-update's previousLineCount stays consistent with the terminal state, so retry messages no longer strand the prior frame's header in scrollback.

Diagnosis (from docs/incidents/647/captures/2026-05-19/)

The original #504/#505 transcript had 3 duplicate headers in 56m. The run log (.sequant/logs/run-2026-05-14T03-16-47-*.json) shows #505 had 3 retries (spec → exec → qa → exec → qa → exec). Each retry historically triggered one of these unbracketed console.log calls in executePhaseWithRetry:

Line (orig) Message Gated by --verbose?
838 Retryable error: ..., retrying... (attempt N/M) yes
855 Cold-start failure detected ..., retrying... yes
872 Phase failed with MCP enabled, retrying without MCP... no
895 Phase succeeded without MCP (MCP cold-start issue detected) no
919 Spec phase failed, retrying with Nms backoff... no
938 Spec phase succeeded on retry no

3 retries × 1 leaked header per write = 3 duplicate headers — matches the observed rate exactly.

Plus 4 verbose-mode console.log calls in executePhase (lines 511, 512, 523, 525) that leak the same way under -v. All 10 callsites now bracketed via the new helper.

Two additional batch-boundary sites in RunOrchestrator.run (the Batch N/M headline and the sequential Batch N failed, stopping notice) also fire between batches with the renderer still alive, so they're bracketed too.

Why appendNotice instead of raw pause()/resume()

An earlier draft used spinner?.pause(); console.log(msg); spinner?.resume(); as the bracket. That works but writes through process.stdout directly, which:

  1. Test harnesses can't observe (the VirtualTerminal only sees the renderer's injected stdoutWrite)
  2. Couples the retry-message path to global process state instead of the renderer's own channel

appendNotice writes through the renderer's internal stdoutWrite (same destination in production, observable in tests), and TTYRenderer's override does the same logUpdateClear → write → redraw flow as normal event lines. NonTTYRenderer's default impl just writes — there's no live zone to manage.

A+ hardening (last commit)

Two structural improvements so this fix doesn't decay:

  1. bracketedConsoleLog moved to src/lib/workflow/notice.ts. The helper previously lived in phase-executor.ts but is imported by run-orchestrator.ts — that was a backwards dependency (orchestrator → executor). Now both import from a sibling notice.ts module that has no executor-specific surface.

  2. ESLint no-restricted-syntax rule on phase-executor.ts bans console.log / console.info / console.warn / console.error / process.stdout.write / process.stderr.write with an error message pointing at bracketedConsoleLog. Any new retry message added to this file with a raw console.log fails CI instead of silently re-introducing the leak. Two existing process.stdout/stderr.write sites in the verbose-streaming callback are annotated with eslint-disable-next-line + rationale (their spinner?.pause() above brackets them intentionally).

    Rule intentionally not applied to run-orchestrator.ts: its remaining console.log sites are pre-flight (before any issue is registered with the renderer) or post-dispose, where the live zone is empty and console.log is correct. The two batch-boundary sites that fire in-window are already bracketed.

Tests (src/lib/cli-ui/scrollback-harness.test.ts)

Plus event-replay harness at docs/incidents/647/captures/2026-05-19/replay-504-505.ts that drives the real TTYRenderer through the exact #504/#505 phase timeline from the run log — zero claude budget, deterministic, reports 0 leaked headers across 7 populated scrollback rows.

Full suite: 3415 passed, 2 expected fail (negative controls), 0 regressions.
Lint: clean (npm run lint).

Audit re-scope: the other "10 leak callsites"

The original audit flagged 43 console.log / process.stdout.write callsites across 5 files; 10 of those (in state-cleanup.ts, state-manager.ts, and run-orchestrator.ts) were initially deferred. Re-checked each against the actual rendered-window exposure during QA:

  • run-orchestrator.ts pre-flight / post-dispose sites (log init failure, state reconciliation, lock acquisition, "already merged — skipping", metrics summary): fire before any issue is registered with the renderer or after renderSummary — live zone is empty, so console.log is correct.
  • state-manager.ts (State: ... audit lines): all gated on config.verbose; emit from operations that happen pre-flight or between phases, outside the rendered window.
  • state-cleanup.ts: standalone sequant clean CLI command — no renderer in the process at all.
  • run-orchestrator.ts batch-boundary sites (lines 814, 823): the two that genuinely fire between batches with the renderer alive — bracketed in this PR.

Net: no separate follow-up issue needed. The audit count was a callsite count, not a leak count.

Test plan

  • npm run build — clean
  • npm run lint — clean (with new no-restricted-syntax rule)
  • npx vitest run src/lib/cli-ui/scrollback-harness.test.ts — all AC-3 tests pass + 2 expected-fail negative controls
  • npx vitest run — full suite passes
  • npx tsx docs/incidents/647/captures/2026-05-19/replay-504-505.ts — reports 0 scrollback headers
  • Manual HITL run with SEQUANT_DEBUG_RENDERER=1 to capture a fresh artifact under the fix (optional confirmation)

Closes #647.

admarble added 2 commits May 20, 2026 09:17
…pendNotice

The audit in docs/incidents/647/captures/2026-05-19/ identified 6 unbracketed
console.log callsites in phase-executor.ts (MCP fallback, spec retry,
verbose-mode retry messages) firing during the renderer-active window. Each
write to process.stdout broke log-update's previousLineCount tracking — the
next eraseLines(N) undershot and stranded the prior frame's header in
scrollback.

This matches the original #504/#505 transcript exactly: that run had 3 retries
(per .sequant/logs/run-2026-05-14T03-16-47-*.json), producing 3 duplicate
headers in 56m.

Fix:
- PhasePauseHandle gains appendNotice(message): mirrors appendEventLine's
  clear → write → redraw flow so log-update's bookkeeping stays consistent.
- BaseRenderer default impl writes via stdoutWrite (sufficient for NonTTY).
- TTYRenderer override does logUpdateClear → stdoutWrite → redraw, skipping
  the clear/redraw when already paused (resume will redraw cleanly).
- RunRenderer interface gains appendNotice so run.ts's renderer ?? undefined
  satisfies the PhasePauseHandle type at the composition root.
- phase-executor.ts gains bracketedConsoleLog(spinner, message): routes
  through spinner.appendNotice when a handle is present, falls back to plain
  console.log for quiet / non-TTY paths. All 10 unbracketed callsites in
  executePhase + executePhaseWithRetry refactored to use it (lines 511, 512,
  523, 525 in executePhase; 838, 855, 872, 895, 919, 938 in
  executePhaseWithRetry).

Tests (scrollback-harness.test.ts):
- AC-3 mechanism: bracketed pause/write/resume around retry messages keeps
  scrollback header count at 1 across a #504/#505-shaped event timeline.
- AC-3 negative control (it.fails): same scenario without the bracket leaks
  N duplicate headers — proves the bracket is load-bearing.
- AC-3 helper: bracketedConsoleLog routes through appendNotice when handle
  is present, falls back to console.log when not.
- AC-3 e2e: production helper + real renderer + harness — notice text
  observable in VT, scrollback still clean.
- phase-pause-handle.test.ts: mock updated to satisfy new interface shape.

Full suite: 3415 passed, 2 expected fail (negative controls).

Entire-Checkpoint: 18c6b6a61f9a
Investigation artifacts that pinned down the AC-3 culprit and validated the
fix architecturally before any code changed.

Inputs:
- terminal.typescript (1.3MB) — HITL re-capture under PR #665's file sink.
  SEQUANT_DEBUG_RENDERER count in pty = 0 (file sink isolated debug
  output cleanly), validating the architectural fix from #664 empirically.
- debug-renderer.jsonl (134KB, 796 records) — file-sink output. Width/wrap
  sanity rule-outs clean: 0/796 rendererCols≠stdoutCols, 0/785
  logicalLines≠wrappedLineCount on impl ops.

Analyzers:
- analyze-trace.ts: VT-replays the typescript at recorded dims, reports
  scrollback header count, validates the 2171× claim. Detects trivial-pass
  scenarios (vt.scrollback.length === 0) and reports INCONCLUSIVE rather
  than overstating coverage.
- replay-504-505.ts: deterministic event-replay harness. Reads
  .sequant/logs/run-2026-05-14T03-16-47-*.json (the motivating #504/#505
  run that produced the original 3-in-56m transcript) and drives the real
  TTYRenderer + log-update + VirtualTerminal through the exact phase
  timeline. Zero claude budget; reproducible.

Outputs:
- analysis-report.txt — 2026-05-19 capture: 0 scrollback headers but
  0 scrollback rows populated → INCONCLUSIVE for AC-3 residual on its own,
  but combined with the audit + event replay closes the question.
- replay-report.txt — #504/#505 event timeline: 1 header total, 0 in
  scrollback across 7 populated scrollback rows. The deterministic
  workload pattern does not reproduce Mechanism #1 post-#665. Combined
  with the phase-executor audit finding (6 unbracketed retry-message
  callsites), this attributes the original 3-in-56m bug to the retry
  console.log path that the AC-3 fix brackets.

notes.md captures: capture command, target scenarios, sanity checks,
decision rule (with the trivial-pass pre-check that the analyzer now
enforces), and an honest "what this validates vs. doesn't" appendix.

Entire-Checkpoint: fab98d1905d5
admarble added 2 commits May 20, 2026 14:15
Two between-batch console.log sites in RunOrchestrator.run fire with
the renderer still alive (live zone populated from the previous batch),
so they had the same scrollback-leak shape as the phase-executor.ts
sites this PR already brackets. Routed through bracketedConsoleLog so
log-update's previousLineCount stays consistent.

CHANGELOG entry under [Unreleased] / Fixed for the AC-3 fix.

Entire-Checkpoint: b1476cd304cb
Move `bracketedConsoleLog` from `phase-executor.ts` to a new
`workflow/notice.ts` module so `run-orchestrator.ts` doesn't import
from a sibling executor (orchestrator → executor was a backwards
dependency direction). Both files now import from `./notice.js`;
test's dynamic import updated to match.

Add a scoped ESLint `no-restricted-syntax` rule on
`src/lib/workflow/phase-executor.ts` that bans `console.log` /
`console.info` / `console.warn` / `console.error` and
`process.stdout/stderr.write`, with the error message pointing at
`bracketedConsoleLog` from `./notice.ts`. Catches future drift —
any new retry message added to this file with a raw `console.log`
fails CI instead of silently re-introducing the scrollback leak.

Two existing `process.stdout/stderr.write` sites in the verbose
streaming callback (lines 676, 687) annotated with
`eslint-disable-next-line` + rationale: `spinner?.pause()` brackets
them above, so they intentionally bypass log-update.

Rule intentionally not applied to `run-orchestrator.ts`: its 10
remaining `console.log` sites are pre-flight (before any issue is
registered with the renderer) or post-dispose, where the live zone
is empty and `console.log` is correct. The two batch-boundary sites
that *do* fire in-window were bracketed in the previous commit.
Forcing the rule there would mean ~10 eslint-disable comments for
zero real catches.

Full suite: 3415 passed, 2 expected fail (negative controls).

Entire-Checkpoint: 1181a179f669
@admarble
admarble merged commit 7d05300 into main May 20, 2026
5 checks passed
@admarble
admarble deleted the feature/647-ac3-bracketed-notice-helper branch May 20, 2026 19:32
admarble added a commit that referenced this pull request May 30, 2026
…downstream (#673)

* docs(#655): HITL capture — renderer emits clean bytes, corruption is downstream

Capture requested by #668 (post-#664/#667 baseline), run from matcha-maps on
two terminal emulators (stale VS Code + fresh iTerm2).

Byte-level findings (both captures):
- script typescript: 0 U+FFFD, fully-valid UTF-8, balanced sync-frames
  (vscode 500/500, iterm2 224/224)
- renderer instrumentation: 0 frames with rendererCols!=stdoutCols,
  0 frames with logicalLines>rendererRows (503 / 228 frames)

Conclusion: sequant's renderer is not corrupting output. Corruption is
downstream — stale terminal-emulator paint (VS Code) and clipboard flattening
of an in-place TUI (iTerm2 paste). Refutes #655's renderer-corruption premise.
Actionable robustness follow-up tracked in #672.

Entire-Checkpoint: d231fd81a2b1

* docs(#668): add capture metadata table to notes.md

Fill the #668 metadata fields derivable from the committed artifacts
(wc -l counts, file-sink sanity, Symptom-A byte-stream check). Run-time-only
fields (UTC, sequant version, wall-clock) left unfilled rather than back-filled
with this repo's values.

Entire-Checkpoint: 6503e65205ae
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(cli): #624's duplicate-header fix doesn't catch real log-update/scrollback bug (v2.3.0 regression confirmed)

1 participant