Skip to content

feat(cli): cost per run where a user looks — one line in the run summary, cost in the run log and sequant logs, from the metrics record, labelled "SDK estimate" #1527

Closed

Description

@admarble

Epic: graph-2026-10-review-surface Tier: mechanical Execution: sequant_run Blocked by: #1523, #1504, #1507

Problem

"Cost per run: whose API key, rough tokens or dollars, and whether the separate review session doubles the bill" was the cold reader's blocking question. The product already knows: .sequant/metrics.json carries metrics.costUSD and tokensUsed per run (154 of 420 runs on this checkout, $935.69 in total; the last run $6.45 and 69,641 tokens for three issues), and sequant stats prints a phase × model table under "SDK estimate, not a billing statement". It is shown nowhere a user looks after a run. This node surfaces the same record in the run summary, the run log (optional cost) and sequant logs, with the same wording (I-7). A run with no metrics record says cost unrecorded, never $0.00.

Acceptance Criteria

  • AC-1: The summary prints the cost line from the metrics record. Evidence: npx vitest run src/lib/cli-ui/run-renderer.cost.test.ts → ≥ 3 passed, 0 failed (a run with costUSD: 6.45, tokensUsed: 69641 prints cost $6.45 (SDK estimate) · 69,641 tokens; a run with no record prints cost unrecorded; a run with tokens but no cost prints tokens and cost unrecorded)
  • AC-2: The run log carries cost as an optional run-level field (metrics are per run, not per issue) and the version is unchanged. Evidence: grep -cE 'cost: ' src/lib/workflow/run-log-schema.ts → ≥ 1 and grep -c 'version: z.literal(1)' src/lib/workflow/run-log-schema.ts → 1
  • AC-3: sequant logs <run> prints it. Evidence: npx vitest run src/commands/logs.cost.test.ts → ≥ 2 passed, 0 failed
  • AC-4: One source (I-2, RD-C). Evidence: grep -rlE 'total_cost_usd|costUSD' src/lib/cli-ui src/commands/logs.ts | wc -l | tr -d ' ' → 0 and grep -c 'cost' src/lib/cli-ui/run-renderer-types.ts → ≥ 1 (renderers take the number from the run-log or summary input; only the orchestrator's usage helper and metrics-writer.ts read the SDK's figure)
  • AC-5: The wording is the stats wording. Evidence: grep -c 'SDK estimate' src/lib/cli-ui/format.ts → ≥ 1 (a non-test file; the earlier glob counted test files)
  • AC-6: The docs say where the number comes from. Evidence: grep -c 'SDK estimate' docs/reference/run-command.md → ≥ 1

Prior fixes / producers

May touch

src/lib/workflow/log-writer.ts, run-log-schema.ts (optional cost, after #1504's block), src/lib/cli-ui/run-renderer-types.ts (optional cost on the summary input), the renderer implementations, src/commands/run-display.ts (where the summary input is assembled), the summary assembly in batch-executor.ts (toIssueSummary, after #1507, or the module #1507 extracts), src/commands/logs.ts, tests, docs/reference/run-command.md, CHANGELOG.

Non-Goals

  • Billing accuracy or a price table of our own (the SDK's estimate is the number).
  • Changing sequant stats.
  • Any new flag (I-4).
  • Any edit under plugin/, .claude/skills/, templates/skills/ (I-1).

Done when

A run ends with its cost on the terminal, and the same number is in its log and in sequant logs.

Activity

  1. added
    graph-2026-10-review-surface
    on Oct 19, 2026
  2. added a commit that references this issue on Oct 26, 2026
  3. admarble commented on Oct 26, 2026

    @admarble
    ContributorAuthor

    Complexity: Standard (6 ACs, 6 directories)

    AC Quality Check

    Run against the base branch (main @ 00bb5ac):

    • AC-4 is vacuous. Its grep … | wc -l already prints 0 today. It gates nothing. Tighten to a pair: the same grep → 0 AND grep -c 'cost' src/lib/cli-ui/run-renderer-types.ts → ≥ 1 (the renderer takes a number it did not read from the SDK).
    • AC-5 is satisfiable by a test file alone. The glob src/lib/cli-ui/*.ts includes *.test.ts. Exclude tests: grep -c 'SDK estimate' src/lib/cli-ui/run-renderer.ts → ≥ 1. Today it is 0, so it fails until the work is done.
    • AC-2 (cost: → 0 today) and AC-1/AC-3 (new test files) fail today, so they gate real work.
    • AC-1's wording: the issue text says the line carries "(SDK estimate)", while I-7 asks for "not a billing statement". Plan uses the AC-1 literal line plus the full stats wording on a muted trailing line (see Open Questions).

    Scope Assessment

    Non-Goals: present (no billing accuracy, no stats change, no new flag, nothing under plugin/, .claude/skills/, templates/skills/).

    Metric Value Status
    Feature count 1 ✅
    AC items 6 ✅
    Directory spread 6 ⚠️

    Verdict: ✅ SCOPE_OK

    Blockers: #1504 and #1507 are CLOSED; #1505 is CLOSED (so the logs.ts block no longer waits). #1523 is the tracker (kept open by design).


    Acceptance Criteria

    AC-1: Summary prints the cost line

    Verification: Unit Test (run-renderer.cost.test.ts, new)
    Scenario: Given costUSD 6.45, tokensUsed 69641 → When renderSummary runs → Then cost $6.45 (SDK estimate) · 69,641 tokens; no record → cost unrecorded; tokens only → tokens plus cost unrecorded.
    Assumptions: cost: 0 is not printed as $0.00; the writer already stores undefined for 0 (run-orchestrator.ts:2472).

    AC-2: Run log carries optional run-level cost, version unchanged

    Verification: Unit Test (schema parse of an old log without cost and a new one with it) + the two greps.
    Scenario: Given a v1 log with no cost → When parsed → Then valid; with cost: {...} → valid.

    AC-3: sequant logs <run> prints it

    Verification: Integration Test (logs.cost.test.ts, new, ≥ 2: with cost, without → cost unrecorded)

    AC-4: One source

    Verification: grep pair (tightened above)

    AC-5: Stats wording

    Verification: tightened grep above

    AC-6: Docs

    Verification: grep -c 'SDK estimate' docs/reference/run-command.md → ≥ 1. Today 0.


    Implementation Plan

    Key finding — ordering. In run-orchestrator.ts the run log is finalized (logWriter.finalize, ~L1796) BEFORE recordMetrics (~L1810) computes driverTotals (L2337). The cost does not exist yet when the log is written. The summary also has no access to it (RunResult carries no cost).

    Phase 1: Compute once, hand to all three surfaces

    1. Extract the usage-totals computation in recordMetrics (L2300–2360: phaseUsage, driverTotals, fallback) into a helper that returns { costUSD?, tokensUsed }. Call it once before logWriter.finalize; recordMetrics consumes the same value (one source, no second sum).
    2. LogWriter.finalize({ cost }) sets finalLog.cost (like suppressed, L387). Schema: optional cost: z.object({ usd: z.number().nonnegative().optional(), tokens: z.number().int().nonnegative().optional() }).optional() after the suppressed block; version: z.literal(1) untouched.
    3. Add cost to RunResult so the summary input can carry it.

    Phase 2: Render

    1. run-renderer-types.ts: optional cost on SummaryRenderInput. run-display.ts displaySummary passes result.cost to both the renderer and the renderRunSummary fallback. Implement the line in run-renderer.ts (all modes) via a shared formatter in format.ts, which holds the only "SDK estimate" string for the CLI-UI.
    2. logs.ts displayLogSummary (~L71–96): print the same formatter's output from log.cost; absent → cost unrecorded.

    Phase 3: Tests and docs

    1. run-renderer.cost.test.ts (3 cases), logs.cost.test.ts (2 cases), schema back-compat test. Update snapshots in cli-ui/__snapshots__ if a summary fixture gains the line.
    2. docs/reference/run-command.md: a "Cost" subsection naming .sequant/metrics.json / the SDK estimate. CHANGELOG entry.

    Mutation records (CLAUDE.md "Testing"): the gate tests for AC-1, AC-3 and AC-4/5 need Mutation-verified: AC-N — <mutation>; <test file path> failed; restored. lines in the PR body, e.g. delete the cost unrecorded branch and confirm the AC-1 test fails.


    Design Review

    1. Where does the logic belong? One formatter in cli-ui/format.ts; numbers computed once in the orchestrator and passed down. Renderers and logs.ts never read costUSD.
    2. Simplest correct approach? Compute totals once pre-finalize and pass them to log, summary, and metrics. Rejected: re-reading .sequant/metrics.json from logs/renderers (a second reader, and the latest record may not be this run's); rejected: adding a field per issue (cost is not attributable per issue).
    3. Existing pattern / re-patch count? The pattern is suppressed (feat(run): a dropped error leaves a trace — noteSuppressed() counts into the run log, batch-executor's 25 silent catches converted #1504), a run-level optional field written in finalize. Prior fixes on the cost record: 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/fix(#986): source token and cost metrics from the SDK modelUsage map #1010, feat(config): model roles — semantic indirection between phase policy/ladders and concrete model strings #975 (2 issues). The AC states the outcome (every surface shows the writer's number), and Phase 1 collapses the producers into one computation, so this is fixing the class, not another site.
    4. Reviewer challenge: "Why not read metrics.json in logs?" See 2. "Why does AC-4 say only the writers read the SDK figure?" The reading actually happens in the orchestrator's recordMetrics, not log-writer.ts; see Open Questions.
    5. Producers/consumers of the cost: producers: agent-driver.ts (costUSD), run-orchestrator.ts recordMetrics → metrics-writer.ts. Consumers today: stats.ts. New consumers: log-writer.ts (via finalize), run-display.ts/renderer, logs.ts. One computation, three consumers; a parity test asserts the log's cost.usd equals the metrics record's costUSD for the same fixture run.

    Feature Quality Planning

    All standard checks pass. Notable items:

    • Runs with a --quiet/non-TTY renderer and the dry-run path must not print a cost line (dry run has no cost).
    • Aborted runs (signal path calls finalize early): cost may be partial; label stays the same, absent if unknown.
    • Rate-limit halts: tokens may exist while cost is absent: covered by AC-1's third case.

    Open Questions

    1. I-7 wording vs AC-1 literal. AC-1 prints (SDK estimate); I-7 wants "not a billing statement" on every cost display. Recommendation: print the AC-1 line exactly and add a muted SDK estimate, not a billing statement footnote once under the summary and in logs. Impact: without it, I-7 is unmet; with it, AC-1 still passes.
    2. AC-4 parenthetical says log-writer.ts reads the SDK figure; in the plan it receives the number from the orchestrator. Recommendation: edit the AC text to "only the orchestrator's usage helper and metrics-writer.ts read the SDK's figure". Impact: if left, /qa may read it literally and flag AC_NOT_MET.
    3. Tighten AC-4 and AC-5 per the quality check. Recommendation: yes.

    Recommended Workflow

    Phases: exec → qa
    Quality Loop: disabled
    Reasoning: Mechanical, well-bounded; ACs declare unit/integration evidence, but the tests are the deliverable and written in exec, so testgen adds little. No UI/browser, no security surface. Tiering note: the tracker says sequant_run; do not background sequant run (bg-pty kill).


    Label Review

    Current: graph-2026-10-review-surface
    Recommended: + planned
    Quality Loop: Won't auto-enable (SCOPE_OK).

  4. added
    planned
    on Oct 26, 2026
  5. admarble commented on Oct 26, 2026

    @admarble
    ContributorAuthor

    QA Verdict: AC_MET_BUT_NOT_A_PLUS

    Gaps:

    • MCP sequant_logs does not show the run cost that sequant logs now prints
    • Misplaced JSDoc: the RunResult comment is stacked above the new RunUsage interface
    • The caveat line appears under cost unrecorded in the summary but not in sequant logs
    • Same-figure-in-log-and-metrics is verified only by reading the code
  6. added 2 commits that reference this issue on Oct 27, 2026
  7. admarble commented on Oct 27, 2026

    @admarble
    ContributorAuthor

    QA Verdict: AC_MET_BUT_NOT_A_PLUS

    AC coverage: 6/6 met

    Gaps:

    • An aborted default (parallel) run logs no cost for issues that finished, and the RunLogSchema cost JSDoc claims it covers them
    • Required CI test check had not reported when QA ran; re-run QA after it does
    • sequant_logs over MCP now carries cost, and its tool description names the estimate.
    • The RunResult JSDoc is back above RunResult.
    • The caveat line now appears only under a recorded cost, in both the summary and sequant logs.
    • A parity test asserts that the log's cost equals the metrics record's costUSD and tokensUsed (run-orchestrator.phase-policy.test.ts:552).
  8. added a commit that references this issue on Oct 27, 2026
  9. admarble commented on Oct 27, 2026

    @admarble
    ContributorAuthor

    QA Verdict: AC_MET_BUT_NOT_A_PLUS

    AC coverage: 6/6 met

    Gaps:

    • The parallel-path recording that feeds costSoFar (the c92b9ce fix for the QA-2 gap) has no regression test, and neither path's costSoFar is exercised on a real orchestrator
  10. added a commit that references this issue on Oct 27, 2026
  11. admarble commented on Oct 27, 2026

    @admarble
    ContributorAuthor

    QA Verdict: NEEDS_VERIFICATION

    AC coverage: 6/6 met

    Gaps:

    • A tokens-only cost prints the SDK-estimate caveat under a 'cost unrecorded' line — dropped: the caveat reasonably qualifies the token figure too and both surfaces agree

    Needs human review:

    • Required CI checks test and canary had not reported when QA ran; re-run QA after they complete
  12. admarble commented on Oct 27, 2026

    @admarble
    ContributorAuthor

    QA Verdict: READY_FOR_MERGE

    AC coverage: 6/6 met

  13. added a commit that references this issue on Oct 27, 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-review-surfaceplanned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions