Skip to content

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

Closed

Description

@admarble

Epic: M1 Blocked by: #863 Tier: judgment Doc: docs/internal/graph-2026-09/PLAN.md §2 D-cost, §5 I-1/I-2/I-3, §7 D6/D14, §9 OQ-1 Graph node: 08

Motivation

metrics.tokensUsed is 0 in 365/365 recorded runs across 11 local projects (124/124 in this repo — every run since metrics began). sequant stats' token panel is therefore dead, and there is no per-phase or per-model spend view at all.

This matters now: top-tier model usage is exhausting the weekly plan quota; #914 gives per-phase model routing, #944 wants cheaper defaults, #971 wants an escalation ladder — and none of that can be evaluated or tuned without knowing what a phase actually costs. Cost visibility is the prerequisite for every cost-routing issue on the board.

Root cause — two independent defects; either alone yields 0

  1. Parser reads the wrong path. .claude/hooks/capture-tokens.sh:38-39 extracts [.[] | .usage // empty] from the transcript JSONL. Claude Code transcripts carry usage at .message.usage. Verified against a live transcript: 0 lines match .usage, 72 match .message.usage. Every token file the hook has ever written is all zeros — the 5 currently in .sequant/ all read input_tokens: 0, output_tokens: 0.
  2. Producer and consumer disagree on the directory. The hook writes .sequant/.token-usage-<sid>.json relative to the session cwd — for phase agents, the worktree. run-orchestrator.ts:1729 reads getTokenUsageForRun(undefined, true) → the main checkout's .sequant/. Worktree .sequant/ dirs contain no token files at all (so either SessionEnd never fires for SDK query() sessions, or the file dies with the worktree). ready-gate.ts:642 reads from worktreePath — the two producers already disagree, same drift class as fix(cli): bare parseInt on run --timeout lets a malformed value abort every phase instantly (sibling of #818) #833. Net effect: the only files the orchestrator ever sees come from the user's own interactive sessions in the main checkout — and those are zeros anyway (defect 1).

Meanwhile the SDK already hands the driver exact numbers and we throw them away: drivers/claude-code.ts:265 returns resultMessage.modelUsage — Record<modelId, { inputTokens, outputTokens, cacheReadInputTokens, cacheCreationInputTokens, costUSD, … }> — and #975 uses it only to pick resolvedModel (the first key).

Design

Non-Goals

Scope (graph plan 2026-09)

Acceptance criteria (graph plan 2026-09)

  • AC-1: aggregate from modelUsage — Verify: npx vitest run src/lib/workflow/phase-executor.test.ts src/lib/workflow/run-orchestrator.phase-policy.test.ts -t "986" → passes; the test feeds a recorded real result message fixture with two model entries and asserts metrics.tokensUsed/inputTokens/outputTokens/cacheTokens/costUSD equal the sums.
  • AC-1b (real run, runner-verified post-merge, D14): after the first sequant run on main that includes this fix — Verify: jq '[.. | objects | select(has("tokensUsed")) | .tokensUsed] | last' .sequant/metrics.json → > 0, pasted as a comment on 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 by the runner.
  • AC-2: metrics.phaseUsage[] rows { phase, model, inputTokens, outputTokens, cacheReadTokens, cacheCreationTokens, costUSD }, one per phase execution, quality-loop retries as separate rows — Verify: same -t "986" run, a case with two qa executions asserts two rows.
  • AC-3: hook parses .message.usage // .usage — Verify: bash templates/hooks/capture-tokens.sh against a fixture transcript with known totals writes matching numbers (test in src/lib/workflow/token-utils.test.ts -t "986 hook"); PR body carries Mutation-verified: AC-3 — reverted jq to .usage; <test> failed; restored.; md5 -q templates/hooks/capture-tokens.sh .claude/hooks/capture-tokens.sh hooks/capture-tokens.sh | uniq | wc -l → 1.
  • AC-4: one worktree-anchored helper for the fallback — Verify: grep -c 'getTokenUsageForRun(undefined' src/lib/workflow/run-orchestrator.ts → 0 (scoped gate test, mutation record in PR body), and ready-gate.ts's default readTokensUsed calls the same helper (grep -n '<helperName>' src/lib/workflow/ready-gate.ts src/lib/workflow/run-orchestrator.ts → both files).
  • AC-5: sequant stats phase × model table with cost, labeled SDK estimate, not a billing statement, shown by default (OQ-1) — Verify: npx vitest run src/commands/stats.test.ts -t "986" → snapshot passes against a fixture metrics.json.
  • AC-6: pre-fix records load and render — Verify: same stats test, a case loading a fixture copied verbatim from today's .sequant/metrics.json (no costUSD/phaseUsage) renders without throwing and shows 0/— for missing fields.
  • AC-7: I-1 — the config surface is untouched, so the fix(ready-gate): driver settings never reach the gate (RunReadyGateOptions lacks the fields) — silently runs claude-code for aider/opencode configs #863 (node 04) parity test still passes — Verify: npx vitest run src/lib/workflow/execution-config-parity.test.ts → passes.

Done when (graph plan 2026-09)

sequant stats prints non-zero tokens and an SDK-estimate cost per phase × model from the driver's modelUsage, with the hook path as a working fallback read from one worktree-anchored helper.

Original acceptance criteria (superseded by the graph-plan ACs above; kept for history)
  • AC-1: a sequant run on the claude-code driver records non-zero metrics.tokensUsed, inputTokens, outputTokens, cacheTokens, and costUSD sourced from the SDK modelUsage map; a unit test with a mocked result message asserts the aggregate equals the sum of the mocked per-model entries.
  • AC-2: metrics.phaseUsage records { phase, model, inputTokens, outputTokens, cacheReadTokens, cacheCreationTokens, costUSD } per phase execution, with quality-loop retries recorded as separate rows rather than merged.
  • AC-3: capture-tokens.sh sums .message.usage (falling back to .usage); a fixture transcript with known totals produces matching output; mutation-verified — revert the jq path and confirm exactly that test fails.
  • AC-4: run and ready read hook-fallback files through one shared helper anchored at the worktree; a grep gate asserts no getTokenUsageForRun(undefined call remains in run-orchestrator.ts.
  • AC-5: sequant stats renders a phase × model table with tokens and cost and labels cost as an SDK estimate; snapshot test against a fixture metrics.json.
  • AC-6: pre-fix metrics.json records (no costUSD / phaseUsage) still load and render — test loads a fixture copied from a current real record.

Human decisions required

  • Whether costUSD shows in stats by default or behind a --cost flag.

Context

#278 (original token-usage observability — closed; this is its regression), #975 (modelUsage → resolvedModel, the plumbing this reuses), #914 / #944 / #971 (consumers), #929 (ready metrics gap, adjacent), #833 (two-producer drift class).

Activity

  1. added
    bug
    graph-2026-09
    on Sep 6, 2026
  2. admarble commented on Sep 8, 2026

    @admarble
    ContributorAuthor

    Runner context — wave 2 launch (2026-09-08, main at ecea618). All wave-1 PRs are merged (#999 #1000 #1001 #1002 #1003 #1004 #1005) plus the plan PR #998 and #1006, so read the plan and your node file from main: docs/internal/graph-2026-09/PLAN.md (§5 invariants, §7 decisions D16–D22, §8 conventions) and docs/internal/graph-2026-09/issues/<NN>-*.md. Launch discipline learned in wave 1: the launcher kills any phase that is silent for 30 minutes and the shutdown cleanup deletes an uncommitted worktree — commit a WIP every ~10 minutes and before any long test run; run tests in the foreground only (never background npm test); prefer the node file's targeted -t commands over the full suite (the full suite takes ~6 min). A phase that reports "Out of credits" at ~30 min was a timeout, not a wallet problem. Consent mode is stop-at-PR: open the PR, do not merge.

    Node file: issues/08-986-tokens-cost-metrics.md. #863 (PR #1004) landed the single-producer ExecutionConfig and routed ready.ts through resolveRunOptions; the ready gate reads tokens through the injected readTokensUsed callback (node file §Why), so your helper replaces that callback's default. AC-1b is runner-verified after merge (D14) — do not try to satisfy it in the PR; every other AC's verify command must be executed literally and its output recorded in the PR body, with the gate-test mutation records in the Mutation-verified: format.

  3. admarble commented on Sep 8, 2026

    @admarble
    ContributorAuthor

    Plan — #986 tokens + cost metrics (/spec)

    Complexity: Standard (8 ACs after parsing, 4 directories)

    AC Quality Check

    lintAcceptanceCriteria → 8/8 pass, 0 flagged. Two parser notes that matter downstream:

    • AC-1b parses as AC-8. extractAcceptanceCriteria does not recognise the -1b suffix and remaps it to a trailing sequential ID. Any sequant state update ac call must use AC-8, not AC-1b. (AC-8 is runner-verified post-merge per D14 — not satisfiable in the PR.)
    • All 8 ACs resolve verificationMethod: "manual" because they use Verify: rather than a declared Evidence: clause. The #938 testgen detector therefore sees zero unit/integration ACs. In substance every AC is a vitest command — see Recommended Workflow for why testgen is still the right skip.

    Scope Assessment

    Non-Goals: found (3) — no cost-based routing (#944/#971), no billing reconciliation, observability only.

    Metric Value Status
    Feature count 3 ❌
    AC items 8 ⚠️
    Directory spread 4 ⚠️

    Verdict: ❌ SCOPE_SPLIT_RECOMMENDED — do not split. The red is a keyword-clustering artifact: the detector bucketed ACs into auth/ui/config from incidental words. This is one causal chain (driver → schema → orchestrator → stats) with a single Done-when. The verdict's real consequence is that it auto-enables the quality loop, which is appropriate here.


    Root cause — re-verified independently on today's main (ecea6182)

    Claim Evidence
    jq path is wrong Live transcript: jq -s '[.[]|.usage//empty]|length' → 0; .message.usage → 35
    every record is zero .sequant/metrics.json now 164 records, latest still "tokensUsed":0
    orchestrator reads main checkout run-orchestrator.ts:1815 getTokenUsageForRun(undefined, true) (baseline grep -c = 1, AC-4's gate)
    the gate reads elsewhere ready-gate.ts:350 defaultReadTokensUsed → path.join(worktreePath, TOKEN_USAGE_DIR)
    the SDK data is already there drivers/claude-code.ts:265 returns modelUsage; phase-executor.ts:1384 takes only Object.keys(...)[0]
    the channel already works end-to-end latest metrics record carries phasePolicies.qa.resolvedModel: "claude-opus-5" — #975 already proves PhaseResult → recordMetrics delivers driver-derived data. Tokens ride the same wire.

    Two corrections to the issue's scope list, both load-bearing:

    1. batch-executor.ts has no readTokensUsed wiring. grep -rn readTokensUsed src/ returns only ready-gate.ts (3 sites) and its two test files. No production caller injects the callback, so defaultReadTokensUsed is the only live path. Drop batch-executor.ts and src/commands/ready.ts from the touch list unless something else pulls them in.
    2. worktreeMap is already in scope at the metrics site. RunOrchestrator.recordMetrics(config, mergedOptions, results, worktreeMap, …) (:1760) already does worktreeMap.get(result.issueNumber) at :1797 for diff stats. AC-4's per-issue anchoring needs no new plumbing — it goes in that existing loop.

    Acceptance Criteria

    AC-1 — aggregate from modelUsage · Integration Test
    Given a recorded real result message with two model entries → When a phase executes and recordMetrics runs → Then metrics.tokensUsed/inputTokens/outputTokens/cacheTokens/costUSD equal the per-model sums.
    Assumption: costUSD is a float. RunMetricsSchema's existing token fields are all z.number().int() — costUSD must be z.number().nonnegative() without .int() or every real run fails schema validation at write time.

    AC-8 (issue's AC-1b) — real-run confirmation · Manual Test (post-merge, D14)
    Given main includes this fix → When the first sequant run completes → Then jq '[..|objects|select(has("tokensUsed"))|.tokensUsed]|last' .sequant/metrics.json > 0, pasted on #986 by the runner. Not attemptable in the PR.

    AC-2 — metrics.phaseUsage[] · Unit Test
    Given two qa executions in one issue's phaseResults → When flattened → Then two rows, not one merged row.
    Assumption: rows are emitted in phaseResults order with no keying by phase name — grouping is what would silently merge retries. ready-gate QA passes do not enter phaseResults, so they are out of scope here (#929).

    AC-3 — hook parses .message.usage // .usage · Integration Test + gate
    Given a fixture transcript with known totals → When capture-tokens.sh runs → Then the written JSON matches. Mutation record required. The mirror clause is blocked — see Open Question 1.

    AC-4 — one worktree-anchored fallback helper · Unit Test + scoped gate
    Given both readers → When either needs fallback tokens → Then both call the same helper; grep -c 'getTokenUsageForRun(undefined' src/lib/workflow/run-orchestrator.ts → 0.
    Assumption: the helper takes an explicit cleanup flag — see Design Review Q4, the two callers disagree about it.

    AC-5 — sequant stats phase × model table · Unit Test (snapshot)
    Given a fixture metrics.json with phaseUsage → When stats renders → Then a phase × model table with cost, labeled SDK estimate, not a billing statement, shown by default.

    AC-6 — pre-fix records render · Unit Test
    Given a fixture copied verbatim from a current .sequant/metrics.json record (no costUSD/phaseUsage) → When stats renders → Then no throw, 0/— for missing fields.
    Note: stats.ts:725 already gates the Token Usage panel on total*Tokens > 0, so the new table needs the same "absent ≠ zero" guard.

    AC-7 — config surface untouched · Unit Test
    npx vitest run src/lib/workflow/execution-config-parity.test.ts → passes. Nothing in this plan touches ExecutionConfig; this is a regression guard on #863.


    Implementation Plan

    Phase 1 — capture at the driver (AC-1, AC-2)

    1. drivers/agent-driver.ts:117-122 — replace modelUsage?: Record<string, unknown> with a typed Record<string, ModelUsageEntry> (inputTokens, outputTokens, cacheReadInputTokens, cacheCreationInputTokens, costUSD). Keep it optional — aider/subprocess don't populate it.
    2. phase-executor.ts:1381-1403 — beside the feat(config): model roles — semantic indirection between phase policy/ladders and concrete model strings #975 resolvedModel extraction, normalize the whole map into usage: PhaseUsage[] (one row per model key) and attach to PhaseResult on both the success and failure paths — a failed phase still burned tokens. Add usage?: PhaseUsage[] to PhaseResult in types.ts.
    3. Fixture: one recorded real SDK result message with two model entries.

    Phase 2 — schema + aggregation (AC-1, AC-2, AC-6, AC-7)
    4. metrics-schema.ts, append-only — PhaseUsageSchema, RunMetricsSchema.costUSD (non-int), RunMetricsSchema.phaseUsage (optional array, omit-when-empty per the phasePolicies/effortEscalations convention). Privacy contract holds: phase enums, model IDs, numbers — no paths, no content.
    5. Thread both fields through createMetricRun. Its metrics: block copies fields one by one; a field added to the schema but not to that copy is silently dropped and lands as undefined/0. This is the same shape as the bug being fixed.
    6. metrics-writer.ts:152 — widen the recordRun metrics param.
    7. run-orchestrator.ts recordMetrics (~:1793-1880) — inside the existing for (const result of results) loop, flatten result.phaseResults[].usage into phaseUsage rows and accumulate the totals. Precedence: driver usage wins whenever any row exists; the hook fallback is consulted only when the flattened set is empty.

    Phase 3 — one worktree-anchored helper (AC-4)
    8. token-utils.ts — add readWorktreeTokenUsage(worktreePath, { cleanup }), the single choke point (#833 pattern). It joins worktreePath with TOKEN_USAGE_DIR; no bare-relative default survives.
    9. ready-gate.ts:350 — defaultReadTokensUsed delegates with cleanup: false (it polls cumulatively across QA passes; cleanup mid-loop would zero its own budget check).
    10. run-orchestrator.ts:1815 — replace with the per-issue call using worktreeMap.get(result.issueNumber)?.path, cleanup: true. AC-4's grep goes to 0.
    11. Sibling site (do not skip): today's cleanup: true runs against the main checkout, so every sequant run deletes the token files written by the user's own interactive sessions there. Once reads move to the worktree, cleanup must move with them — otherwise the fix leaves a destructive orphan behind.

    Phase 4 — hook fallback (AC-3)
    12. capture-tokens.sh:38 — [.[] | .message.usage // .usage // empty], plus the dedupe in Open Question 2.
    13. Mirror/plugin placement — blocked on Open Question 1.

    Phase 5 — stats (AC-5, AC-6)
    14. calculateMetricsAnalytics (stats.ts:460) — roll phaseUsage up into a phase × model map with tokens + cost, tolerating records that lack the field.
    15. displayMetricsAnalytics (:657) — render beside the existing Token Usage panel at :731, default-on, with the SDK estimate, not a billing statement label.


    Design Review

    1. Where does this logic belong? Normalization at phase-executor (the only place holding a driver result and its phase identity); aggregation at run-orchestrator.recordMetrics (the only place holding all results plus worktreeMap); presentation entirely in stats.ts. token-utils.ts owns the fallback and becomes the only module that knows where token files live.
    2. Simplest correct approach? Ride the channel feat(config): model roles — semantic indirection between phase policy/ladders and concrete model strings #975 already proved: PhaseResult → recordMetrics. resolvedModel reaching today's records means the wire works — this adds a field to it. Rejected: a new metrics event stream (feat(cli): replace start/complete event journal with in-place phase-matrix #672-style); a phaseUsage map keyed by phase (cannot express AC-2's retry rows); repairing only the hook (the SDK numbers are strictly better and already in hand).
    3. What existing pattern does this follow? Additive optional schema fields, omitted-when-empty — exactly failureCategory (feat: detect rate-limit failures mid-chain and halt cleanly instead of timeout-cascading #761), phasePolicies (feat(run): per-phase model and effort configuration for the claude-code driver #914/feat(config): model roles — semantic indirection between phase policy/ladders and concrete model strings #975), effortEscalations (feat(loop): evidence-based effort escalation on quality-loop retries #915). Plus the fix(cli): bare parseInt on run --timeout lets a malformed value abort every phase instantly (sibling of #818) #833 single-choke-point rule for the two-producer split.
    4. What would a senior reviewer challenge? "Why does the shared helper need a cleanup flag — isn't that two behaviours in one function?" Because the two callers genuinely differ: the gate polls the same directory repeatedly inside its QA loop and must not delete; run reads once at the end and must. Sharing the path resolution is the point of AC-4; sharing the deletion policy would break the gate's budget accounting. The flag is the seam, and both call sites should carry a comment saying which side they're on.

    Open Questions

    1. AC-3's mirror clause is unsatisfiable as written, and contradicts a documented decision. capture-tokens.sh exists only in .claude/hooks/. templates/hooks/capture-tokens.sh and hooks/capture-tokens.sh do not exist — so bash templates/hooks/capture-tokens.sh cannot run and md5 -q … | uniq | wc -l cannot return 1. This is deliberate: scripts/sync-hooks.sh:8 says "Local-only files (e.g. capture-tokens.sh) are left untouched" and hook-sync.test.ts:11-13 says ".claude/hooks/ MAY contain extra files … e.g. capture-tokens.sh, which is sequant-specific and intentionally local." Separately, hooks/hooks.json registers only PreToolUse/PostToolUse — dropping a file into hooks/ without a SessionEnd entry ships a script nothing ever calls.
      Recommendation: promote it — templates/hooks/ becomes the source of truth, npm run sync-hooks regenerates .claude/hooks/, hooks/capture-tokens.sh plus a SessionEnd entry in hooks.json gives plugin users the fallback, and both "intentionally local" comments get updated. Otherwise the fallback path this issue is fixing only ever works in this repo. Impact if wrong: the alternative — descope AC-3 to .claude/hooks/ only — is one line of AC edit and no code, but leaves consumer projects with the broken-by-absence fallback forever. This is a scope expansion into the plugin's hook surface, so it needs your call before Phase 4 starts.

    2. The naive sum double-counts. On a live transcript: 35 lines carry .message.usage, all 35 have unique uuid, but only 13 unique message.id — the same assistant message is re-emitted (streaming/compaction). Summing every line over-reports ~2.7×, and "wrong by 2.7×" is worse than the honest 0 we have now, because it looks plausible. Recommendation: unique_by(.message.id) over usage-bearing lines before summing, and make the AC-3 fixture transcript contain a duplicated message so the dedupe is what the test locks — a fixture without one passes either way. Impact if wrong: feat(run): adopt cheaper per-phase model/effort defaults from #916 benchmark results — testgen, docs, assess candidates #944/feat(run): model escalation ladder on capability-bound non-convergence #971 tune cost routing against inflated fallback numbers.

    3. costUSD default-on is already decided. The issue lists "default vs --cost flag" as a human decision, but AC-5 resolves it (shown by default (OQ-1)). Proceeding default-on per AC-5. Flag now if that reading is wrong — it changes the AC-5 snapshot.

    4. Ready-gate QA passes produce no phaseUsage rows. They don't flow through phaseResults. Recommendation: leave it — ready metrics are feat(ready): sequant ready never records run metrics — no visibility into escalation, iteration counts, or gate outcomes #929, and the issue's Non-Goals say so explicitly. Noting it so /qa doesn't read the gap as a miss.


    Coordination Risk

    No in-flight conflicts today: the 862/916/919 worktrees are all zero commits ahead of origin/main. But node 12 (#862, opencode driver) also touches drivers/agent-driver.ts — this issue's typed modelUsage map and #862's second driver land in the same interface. Whichever merges second should expect a conflict there. Keeping the type change to a single additive ModelUsageEntry interface keeps that conflict trivial.


    Recommended Workflow

    Phases: exec → qa
    Quality Loop: enabled
    Reasoning: bug label, no UI, no browser test. testgen skipped: the #938 detector reads 0 declared-evidence and 0 inferred unit/integration ACs (all 8 use Verify:, not Evidence:), and independently all five target test files already exist — phase-executor.test.ts (2592 lines), run-orchestrator.phase-policy.test.ts, token-utils.test.ts, stats.test.ts, execution-config-parity.test.ts — so stub generation would only add untracked scaffolding into large existing suites. Quality loop is on because the scope verdict is red and because AC-3/AC-4 are gate tests needing mutation records.

    PR-body requirements (do not defer to /qa)

    • Every AC's Verify: command run literally, output pasted.
    • Mutation-verified: AC-3 — reverted jq to .usage; <test> failed; restored.
    • Mutation-verified: AC-4 — <mutation>; <test> failed; restored.
    • Commit before mutation-testing — git checkout <file> wipes uncommitted edits.
    • AC-8/AC-1b is runner-verified post-merge; do not claim it in the PR.

    Label Review

    Current: bug, graph-2026-09
    Recommended: add planned
    Reason: phase marker; no ui (no .tsx/.jsx in scope), no complex (8 ACs, one causal chain).
    Quality Loop: auto-enabled by SCOPE_SPLIT_RECOMMENDED.

  4. added
    planned
    on Sep 8, 2026
  5. admarble commented on Sep 8, 2026

    @admarble
    ContributorAuthor

    Runner context — exec was killed by the launcher's 30-minute no-progress ceiling at 05:02Z and the shutdown cleanup deleted the worktree. Your committed work is safe: branch feature/986-fix-metrics-tokensused-is-0-on-every-recorded-run- has 7 commits ahead of main (last: 358eb80b docs(#986): CHANGELOG entries for token/cost metrics fix) and is now pushed to origin, so the re-dispatch reuses it. Only the uncommitted tail is lost — the transcript's last step was the AC-4 gate mutation record (getTokenUsageForRun(undefined grep gate): re-run that mutation, record it in the PR body, then run every node-08 verify command and open the PR. The dead session's transcript is /Users/tony/.claude/projects/-Users-tony-Projects-worktrees-feature-986-fix-metrics-tokensused-is-0-on-every-recorded-run-/4ae9aa04-3afb-4095-b528-430152007844.jsonl; replay only what post-dates the last commit (jq -c 'select(.type=="assistant") | .message.content[]? | select(.type=="tool_use" and (.name=="Write" or .name=="Edit" or .name=="Bash")) | {name, input}'). Commit within the first 5 minutes and every ~10 minutes after; foreground targeted tests only; open the PR as soon as the ACs' verify commands pass — a phase silent for 30 minutes is killed again.

  6. added 2 commits that reference this issue on Sep 8, 2026
  7. admarble commented on Sep 8, 2026

    @admarble
    ContributorAuthor

    QA Verdict: AC_MET_BUT_NOT_A_PLUS

    AC coverage: 7/8 met

    Gaps:

    • Populating modelUsage on failure paths also changes feat(config): model roles — semantic indirection between phase policy/ladders and concrete model strings #975's resolvedModel behavior so it can now be sourced from a failed execution, with no test pinning it and no mention in the PR body
    • getTokenUsageForRun is a dead export whose only remaining references are its own tests and the AC-4 gate assertion
    • The plugin-wide SessionEnd registration makes the hook create a .sequant directory in every directory a plugin user ends a Claude Code session in, not just sequant projects
    • The hook fallback path's liveness under SDK sessions is untested and masked by the now-working primary modelUsage path

    Suggestions:

  8. admarble commented on Sep 8, 2026

    @admarble
    ContributorAuthor

    Runner verification — node 08 (PR #1010, QA verdict AC_MET_BUT_NOT_A_PLUS, iteration 2)

    Verify commands from issues/08-986-tokens-cost-metrics.md, run verbatim in the worktree at the QA'd 7b8cd82b, and the targeted set re-run at 43b1ac88 (merge of main incl. #935/#862):

    AC Command Result
    AC-1, AC-2 npx vitest run src/lib/workflow/phase-executor.test.ts src/lib/workflow/run-orchestrator.phase-policy.test.ts -t "986" 11 passed (recorded modelUsage fixture sums; two qa executions → two phaseUsage rows)
    AC-3 src/lib/workflow/token-utils.test.ts -t "986 hook"; md5 -q over the three capture-tokens.sh copies 3 passed; 1 distinct md5 (copies identical); hook reads .message.usage // .usage
    AC-4 grep -c 'getTokenUsageForRun(undefined' src/lib/workflow/run-orchestrator.ts 0; ready-gate.ts default readTokensUsed delegates to the shared helper
    AC-5, AC-6 src/commands/stats.test.ts -t "986" 5 passed (phase × model cost table labelled SDK estimate; pre-fix records render 0/—)
    AC-7 execution-config-parity.test.ts 9 passed (13 with the shutdown test after the merge)
    gate PR body mutation records 5 markers present
    AC-1b runner duty after merge (D14) pending — will be pasted here after the first sequant run on main that includes this fix

    Run history: first exec killed by the launcher's 30-minute ceiling (05:02Z), worktree deleted, 7 commits pushed and resumed; iteration-1 QA AC_NOT_MET, loop fixed it, iteration 2 AC_MET_BUT_NOT_A_PLUS. Sequant's post-run step then rebased the worktree onto main; the PR branch was instead synced by merging main (no conflict).

    Merging on the owner's standing instruction once CI is green.

  9. added a commit that references this issue on Sep 8, 2026
  10. admarble commented on Sep 8, 2026

    @admarble
    ContributorAuthor

    AC-1b — runner-verified post-merge (PLAN D14)

    First sequant run on main that includes this fix: the #993 re-dispatch (exec,qa with quality loop, 3 iterations, 06:17Z–06:52Z on 2026-09-08, dist rebuilt at 0f278b40).

    $ jq '[.. | objects | select(has("tokensUsed")) | .tokensUsed] | last' .sequant/metrics.json
    119693
    

    Same record: inputTokens: 316, outputTokens: 119377, costUSD: 26.0247… (SDK estimate), phaseUsage: 8 rows (exec ×3, qa ×3, loop ×2). The two records before it, from runs started under the pre-fix dist, still read tokensUsed: 0, which is the expected boundary.

    AC-1b met (> 0).

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

    buggraph-2026-09planned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions