Skip to content

fix(#664): route SEQUANT_DEBUG_RENDERER to file sink, eliminate 2171× scrollback amplifier - #665

Merged
admarble merged 4 commits into
mainfrom
feature/664-fix-cli-route-sequant-debug-renderer-to-file-s
May 19, 2026
Merged

admarble merged 4 commits into
mainfrom
feature/664-fix-cli-route-sequant-debug-renderer-to-file-s

Conversation

@admarble

Copy link
Copy Markdown
Contributor

Summary

  • Route SEQUANT_DEBUG_RENDERER output to .sequant/debug-renderer.jsonl (override via SEQUANT_DEBUG_RENDERER_FILE=<path>) instead of process.stderr. Eliminates the 2171× scrollback amplifier that the fix(cli): #624's duplicate-header fix doesn't catch real log-update/scrollback bug (v2.3.0 regression confirmed) #647 AC-1 capture forensics revealed: when stdout and stderr share a pty, debug stderr writes scroll the terminal between log-update redraws, so eraseLines(previousLineCount) undershoots and the prior frame's top survives in scrollback.
  • Falls through to a no-op (with one-shot startup notice on stderr) if the file cannot be opened — won't crash the run on a read-only fs or missing parent dir.
  • Preserves identical JSON schema and per-op cadence so existing diagnostic replay tooling keeps working unchanged.

Changes

  • src/lib/cli-ui/run-renderer.ts — emitDebug opens an append-mode fd at construction (sync mkdirSync + openSync), writes per-op via fs.writeSync; fd lives for process lifetime. Used || instead of ?? for the env-var fallback so empty SEQUANT_DEBUG_RENDERER_FILE= behaves like "unset" rather than passing "" to openSync.
  • src/lib/cli-ui/scrollback-harness.test.ts — 4 new tests for fix(cli): route SEQUANT_DEBUG_RENDERER to file sink, eliminate 2171× scrollback amplifier #664 covering the default path (with a throwingStderr stub that fails loudly if debug output ever falls back to stderr), the override path, the JSON schema integrity, and the unwritable-file fallback. Updated the existing harness comment that referenced the now-resolved stderr routing.
  • docs/incidents/647/captures/2026-05-17/notes.md — marked the "Caveat — script wrapper interference" section as resolved going forward.
  • CHANGELOG.md — Fixed entry under [Unreleased].

Test plan

  • npm run build — clean
  • npm run lint — 0 warnings
  • npx vitest run src/lib/cli-ui/ — 96 passed + 1 expected-fail (the unchanged AC-2 it.fails marker)
  • AC-1 / AC-5: default path test uses throwing-stderr stub; passes (proves debug never falls back to stderr)
  • AC-2: override path test verifies file lands at override AND default path is not created
  • AC-3: schema test parses every line and verifies all 7 required keys
  • AC-4: unwritable test uses /dev/null/foo/debug.jsonl; asserts no throw, exactly 1 fallback notice, no per-op stderr leakage

AC verification

AC Status Evidence
AC-1: writes to .sequant/debug-renderer.jsonl, not stderr ✅ MET run-renderer.ts:578-583 + harness test L545-595
AC-2: SEQUANT_DEBUG_RENDERER_FILE override ✅ MET run-renderer.ts:580 + test L597-633
AC-3: identical JSON schema + per-op cadence ✅ MET run-renderer.ts:621-637 + test L635-695
AC-4: no-op fallback on unwritable, one-shot stderr notice ✅ MET run-renderer.ts:584-592 + test L697-744
AC-5: throwing-stderr stub test in harness ✅ MET scrollback-harness.test.ts:550-560
AC-6: update notes.md Caveat ✅ MET notes.md:54 ("Resolved going forward (#664)")

Closes

Closes #664

… scrollback amplifier

The #647 AC-1 capture's "Mechanism #1 at 2181×" headline was 2171× of stderr
co-writer noise, not the underlying #647 bug. When stdout and stderr share a
pty, debug writes scroll the terminal between log-update redraws — log-update
has no record of them, so eraseLines(previousLineCount) misses rows and the
prior frame's top survives in scrollback.

Routes SEQUANT_DEBUG_RENDERER output to .sequant/debug-renderer.jsonl by
default, overridable via SEQUANT_DEBUG_RENDERER_FILE=<path>. Falls through to
a no-op (with one-shot startup notice on stderr) if the file cannot be opened.
JSON schema and per-op cadence are unchanged so existing diagnostic replay
tooling keeps working.

- run-renderer.ts: replace stderrWrite call with mkdirSync+openSync+writeSync;
  fd lives for process lifetime, no close on dispose
- scrollback-harness.test.ts: 4 new #664 tests (default path, override,
  schema, unwritable fallback) plus updated comment on stderr routing
- docs/incidents/647/captures/2026-05-17/notes.md: mark Caveat resolved
- CHANGELOG: Fixed entry under [Unreleased]
admarble added 3 commits May 18, 2026 17:07
QA self-review caught three doc locations that still described
SEQUANT_DEBUG_RENDERER as emitting to stderr:

- docs/features/run-renderer.md: user-facing reference. Updated env
  var table, debugging section, and example commands. The previous
  example (`2> /tmp/debug.jsonl`) would have produced an empty file
  post-fix.
- docs/incidents/655/negative-result.md:36: stderr writers audit
  table — updated to reflect that renderer's stderrWrite now only
  fires the one-shot fallback notice.
- docs/incidents/655/negative-result.md:53: AC-1 capture instructions
  — updated to point at the JSONL file.
- docs/incidents/647/captures/2026-05-17/analysis.md:57: proposed
  fix recommendation — annotated with "(Implemented in #664)".

Historical references in analysis.md (lines 11, 12, 33) and notes.md
(line 53) are preserved as historical record — they describe the
state at the time of the capture, which the existing footer in
notes.md already marks as resolved going forward.
Addresses two QA self-review gaps without changing behaviour:

Gap 5 — cwd-relative default path was implicit. The codebase convention
is `.sequant/` resolved against `process.cwd()` (see relay/paths.ts:39,
ci/config.ts:42). My initial code relied on `path.join(".sequant", ...)`
producing a relative path that openSync would resolve against cwd at call
time — same effective behaviour, but the cwd-relative assumption was
invisible from reading the line. Switched to an explicit
`path.join(process.cwd(), ...)` matching relay/paths.ts. Added a docs
caveat in run-renderer.md explaining that invoking sequant from a
subdirectory puts the file outside the project root's .sequant/* gitignore
reach, with the absolute-path workaround.

Gap 4 — `||`-vs-`??` semantics was inline-documented but not regression-
guarded. Added two lock-in tests in scrollback-harness.test.ts:
  - "AC-2 (lockin): empty SEQUANT_DEBUG_RENDERER_FILE falls back to
    default path, not empty-string openSync" — uses a stderrWrite stub
    that records fallback-notice calls; if anyone refactors `||` to `??`,
    "" propagates to openSync, openSync throws, the fallback notice fires,
    and the test fails loudly with a specific assertion.
  - "AC-1 (lockin): default path resolves against process.cwd() at
    construction time" — chdir's to a tmpdir before constructing the
    renderer and asserts the file lands there, pinning that the cwd lookup
    happens at constructor time (not module load).

Tests: 11 passed + 1 expected-fail in scrollback-harness.test.ts (was 9+1).
Build + lint clean.
The test added in f52b3ef was effectively a duplicate of the existing
AC-1/AC-5 test (both chdir to tmpDir, set SEQUANT_DEBUG_RENDERER=1 with
empty FILE env, assert file lands at tmpDir/.sequant/debug-renderer.jsonl).
The only "new" assertion was `expect(expectedPath).not.toBe(wrongPath)` —
a tautology comparing two literal paths, not testing renderer behavior.

The AC-2 (lockin) test added in the same commit stays — it specifically
watches the fallback-notice path and would fire if anyone refactored
`||` back to `??`. That coverage was genuinely missing.
@admarble
admarble merged commit 54be7cd into main May 19, 2026
5 checks passed
@admarble
admarble deleted the feature/664-fix-cli-route-sequant-debug-renderer-to-file-s branch May 19, 2026 02:09
admarble added a commit that referenced this pull request May 20, 2026
…pendNotice (#667)

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

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

* docs(#647): AC-3 audit + capture kit + event-replay harness (2026-05-19)

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

* fix(#647): bracket batch-boundary log lines + add CHANGELOG entry

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

* chore(#647): extract bracketedConsoleLog + add lint guard (A+ hardening)

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
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): route SEQUANT_DEBUG_RENDERER to file sink, eliminate 2171× scrollback amplifier

1 participant