Skip to content

fix(mcp): log-file lookup races on concurrent runs and stale same-issue logs #631

Closed

Description

@admarble

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:

  1. Concurrent MCP runs. The recency filter (run.ts:163) has only a lower bound: fileTime >= runStartTime - MAX_LOG_AGE_MS. Two sequant_run calls in flight, each calling readLatestRunLog(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.

  2. 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:

  1. CLI emits runId on stderr at startup — single line, e.g. SEQUANT_RUN_ID:<uuid>. Reuses the existing SEQUANT_PROGRESS: stderr-event channel that parseProgressLine already consumes.
  2. MCP captures it in the existing line-buffer (run.ts:494-499) and passes it to a new readRunLogById(runId) helper.
  3. readRunLogById does an exact-filename match on run-*-<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 any SEQUANT_PROGRESS event, in bin/cli.ts (or wherever runId is generated)
  • AC-2: readRunLogById(runId: string): Promise<RunLog | null> added to src/mcp/tools/run.ts, looks up run-*-<runId>.json by exact suffix match, returns null if absent
  • AC-3: MCP sequant_run captures the SEQUANT_RUN_ID line in the existing line-buffer and uses readRunLogById instead of readLatestRunLog when available
  • AC-4: Fallback to readLatestRunLog(runStartTime) when runId was not captured (preserves today's behavior on older CLIs)
  • AC-5: Test: two concurrent MCP sequant_run calls 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

References

  • src/mcp/tools/run.ts:32 — MAX_LOG_AGE_MS = 5 * 60 * 1000
  • src/mcp/tools/run.ts:137-173 — readLatestRunLog (the function to supplement)
  • src/mcp/tools/run.ts:494-499 — existing stderr line-buffer where SEQUANT_RUN_ID would be parsed
  • src/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

  1. added
    bug
    on May 12, 2026
  2. admarble commented on May 13, 2026

    @admarble
    ContributorAuthor

    → 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 -q

    ACs are concrete (6) and reference specific file:line targets in src/mcp/tools/run.ts and bin/cli.ts. Touches MCP server + CLI stderr channel + new helper; -q recommended for multi-file scope.

  3. admarble commented on May 13, 2026

    @admarble
    ContributorAuthor

    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.

    Metric Value Status
    Feature count 1 (runId threading) ✅
    AC items 6 ⚠️ (yellow threshold)
    Directory spread 2 (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 any SEQUANT_PROGRESS event

    Verification: Unit Test
    Scenario: Given LogWriter.initialize has run with SEQUANT_ORCHESTRATOR set → When the orchestrator hands off to batch-executor → Then stderr contains exactly one SEQUANT_RUN_ID:<uuid>\n line, emitted before the first SEQUANT_PROGRESS: line.
    Assumptions: Emit lives in run-orchestrator.ts immediately after await logWriter.initialize(...) (line ~456); gated on process.env.SEQUANT_ORCHESTRATOR the same way emitProgressLine is, so CLI users see nothing extra.

    AC-2: readRunLogById(runId) added to src/mcp/tools/run.ts

    Verification: Unit Test
    Scenario: Given a log dir containing run-<ts>-<uuid>.json → When readRunLogById(uuid) is called → Then it parses and returns the RunLog; when called with an unknown id, returns null.
    Assumptions: Exact suffix match (endsWith(-${runId}.json)) avoids re-globbing; reuses RunLogSchema.parse and resolveLogDir().

    AC-3: MCP captures SEQUANT_RUN_ID and uses readRunLogById when available

    Verification: Integration Test
    Scenario: Given a spawned CLI emits SEQUANT_RUN_ID:<uuid> early → When sequant_run finishes → Then buildStructuredResponse is fed the log from readRunLogById(capturedRunId), not readLatestRunLog.
    Assumptions: Adds parseRunIdLine helper (sibling to parseProgressLine). See Open Question 1 — current line-buffer at run.ts:514 is gated on hasProgressToken; this fix requires the buffer to always run (or a runId-only buffer added).

    AC-4: Fallback to readLatestRunLog(runStartTime) when runId not captured

    Verification: Integration Test
    Scenario: Given the CLI does not emit SEQUANT_RUN_ID (older CLI / startup race) → When sequant_run finishes → Then MCP uses the existing readLatestRunLog(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_run calls return their own logs

    Verification: Integration Test
    Scenario: Given two sequant_run calls overlap in time → When both complete → Then each response references the runId from its own subprocess (assert via RunLog.runId field on the parsed log).
    Assumptions: Test fixture mocks the CLI to emit a controlled SEQUANT_RUN_ID and 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>.json exists from 2 min ago for issue #N → When a new sequant_run for #N starts, emits SEQUANT_RUN_ID:<uuidB>, and writes run-<ts2>-<uuidB>.json → Then the response is built from the uuidB log, 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)

    1. src/lib/workflow/batch-executor.ts — add emitRunIdLine(runId: string) alongside emitProgressLine (~line 128). Same process.env.SEQUANT_ORCHESTRATOR gate. Prefix constant SEQUANT_RUN_ID:.
    2. src/lib/workflow/run-orchestrator.ts:456 — immediately after await logWriter.initialize(runConfig), call emitRunIdLine(logWriter.getRunId()!). Verify getRunId() returns the value post-initialize (it does — log-writer.ts:299).

    Phase 2 — MCP capture & lookup

    1. src/mcp/tools/run.ts — add PROGRESS_LINE_PREFIX sibling RUN_ID_LINE_PREFIX = "SEQUANT_RUN_ID:" and exported parseRunIdLine(line): string | null (~near line 289).
    2. Add exported readRunLogById(runId: string): Promise<RunLog | null> — readdir(logDir), find(f => f.endsWith(-${runId}.json)), parse and return; null on miss/exception.
    3. run.ts:505-516 — restructure the line-buffer so it captures both progress events AND a capturedRunId closure variable. Two options (see Open Q1).
    4. run.ts:544 — replace await readLatestRunLog(runStartTime) with:
      const runLog = capturedRunId
        ? (await readRunLogById(capturedRunId)) ?? (await readLatestRunLog(runStartTime))
        : await readLatestRunLog(runStartTime);
      The ?? readLatestRunLog keeps AC-4 honest even if the file exists but the runId lookup mis-fires.

    Phase 3 — Tests

    1. Unit: parseRunIdLine accepts valid UUID, rejects junk, rejects SEQUANT_PROGRESS: lines.
    2. Unit: readRunLogById exact-match + null-on-absent.
    3. Integration (AC-5): two concurrent fake runs with distinct emitted runIds → distinct logs returned.
    4. Integration (AC-6): stale run-*-<uuidA>.json + new run emits uuidB → response built from uuidB log.

    Sibling-site scan: readLatestRunLog has exactly one production caller (run.ts:544). No sibling sites need updating.

    Design Review

    1. Where does this logic belong? Emit lives in the CLI's run-orchestrator (closest to where runId is generated); capture/lookup lives in the MCP tool that owns log resolution. Both are existing layer-correct homes.
    2. What's the simplest correct approach? Stderr line emission reuses the exact channel SEQUANT_PROGRESS already 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).
    3. What existing pattern does this follow? Mirrors emitProgressLine ↔ parseProgressLine ↔ createLineBuffer. No new abstraction.
    4. What would a senior reviewer challenge? "Why not parse runId from 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:

    • Backward compatibility: Old MCP clients against new CLI ignore the extra stderr line (it's just a string that doesn't match SEQUANT_PROGRESS:). New MCP against old CLI falls back to readLatestRunLog — AC-4 covers this explicitly.
    • No new failure modes: If readRunLogById returns null, the chained ?? readLatestRunLog keeps behavior no-worse-than-today.
    • Test honesty: AC-5 and AC-6 explicitly call out that today's tests pass "by luck of filesystem ordering" — the new tests must be deterministic (fixed clock or controlled emit ordering, not real concurrent spawns).

    Open Questions

    1. Always-on stderr line buffer, or runId-only buffer? — Currently stderrLineBuffer is created only when hasProgressToken (run.ts:514). Recommendation: make it always-on and have handleLine route to both parseProgressLine (only emits if progressToken set) and parseRunIdLine (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.

    2. Where exactly to emit? Inside run-orchestrator.ts after logWriter.initialize (recommended) vs inside LogWriter.initialize itself. Recommendation: the orchestrator, so LogWriter stays unaware of the MCP wire protocol.

    Recommended Workflow

    Phases: spec → exec → qa
    Quality Loop: enabled
    Reasoning: Matches /assess recommendation. ACs are all Unit/Integration — no testgen needed (bug-label override, and the test ACs are concrete enough to author inline). No UI involved → no test phase.

    Label Review

    Current: bug
    Recommended: bug, planned
    Reason: Standard tier, single concrete fix; no complex/refactor warranted. Quality loop auto-enables via /assess marker.

    → gh issue edit 631 --add-label planned

  4. added
    planned
    on May 13, 2026
  5. admarble commented on May 13, 2026

    @admarble
    ContributorAuthor

    Progress Update — /exec complete

    PR: #635

    AC Coverage

    AC Source Description Status Evidence
    AC-1 Original CLI emits SEQUANT_RUN_ID:<uuid> once on stderr, before any SEQUANT_PROGRESS ✅ Implemented emitRunIdLine in src/lib/workflow/batch-executor.ts; called in run-orchestrator.ts immediately after logWriter.initialize(). Test should be emittable before emitProgressLine (ordering invariant) pins ordering
    AC-2 Original readRunLogById(runId) added; exact filename suffix; null on miss ✅ Implemented src/mcp/tools/run.ts:readRunLogById — endsWith(-${runId}.json). 6 tests covering miss, hit, parse failure, readdir rejection, plus AC-5/AC-6 scenarios
    AC-3 Original MCP captures SEQUANT_RUN_ID and uses readRunLogById when available ✅ Implemented handleLine now routes runId lines into capturedRunId before falling through to progress parsing; line buffer flipped to always-on so capture works without a progressToken
    AC-4 Original Fallback to readLatestRunLog(runStartTime) when runId not captured ✅ Implemented (capturedRunId !== null ? readRunLogById(...) : null) ?? readLatestRunLog(runStartTime) — also handles lookup-miss case so behavior degrades to today's, not worse
    AC-5 Original Two concurrent sequant_run calls return their own logs ✅ Implemented Test should return the caller's own log when concurrent run logs coexist — both filenames pass the time filter; runId lookup returns each caller's own log
    AC-6 Original Stale same-issue log inside 5-min window not returned for fresh run ✅ Implemented Test should not return a stale same-issue log when looked up by fresh runId — stale file lexicographically later (would win under readLatestRunLog), runId lookup ignores it

    Quality Plan Alignment

    Quality Dimension Items Addressed Notes
    Backward compatibility 1/1 Old MCP client + new CLI: extra stderr line is ignored. New MCP + old CLI: capturedRunId stays null, fallback path runs
    No new failure modes 1/1 readRunLogById returns null on miss/parse/IO error; chained ?? preserves today's path
    Test honesty 2/2 Concurrent + stale tests use deterministic fixtures (controlled filename ordering, distinct runIds), not real spawns

    Derived ACs: None — /spec comment had no Derived ACs table.

    Files Changed

    • src/lib/workflow/batch-executor.ts — new emitRunIdLine
    • src/lib/workflow/run-orchestrator.ts — call emitRunIdLine after logWriter.initialize
    • src/mcp/tools/run.ts — RUN_ID_LINE_PREFIX, parseRunIdLine, readRunLogById; always-on line buffer; prefer runId lookup with fallback
    • src/mcp/tools/run.test.ts — 13 new tests (parseRunIdLine, readRunLogById, emitRunIdLine)
    • CHANGELOG.md — entry under ## [Unreleased] > ### Fixed

    Pre-PR Quality Gates

    Check Result
    npm run build ✅ pass
    npm run lint ✅ pass
    npx vitest run src/mcp src/lib/workflow src/commands/run.test.ts ✅ 1100/1100
    npx vitest run __tests__/integration/mcp-e2e.integration.test.ts __tests__/integration/run-orchestrator.integration.test.ts ✅ 19/19

    Pre-PR Confidence Check

    • Weakest part: Tests exercise readRunLogById and 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.
    • Coverage gaps: run-orchestrator.ts change is a 2-line addition (getRunId() + conditional emitRunIdLine) covered indirectly by run-orchestrator.integration.test.ts (19 passing). No dedicated unit test for the call-site since it's behind real file I/O.
  6. admarble commented on May 13, 2026

    @admarble
    ContributorAuthor

    QA Review for Issue #631

    AC Coverage

    AC Source Description Status Notes
    AC-1 Original CLI emits SEQUANT_RUN_ID:<uuid> once on stderr, before any SEQUANT_PROGRESS MET emitRunIdLine (batch-executor.ts:158) is SEQUANT_ORCHESTRATOR-gated, called in run-orchestrator.ts:458-459 immediately after logWriter.initialize(). Ordering invariant pinned by should be emittable before emitProgressLine (ordering invariant) test
    AC-2 Original readRunLogById(runId) added; exact filename suffix; null on miss MET run.ts:139 — endsWith(-${runId}.json). 6 tests cover miss, hit, parse failure, readdir rejection, plus AC-5/AC-6 scenarios
    AC-3 Original MCP captures SEQUANT_RUN_ID and uses readRunLogById when available MET handleLine (run.ts:555-565) routes runId lines into capturedRunId before falling through to progress parsing. Line buffer flipped to always-on (run.ts:571) so capture works without a progressToken — directly resolves spec Open Question 1
    AC-4 Original Fallback to readLatestRunLog(runStartTime) when runId not captured MET (capturedRunId !== null ? readRunLogById(...) : null) ?? readLatestRunLog(...) (run.ts:602-605). Also handles lookup-miss case — behavior degrades to today's, not worse
    AC-5 Original Two concurrent sequant_run calls return their own logs MET should return the caller's own log when concurrent run logs coexist — both filenames pass the time filter, runIdB filename is lexicographically later (would win .sort().reverse()), runId lookup returns each caller's own log
    AC-6 Original Stale same-issue log inside 5-min window not returned for fresh run MET should not return a stale same-issue log when looked up by fresh runId — stale file lexicographically later, fresh runId lookup ignores it; mockedReadFile throws if stale path is read

    Coverage: 6/6 AC items fully met
    Original ACs: 6/6 met
    Derived ACs: None (spec had no Derived ACs)


    Quality Plan Verification

    Dimension Items Planned Items Addressed Status
    Backward compatibility 1 1 Complete (old CLI → null capturedRunId → fallback path; old MCP → ignores unknown stderr line)
    No new failure modes 1 1 Complete (readRunLogById returns null on miss/parse/IO; chained ?? preserves today's path)
    Test honesty 2 2 Complete (concurrent + stale tests use deterministic fixtures — controlled filename ordering and distinct runIds, not real spawns)

    Quality Plan Status: Complete


    CI Status

    Check State Bucket Impact
    typecheck SUCCESS pass MET
    build (20.x) SUCCESS pass MET
    build (22.x) SUCCESS pass MET
    validate-skills SUCCESS pass MET
    validate-plugin SUCCESS pass MET

    CI Summary: 5 passed, 0 pending, 0 failed


    Quality Metrics

    Metric Value Status
    Type issues (any) 9 OK (all are intentional as any on mocked readdir/readFile return values in tests, with eslint-disable markers)
    Deleted tests 0 OK
    Files changed 5 OK
    Lines added +295 -
    Lines deleted -11 -
    Commits behind main 0 OK

    Build Verification

    N/A — npm run build passed cleanly on the feature branch.


    Test Coverage Analysis

    Changed File Tier Has Tests? Test File
    src/lib/workflow/batch-executor.ts (new emitRunIdLine) Standard Yes src/mcp/tools/run.test.ts — emitRunIdLine (#631 AC-1) describe block
    src/lib/workflow/run-orchestrator.ts (2-line call-site) Standard Indirect Covered by existing __tests__/integration/run-orchestrator.integration.test.ts (19 passing) — no dedicated unit test for the 2-line addition
    src/mcp/tools/run.ts (parseRunIdLine, readRunLogById, always-on buffer, lookup branch) Standard Yes src/mcp/tools/run.test.ts — 13 new tests across 3 describe blocks

    Coverage: 3/3 changed source files have tests. run-orchestrator.ts 2-line call-site has only indirect integration coverage — acceptable for the surface area.


    Code Review

    Strengths:

    • Layer-correct: CLI emit lives where runId is generated; MCP capture/lookup lives where log resolution belongs. Mirrors the existing emitProgressLine ↔ parseProgressLine ↔ createLineBuffer triad with no new abstractions.
    • Conservative fallback chain: ?? readLatestRunLog(...) covers both "no runId captured" and "runId captured but lookup returned null" — strictly better than the AC-4 minimum.
    • UUID validation in parseRunIdLine (UUID_RE regex) rejects malformed payloads before they're cached as capturedRunId, preventing junk on stderr from poisoning the lookup.
    • Capture short-circuits via if (capturedRunId === null) so progress events still flow after the runId line; ordering test pins this contract.
    • Test honesty exactly as the spec demanded — AC-5 fixture intentionally orders runIdB lexicographically later (would win .sort().reverse()), and AC-6 fixture has mockedReadFile throw 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 to LogWriter.initialize() semantics.

    Issues:

    • None blocking.

    Suggestions:

    • The always-on stderrLineBuffer (was previously gated on hasProgressToken) is a behavior change beyond strict runId capture: every MCP sequant_run now line-buffers stderr unconditionally. Cost is negligible (one startsWith per line for non-progress clients), but worth flagging as the spec's Open Question 1 resolved in favor of always-on. The code comment at run.ts:567-569 documents this clearly.
    • hasProgressToken is still declared at run.ts:570 purely to gate onProgress for timeout-reset semantics. Reads naturally — no change needed.

    Test Quality Review

    Category Status Notes
    Behavior vs Implementation OK Tests assert on output of parseRunIdLine/readRunLogById, not internals. Concurrent-runs test asserts result.runId === runIdA, not implementation details
    Coverage Depth OK Happy path + 4 negative paths (parseRunIdLine rejects: non-RUN_ID lines, malformed UUID, empty payload, PROGRESS line). readRunLogById covers: miss, hit, parse failure, readdir rejection, concurrent, stale
    Mock Hygiene OK Only fs/promises mocked (external dependency). process.stderr.write spied via vi.spyOn. No internal modules mocked
    Test Reliability OK Deterministic — fixed UUIDs, controlled readdir ordering. No timing dependencies. originalEnv save/restore for SEQUANT_ORCHESTRATOR

    Issues Found: None.


    Anti-Pattern Detection

    Dependency Audit: N/A — no package.json changes.

    Code Patterns: No N+1 queries, empty catches, hardcoded secrets, or memory leaks introduced. The try { ... } catch { return null; } in readRunLogById is a deliberate AC-2 design choice (returns null on parse/IO error so the chained ?? readLatestRunLog fallback kicks in) — documented in the function JSDoc.

    Critical Issues: 0
    Warnings: 0


    Call-Site Review

    New exported functions detected: 3 (emitRunIdLine, readRunLogById, parseRunIdLine)

    Function Call Sites Loop? Conditions AC Match
    emitRunIdLine(runId) run-orchestrator.ts:459, plus tests No if (runId) (post-getRunId() null check); function-internal if (!process.env.SEQUANT_ORCHESTRATOR) return; Matches AC-1 — single call, ordering guaranteed by being immediately after logWriter.initialize and before any phase iteration
    readRunLogById(runId) run.ts:604, plus tests No Inside (capturedRunId !== null ? ... : null) ?? readLatestRunLog(...) ternary Matches AC-2/AC-3/AC-4 — single call-site with proper fallback chain
    parseRunIdLine(line) run.ts:557 (inside handleLine), plus tests No (lines arrive via buffer callbacks) Inside if (capturedRunId === null) guard — only parses until first capture Matches AC-3 — capture-once semantics enforced at the guard

    Findings: 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 in src/lib/workflow/ and src/mcp/tools/, all exercised by the test suite.


    Skill Command Verification

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


    CLI Registration Verification

    N/A — no RunOptions interface 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.ts and __tests__/integration/run-orchestrator.integration.test.ts (19/19 passing per exec evidence).


    CHANGELOG Verification

    Check Status
    CHANGELOG.md exists Found
    User-facing changes Yes (bug fix affecting MCP sequant_run callers)
    [Unreleased] entry Present under ### Fixed
    Entry format Valid (starts with bold marker, includes file:line context, references #631)

    Result: CHANGELOG requirements met.


    Self-Evaluation

    • Verified working: Yes — read all 5 changed files in full, traced runId through CLI emit → MCP capture → lookup. Tests cover the exact AC-5/AC-6 race scenarios that the bug report names, with adversarial fixtures (stale file lexicographically later than fresh; concurrent runIdB sorts after runIdA). Build green, 63/63 tests pass locally, 5/5 CI checks pass.
    • Test efficacy: High — AC-5 and AC-6 fixtures would FAIL on main (the bug they describe). Concurrent test asserts each caller gets its OWN log by runId. Stale test has mockedReadFile throw if the stale path is read, so a regression fails loudly.
    • Likely failure mode: Subprocess startup race where SEQUANT_RUN_ID line is somehow emitted after the first phase event — explicitly mitigated by AC-1's ordering test and by emit happening synchronously right after logWriter.initialize() before any phase loop. Secondary risk: LogWriter.initialize future change that makes getRunId() return null — the if (runId) guard at the call-site degrades to fallback path silently.
    • Verdict confidence: High. The change is narrow (5 files, +295/-11), the fallback chain is conservative (?? covers lookup-miss too), and the tests directly exercise the named race scenarios with fixtures designed to fail on the old readLatestRunLog-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 emitProgressLine triad), conservatively falls back to today's behavior on any lookup miss, and adds no new failure modes. CHANGELOG entry present.

    Documentation

    • CHANGELOG entry added under [Unreleased] > Fixed
    • N/A — README/docs unchanged (internal MCP↔CLI protocol; no user-facing CLI flag or behavior change beyond bug fix)

    Documentation: 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

    1. Merge PR 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).
    2. Cleanup worktree after merge: `echo y | bash scripts/cleanup-worktree.sh 631`.
  7. added
    ready-for-review
    on May 13, 2026
  8. added a commit that references this issue on May 13, 2026
  9. admarble commented on May 13, 2026

    @admarble
    ContributorAuthor

    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

    Gap Resolution
    1. AC-5/AC-6 verification methodology drift Extracted createRunIdCapture() factory. New tests drive the real createLineBuffer end-to-end (chunk-boundary reconstruction; two concurrent captures resolve to their own logs; stale same-issue log is rejected). mockedReadFile throws on the stale path so a regression would fail loudly.
    2. No test for readRunLogById → null → readLatestRunLog fallback Extracted resolveRunLog(capturedRunId, runStartTime). New unit tests cover all four branches: hit, miss-with-fallback, null-capturedRunId, both-null.
    3. Silent fallback masks readRunLogById parse failures resolveRunLog now emits [mcp:run] runId <id> lookup miss — falling back to readLatestRunLog on the MCP server's own stderr via console.error when a captured runId fails to resolve. Tests assert the message fires on miss and does NOT fire on hit / null-capturedRunId.
    4. hasProgressToken survives without buffer-gating Updated the inline comment to document its surviving purpose: it gates only the onProgress callback that controls spawnAsync's timeout-reset behavior.

    Test impact

    • src/mcp/tools/run.test.ts: 63 → 77 tests (14 new)
    • Full adjacent suite: npx vitest run src/mcp src/lib/workflow src/commands/run.test.ts → 1114/1114 pass
    • npm run build → clean
    • npm run lint → 0 warnings

    Verdict (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.

  10. added a commit that references this issue on May 13, 2026
  11. added 2 commits that reference this issue on Sep 9, 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

    bugplannedready-for-review

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions