You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In #372, sequant_run returns output.slice(-2000) — the raw tail of stdout. For multi-issue workflows, this may only capture the end of the last issue with no summary of earlier ones.
Goal
Return structured output from sequant_run so MCP clients get a useful summary regardless of output length.
Acceptance Criteria
sequant_run returns structured JSON with per-issue summaries
These types align with the existing RunLog / IssueLog / PhaseLog schemas in run-log-schema.ts — we reuse the same shape.
Phase 2: Parse structured data from run output
Add a log-file reader to the tool handler. Since --log-json is always passed, after spawnAsync completes:
Read the most recent log file from .sequant/logs/
Parse it with RunLogSchema.parse()
Extract per-issue summaries
Why read the log file instead of parsing stdout? The LogWriter already produces validated, structured JSON. Parsing stdout is fragile (mixed with human-readable output). The log file is the authoritative structured record.
Fallback: If log file is missing or unparseable (e.g., process crashed before finalizing), fall back to the current output.slice(-2000) behavior with issues: [].
Phase 3: Build and return structured response
Replace the current response construction (lines 89–119 in run.ts) with:
Map RunLog.issues → RunToolIssueSummary[]
Compute summary stats from RunLog.summary
Include rawOutput: result.stdout.slice(-2000) as secondary field
Enforce size limit: if total JSON > 64 KB, progressively truncate rawOutput
Size guard: JSON.stringify() the response, check .length, and shrink rawOutput if needed.
Phase 4: Tests
Unit tests in src/mcp/server.test.ts or a new src/mcp/tools/run.test.ts:
Mock spawnAsync to return known stdout
Mock log file reads to return known RunLog data
Verify structured response shape
Verify size limit enforcement
Verify fallback when no log file exists
Feature Quality Planning
Completeness Check
All AC items have corresponding implementation steps
Selected: Option A recommended — #389 is a small targeted fix.
Open Questions
MCP response size limit threshold
Recommendation: 64 KB (conservative; most MCP clients handle 100 KB+)
Impact: Too small → useful output truncated; too large → client buffering issues
Recommended Workflow
Phases: spec → testgen → exec → qa Quality Loop: disabled Reasoning: New feature with 4 AC items and Unit Test verification methods. testgen will create test stubs before implementation. Single-feature scope, no browser testing needed.
Label Review
Current: enhancement, multi-agent Recommended: enhancement, multi-agent, mcp Reason: All MCP server issues should share a label for filtering.
issues array with RunToolIssueSummary objects, summary aggregate stats. Verified in 16 unit tests + integration test.
AC-2
Original
Per-issue status/phases/verdict/duration
MET
Each issue has status, phases[] (with per-phase duration), conditional verdict (only when QA ran), durationSeconds. Test verifies verdict omission when no QA.
AC-3
Original
Raw output as secondary field
MET
rawOutput field with 2000-char tail truncation. Primary fields are structured issues/summary.
AC-4
Original
MCP response size limits
MET
64 KB limit enforced via enforceResponseSizeLimit() with progressive truncation (rawOutput first, then error). Test creates 100 KB input and verifies output ≤ 64 KB.
Derived ACs
AC-5
Derived (Error Handling)
Graceful fallback when log unavailable
MET
readLatestRunLog() returns null on missing dir, empty dir, or corrupt JSON. buildFallbackResponse() returns empty issues[] with raw output. 4 tests cover fallback paths.
AC-6
Derived (Best Practices)
Backwards-compatible status field
MET
Top-level `status: "success"
Coverage: 6/6 AC items fully met Original ACs: 4/4 met Derived ACs: 2/2 met
Quality Plan Verification
Quality Plan found: Yes (from spec comment)
Dimension
Items Planned
Items Addressed
Status
Completeness
4
4
✅ Complete
Error Handling
3
3
✅ Complete (missing log, corrupt log, process crash)
Code Quality
3
3
✅ Complete (types defined, reuses RunLog schema, named constants)
✅ Complete (no new deps, no user input in paths, backwards compat)
Polish
N/A
N/A
- (not UI feature)
Derived ACs: 2/2 addressed Quality Plan Status: Complete
CI Status
No CI checks configured for this repository.
CI-related AC items: None
Quality Metrics
Metric
Value
Status
Type issues (any)
2 (test-only as any for fs mock typing)
OK
Deleted tests
0
OK
Files changed
4
OK
Lines added
+589
OK
Lines deleted
-26
OK
Stale Branch Check
Check
Value
Commits behind main
4
Threshold
5
Status
⚠️ Warning
Feature branch is 4 commits behind main. Consider rebasing before merge.
Test Coverage Analysis
Changed File
Tier
Has Tests?
Test File
src/mcp/tools/run.ts
Standard
✅ Yes
src/mcp/tools/run.test.ts (16 tests)
src/mcp/server-extended.test.ts
-
Test file itself
-
CHANGELOG.md
Optional
N/A
-
Coverage: 1/1 changed source files have corresponding tests Critical paths without tests: None
Code Review
Strengths:
Clean separation: buildStructuredResponse, buildFallbackResponse, enforceResponseSizeLimit as focused functions
Reuses existing RunLogSchema and RunLog types — no type duplication
Progressive truncation strategy is well-designed (rawOutput → error → done)
Test coverage is thorough: 16 unit tests covering happy path, edge cases, size limits, and all fallback paths
Integration test updated to validate new response shape
CHANGELOG entry is well-structured with correct format
Issues:
Stale log risk (minor):readLatestRunLog() reads the most recent log file by filename sort but doesn't verify the log belongs to the run that just completed. If a previous run's log exists and the current run crashes before writing its log, stale data would be returned. Mitigation: The fallback path handles this gracefully (empty issues array), and in practice the most recent log should match since --log-json always writes. Consider correlating by timestamp window in a follow-up.
Suggestions (non-blocking):
Lines 282/291: overallStatus as "success" | "failure" is a redundant cast — the ternary already produces that type
enforceResponseSizeLimit mutates the response object directly. Consider returning a new object for purity, though this is minor since it's called at the end of construction
Verified working: Yes — build passes, all 1773 tests pass (including 16 new + updated integration tests)
Test efficacy: High — tests cover structured response shape, size limits, fallback paths, edge cases (0 issues, single issue, no QA verdict)
Likely failure mode: Stale log file from a previous run being read instead of the current run's log. Mitigated by fallback path returning empty issues, and in practice the most recent log should match.
Verdict confidence: High — all AC items verified literally against implementation and tests
Verdict: READY_FOR_MERGE
All 6 AC items (4 original + 2 derived) are fully met. Implementation is clean, well-tested, and follows existing patterns. The stale-log-risk is minor and non-blocking (graceful fallback exists). Branch is 4 commits behind main — recommend rebasing before merge.
Documentation
CHANGELOG entry added
N/A - No new user-facing CLI flags or config options requiring README update
issues array with RunToolIssueSummary objects, summary aggregate stats. 16 unit tests + integration test.
AC-2
Original
Per-issue status/phases/verdict/duration
MET
Each issue has status, phases[] (with per-phase duration), conditional verdict (only when QA ran), durationSeconds.
AC-3
Original
Raw output as secondary field
MET
rawOutput field with 2000-char tail truncation. Primary fields are structured issues/summary.
AC-4
Original
MCP response size limits (64KB)
MET
enforceResponseSizeLimit() with progressive truncation. Test verifies 100KB input → ≤64KB output.
Derived ACs
AC-5
Derived (Error Handling)
Graceful fallback when log unavailable
MET
readLatestRunLog() returns null on missing/empty/corrupt. buildFallbackResponse() returns empty issues with raw output.
AC-6
Derived (Best Practices)
Backwards-compatible status field
MET
Top-level `status: "success"
Coverage: 6/6 AC items fully met Original ACs: 4/4 met Derived ACs: 2/2 met
Quality Plan Verification
Quality Plan found: Yes
Dimension
Items Planned
Items Addressed
Status
Completeness
4
4
✅ Complete
Error Handling
3
3
✅ Complete
Code Quality
3
3
✅ Complete
Test Coverage
4
4
✅ Complete
Best Practices
3
3
✅ Complete
Polish
N/A
N/A
- (not UI)
Derived ACs: 2/2 addressed Quality Plan Status: Complete
CI Status
No CI checks configured for this repository.
Stale Branch Check
Check
Value
Commits behind main
5
Threshold
5
Status
⚠️ Warning
⚠️ MERGE RISK: Main now uses spawnAsync (commit 9aba881, #388) and resolveCliBinary (#389). This branch still uses spawnSync. Rebase will require adapting the structured output code to the async API — not a trivial merge.
Quality Metrics
Metric
Value
Status
Type issues (any)
2 (test-only as any for fs mock)
OK
Deleted tests
0
OK
Files changed
4
OK
Lines added
+589
OK
Lines deleted
-26
OK
Test Coverage Analysis
Changed File
Tier
Has Tests?
Test File
src/mcp/tools/run.ts
Standard
✅ Yes
src/mcp/tools/run.test.ts (16 tests)
src/mcp/server-extended.test.ts
-
Test file itself
-
CHANGELOG.md
Optional
N/A
-
Coverage: 1/1 changed source files have corresponding tests Critical paths without tests: None
Code Review
Strengths:
Clean separation of concerns: buildStructuredResponse, buildFallbackResponse, enforceResponseSizeLimit, readLatestRunLog as focused functions
Reuses existing RunLogSchema and RunLog types — no duplication
Progressive truncation strategy (rawOutput → error) is well-designed
Test coverage is thorough: happy path, edge cases (0/1/N issues), size limits, all fallback paths
Verdict conditionally included via ...(verdict ? { verdict } : {}) — verified absent when no QA phase
Issues:
Stale log risk (minor):readLatestRunLog() reads the most recent file by filename sort without verifying it belongs to the current run. If a previous run's log exists and the current run crashes before writing, stale data could be returned. Mitigated by the fallback path and in-practice --log-json always writing.
Redundant cast (cosmetic): Lines 282/291 — overallStatus as "success" | "failure" is unnecessary since the ternary already produces that type.
Mutation in enforceResponseSizeLimit (cosmetic): Mutates the response object in-place. Non-issue since called at end of construction.
Suggestions (non-blocking):
Remove redundant as "success" | "failure" casts
Consider correlating log file to current run by timestamp window in a follow-up
Test efficacy: High — tests cover structured shape, size limits, fallback paths, edge cases
Likely failure mode: Stale log file from previous run returned. Mitigated by fallback path.
Verdict confidence: High — all AC items verified literally against implementation and tests
Verdict: READY_FOR_MERGE
All 6 AC items (4 original + 2 derived) are fully met. Implementation is clean, well-tested, and follows existing patterns.
⚠️ IMPORTANT: Branch is 5 commits behind main. Main has replaced spawnSync with spawnAsync (#388) and added resolveCliBinary (#389). Rebase will require adapting the structured output code to the async spawn API — plan for non-trivial merge resolution.
Documentation
CHANGELOG entry added
N/A — No new CLI flags or config options
Next Steps
Rebase on main — adapt structured output to spawnAsync API (exitCode vs status, signal support)
Fallback behavior — what happens when the run log is unavailable
No separate doc file needed:
This feature enhances an existing MCP tool (sequant_run), not a new tool. The response format documentation was added inline to the existing docs/features/mcp-server.md under the sequant_run section.
Activity
admarble commentedon Mar 23, 2026
Spec Plan — #391: MCP server: improve sequant_run output structure
AC Quality Check
AC-N:identifiers). Renumbered below for tracking.→ Suggest: Define a concrete limit (e.g., total response ≤ 64 KB; truncate
rawOutputto fit)Summary: 3/4 AC items clear; 1 flagged for threshold clarification.
Scope Assessment
Non-Goals (Required)
sequant runCLI output formatsequant_logstool (it already has structured data)Scope Metrics
src/mcp/tools/,src/lib/workflow/)Scope Verdict
✅ SCOPE_OK — Single focused feature, modifying output format of one MCP tool.
Acceptance Criteria
AC-1:
sequant_runreturns structured JSON with per-issue summariesVerification Method: Unit Test + Integration Test
Test Scenario:
sequant_runcompletes a multi-issue run (mockedspawnAsync)issuesarray with one entry per issue processed, each containing summary fieldsIntegration Points:
spawnAsync,LogWriterJSON output,run-log-schema.tstypesAC-2: Each issue includes status, phases completed, verdict (if QA ran), duration
Verification Method: Unit Test
Test Scenario:
status,phases(array of {phase, status}),verdict(present only when QA ran),durationSecondsAC-3: Raw output still available but as a secondary field
Verification Method: Unit Test
Test Scenario:
rawOutputfield containing the tail of stdout (≤ 2000 chars), and the primary fields are the structured summaryAC-4: Total output respects MCP response size limits
Verification Method: Unit Test
Test Scenario:
rawOutputis truncated to fit; structured fields are preserved in fullAssumptions to Validate:
Implementation Plan
Phase 1: Define structured response types
Create response type in
src/mcp/tools/run.ts(or a shared types file):These types align with the existing
RunLog/IssueLog/PhaseLogschemas inrun-log-schema.ts— we reuse the same shape.Phase 2: Parse structured data from run output
Add a log-file reader to the tool handler. Since
--log-jsonis always passed, afterspawnAsynccompletes:.sequant/logs/RunLogSchema.parse()Why read the log file instead of parsing stdout? The LogWriter already produces validated, structured JSON. Parsing stdout is fragile (mixed with human-readable output). The log file is the authoritative structured record.
Fallback: If log file is missing or unparseable (e.g., process crashed before finalizing), fall back to the current
output.slice(-2000)behavior withissues: [].Phase 3: Build and return structured response
Replace the current response construction (lines 89–119 in
run.ts) with:RunLog.issues→RunToolIssueSummary[]RunLog.summaryrawOutput: result.stdout.slice(-2000)as secondary fieldrawOutputSize guard:
JSON.stringify()the response, check.length, and shrinkrawOutputif needed.Phase 4: Tests
src/mcp/server.test.tsor a newsrc/mcp/tools/run.test.ts:spawnAsyncto return known stdoutRunLogdataFeature Quality Planning
Completeness Check
spawnAsync(produces stdout),run-log-schema.ts(types)Error Handling
issues: []rawOutputtruncationCode Quality
sequant_logsalready reads log files)Test Coverage Plan
Best Practices
status/outputfieldsDerived ACs
statusfield for backwards compatibilityConflict Risk Analysis
In-flight work detected: Issue #389 (
feature/389-mcp-server-prevent-nested-npx-version-mismatch-in-)Overlapping files:
src/mcp/tools/run.ts— MCP server: prevent nested npx version mismatch in sequant_run #389 modifies command construction (addsresolveCliBinary())src/mcp/server-extended.test.tsRecommended approach:
Selected: Option A recommended — #389 is a small targeted fix.
Open Questions
Recommended Workflow
Phases: spec → testgen → exec → qa
Quality Loop: disabled
Reasoning: New feature with 4 AC items and Unit Test verification methods.
testgenwill create test stubs before implementation. Single-feature scope, no browser testing needed.Label Review
Current: enhancement, multi-agent
Recommended: enhancement, multi-agent, mcp
Reason: All MCP server issues should share a label for filtering.
→
gh issue edit 391 --add-label mcpVerification Methods Summary
feat(#391): return structured JSON from sequant_run MCP tool
admarble commentedon Mar 23, 2026
Exec Phase — Progress Update
AC Coverage
Key Files Changed
src/mcp/tools/run.tssrc/mcp/tools/run.test.tssrc/mcp/server-extended.test.tsCHANGELOG.mdQuality Results
npm run buildnpm run lintnpm testQuality Plan Alignment
Derived ACs: 2/2 addressed
PR
✅ Created: #407
admarble commentedon Mar 23, 2026
QA Review for Issue #391
AC Coverage
issuesarray withRunToolIssueSummaryobjects,summaryaggregate stats. Verified in 16 unit tests + integration test.status,phases[](with per-phase duration), conditionalverdict(only when QA ran),durationSeconds. Test verifies verdict omission when no QA.rawOutputfield with 2000-char tail truncation. Primary fields are structuredissues/summary.enforceResponseSizeLimit()with progressive truncation (rawOutput first, then error). Test creates 100 KB input and verifies output ≤ 64 KB.readLatestRunLog()returnsnullon missing dir, empty dir, or corrupt JSON.buildFallbackResponse()returns emptyissues[]with raw output. 4 tests cover fallback paths.Coverage: 6/6 AC items fully met
Original ACs: 4/4 met
Derived ACs: 2/2 met
Quality Plan Verification
Quality Plan found: Yes (from spec comment)
Derived ACs: 2/2 addressed
Quality Plan Status: Complete
CI Status
No CI checks configured for this repository.
CI-related AC items: None
Quality Metrics
any)as anyfor fs mock typing)Stale Branch Check
Feature branch is 4 commits behind main. Consider rebasing before merge.
Test Coverage Analysis
src/mcp/tools/run.tssrc/mcp/tools/run.test.ts(16 tests)src/mcp/server-extended.test.tsCHANGELOG.mdCoverage: 1/1 changed source files have corresponding tests
Critical paths without tests: None
Code Review
Strengths:
buildStructuredResponse,buildFallbackResponse,enforceResponseSizeLimitas focused functionsRunLogSchemaandRunLogtypes — no type duplicationIssues:
readLatestRunLog()reads the most recent log file by filename sort but doesn't verify the log belongs to the run that just completed. If a previous run's log exists and the current run crashes before writing its log, stale data would be returned. Mitigation: The fallback path handles this gracefully (empty issues array), and in practice the most recent log should match since--log-jsonalways writes. Consider correlating by timestamp window in a follow-up.Suggestions (non-blocking):
overallStatus as "success" | "failure"is a redundant cast — the ternary already produces that typeenforceResponseSizeLimitmutates the response object directly. Consider returning a new object for purity, though this is minor since it's called at the end of constructionTest Quality Review
fsmodule mocked (external dependency)Issues Found: None
Anti-Pattern Detection
Dependency Audit
N/A - No dependency changes
Code Patterns
run.ts:87Critical Issues: 0
Warnings: 0
Call-Site Review
New exported functions detected: 2
readLatestRunLog()run.ts:275buildStructuredResponse()run.ts:279if (runLog)guardFindings: All call sites match AC constraints correctly. Fallback path correctly uses
buildFallbackResponsewhenreadLatestRunLogreturns null.Execution Evidence
N/A - No scripts/ or CLI command changes
Skill Command Verification
N/A - No skill files changed
CLI Registration Verification
N/A - No option interface changes
CHANGELOG Verification
Result: CHANGELOG requirements met
Self-Evaluation
Verdict: READY_FOR_MERGE
All 6 AC items (4 original + 2 derived) are fully met. Implementation is clean, well-tested, and follows existing patterns. The stale-log-risk is minor and non-blocking (graceful fallback exists). Branch is 4 commits behind main — recommend rebasing before merge.
Documentation
Next Steps
QA completed: 6/6 AC items met
admarble commentedon Mar 24, 2026
QA Review for Issue #391 (Re-run)
AC Coverage
issuesarray withRunToolIssueSummaryobjects,summaryaggregate stats. 16 unit tests + integration test.status,phases[](with per-phase duration), conditionalverdict(only when QA ran),durationSeconds.rawOutputfield with 2000-char tail truncation. Primary fields are structuredissues/summary.enforceResponseSizeLimit()with progressive truncation. Test verifies 100KB input → ≤64KB output.readLatestRunLog()returns null on missing/empty/corrupt.buildFallbackResponse()returns empty issues with raw output.Coverage: 6/6 AC items fully met
Original ACs: 4/4 met
Derived ACs: 2/2 met
Quality Plan Verification
Quality Plan found: Yes
Derived ACs: 2/2 addressed
Quality Plan Status: Complete
CI Status
No CI checks configured for this repository.
Stale Branch Check
spawnAsync(commit 9aba881, #388) andresolveCliBinary(#389). This branch still usesspawnSync. Rebase will require adapting the structured output code to the async API — not a trivial merge.Quality Metrics
any)as anyfor fs mock)Test Coverage Analysis
src/mcp/tools/run.tssrc/mcp/tools/run.test.ts(16 tests)src/mcp/server-extended.test.tsCHANGELOG.mdCoverage: 1/1 changed source files have corresponding tests
Critical paths without tests: None
Code Review
Strengths:
buildStructuredResponse,buildFallbackResponse,enforceResponseSizeLimit,readLatestRunLogas focused functionsRunLogSchemaandRunLogtypes — no duplication...(verdict ? { verdict } : {})— verified absent when no QA phaseIssues:
readLatestRunLog()reads the most recent file by filename sort without verifying it belongs to the current run. If a previous run's log exists and the current run crashes before writing, stale data could be returned. Mitigated by the fallback path and in-practice--log-jsonalways writing.overallStatus as "success" | "failure"is unnecessary since the ternary already produces that type.Suggestions (non-blocking):
as "success" | "failure"castsTest Quality Review
fsmodule mockedAnti-Pattern Detection
Dependency Audit
N/A — No dependency changes
Code Patterns
run.ts:87Critical Issues: 0
Warnings: 0
Call-Site Review
New exported functions detected: 2
readLatestRunLog()run.ts:275buildStructuredResponse()run.ts:279if (runLog)guardExecution Evidence
N/A — No scripts/ or CLI command changes
Skill Command Verification
N/A — No skill files changed
CLI Registration Verification
N/A — No option interface changes
CHANGELOG Verification
Result: CHANGELOG requirements met
Self-Evaluation
Verdict: READY_FOR_MERGE
All 6 AC items (4 original + 2 derived) are fully met. Implementation is clean, well-tested, and follows existing patterns.
spawnSyncwithspawnAsync(#388) and addedresolveCliBinary(#389). Rebase will require adapting the structured output code to the async spawn API — plan for non-trivial merge resolution.Documentation
Next Steps
spawnAsyncAPI (exitCode vs status, signal support)QA completed: 6/6 AC items met
fix(#391): merge main and resolve async spawn + structured output con…
fix(#391): resolve remaining minor gaps in structured output
fix(#391): revert over-engineered changes, keep docs
Merge pull request #407 from sequant-io/feature/391-mcp-server-improv…
docs(#391): update mcp-server.md provenance line
admarble commentedon Mar 24, 2026
Documentation Complete
File:
docs/features/mcp-server.md(updated, not new — documentation lives with the existing MCP server docs)What was documented:
The
sequant_runresponse format was added to the Tools Reference section:status,exitCode,issues,summary,phases,rawOutput,errorissueNumber,status,phases,verdict,durationSecondsNo separate doc file needed:
This feature enhances an existing MCP tool (
sequant_run), not a new tool. The response format documentation was added inline to the existingdocs/features/mcp-server.mdunder thesequant_runsection.Documentation complete.
fix(#394): merge main and resolve conflicts with #389 and #391