Skip to content

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

Closed

Description

@admarble

Context

While diagnosing #647, the AC-1 capture's "Mechanism #1 at 2181×" headline turned out to be a 2171× amplifier of stderr instrumentation, not the original bug. See PR #663 / docs/incidents/647/captures/2026-05-17/analysis.md for the forensic writeup.

The amplifier is run-renderer.ts:606 calling this.stderrWrite("SEQUANT_DEBUG_RENDERER ...\n") once per impl/clear/done op. In any terminal where stderr and stdout share a pty (the normal case), those writes scroll the terminal in ways log-update has no record of, breaking previousLineCount.

Proposed fix

Route SEQUANT_DEBUG_RENDERER output to a file sink instead of stderr.

Default: .sequant/debug-renderer.jsonl (gitignored already via .sequant/).
Override: SEQUANT_DEBUG_RENDERER_FILE=<path> env var.

Implementation sketch (~20 LOC in run-renderer.ts:564-607):

const debugEnabled = process.env.SEQUANT_DEBUG_RENDERER === "1";
const debugPath =
  process.env.SEQUANT_DEBUG_RENDERER_FILE ?? ".sequant/debug-renderer.jsonl";
// Open once, append-only, sync writes — diagnostic only, perf is fine.
const debugStream = debugEnabled
  ? fs.openSync(debugPath, "a")
  : null;
// ...
const emitDebug = (op, text) => {
  if (debugStream === null) return;
  fs.writeSync(debugStream, `SEQUANT_DEBUG_RENDERER ${JSON.stringify(record)}\n`);
};

Acceptance criteria

  • SEQUANT_DEBUG_RENDERER=1 npx sequant run <issue> writes to .sequant/debug-renderer.jsonl, not stderr.
  • SEQUANT_DEBUG_RENDERER_FILE=/tmp/foo.jsonl SEQUANT_DEBUG_RENDERER=1 ... honours the override path.
  • No regression of the AC-1 capture's diagnostic value — same JSON schema per line, same one-line-per-op frequency.
  • If the file can't be opened (read-only fs, parent dir missing), fall through to a no-op rather than crashing the run. Log the fallback once to stderr at startup.
  • Test: extend scrollback-harness.test.ts to verify that with SEQUANT_DEBUG_RENDERER=1 set and a writeable temp file, the renderer's stderrWrite is NOT called for debug output (use a stub that throws on stderr write).
  • Update docs/incidents/647/captures/2026-05-17/notes.md "Caveat — script wrapper interference" section noting the issue is resolved going forward.

Why this is worth doing

Out of scope

Related

Activity

  1. added
    bug
    cli
    on May 18, 2026
  2. admarble commented on May 18, 2026

    @admarble
    ContributorAuthor

    Plan Complete

    Acceptance Criteria

    AC-1: Debug output goes to default file, not stderr

    Verification: Integration test (vitest with stub stderr that throws)

    • Given: SEQUANT_DEBUG_RENDERER=1 set, no override env var
    • When: Renderer fires impl/clear/done ops
    • Then: Writes land in .sequant/debug-renderer.jsonl; stderrWrite not invoked for debug output

    AC-2: SEQUANT_DEBUG_RENDERER_FILE overrides the default path

    Verification: Integration test (temp dir)

    • Given: SEQUANT_DEBUG_RENDERER_FILE=/tmp/foo.jsonl + SEQUANT_DEBUG_RENDERER=1
    • When: Renderer fires ops
    • Then: Lines append to /tmp/foo.jsonl, not the default

    AC-3: No regression of diagnostic value

    Verification: Integration test — read back file content

    • Given: Same conditions as AC-1
    • When: N ops fire
    • Then: File contains N lines, each SEQUANT_DEBUG_RENDERER {...JSON...}\n matching prior schema (t, op, frame, rendererCols, rendererRows, stdoutCols, stdoutRows, logicalLines, wrappedLineCount)

    AC-4: Graceful no-op on unwritable file

    Verification: Integration test — point at read-only dir, capture stderr

    • Given: SEQUANT_DEBUG_RENDERER_FILE=/nonexistent-parent/x.jsonl
    • When: Renderer constructed with debug enabled
    • Then: No crash; single one-shot fallback line on stderr at startup; emitDebug becomes no-op

    AC-5: Stub-throws stderr test in scrollback harness

    Verification: Add test to scrollback-harness.test.ts

    • Given: Renderer with SEQUANT_DEBUG_RENDERER=1 and a stderrWrite stub that throws
    • When: Multi-event sequence runs
    • Then: Test passes (no throw triggered by debug path)

    AC-6: Update docs/incidents/647/captures/2026-05-17/notes.md

    Verification: Manual read of diff

    • Mark the "Caveat — script wrapper interference" section as resolved going forward, with a brief note pointing at this fix.

    Implementation Plan

    Phase 1: Renderer fix (run-renderer.ts:558–607)

    1. Add import fs from "node:fs" and import path from "node:path" at top of file.
    2. Replace the emitDebug block with file-sink variant:
      • Compute debugPath from env (SEQUANT_DEBUG_RENDERER_FILE or .sequant/debug-renderer.jsonl).
      • Ensure parent dir exists via mkdirSync(dirname, {recursive: true}) wrapped in try/catch.
      • fs.openSync(debugPath, "a") wrapped in try/catch; on failure, write a single fallback line to stderr ("SEQUANT_DEBUG_RENDERER: file sink unavailable (<error msg>), debug output suppressed\n") and set debugStream = null.
      • Inside emitDebug, if debugStream === null → return; else fs.writeSync(debugStream, line).
    3. Keep the JSON schema and one-line-per-op cadence identical (AC-3).
    4. The destructor/dispose path: no fs.closeSync needed — process exit closes the fd. (Renderer instances are per-process singletons; opening once and leaking the fd until process exit is fine for a diagnostic-only sink.)

    Phase 2: Tests
    5. Add new describe("#664 SEQUANT_DEBUG_RENDERER file sink", ...) block to scrollback-harness.test.ts:

    • AC-1+5 test: stderrWrite is a vi.fn() that throws on debug-format calls; assert no throw and asserts on file content.
    • AC-2 test: override env, assert file content lands at override path, default path not created.
    • AC-3 test: read back JSON, validate every record matches schema.
    • AC-4 test: point SEQUANT_DEBUG_RENDERER_FILE at a path whose parent dir cannot be created (e.g., /dev/null/foo.jsonl which has a non-dir "parent"); capture stderr; assert one-shot fallback line and no crash.
    • Use vi.stubEnv + vi.unstubAllEnvs in beforeEach/afterEach for env isolation.
    • Use os.tmpdir() + mkdtempSync for AC-2/3 temp paths.

    Phase 3: Docs
    6. Update docs/incidents/647/captures/2026-05-17/notes.md "Caveat" section: add a "Resolved (#664): ..." footer pointing at this PR.


    Design Review

    1. Where does this logic belong? Inside the existing emitDebug closure in TTYRenderer.constructor (run-renderer.ts:564–607). The instrumentation is internal to the renderer; no need to extract to a separate module.

    2. What's the simplest correct approach? Open a single append-mode fd at construction, write synchronously per op. Reject: (a) async writes with backpressure handling (overkill for diagnostic-only), (b) buffering/batching (defeats real-time tail behaviour), (c) a separate DebugSink class (premature abstraction for ~25 LOC).

    3. What existing pattern does this follow? The "open-once, sync-append, fall-through-on-error" pattern matches how .sequant/state.json and run logs are handled — sync I/O at the boundary, graceful degrade on filesystem errors. The renderer is already a long-lived singleton, so fd leak until process exit is acceptable.

    4. What would a senior reviewer challenge?

      • "Why not close the fd?" → Process-lifetime singleton; closing on dispose adds risk of writes-after-close in late-fire callbacks. Keeping it open is simpler.
      • "Why not use a writable stream instead of openSync/writeSync?" → Stream backpressure is async; the existing per-op call is sync. A WriteStream would force await plumbing or risk drops on process exit.
      • "What about race conditions with multiple instances?" → O_APPEND guarantees atomic line appends on POSIX; multi-instance is not a use case for this diagnostic.
      • "Test ergonomics?" → Env-var-driven config is awkward to mock; vi.stubEnv + tmpdir paths keep tests hermetic.

    Open Questions

    1. Should the fallback stderr line repeat per-op or fire once at startup?

      • Recommendation: Once at startup (during constructor's failed open). The issue body says "Log the fallback once to stderr at startup" — explicit. Per-op spam would defeat the whole purpose of moving off stderr.
      • Impact: If we forget the gate, fallback writes amplify scrollback again.
    2. Should we close the fd on dispose()?

      • Recommendation: No. Renderer lifetime ≈ process lifetime; OS reaps the fd on exit. Adding close adds risk of late writes hitting a closed fd.
      • Impact: One leaked fd per process — negligible.

    Conflict Risk Analysis

    In-flight scan:

    Risk: Low. Worktree cleanup of #652 is unrelated to this fix.


    Recommended Workflow

    Phases: spec → exec → qa
    Quality Loop: disabled
    Reasoning: Bug fix with explicit fix sketch, tight scope (~25 LOC + tests + docs), no UI surface. no-browser-test not needed; absence of ui/frontend/admin labels skips /test automatically.


    Label Review

    Current: bug, cli
    Recommended: bug, cli (no change)
    Reason: Scope matches existing labels; not a refactor (< 5 files), no breaking changes, no UI.
    Quality Loop: Won't auto-enable (no complex/refactor/breaking label).

  3. added
    planned
    on May 18, 2026
  4. admarble commented on May 18, 2026

    @admarble
    ContributorAuthor

    QA Review for Issue #664

    AC Coverage

    AC Source Description Status Notes
    AC-1 Original SEQUANT_DEBUG_RENDERER=1 writes to .sequant/debug-renderer.jsonl, not stderr MET run-renderer.ts:578-583 opens file at default path; harness test L545-595 uses throwing stderr stub to prove stderr is never invoked for debug output
    AC-2 Original SEQUANT_DEBUG_RENDERER_FILE env var override is honoured MET run-renderer.ts:580 reads override; test L597-633 asserts file lands at override path AND default path is NOT created
    AC-3 Original No regression of diagnostic value — same JSON schema, same per-op cadence MET run-renderer.ts:621-637 keeps the original record shape; test L635-695 parses every line and asserts all 7 required keys (t, op, frame, rendererCols, rendererRows, stdoutCols, stdoutRows) plus valid op enum. Cadence is preserved because only the destination changed
    AC-4 Original Falls through to no-op on unwritable file; one-shot startup notice to stderr MET run-renderer.ts:584-592 try/catch around mkdirSync+openSync; test L697-744 points at /dev/null/foo/debug.jsonl, asserts no throw, exactly 1 fallback notice, zero per-op stderr leakage
    AC-5 Original Test verifies stderrWrite is NOT called for debug output (throwing stub) MET scrollback-harness.test.ts:550-560 defines throwingStderr that throws on any line starting with SEQUANT_DEBUG_RENDERER ; test runs full event sequence without triggering the throw
    AC-6 Original Update docs/incidents/647/captures/2026-05-17/notes.md Caveat section MET notes.md:54 added "Resolved going forward (#664)." footer referencing the file sink + override env var

    Coverage: 6/6 AC items fully met. Verified literally against AC text, not just spirit.


    Quality Plan Verification

    N/A — No quality plan section in issue comments (issue body included the fix sketch directly).


    CI Status

    No PR exists yet — branch feature/664-fix-cli-route-sequant-debug-renderer-to-file-s pushed to origin in /exec phase, PR creation deferred to Phase 5 (/fullsolve orchestrator). CI will run on PR creation.


    Quality Metrics

    Metric Value Status
    Type issues (any) 0 ✅ OK
    Deleted tests 0 ✅ OK
    Files changed 4 ✅ OK (focused)
    Lines added +286 -
    Lines deleted -12 -
    Branch behind main 0 commits ✅ OK

    Cache Status

    N/A — fresh QA run, no prior context.


    Build Verification

    N/A — npm run build passed cleanly in exec phase (no errors).


    Test Coverage Analysis

    Changed File Tier Has Tests? Test File
    src/lib/cli-ui/run-renderer.ts Standard ✅ Yes src/lib/cli-ui/scrollback-harness.test.ts (4 new #664 tests)
    src/lib/cli-ui/scrollback-harness.test.ts Test N/A (is itself a test)
    docs/incidents/647/captures/2026-05-17/notes.md Optional N/A (docs)
    CHANGELOG.md Optional N/A (changelog)

    Coverage: 1/1 changed source file has corresponding tests.
    Critical paths without tests: None.
    cli-ui test suite: 96 passed + 1 expected-fail (the unchanged AC-2 it.fails marker).


    Code Review

    Strengths:

    • Implementation matches the issue's fix sketch closely; ~25 LOC of net renderer change as estimated.
    • || instead of ?? for the env-var fallback (run-renderer.ts:578-583) is the correct choice: an empty SEQUANT_DEBUG_RENDERER_FILE= should behave like "unset" rather than passing "" to openSync and silently disabling debug. Rationale documented inline.
    • Inline comment block at run-renderer.ts:567-574 explicitly explains the amplifier mechanism and references the AC-1 capture analysis — future readers can connect the fix to the historical context without spelunking commits.
    • Test uses real log-update via the harness (not a mock), so the file-sink behaviour is exercised on the actual production code path.
    • The throwingStderr stub in test L550-560 is the strongest possible no-regression guard: any future code change that routes debug to stderr will fail immediately with a clear error message rather than passing silently.
    • Schema test (AC-3) iterates every line and parses JSON — catches any drift in the record shape, not just the first record.

    Issues:

    • None blocking.

    Suggestions:

    • The fd is intentionally leaked for process lifetime (documented in code). For an MCP server that spawns many short-lived TTYRenderer instances in one process, this could accumulate fds at one per sequant run invocation. Worth monitoring but not a current concern — TTYRenderer is constructed once per CLI run and SEQUANT_ORCHESTRATOR mode uses OrchestratorRenderer instead. No action required.

    Test Quality Review

    Category Status Notes
    Behavior vs Implementation ✅ OK Tests assert on file contents and stderr-call observability, not internal state
    Coverage Depth ✅ OK All 4 AC items have dedicated tests; AC-1/AC-5 share a test because they describe the same invariant from two angles
    Mock Hygiene ✅ OK Only vi.stubEnv for env vars and a custom stderrWrite function — no module mocks
    Test Reliability ✅ OK Deterministic: mkdtempSync per test, afterEach cleanup, vi.unstubAllEnvs, fixed FIXED_NOW/FIXED_DATE. The AC-4 test relies on POSIX /dev/null non-directory semantics; would need adjustment for Windows CI but matches the rest of the suite's POSIX assumptions

    Issues Found: None.


    Anti-Pattern Detection

    Dependency Audit

    N/A — no package.json changes.

    Code Patterns

    No anti-patterns detected:

    • No N+1 queries (no loops with await)
    • No empty catch blocks — the try/catch at run-renderer.ts:584-592 explicitly handles the error (logs fallback notice, sets debugFd=null)
    • No hardcoded secrets
    • No SQL concatenation (no SQL)
    • No uncleared intervals/timeouts
    • fs.writeSync is synchronous by design — appropriate for diagnostic-only sink, comment explains the choice
    • Imports added: node:fs, node:path — both Node built-ins, no third-party deps

    Call-Site Review

    No new exported functions. emitDebug remains a closure inside the constructor; its call sites (impl/clear/done) are unchanged. No re-routing required.


    Execution Evidence

    N/A — no scripts/ or bin/ files modified. The change is library code with integration test coverage via the real log-update driver in the harness.


    Skill Command Verification

    N/A — no .claude/skills/**/*.md files modified.


    CLI Registration Verification

    N/A — no RunOptions or bin/cli.ts changes. The fix is internal to TTYRenderer and reads env vars directly (the canonical pattern for SEQUANT_* diagnostic flags).


    Smoke Test

    Workflow-affecting changes: renderer behaviour modification. Verified via the harness integration tests (which drive the real log-update through the actual rendering path), so a separate sequant run smoke is redundant — the harness IS the smoke test.

    Test Command Result Notes
    Default path happy AC-1/AC-5 test ✅ File created, no stderr
    Override path AC-2 test ✅ Override honoured, default skipped
    Schema integrity AC-3 test ✅ All 7 required keys, valid op enum
    Unwritable fallback AC-4 test ✅ No throw, 1 fallback notice

    Smoke Test Status: Complete


    CHANGELOG Verification

    Check Status
    CHANGELOG.md exists ✅ Found
    User-facing changes ✅ Yes (fix: commit, env var behavior change)
    [Unreleased] entry ✅ Present under ### Fixed
    Entry format ✅ Valid (starts with "SEQUANT_DEBUG_RENDERER routes to file sink, eliminating 2171× scrollback amplifier", includes (#664))

    Result: CHANGELOG requirements met.


    Self-Evaluation

    • Verified working: Yes — ran the test suite with real log-update against a virtual terminal; verified file is created at default path, override path is honoured, schema lines parse correctly, and the unwritable-path branch emits the fallback notice and continues without crashing. The throwing-stderr stub provides defense-in-depth against accidental regression.
    • Test efficacy: High — the throwingStderr stub at test L550-560 is the strongest possible guard against the bug regressing (any future code that routes debug to stderr fails loudly). The schema check iterates every line, not just the first, so partial drift is caught.
    • Likely failure mode: If fs.writeSync is interrupted by a signal mid-line, you could get a torn record — but writeSync retries on EINTR per Node's libuv layer, and the diagnostic file isn't safety-critical. The more plausible concern is fd accumulation in long-lived processes that construct many TTYRenderers (e.g. an MCP server holding state across runs), but the orchestrator uses OrchestratorRenderer instead, sidestepping this entirely.
    • Verdict confidence: High. The change is small, focused, has literal AC-mapped tests, and includes a strong no-regression guard. The one design choice that deserves callout (|| vs ?? for the env-var fallback) is documented inline and is the more user-friendly behaviour. The fix scope is unrelated to the in-flight fix(cli): #624's duplicate-header fix doesn't catch real log-update/scrollback bug (v2.3.0 regression confirmed) #647 AC-3 work — independent and ship-standalone as the issue body promised.

    Verdict: READY_FOR_MERGE

    All 6 AC items literally met (verified against AC text, not just spirit). Code quality is A+: small focused diff, no any types, no deleted tests, integration test exercises the production code path via real log-update, CHANGELOG entry added, documentation updated to mark the related #647 capture caveat as resolved. The one design judgment call (|| over ??) is the right one and documented inline.

    Documentation

    Next Steps

    1. Create PR (Phase 5 of /fullsolve orchestration) and let CI run
    2. Merge when CI is green
    3. Optional follow-up: capture another sequant run with SEQUANT_DEBUG_RENDERER=1 post-merge to confirm the fix(cli): #624's duplicate-header fix doesn't catch real log-update/scrollback bug (v2.3.0 regression confirmed) #647 Mechanism feat: Complete remaining v1.0 features (AC-10, AC-13, AC-14) #1 count drops dramatically (this is the empirical validation of the "2171×" claim in the issue body; not blocking merge since the harness already proves the mechanism is removed)
  5. admarble commented on May 18, 2026

    @admarble
    ContributorAuthor

    /fullsolve Complete

    Issue: #664
    Status: READY_FOR_MERGE
    PR: #665 (#665)

    Summary

    Metric Value
    AC met 6/6 (literal verification)
    Test suite 96 passed + 1 expected-fail in src/lib/cli-ui/
    Build ✅ clean
    Lint ✅ 0 warnings
    Diff 4 files, +286/-12
    Mergeable ✅ MERGEABLE

    Iterations

    • Spec loop: 1
    • Exec loop: 1 (1 test failure caught & fixed mid-exec: ?? → || for env var fallback)
    • QA loop: 1

    Key changes


    Ready for human review and merge.

  6. added 4 commits that reference this issue on May 18, 2026
  7. added a commit that references this issue on May 20, 2026
  8. added a commit that references this issue on May 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugcliplanned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions