Repository navigation
Description
Context
Carved out from #508 per its 2026-04-09 architecture review: "File a separate small bug for the log polling race condition (the only user-facing issue)." #508 itself remains parked; this is the concrete fix that doesn't require the full in-process MCP rewrite.
Problem
readLatestRunLog in src/mcp/tools/run.ts:137-173 matches the wrong run log under two scenarios:
-
Concurrent MCP runs. The recency filter (
run.ts:163) has only a lower bound:fileTime >= runStartTime - MAX_LOG_AGE_MS. Twosequant_runcalls in flight, each callingreadLatestRunLog(runStartTime)after their subprocess exits — both filters pass for both log files, and.sort().reverse()returns whichever filename is lexicographically latest. The wrong run can return another run's results. -
Stale same-issue log. If an issue ran in the last 5 minutes and is invoked again, the previous run's log filename passes the recency filter. If for any reason the new log isn't on disk yet (fsync lag, slow filesystem, write buffer), the previous log is returned instead.
The shared root cause: the MCP server has no way to identify which log file belongs to this subprocess invocation. The CLI generates a runId internally and writes run-<startTime>-<runId>.json, but that runId is never communicated back to the MCP caller.
Approach
Thread the runId from the spawned CLI back to MCP, then look up by exact filename instead of fuzzy time-window match.
Three small pieces:
- CLI emits runId on stderr at startup — single line, e.g.
SEQUANT_RUN_ID:<uuid>. Reuses the existingSEQUANT_PROGRESS:stderr-event channel thatparseProgressLinealready consumes. - MCP captures it in the existing line-buffer (
run.ts:494-499) and passes it to a newreadRunLogById(runId)helper. readRunLogByIddoes an exact-filename match onrun-*-<runId>.json— no time filter needed.
Fallback path: if no runId was captured (older CLI, race during startup), fall back to current readLatestRunLog(runStartTime) so behavior degrades to today's, not worse.
Acceptance Criteria
- AC-1: CLI emits
SEQUANT_RUN_ID:<uuid>on stderr exactly once, before anySEQUANT_PROGRESSevent, inbin/cli.ts(or whereverrunIdis generated) - AC-2:
readRunLogById(runId: string): Promise<RunLog | null>added tosrc/mcp/tools/run.ts, looks uprun-*-<runId>.jsonby exact suffix match, returnsnullif absent - AC-3: MCP
sequant_runcaptures theSEQUANT_RUN_IDline in the existing line-buffer and usesreadRunLogByIdinstead ofreadLatestRunLogwhen available - AC-4: Fallback to
readLatestRunLog(runStartTime)whenrunIdwas not captured (preserves today's behavior on older CLIs) - AC-5: Test: two concurrent MCP
sequant_runcalls return their own logs (not each other's). Currently passes only by luck of filesystem ordering - AC-6: Test: a stale log from the same issue within the 5-minute window does not get returned for a fresh run
Non-Goals
- Replace log-file polling with in-process events — that's arch: in-process MCP engine — eliminate subprocess indirection and enable real-time streaming #508's full scope
- Add upper-bound to the filename time filter —
runIdlookup makes the filter unnecessary - Change the log filename format —
runIdis already in there
References
src/mcp/tools/run.ts:32—MAX_LOG_AGE_MS = 5 * 60 * 1000src/mcp/tools/run.ts:137-173—readLatestRunLog(the function to supplement)src/mcp/tools/run.ts:494-499— existing stderr line-buffer whereSEQUANT_RUN_IDwould be parsedsrc/lib/workflow/run-log-schema.ts:281—generateLogFilename(runId, startTime)(filename source of truth)- arch: in-process MCP engine — eliminate subprocess indirection and enable real-time streaming #508 — parent architecture issue (parked); 2026-04-09 architecture review carved this out as the actionable bug
Activity
admarble commentedon May 13, 2026
→ PROCEED — MCP log-file lookup race: thread runId through CLI→MCP and look up by exact filename
Workflow: spec → exec → qa
Command:
npx sequant run 631 -qACs are concrete (6) and reference specific file:line targets in
src/mcp/tools/run.tsandbin/cli.ts. Touches MCP server + CLI stderr channel + new helper; -q recommended for multi-file scope.admarble commentedon May 13, 2026
Complexity: Standard (6 ACs, 2 directories)
AC Quality Check
All 6 ACs are concrete with file:line targets. No vague/unmeasurable patterns. AC-3 references "when available" but AC-4 defines the fallback explicitly, so the pair is unambiguous.
Scope Assessment
Non-Goals: ✅ Present in issue body (3 items). Notably excludes #508's full in-process MCP rewrite and the upper-bound time filter.
src/mcp/tools/,src/lib/workflow/)Verdict: ✅ SCOPE_OK — yellow AC count is offset by single-feature, narrow directory spread. No split needed.
Acceptance Criteria
AC-1: CLI emits
SEQUANT_RUN_ID:<uuid>on stderr exactly once, before anySEQUANT_PROGRESSeventVerification: Unit Test
Scenario: Given
LogWriter.initializehas run withSEQUANT_ORCHESTRATORset → When the orchestrator hands off tobatch-executor→ Then stderr contains exactly oneSEQUANT_RUN_ID:<uuid>\nline, emitted before the firstSEQUANT_PROGRESS:line.Assumptions: Emit lives in
run-orchestrator.tsimmediately afterawait logWriter.initialize(...)(line ~456); gated onprocess.env.SEQUANT_ORCHESTRATORthe same wayemitProgressLineis, so CLI users see nothing extra.AC-2:
readRunLogById(runId)added tosrc/mcp/tools/run.tsVerification: Unit Test
Scenario: Given a log dir containing
run-<ts>-<uuid>.json→ WhenreadRunLogById(uuid)is called → Then it parses and returns theRunLog; when called with an unknown id, returnsnull.Assumptions: Exact suffix match (
endsWith(-${runId}.json)) avoids re-globbing; reusesRunLogSchema.parseandresolveLogDir().AC-3: MCP captures
SEQUANT_RUN_IDand usesreadRunLogByIdwhen availableVerification: Integration Test
Scenario: Given a spawned CLI emits
SEQUANT_RUN_ID:<uuid>early → Whensequant_runfinishes → ThenbuildStructuredResponseis fed the log fromreadRunLogById(capturedRunId), notreadLatestRunLog.Assumptions: Adds
parseRunIdLinehelper (sibling toparseProgressLine). See Open Question 1 — current line-buffer atrun.ts:514is gated onhasProgressToken; this fix requires the buffer to always run (or a runId-only buffer added).AC-4: Fallback to
readLatestRunLog(runStartTime)when runId not capturedVerification: Integration Test
Scenario: Given the CLI does not emit
SEQUANT_RUN_ID(older CLI / startup race) → Whensequant_runfinishes → Then MCP uses the existingreadLatestRunLog(runStartTime)path; response identical to today's behavior.Assumptions: No new "could not find log" failure mode introduced; absence of runId is silent, not an error.
AC-5: Two concurrent
sequant_runcalls return their own logsVerification: Integration Test
Scenario: Given two
sequant_runcalls overlap in time → When both complete → Then each response references therunIdfrom its own subprocess (assert viaRunLog.runIdfield on the parsed log).Assumptions: Test fixture mocks the CLI to emit a controlled
SEQUANT_RUN_IDand write a matching log file; doesn't require real workflow execution.AC-6: Stale same-issue log inside 5-min window is not returned for a fresh run
Verification: Integration Test
Scenario: Given a prior log
run-<ts1>-<uuidA>.jsonexists from 2 min ago for issue #N → When a newsequant_runfor #N starts, emitsSEQUANT_RUN_ID:<uuidB>, and writesrun-<ts2>-<uuidB>.json→ Then the response is built from theuuidBlog, regardless of fsync ordering.Assumptions: Test seeds the stale file before spawn and uses a fake CLI that delays the new log write.
Implementation Plan
Phase 1 — CLI emit (single touchpoint)
src/lib/workflow/batch-executor.ts— addemitRunIdLine(runId: string)alongsideemitProgressLine(~line 128). Sameprocess.env.SEQUANT_ORCHESTRATORgate. Prefix constantSEQUANT_RUN_ID:.src/lib/workflow/run-orchestrator.ts:456— immediately afterawait logWriter.initialize(runConfig), callemitRunIdLine(logWriter.getRunId()!). VerifygetRunId()returns the value post-initialize (it does —log-writer.ts:299).Phase 2 — MCP capture & lookup
src/mcp/tools/run.ts— addPROGRESS_LINE_PREFIXsiblingRUN_ID_LINE_PREFIX = "SEQUANT_RUN_ID:"and exportedparseRunIdLine(line): string | null(~near line 289).readRunLogById(runId: string): Promise<RunLog | null>—readdir(logDir),find(f => f.endsWith(-${runId}.json)), parse and return; null on miss/exception.run.ts:505-516— restructure the line-buffer so it captures both progress events AND acapturedRunIdclosure variable. Two options (see Open Q1).run.ts:544— replaceawait readLatestRunLog(runStartTime)with:?? readLatestRunLogkeeps AC-4 honest even if the file exists but the runId lookup mis-fires.Phase 3 — Tests
parseRunIdLineaccepts valid UUID, rejects junk, rejectsSEQUANT_PROGRESS:lines.readRunLogByIdexact-match + null-on-absent.run-*-<uuidA>.json+ new run emitsuuidB→ response built fromuuidBlog.Sibling-site scan:
readLatestRunLoghas exactly one production caller (run.ts:544). No sibling sites need updating.Design Review
runIdis generated); capture/lookup lives in the MCP tool that owns log resolution. Both are existing layer-correct homes.SEQUANT_PROGRESSalready proves out. Rejected: passing runId via temp file (more I/O surface), or via an MCP-only env var (can't survive subprocess→parent direction).emitProgressLine↔parseProgressLine↔createLineBuffer. No new abstraction.runIdfrom the SEQUANT_PROGRESS payload itself?" — because progress events fire per phase, not at startup, and the first one might be slow. Emitting a dedicated startup line is cheaper than mutating the progress schema.Feature Quality Planning
All standard checks pass. Notable items:
SEQUANT_PROGRESS:). New MCP against old CLI falls back toreadLatestRunLog— AC-4 covers this explicitly.readRunLogByIdreturns null, the chained?? readLatestRunLogkeeps behavior no-worse-than-today.Open Questions
Always-on stderr line buffer, or runId-only buffer? — Currently
stderrLineBufferis created only whenhasProgressToken(run.ts:514). Recommendation: make it always-on and havehandleLineroute to bothparseProgressLine(only emits if progressToken set) andparseRunIdLine(always captures). Impact if we don't: runId capture won't work for MCP clients that don't pass a progressToken, and the fallback path always wins for them — defeats AC-5/AC-6 for those clients.Where exactly to emit? Inside
run-orchestrator.tsafterlogWriter.initialize(recommended) vs insideLogWriter.initializeitself. Recommendation: the orchestrator, soLogWriterstays unaware of the MCP wire protocol.Recommended Workflow
Phases: spec → exec → qa
Quality Loop: enabled
Reasoning: Matches
/assessrecommendation. ACs are all Unit/Integration — notestgenneeded (bug-label override, and the test ACs are concrete enough to author inline). No UI involved → notestphase.Label Review
Current:
bugRecommended:
bug,plannedReason: Standard tier, single concrete fix; no
complex/refactorwarranted. Quality loop auto-enables via/assessmarker.→
gh issue edit 631 --add-label plannedadmarble commentedon May 13, 2026
Progress Update — /exec complete
PR: #635
AC Coverage
SEQUANT_RUN_ID:<uuid>once on stderr, before anySEQUANT_PROGRESSemitRunIdLineinsrc/lib/workflow/batch-executor.ts; called inrun-orchestrator.tsimmediately afterlogWriter.initialize(). Testshould be emittable before emitProgressLine (ordering invariant)pins orderingreadRunLogById(runId)added; exact filename suffix; null on misssrc/mcp/tools/run.ts:readRunLogById—endsWith(-${runId}.json). 6 tests covering miss, hit, parse failure, readdir rejection, plus AC-5/AC-6 scenariosSEQUANT_RUN_IDand usesreadRunLogByIdwhen availablehandleLinenow routes runId lines intocapturedRunIdbefore falling through to progress parsing; line buffer flipped to always-on so capture works without aprogressTokenreadLatestRunLog(runStartTime)when runId not captured(capturedRunId !== null ? readRunLogById(...) : null) ?? readLatestRunLog(runStartTime)— also handles lookup-miss case so behavior degrades to today's, not worsesequant_runcalls return their own logsshould return the caller's own log when concurrent run logs coexist— both filenames pass the time filter; runId lookup returns each caller's own logshould not return a stale same-issue log when looked up by fresh runId— stale file lexicographically later (would win underreadLatestRunLog), runId lookup ignores itQuality Plan Alignment
capturedRunIdstays null, fallback path runsreadRunLogByIdreturns null on miss/parse/IO error; chained??preserves today's pathDerived ACs: None —
/speccomment had no Derived ACs table.Files Changed
src/lib/workflow/batch-executor.ts— newemitRunIdLinesrc/lib/workflow/run-orchestrator.ts— callemitRunIdLineafterlogWriter.initializesrc/mcp/tools/run.ts—RUN_ID_LINE_PREFIX,parseRunIdLine,readRunLogById; always-on line buffer; prefer runId lookup with fallbacksrc/mcp/tools/run.test.ts— 13 new tests (parseRunIdLine, readRunLogById, emitRunIdLine)CHANGELOG.md— entry under## [Unreleased] > ### FixedPre-PR Quality Gates
npm run buildnpm run lintnpx vitest run src/mcp src/lib/workflow src/commands/run.test.tsnpx vitest run __tests__/integration/mcp-e2e.integration.test.ts __tests__/integration/run-orchestrator.integration.test.tsPre-PR Confidence Check
readRunLogByIdand the wire-protocol pieces in isolation rather than full subprocess spawning. The runtime call-site ((capturedRunId !== null ? ...) ?? readLatestRunLog(...)) is covered by the existing integration tests' continued success, but the new race-fix logic itself relies on unit-test fidelity to the spawn lifecycle. Mitigated by AC-1's ordering-invariant test plus the always-on buffer change being a one-line restructure.run-orchestrator.tschange is a 2-line addition (getRunId()+ conditionalemitRunIdLine) covered indirectly byrun-orchestrator.integration.test.ts(19 passing). No dedicated unit test for the call-site since it's behind real file I/O.admarble commentedon May 13, 2026
QA Review for Issue #631
AC Coverage
SEQUANT_RUN_ID:<uuid>once on stderr, before anySEQUANT_PROGRESSemitRunIdLine(batch-executor.ts:158) isSEQUANT_ORCHESTRATOR-gated, called inrun-orchestrator.ts:458-459immediately afterlogWriter.initialize(). Ordering invariant pinned byshould be emittable before emitProgressLine (ordering invariant)testreadRunLogById(runId)added; exact filename suffix; null on missrun.ts:139—endsWith(-${runId}.json). 6 tests cover miss, hit, parse failure, readdir rejection, plus AC-5/AC-6 scenariosSEQUANT_RUN_IDand usesreadRunLogByIdwhen availablehandleLine(run.ts:555-565) routes runId lines intocapturedRunIdbefore falling through to progress parsing. Line buffer flipped to always-on (run.ts:571) so capture works without aprogressToken— directly resolves spec Open Question 1readLatestRunLog(runStartTime)when runId not captured(capturedRunId !== null ? readRunLogById(...) : null) ?? readLatestRunLog(...)(run.ts:602-605). Also handles lookup-miss case — behavior degrades to today's, not worsesequant_runcalls return their own logsshould return the caller's own log when concurrent run logs coexist— both filenames pass the time filter,runIdBfilename is lexicographically later (would win.sort().reverse()), runId lookup returns each caller's own logshould not return a stale same-issue log when looked up by fresh runId— stale file lexicographically later, fresh runId lookup ignores it;mockedReadFilethrows if stale path is readCoverage: 6/6 AC items fully met
Original ACs: 6/6 met
Derived ACs: None (spec had no Derived ACs)
Quality Plan Verification
capturedRunId→ fallback path; old MCP → ignores unknown stderr line)readRunLogByIdreturns null on miss/parse/IO; chained??preserves today's path)Quality Plan Status: Complete
CI Status
typecheckbuild (20.x)build (22.x)validate-skillsvalidate-pluginCI Summary: 5 passed, 0 pending, 0 failed
Quality Metrics
any)as anyon mockedreaddir/readFilereturn values in tests, with eslint-disable markers)Build Verification
N/A —
npm run buildpassed cleanly on the feature branch.Test Coverage Analysis
src/lib/workflow/batch-executor.ts(newemitRunIdLine)src/mcp/tools/run.test.ts—emitRunIdLine (#631 AC-1)describe blocksrc/lib/workflow/run-orchestrator.ts(2-line call-site)__tests__/integration/run-orchestrator.integration.test.ts(19 passing) — no dedicated unit test for the 2-line additionsrc/mcp/tools/run.ts(parseRunIdLine, readRunLogById, always-on buffer, lookup branch)src/mcp/tools/run.test.ts— 13 new tests across 3 describe blocksCoverage: 3/3 changed source files have tests.
run-orchestrator.ts2-line call-site has only indirect integration coverage — acceptable for the surface area.Code Review
Strengths:
runIdis generated; MCP capture/lookup lives where log resolution belongs. Mirrors the existingemitProgressLine ↔ parseProgressLine ↔ createLineBuffertriad with no new abstractions.?? readLatestRunLog(...)covers both "no runId captured" and "runId captured but lookup returned null" — strictly better than the AC-4 minimum.parseRunIdLine(UUID_REregex) rejects malformed payloads before they're cached ascapturedRunId, preventing junk on stderr from poisoning the lookup.if (capturedRunId === null)so progress events still flow after the runId line; ordering test pins this contract.runIdBlexicographically later (would win.sort().reverse()), and AC-6 fixture hasmockedReadFilethrow if the stale path is read, so a regression would fail loudly rather than silently.getRunId()is properly null-checked at the call-site (if (runId) emitRunIdLine(runId)) — defensive against future changes toLogWriter.initialize()semantics.Issues:
Suggestions:
stderrLineBuffer(was previously gated onhasProgressToken) is a behavior change beyond strict runId capture: every MCPsequant_runnow line-buffers stderr unconditionally. Cost is negligible (onestartsWithper line for non-progress clients), but worth flagging as the spec's Open Question 1 resolved in favor of always-on. The code comment atrun.ts:567-569documents this clearly.hasProgressTokenis still declared atrun.ts:570purely to gateonProgressfor timeout-reset semantics. Reads naturally — no change needed.Test Quality Review
parseRunIdLine/readRunLogById, not internals. Concurrent-runs test assertsresult.runId === runIdA, not implementation detailsparseRunIdLinerejects: non-RUN_ID lines, malformed UUID, empty payload, PROGRESS line).readRunLogByIdcovers: miss, hit, parse failure, readdir rejection, concurrent, stalefs/promisesmocked (external dependency).process.stderr.writespied viavi.spyOn. No internal modules mockedreaddirordering. No timing dependencies.originalEnvsave/restore forSEQUANT_ORCHESTRATORIssues Found: None.
Anti-Pattern Detection
Dependency Audit: N/A — no
package.jsonchanges.Code Patterns: No N+1 queries, empty catches, hardcoded secrets, or memory leaks introduced. The
try { ... } catch { return null; }inreadRunLogByIdis a deliberate AC-2 design choice (returnsnullon parse/IO error so the chained?? readLatestRunLogfallback kicks in) — documented in the function JSDoc.Critical Issues: 0
Warnings: 0
Call-Site Review
New exported functions detected: 3 (
emitRunIdLine,readRunLogById,parseRunIdLine)emitRunIdLine(runId)run-orchestrator.ts:459, plus testsif (runId)(post-getRunId()null check); function-internalif (!process.env.SEQUANT_ORCHESTRATOR) return;logWriter.initializeand before any phase iterationreadRunLogById(runId)run.ts:604, plus tests(capturedRunId !== null ? ... : null) ?? readLatestRunLog(...)ternaryparseRunIdLine(line)run.ts:557(insidehandleLine), plus testsif (capturedRunId === null)guard — only parses until first captureFindings: No call-site mismatches. The conditional guards (
if (runId),capturedRunId !== null,if (capturedRunId === null)) all align with AC constraints.Execution Evidence
N/A — no
scripts/or CLI entry-point changes. Changes are library code insrc/lib/workflow/andsrc/mcp/tools/, all exercised by the test suite.Skill Command Verification
N/A — no
.claude/skills/**/*.mdfiles modified.CLI Registration Verification
N/A — no
RunOptionsinterface fields added; no new CLI flags.Smoke Test
N/A — change is internal to MCP↔CLI wire protocol. Validated end-to-end via existing
__tests__/integration/mcp-e2e.integration.test.tsand__tests__/integration/run-orchestrator.integration.test.ts(19/19 passing per exec evidence).CHANGELOG Verification
sequant_runcallers)[Unreleased]entry### FixedResult: CHANGELOG requirements met.
Self-Evaluation
main(the bug they describe). Concurrent test asserts each caller gets its OWN log byrunId. Stale test hasmockedReadFilethrow if the stale path is read, so a regression fails loudly.SEQUANT_RUN_IDline is somehow emitted after the first phase event — explicitly mitigated by AC-1's ordering test and by emit happening synchronously right afterlogWriter.initialize()before any phase loop. Secondary risk:LogWriter.initializefuture change that makesgetRunId()return null — theif (runId)guard at the call-site degrades to fallback path silently.??covers lookup-miss too), and the tests directly exercise the named race scenarios with fixtures designed to fail on the oldreadLatestRunLog-only path.Verdict: READY_FOR_MERGE
All 6 ACs fully met with concrete evidence. CI green (5/5). Tests deterministic and cover the named AC-5/AC-6 race scenarios with adversarial fixtures. Code is layer-correct (mirrors existing
emitProgressLinetriad), conservatively falls back to today's behavior on any lookup miss, and adds no new failure modes. CHANGELOG entry present.Documentation
[Unreleased] > FixedDocumentation: Before merging, run `/docs 631` if you want to capture this MCP race-fix in admin docs (optional — bug fix with no new user surface).
Next Steps
fix(#631): thread runId from CLI to MCP for exact log lookup).fix(#631): close QA gaps — testable capture/resolve helpers + fallbac…
admarble commentedon May 13, 2026
QA Gap Closure — follow-up commit a68cdd8
Addressed all 4 gaps from the prior QA review without altering AC verdicts. PR #635 now contains a second commit that refactors testability and adds observability for the silent fallback path.
What changed
createRunIdCapture()factory. New tests drive the realcreateLineBufferend-to-end (chunk-boundary reconstruction; two concurrent captures resolve to their own logs; stale same-issue log is rejected).mockedReadFilethrows on the stale path so a regression would fail loudly.readRunLogById → null → readLatestRunLogfallbackresolveRunLog(capturedRunId, runStartTime). New unit tests cover all four branches: hit, miss-with-fallback, null-capturedRunId, both-null.readRunLogByIdparse failuresresolveRunLognow emits[mcp:run] runId <id> lookup miss — falling back to readLatestRunLogon the MCP server's own stderr viaconsole.errorwhen a captured runId fails to resolve. Tests assert the message fires on miss and does NOT fire on hit / null-capturedRunId.hasProgressTokensurvives without buffer-gatingonProgresscallback that controlsspawnAsync's timeout-reset behavior.Test impact
src/mcp/tools/run.test.ts: 63 → 77 tests (14 new)npx vitest run src/mcp src/lib/workflow src/commands/run.test.ts→ 1114/1114 passnpm run build→ cleannpm run lint→ 0 warningsVerdict (unchanged): READY_FOR_MERGE
The original 6 ACs remain MET. The follow-up commit improves test fidelity for AC-5/AC-6 (now exercise the actual wire-protocol path, not just the helper) and adds observability for a silent failure mode without changing user-facing behavior.
fix(#631): thread runId from CLI to MCP for exact log lookup (#635)
fix(#631): thread runId from CLI to MCP for exact log lookup
fix(#631): close QA gaps — testable capture/resolve helpers + fallbac…