Repository navigation
Description
Epic: graph-2026-10-freeze Tier: mechanical Execution: sequant_run
Motivation
sequant run (including sequant run --ready-gate) records every run to .sequant/metrics.json via RunOrchestrator.recordMetrics → MetricsWriter.recordRun. Standalone sequant ready <issue> never has — this predates #915 and is not specific to it, but #915 surfaced it concretely: sequant ready --escalate-effort --verbose prints effort: <base> → <escalated> (<phase> retry) to stdout, but that escalation is never recorded anywhere durable. The same gap applies to ready's other outcomes — iterations, finalVerdict, tokensUsed, autoFixed — all computed and returned by runReadyGate as a ReadyResult, all currently discarded once the CLI prints its report.
Practically: anyone using sequant stats or the dashboard to understand run behavior sees a complete picture for sequant run and a blind spot for standalone sequant ready. If --ready-gate usage and standalone ready usage diverge over time (e.g. teams that always gate manually rather than inline), that blind spot grows.
Non-Goals
-
Any edit under
plugin/,.claude/skills/ortemplates/skills/(plugin freeze, I-1 of the graph doc). -
Not proposing
readyinheritrun's exactMetricRunshape wholesale — a ready-gate pass isn't arun(nophases: MetricPhase[]in the same sense, no singleRunOutcomethat obviously maps fromReadyTerminalReason). -
Not proposing metrics become mandatory/blocking — should fail open like
run's own metrics recording does (best-effort, never fails the command). -
Not touching
run --ready-gate's existing recording path — that already works today (IssueResult.readyGate.effortEscalations→RunOrchestrator.recordMetrics→MetricsWriter.recordRun, added in feat(loop): evidence-based effort escalation on quality-loop retries #915).
Design sketch (needs a decision, not prescribed here)
Two shapes worth weighing:
- Reuse
MetricRunas-is. MapReadyTerminalReason→RunOutcome(e.g.READY_FOR_MERGE/AC_MET→success, everything else →failure), treat the gate'sqa/loopdispatches asphases,iterationsasqaIterationsin the metrics sub-object. Reuses the existing schema andsequant stats/dashboard code with zero changes there, at the cost of a slightly awkward outcome mapping. - A parallel, ready-scoped metric record. A new schema entry (or a new top-level array) shaped around
ReadyResultdirectly —policy,reason,iterations,autoFixed.length,remaining.length,effortEscalations,tokensUsed. Cleaner fit for the data, but needs its ownsequant stats/dashboard support to be visible at all, and a second schema to maintain alongsideMetricRun.
Whichever shape is chosen, wire it in commands/ready.ts right after runReadyGate() returns (same place the new --verbose escalation print already lives, added in #915), reusing the existing MetricsWriter — no new writer/storage layer needed.
Acceptance Criteria
Decision (graph doc D-3, accepted by the owner on 2026-10-09): reuse MetricRun with a source: "run" | "ready" discriminator.
- AC-1: A standalone
sequant ready <issue>run writes oneMetricRunrecord withsource: "ready"to.sequant/metrics.json, and a metrics write failure leaves the command's exit code unchanged. Evidence: a unit test oncommands/ready.tsassertingMetricsWriter.recordRunis called withsource: "ready"afterrunReadyGate()resolves, and a test where the writer throws and the exit code is unchanged. - AC-2: The record carries policy, terminal reason mapped to an outcome, iteration count and
effortEscalationsin feat(loop): evidence-based effort escalation on quality-loop retries #915's shape. Evidence: the same unit test asserting those fields. - AC-3:
sequant statsshows standalonereadyruns separately fromsequant runruns. Evidence: a test on the stats aggregation with one record of each source, asserting two separate counts. - AC-4: Records written before this change (no
sourcefield) read assource: "run". Evidence: a test that loads a legacy metrics file. - AC-5:
sequant run --ready-gatemetrics recording is unchanged. Evidence: the existing feat(loop): evidence-based effort escalation on quality-loop retries #915 tests pass unmodified.
Context
Surfaced during QA/adversarial review of #915 (evidence-based effort escalation on quality-loop retries) — see that issue's QA comments for the full investigation. Not blocking #915's merge; disclosed there as a pre-existing, out-of-scope gap.
May touch
src/commands/ready.ts, the metrics schema and writer, src/commands/stats.ts, their tests.
Activity
fix(#915): verify SDK default effort against installed types; add end…
feat(#915): evidence-based effort escalation on quality-loop retries (#…
admarble commentedon Sep 8, 2026
Runner context — opencode dogfood sample (graph-2026-09 node 16, #997). This issue is being run spec→exec→qa twice as a sample for the opencode promotion gate: once with
--agent opencode(base branchdogfood/opencode-2026-09, which carries the generated.opencode/wrappers and hook shim), then once with the default claude-code driver. The resulting PRs are samples and will not be merged; the owner reads them for defects and the runner records verdict, skill-marker presence, fan-out, cost and wall time indocs/investigations/multi-backend-2026-07.md("Dogfood 2026-09"). Work the issue exactly as you would for real — same ACs, same PR body discipline, mutation records for gate tests — but do not file any issue and do not merge. Commit a WIP within 5 minutes and every ~10 minutes; targeted tests in the foreground only; a phase silent for 30 minutes is killed. Cost cap for the opencode arm across all three sample issues: $30.docs(#1390): graph-2026-10-freeze founding doc, issue graph and as-fi…
admarble commentedon Oct 10, 2026
Runner context for the phase agents (graph-2026-10-freeze, wave 2). This applies to spec, exec and qa by name.
The shape is decided (graph doc D-3, owner-accepted 2026-10-09, repeated in the AC block): reuse
MetricRunwith asource: "run" | "ready"discriminator. A record with nosourcereads as"run". Don't reopen the design sketch's option 2.npm testin exec or qa. Up to three phases run in parallel in this wave, and a full-suite run (10–13 min) under that load crosses the 30-minute phase wall and kills the phase. Run the test files you touch or add plus the stack's affected-tests command, in the foreground, withtimeout, after a WIP commit. CI's requiredtestcheck runs the full suite on the PR, and the runner waits for it before any merge.plugin/,.claude/skills/ortemplates/skills/.CHANGELOG.md[Unreleased]: add your line. Conflicts with sibling PRs are expected, and the runner resolves them.failedTeststarts with the test file path.admarble commentedon Oct 10, 2026
Complexity: Standard (5 ACs, 3 directories)
AC Quality Check
ready.tsnever callsMetricsWriter.MetricRun. Plan records it inflags(--policy=<p>), the same slotrunuses for--chainetc. "terminal reason mapped to an outcome" maps toRunOutcome=success|partial|failed(the issue body'sfailureis not a member).sourceyieldsruns[0].source === "run". That fails onmainand passes only once the field exists.source(therun-orchestratorcall shape) reads backsource: "run". That fails today and pins the default.All five lines are single-line with
Evidence:;## Non-Goalsis present.Scope Assessment
Non-Goals: present (no
plugin/,.claude/skills/,templates/skills/edits; no wholesaleMetricRunreshaping; metrics fail open;run --ready-gatepath untouched).src/commands,src/lib/workflow,docs/reference)Verdict: ✅ SCOPE_OK
Acceptance Criteria
AC-1:
sequant readywrites onesource: "ready"record; write failure keeps exit codeVerification: Unit Test (
src/commands/ready.test.ts)Scenario: Given
runReadyGateresolves → WhenreadyCommandfinishes → ThenMetricsWriter.recordRunwas called once withsource: "ready". Given the writer throws → Thenprocess.exitCodeequalsgetReadyExitCode(result).Assumptions:
ready.test.tsmocksmetrics-writer.js; today it mocks nothing there.AC-2: Record carries policy, outcome, iterations,
effortEscalationsVerification: Unit Test (same file)
Scenario: Given a
ReadyResultwith policya-plus,ready: false,iterations: 2, one effort escalation → Then payload hasflagscontaining--policy=a-plus,outcome: "failed",metrics.qaIterations: 2,effortEscalationsequal to the result's.AC-3:
sequant statsseparatesreadyfromrunVerification: Unit Test (
src/commands/stats.test.ts)Scenario: Given a metrics file with one run of each source → Then analytics (and
--json) reportbySource.run.total === 1andbySource.ready.total === 1.AC-4: Legacy records read as
source: "run"Verification: Unit Test (
metrics-schema.test.ts, tightened Evidence above)AC-5:
run --ready-gaterecording unchangedVerification: Unit Test (existing #915 tests, unmodified, plus the default-pinning test above)
Implementation Plan
Phase 1: Schema (
src/lib/workflow/metrics-schema.ts,metrics-writer.ts)RunSourceSchema = z.enum(["run","ready"])andsource: RunSourceSchema.default("run")onMetricRunSchema. The zod default makes AC-4 hold at parse time with no migration and noversionbump (additive, same convention asfailureCategory).createMetricRuntakes optionalsourceand always emits it (default"run"). The output typeMetricRunnow requiressource, sotscwill flag any hand-builtMetricRunfixtures; fix those.MetricsWriter.recordRunhas its own copy of the option bag. Addsourcethere too (the fix(metrics): tokensUsed is 0 on every recorded run — capture-tokens.sh reads .usage (transcripts carry .message.usage) and run reads the wrong dir; wire SDK modelUsage tokens+costUSD per phase × model into metrics and stats #986 note increateMetricRunwarns that field-by-field copies drop silently).Phase 2: Command (
src/commands/ready.ts)runReadyGatewith a wall clock. After it resolves and after the state-persist block, but before any report/JSON output, call a small exportedrecordReadyMetrics(result, config, durationSeconds)insidetry/catch. On failure, warn via the same non-fatal warning helperrunuses, and write it to stderr so--jsonstdout stays parseable. Never touchprocess.exitCode.outcome = result.ready ? "success" : "failed"(nopartial;readyalready encodesAC_MET/READY_FOR_MERGE).phases = ["qa"]plus"loop"wheniterations > 1.qaIterations = iterations,tokensUsed = result.tokensUsed, pluseffortEscalations/modelEscalationsfrom the result,phasePoliciesfromconfig, andflags = ["--policy=<policy>"].issues = [issueNumber].Phase 3: Stats and docs
stats.ts: addbySourcecounts (total/success/partial/failed) toMetricsAnalytics, a "By source" block in the display shown only when areadyrecord exists, andbySourcein--json. Compute the existing headline aggregates oversource === "run"records only, so zero-file/zero-line ready records do not dragavgFilesChanged; this must guard the empty-run-subset case (all-ready file).docs/reference/analytics.mdandCHANGELOG.md[Unreleased]line.Design Review
ready.tsowns the mapping fromReadyResult;stats.tsowns grouping.run-orchestrator.tsis deliberately not edited (it relies on the default; feat(worktree): configurable worktree root #1199 and fix(run): a watchdog-killed run writes no run log and half-deletes a clean worktree — worktree removal outruns the 5 s SIGKILL grace #1222 are editing it in flight).readyReasonfield (no consumer asks for it; add when one does).MetricRunfields: feat: detect rate-limit failures mid-chain and halt cleanly instead of timeout-cascading #761failureCategory, feat(run): per-phase model and effort configuration for the claude-code driver #914phasePolicies, feat(loop): evidence-based effort escalation on quality-loop retries #915effortEscalations, feat(run): model escalation ladder on capability-bound non-convergence #971modelEscalations, fix(metrics): tokensUsed is 0 on every recorded run — capture-tokens.sh reads .usage (transcripts carry .message.usage) and run reads the wrong dir; wire SDK modelUsage tokens+costUSD per phase × model into metrics and stats #986phaseUsage. All extensions, none fixes of a prior field. Fewer than 2 prior fixes to this class, so proceed.partialfor MAX_ITERATIONS?" Because the owner-accepted mapping is binary andpartialmeans some issues in a batch passed. "Why exclude ready from headline averages?" See step 6.MetricRun:run-orchestrator.recordMetricsand the newready.tscall, both throughMetricsWriter.recordRuntocreateMetricRun, a single record builder. Parity is covered by AC-5's default-pinning test. Consumers:stats.ts(loadMetrics,calculateMetricsAnalytics, insights,--jsonruns). No dashboard consumer exists insrc/.Feature Quality Planning
All standard checks pass. Notable items:
Mutation-verified:records in the PR body;failedTeststarts with the file path.sequantreading a newer file strips the unknownsourcekey (zod default), so there is no forward-compat break.readywrites.sequant/metrics.jsonrelative to cwd, the same asrun; no new path logic.Open Questions
runReadyGatethrows (exit 2)? Recommendation: no. AC-1 says "afterrunReadyGate()resolves", and a throw has noReadyResultto map. Impact if wrong: crashed gates stay invisible in stats.readyrecords from headline averages? Recommendation: yes (step 6). Impact if wrong: ready runs dilute file/line averages, but nothing breaks.Recommended Workflow
Phases: testgen → exec → qa
Quality Loop: disabled
Reasoning: AC-1..AC-4 declare unit-test evidence, so testgen stubs them first. No UI, no security surface. Per runner context, exec and qa run touched test files only, not the full suite.
Label Review
Current: graph-2026-10-freeze
Recommended: graph-2026-10-freeze, planned
Reason: planning complete
Quality Loop: won't auto-enable (scope OK)
admarble commentedon Oct 10, 2026
Test Stubs Generated
Files
src/commands/ready.metrics.test.ts(AC-1, AC-2)src/commands/stats-source.test.ts(AC-3)src/lib/workflow/metrics-schema.source.test.ts(AC-4, AC-5 default pin)All 16 stubs throw
Test stub - implement this testand fail until /exec fills them in. The existing #915 tests stay unmodified for AC-5.Notes for /exec
sequant ready— wire live phase-matrix renderer (parity withsequant run) #697" block inready.test.tsand add ametrics-writer.jsmock.serveMetrics()pattern from the fix(metrics): tokensUsed is 0 on every recorded run — capture-tokens.sh reads .usage (transcripts carry .message.usage) and run reads the wrong dir; wire SDK modelUsage tokens+costUSD per phase × model into metrics and stats #986 block ofstats.test.ts.Mutation-verified:records in the PR body, withfailedTeststarting with the file path.Generated with Claude Code
admarble commentedon Oct 10, 2026
QA Verdict: AC_MET_BUT_NOT_A_PLUS
AC coverage: 5/5 met
Gaps:
fix(#929): ready --json --verbose keeps stdout to the JSON payload; c…
feat(#929): sequant ready records run metrics with a source discrimin…