Skip to content

feat(ready): sequant ready never records run metrics — no visibility into escalation, iteration counts, or gate outcomes #929

Closed

Description

@admarble

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/ or templates/skills/ (plugin freeze, I-1 of the graph doc).

  • Not proposing ready inherit run's exact MetricRun shape wholesale — a ready-gate pass isn't a run (no phases: MetricPhase[] in the same sense, no single RunOutcome that obviously maps from ReadyTerminalReason).

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

  1. Reuse MetricRun as-is. Map ReadyTerminalReason → RunOutcome (e.g. READY_FOR_MERGE/AC_MET → success, everything else → failure), treat the gate's qa/loop dispatches as phases, iterations as qaIterations in the metrics sub-object. Reuses the existing schema and sequant stats/dashboard code with zero changes there, at the cost of a slightly awkward outcome mapping.
  2. A parallel, ready-scoped metric record. A new schema entry (or a new top-level array) shaped around ReadyResult directly — policy, reason, iterations, autoFixed.length, remaining.length, effortEscalations, tokensUsed. Cleaner fit for the data, but needs its own sequant stats/dashboard support to be visible at all, and a second schema to maintain alongside MetricRun.

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 one MetricRun record with source: "ready" to .sequant/metrics.json, and a metrics write failure leaves the command's exit code unchanged. Evidence: a unit test on commands/ready.ts asserting MetricsWriter.recordRun is called with source: "ready" after runReadyGate() 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 effortEscalations in feat(loop): evidence-based effort escalation on quality-loop retries #915's shape. Evidence: the same unit test asserting those fields.
  • AC-3: sequant stats shows standalone ready runs separately from sequant run runs. 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 source field) read as source: "run". Evidence: a test that loads a legacy metrics file.
  • AC-5: sequant run --ready-gate metrics 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

  1. added 2 commits that reference this issue on Aug 10, 2026
  2. admarble commented on Sep 8, 2026

    @admarble
    ContributorAuthor

    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 branch dogfood/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 in docs/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.

  3. added
    graph-2026-10-freeze
    on Oct 9, 2026
  4. added a commit that references this issue on Oct 10, 2026
  5. admarble commented on Oct 10, 2026

    @admarble
    ContributorAuthor

    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 MetricRun with a source: "run" | "ready" discriminator. A record with no source reads as "run". Don't reopen the design sketch's option 2.

    • No full npm test in 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, with timeout, after a WIP commit. CI's required test check runs the full suite on the PR, and the runner waits for it before any merge.
    • Plugin freeze (graph doc I-1): the diff must not touch plugin/, .claude/skills/ or templates/skills/.
    • CHANGELOG.md [Unreleased]: add your line. Conflicts with sibling PRs are expected, and the runner resolves them.
    • Gate-test ACs need the mutation record in the PR body (CLAUDE.md, Testing). failedTest starts with the test file path.
  6. admarble commented on Oct 10, 2026

    @admarble
    ContributorAuthor

    Complexity: Standard (5 ACs, 3 directories)

    AC Quality Check

    AC Finding
    AC-1 Two claims in one line (record written; write failure leaves exit code unchanged). Evidence names two tests, so both must exist. Fails today: ready.ts never calls MetricsWriter.
    AC-2 "policy" has no field on MetricRun. Plan records it in flags (--policy=<p>), the same slot run uses for --chain etc. "terminal reason mapped to an outcome" maps to RunOutcome = success|partial|failed (the issue body's failure is not a member).
    AC-4 Vacuous as written. A legacy file already loads today. Tighten to: loading a file whose run has no source yields runs[0].source === "run". That fails on main and passes only once the field exists.
    AC-5 Passes on unchanged code by construction, so it gates nothing alone. Add a test that a run recorded without source (the run-orchestrator call shape) reads back source: "run". That fails today and pins the default.

    All five lines are single-line with Evidence:; ## Non-Goals is present.


    Scope Assessment

    Non-Goals: present (no plugin/, .claude/skills/, templates/skills/ edits; no wholesale MetricRun reshaping; metrics fail open; run --ready-gate path untouched).

    Metric Value Status
    Feature count 1 ✅
    AC items 5 ✅
    Directory spread 3 (src/commands, src/lib/workflow, docs/reference) ✅

    Verdict: ✅ SCOPE_OK


    Acceptance Criteria

    AC-1: sequant ready writes one source: "ready" record; write failure keeps exit code

    Verification: Unit Test (src/commands/ready.test.ts)
    Scenario: Given runReadyGate resolves → When readyCommand finishes → Then MetricsWriter.recordRun was called once with source: "ready". Given the writer throws → Then process.exitCode equals getReadyExitCode(result).
    Assumptions: ready.test.ts mocks metrics-writer.js; today it mocks nothing there.

    AC-2: Record carries policy, outcome, iterations, effortEscalations

    Verification: Unit Test (same file)
    Scenario: Given a ReadyResult with policy a-plus, ready: false, iterations: 2, one effort escalation → Then payload has flags containing --policy=a-plus, outcome: "failed", metrics.qaIterations: 2, effortEscalations equal to the result's.

    AC-3: sequant stats separates ready from run

    Verification: Unit Test (src/commands/stats.test.ts)
    Scenario: Given a metrics file with one run of each source → Then analytics (and --json) report bySource.run.total === 1 and bySource.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-gate recording unchanged

    Verification: 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)

    1. Add RunSourceSchema = z.enum(["run","ready"]) and source: RunSourceSchema.default("run") on MetricRunSchema. The zod default makes AC-4 hold at parse time with no migration and no version bump (additive, same convention as failureCategory).
    2. createMetricRun takes optional source and always emits it (default "run"). The output type MetricRun now requires source, so tsc will flag any hand-built MetricRun fixtures; fix those.
    3. MetricsWriter.recordRun has its own copy of the option bag. Add source there 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 in createMetricRun warns that field-by-field copies drop silently).

    Phase 2: Command (src/commands/ready.ts)

    1. Time runReadyGate with a wall clock. After it resolves and after the state-persist block, but before any report/JSON output, call a small exported recordReadyMetrics(result, config, durationSeconds) inside try/catch. On failure, warn via the same non-fatal warning helper run uses, and write it to stderr so --json stdout stays parseable. Never touch process.exitCode.
    2. Mapping: outcome = result.ready ? "success" : "failed" (no partial; ready already encodes AC_MET/READY_FOR_MERGE). phases = ["qa"] plus "loop" when iterations > 1. qaIterations = iterations, tokensUsed = result.tokensUsed, plus effortEscalations/modelEscalations from the result, phasePolicies from config, and flags = ["--policy=<policy>"]. issues = [issueNumber].

    Phase 3: Stats and docs

    1. stats.ts: add bySource counts (total/success/partial/failed) to MetricsAnalytics, a "By source" block in the display shown only when a ready record exists, and bySource in --json. Compute the existing headline aggregates over source === "run" records only, so zero-file/zero-line ready records do not drag avgFilesChanged; this must guard the empty-run-subset case (all-ready file).
    2. docs/reference/analytics.md and CHANGELOG.md [Unreleased] line.

    Design Review

    1. Where does this logic belong? Schema/writer own the discriminator; ready.ts owns the mapping from ReadyResult; stats.ts owns grouping. run-orchestrator.ts is 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).
    2. Simplest correct approach? One optional-with-default field plus one call site. Rejected: a ready-specific schema (D-3), a readyReason field (no consumer asks for it; add when one does).
    3. Existing pattern / re-patch count? Additive optional MetricRun fields: feat: detect rate-limit failures mid-chain and halt cleanly instead of timeout-cascading #761 failureCategory, feat(run): per-phase model and effort configuration for the claude-code driver #914 phasePolicies, feat(loop): evidence-based effort escalation on quality-loop retries #915 effortEscalations, feat(run): model escalation ladder on capability-bound non-convergence #971 modelEscalations, 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 phaseUsage. All extensions, none fixes of a prior field. Fewer than 2 prior fixes to this class, so proceed.
    4. Reviewer challenge? "Why not partial for MAX_ITERATIONS?" Because the owner-accepted mapping is binary and partial means some issues in a batch passed. "Why exclude ready from headline averages?" See step 6.
    5. Producers and consumers. Producers of MetricRun: run-orchestrator.recordMetrics and the new ready.ts call, both through MetricsWriter.recordRun to createMetricRun, a single record builder. Parity is covered by AC-5's default-pinning test. Consumers: stats.ts (loadMetrics, calculateMetricsAnalytics, insights, --json runs). No dashboard consumer exists in src/.

    Feature Quality Planning

    All standard checks pass. Notable items:

    • Gate tests (AC-1, AC-3, AC-4) need Mutation-verified: records in the PR body; failedTest starts with the file path.
    • An older sequant reading a newer file strips the unknown source key (zod default), so there is no forward-compat break.
    • ready writes .sequant/metrics.json relative to cwd, the same as run; no new path logic.

    Open Questions

    1. Record when runReadyGate throws (exit 2)? Recommendation: no. AC-1 says "after runReadyGate() resolves", and a throw has no ReadyResult to map. Impact if wrong: crashed gates stay invisible in stats.
    2. Exclude ready records 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)

  7. added
    planned
    on Oct 10, 2026
  8. admarble commented on Oct 10, 2026

    @admarble
    ContributorAuthor

    Test Stubs Generated

    AC Verification Happy Path Failure Paths
    AC-1 Unit Test 2 tests 2 error cases
    AC-2 Unit Test 3 tests covered by AC-1 failure stubs
    AC-3 Unit Test 2 tests 2 edge cases
    AC-4 Unit Test 2 tests 1 invalid-value case
    AC-5 Unit Test 2 tests (default-pinning) -

    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 test and fail until /exec fills them in. The existing #915 tests stay unmodified for AC-5.

    Notes for /exec


    Generated with Claude Code

  9. admarble commented on Oct 10, 2026

    @admarble
    ContributorAuthor

    QA Verdict: AC_MET_BUT_NOT_A_PLUS

    AC coverage: 5/5 met

    Gaps:

    • Comment is now false: modelEscalations are recorded to metrics by recordReadyMetrics
    • With --json --verbose a non-JSON line reaches stdout, contradicting the CHANGELOG claim that --json stdout is left alone
    • Mutation-verification records requested by the runner are missing from the PR body
  10. added a commit that references this issue on Oct 10, 2026
  11. added a commit that references this issue on Oct 10, 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

    graph-2026-10-freezeplanned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions