Repository navigation
Description
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.tsto verify that withSEQUANT_DEBUG_RENDERER=1set and a writeable temp file, the renderer'sstderrWriteis NOT called for debug output (use a stub that throws on stderr write). - Update
docs/incidents/647/captures/2026-05-17/notes.md"Caveat —scriptwrapper interference" section noting the issue is resolved going forward.
Why this is worth doing
- The AC-1 capture (PR docs(#647): AC-1 capture — Mechanism #1 confirmed at 2181× over 36m #661) overstated Mechanism feat: Complete remaining v1.0 features (AC-10, AC-13, AC-14) #1 by 2171× because of this. Any future production capture risks the same misreading.
- Independent of the fix(cli): #624's duplicate-header fix doesn't catch real log-update/scrollback bug (v2.3.0 regression confirmed) #647 AC-3 fix — can ship standalone.
- Tiny blast radius. Only the renderer's debug path changes; production no-debug runs behave identically.
Out of scope
- Fixing the underlying Mechanism docs: Add pre-release checklist #2 (out-of-band writes breaking log-update). That's fix(cli): #624's duplicate-header fix doesn't catch real log-update/scrollback bug (v2.3.0 regression confirmed) #647 AC-3, which still needs the clean-baseline capture before fix design.
- Replacing the SEQUANT_DEBUG_RENDERER instrumentation with structured logging — too broad. Keep the JSON-per-line format as-is.
Related
- fix(cli): #624's duplicate-header fix doesn't catch real log-update/scrollback bug (v2.3.0 regression confirmed) #647 (parent, AC-3 fix iteration)
- PR test(#647): AC-1 re-analysed — Mechanism #1 was wire traffic; deterministic repro via out-of-band write harness #663 (where the amplifier was diagnosed)
- PR docs(#647): AC-1 capture — Mechanism #1 confirmed at 2181× over 36m #661 (capture that the diagnosis revised)
Activity
admarble commentedon May 18, 2026
Plan Complete
Acceptance Criteria
AC-1: Debug output goes to default file, not stderr
Verification: Integration test (vitest with stub stderr that throws)
SEQUANT_DEBUG_RENDERER=1set, no override env var.sequant/debug-renderer.jsonl;stderrWritenot invoked for debug outputAC-2:
SEQUANT_DEBUG_RENDERER_FILEoverrides the default pathVerification: Integration test (temp dir)
SEQUANT_DEBUG_RENDERER_FILE=/tmp/foo.jsonl+SEQUANT_DEBUG_RENDERER=1/tmp/foo.jsonl, not the defaultAC-3: No regression of diagnostic value
Verification: Integration test — read back file content
SEQUANT_DEBUG_RENDERER {...JSON...}\nmatching 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
SEQUANT_DEBUG_RENDERER_FILE=/nonexistent-parent/x.jsonlAC-5: Stub-throws stderr test in scrollback harness
Verification: Add test to
scrollback-harness.test.tsSEQUANT_DEBUG_RENDERER=1and astderrWritestub that throwsAC-6: Update
docs/incidents/647/captures/2026-05-17/notes.mdVerification: Manual read of diff
scriptwrapper 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)
import fs from "node:fs"andimport path from "node:path"at top of file.emitDebugblock with file-sink variant:debugPathfrom env (SEQUANT_DEBUG_RENDERER_FILEor.sequant/debug-renderer.jsonl).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 setdebugStream = null.emitDebug, ifdebugStream === null→ return; elsefs.writeSync(debugStream, line).fs.closeSyncneeded — 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 toscrollback-harness.test.ts:stderrWriteis avi.fn()that throws on debug-format calls; assert no throw and asserts on file content.SEQUANT_DEBUG_RENDERER_FILEat a path whose parent dir cannot be created (e.g.,/dev/null/foo.jsonlwhich has a non-dir "parent"); capture stderr; assert one-shot fallback line and no crash.vi.stubEnv+vi.unstubAllEnvsinbeforeEach/afterEachfor env isolation.os.tmpdir()+mkdtempSyncfor 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
Where does this logic belong? Inside the existing
emitDebugclosure inTTYRenderer.constructor(run-renderer.ts:564–607). The instrumentation is internal to the renderer; no need to extract to a separate module.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
DebugSinkclass (premature abstraction for ~25 LOC).What existing pattern does this follow? The "open-once, sync-append, fall-through-on-error" pattern matches how
.sequant/state.jsonand 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.What would a senior reviewer challenge?
awaitplumbing or risk drops on process exit.O_APPENDguarantees atomic line appends on POSIX; multi-instance is not a use case for this diagnostic.vi.stubEnv+ tmpdir paths keep tests hermetic.Open Questions
Should the fallback stderr line repeat per-op or fire once at startup?
Should we close the fd on
dispose()?Conflict Risk Analysis
In-flight scan:
feature/652-fix-cli-renderer-bottom-outputworktree exists with unmerged commits touchingrun-renderer.ts, including a refactor of the sameemitDebugblock. However, issue fix(cli): renderer bottom-output corruption — ✔ #5loop missing chars + U+FFFD in summary separator #652 is CLOSED and PR fix(#652): renderer bottom-output corruption — column-binding + renderSummary teardown order #654 was CLOSED (not merged) — that branch is abandoned. No live conflict.src/lib/cli-ui/.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-testnot needed; absence ofui/frontend/adminlabels skips/testautomatically.Label Review
Current:
bug,cliRecommended:
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/breakinglabel).admarble commentedon May 18, 2026
QA Review for Issue #664
AC Coverage
SEQUANT_DEBUG_RENDERER=1writes to.sequant/debug-renderer.jsonl, not stderrrun-renderer.ts:578-583opens file at default path; harness test L545-595 uses throwing stderr stub to prove stderr is never invoked for debug outputSEQUANT_DEBUG_RENDERER_FILEenv var override is honouredrun-renderer.ts:580reads override; test L597-633 asserts file lands at override path AND default path is NOT createdrun-renderer.ts:621-637keeps the original record shape; test L635-695 parses every line and asserts all 7 required keys (t,op,frame,rendererCols,rendererRows,stdoutCols,stdoutRows) plus validopenum. Cadence is preserved because only the destination changedrun-renderer.ts:584-592try/catch aroundmkdirSync+openSync; test L697-744 points at/dev/null/foo/debug.jsonl, asserts no throw, exactly 1 fallback notice, zero per-op stderr leakagescrollback-harness.test.ts:550-560definesthrowingStderrthat throws on any line starting withSEQUANT_DEBUG_RENDERER; test runs full event sequence without triggering the throwdocs/incidents/647/captures/2026-05-17/notes.mdCaveat sectionnotes.md:54added "Resolved going forward (#664)." footer referencing the file sink + override env varCoverage: 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-spushed to origin in/execphase, PR creation deferred to Phase 5 (/fullsolveorchestrator). CI will run on PR creation.Quality Metrics
any)Cache Status
N/A — fresh QA run, no prior context.
Build Verification
N/A —
npm run buildpassed cleanly in exec phase (no errors).Test Coverage Analysis
src/lib/cli-ui/run-renderer.tssrc/lib/cli-ui/scrollback-harness.test.ts(4 new #664 tests)src/lib/cli-ui/scrollback-harness.test.tsdocs/incidents/647/captures/2026-05-17/notes.mdCHANGELOG.mdCoverage: 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:
||instead of??for the env-var fallback (run-renderer.ts:578-583) is the correct choice: an emptySEQUANT_DEBUG_RENDERER_FILE=should behave like "unset" rather than passing""toopenSyncand silently disabling debug. Rationale documented inline.run-renderer.ts:567-574explicitly explains the amplifier mechanism and references the AC-1 capture analysis — future readers can connect the fix to the historical context without spelunking commits.log-updatevia the harness (not a mock), so the file-sink behaviour is exercised on the actual production code path.throwingStderrstub 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.Issues:
Suggestions:
sequant runinvocation. Worth monitoring but not a current concern — TTYRenderer is constructed once per CLI run andSEQUANT_ORCHESTRATORmode usesOrchestratorRendererinstead. No action required.Test Quality Review
vi.stubEnvfor env vars and a customstderrWritefunction — no module mocksmkdtempSyncper test,afterEachcleanup,vi.unstubAllEnvs, fixedFIXED_NOW/FIXED_DATE. The AC-4 test relies on POSIX/dev/nullnon-directory semantics; would need adjustment for Windows CI but matches the rest of the suite's POSIX assumptionsIssues Found: None.
Anti-Pattern Detection
Dependency Audit
N/A — no
package.jsonchanges.Code Patterns
No anti-patterns detected:
run-renderer.ts:584-592explicitly handles the error (logs fallback notice, sets debugFd=null)fs.writeSyncis synchronous by design — appropriate for diagnostic-only sink, comment explains the choicenode:fs,node:path— both Node built-ins, no third-party depsCall-Site Review
No new exported functions.
emitDebugremains a closure inside the constructor; its call sites (impl/clear/done) are unchanged. No re-routing required.Execution Evidence
N/A — no
scripts/orbin/files modified. The change is library code with integration test coverage via the reallog-updatedriver in the harness.Skill Command Verification
N/A — no
.claude/skills/**/*.mdfiles modified.CLI Registration Verification
N/A — no
RunOptionsorbin/cli.tschanges. The fix is internal toTTYRendererand reads env vars directly (the canonical pattern forSEQUANT_*diagnostic flags).Smoke Test
Workflow-affecting changes: renderer behaviour modification. Verified via the harness integration tests (which drive the real
log-updatethrough the actual rendering path), so a separatesequant runsmoke is redundant — the harness IS the smoke test.openumSmoke Test Status: Complete
CHANGELOG Verification
fix:commit, env var behavior change)[Unreleased]entry### FixedSEQUANT_DEBUG_RENDERERroutes to file sink, eliminating 2171× scrollback amplifier", includes(#664))Result: CHANGELOG requirements met.
Self-Evaluation
log-updateagainst 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.throwingStderrstub 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.fs.writeSyncis interrupted by a signal mid-line, you could get a torn record — butwriteSyncretries 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 usesOrchestratorRendererinstead, sidestepping this entirely.||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
anytypes, no deleted tests, integration test exercises the production code path via reallog-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
### Fixed[Unreleased](fix(cli): route SEQUANT_DEBUG_RENDERER to file sink, eliminate 2171× scrollback amplifier #664)docs/incidents/647/captures/2026-05-17/notes.mdCaveat section updated with resolution footerSEQUANT_DEBUG_RENDERER(it's a diagnostic flag for incident response, not a documented public surface)Next Steps
/fullsolveorchestration) and let CI runsequant runwithSEQUANT_DEBUG_RENDERER=1post-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)admarble commentedon May 18, 2026
/fullsolve Complete
Issue: #664
Status: READY_FOR_MERGE
PR: #665 (#665)
Summary
src/lib/cli-ui/Iterations
??→||for env var fallback)Key changes
src/lib/cli-ui/run-renderer.ts—emitDebugwrites to file sink instead of stderr; one-shot fallback notice on unwritable pathsrc/lib/cli-ui/scrollback-harness.test.ts— 4 new fix(cli): route SEQUANT_DEBUG_RENDERER to file sink, eliminate 2171× scrollback amplifier #664 tests + updated comment on the (now-removed) stderr amplifier pathdocs/incidents/647/captures/2026-05-17/notes.md— Caveat marked resolvedCHANGELOG.md— Fixed entry under[Unreleased]Ready for human review and merge.
docs(#664): update stale stderr references in renderer + incident docs
fix(#664): explicit cwd resolution + lock-in tests for env-var semantics
test(#664): remove duplicate "AC-1 (lockin)" test
fix(#664): route SEQUANT_DEBUG_RENDERER to file sink, eliminate 2171×…
fix(#647): AC-3 — route retry/fallback messages through renderer's ap…
docs(#655): HITL capture — renderer emits clean bytes, corruption is …