Skip to content

fix(#986): source token and cost metrics from the SDK modelUsage map - #1010

Merged
admarble merged 10 commits into
mainfrom
feature/986-fix-metrics-tokensused-is-0-on-every-recorded-run-
Sep 8, 2026
Merged

admarble merged 10 commits into
mainfrom
feature/986-fix-metrics-tokensused-is-0-on-every-recorded-run-

Conversation

@admarble

@admarble admarble commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Summary

metrics.tokensUsed was 0 in 365/365 recorded runs because of two independent defects, either of which alone yields 0:

  1. The hook parsed the wrong path. capture-tokens.sh read .usage from the transcript JSONL; Claude Code carries usage at .message.usage. Every token file the hook ever wrote was all zeros.
  2. Producer and consumer disagreed on the directory. The hook writes into the session's cwd (the worktree); recordMetrics read getTokenUsageForRun(undefined, true) — the main checkout's .sequant/ — and deleted the user's own interactive-session files there while it was at it.

The fix makes the SDK's modelUsage map the primary source (the driver already returned it and the pipeline discarded everything but the first key), keeps the hook as a fallback for drivers that report no usage (aider/subprocess), and routes both run and the ready gate through one worktree-anchored helper (#833 single-choke-point pattern). sequant stats grows a phase × model cost table labeled "SDK estimate, not a billing statement".

A third defect surfaced in review (7b8cd82b): the driver returned modelUsage only on the success path. The is_error, error_max_turns and error_max_budget_usd returns dropped it, so failed, capped and over-budget phases reported zero tokens and zero cost — while PhaseResult.usage's own docs claimed usage was captured on both paths. modelUsage is a required field on every SDK result variant, error ones included. These are the expensive shapes: a capped agent ran to its full turn ceiling, and a budget-limit failure reporting zero cost is a contradiction in terms.

Acceptance criteria

AC Status Evidence
AC-1: aggregate from modelUsage ✅ phase-executor.ts:normalizeModelUsage + run-orchestrator.ts:1800-1860; -t "986" asserts totals equal the recorded-fixture sums. Failure paths now carry usage too (claude-code.ts:259/296/325)
AC-1b: real-run tokensUsed > 0 🔄 Post-merge Runner-verified after the first sequant run on main (D14)
AC-2: metrics.phaseUsage[], retries unmerged ✅ Rows appended in phaseResults order, never keyed by phase name. Verified against the live pipeline, not just the fixture: batch-executor.ts:1397 re-runs the whole phase list per quality-loop iteration and :1500 pushes each execution
AC-3: hook parses .message.usage // .usage ✅ templates/hooks/capture-tokens.sh; md5 across all three copies → 1
AC-4: one worktree-anchored helper ✅ readWorktreeTokenUsage(); grep -c 'getTokenUsageForRun(undefined' run-orchestrator.ts → 0; helper used by both run and ready-gate.ts
AC-5: stats phase × model cost table ✅ stats.ts:820-853, shown by default (OQ-1)
AC-6: pre-fix records load and render ✅ Fixture copied verbatim from today's .sequant/metrics.json; renders 0/—
AC-7: config surface untouched, #863 parity holds ✅ execution-config-parity.test.ts → 9 passed

Beyond the ACs, the hook also dedupes by message.id: streaming and compaction re-emit the same assistant message (55 usage-bearing lines vs 29 unique ids on the sampled live transcript), so summing every line over-reports. A plausible-looking wrong number is worse than an honest 0.

Mutation verification

Mutation-verified: AC-3 — reverted the hook jq to ((.usage) // empty) in all three copies; src/lib/workflow/token-utils.test.ts > 986 hook sums .message.usage from a real transcript, deduped by message.id failed (expected 7 to be 73); restored.

Mutation-verified: AC-3 — appended a comment line to hooks/capture-tokens.sh to break three-copy parity; src/lib/workflow/token-utils.test.ts > 986 hook is byte-identical across templates/, .claude/ and the plugin hooks/ dir failed; restored.

Mutation-verified: AC-3 — renamed "SessionEnd" to "SessionEndX" in hooks/hooks.json; src/lib/workflow/token-utils.test.ts > 986 hook registers SessionEnd on both the plugin and project surfaces failed; restored.

Mutation-verified: AC-4 — restored the pre-fix getTokenUsageForRun(undefined, true) call in recordMetrics; src/lib/workflow/run-orchestrator.phase-policy.test.ts > 986 leaves no getTokenUsageForRun(undefined call in recordMetrics failed, along with the two sibling AC-4 assertions; restored.

Mutation-verified: AC-1 — deleted modelUsage: resultMessage.modelUsage from the three failure returns in claude-code.ts while keeping the success one; all three src/lib/workflow/drivers/claude-code.test.ts > 986 keeps modelUsage ... tests failed (expected undefined to deeply equal); restored.

Test plan

  • npm run build — passes
  • npm run lint — passes (0 warnings, --max-warnings 0)
  • npm test — 5936 passed, 3 failed
  • All 3 failures reproduce identically on origin/main in this same worktree: __tests__/integration/relay-hook.integration.test.ts, src/commands/__tests__/prompt-wait.test.ts, src/lib/workflow/batch-executor.test.ts > withActivityHook (#543). Pre-existing, not introduced here.
  • npx vitest run src/lib/workflow/phase-executor.test.ts src/lib/workflow/run-orchestrator.phase-policy.test.ts -t "986" → 11 passed
  • npx vitest run src/lib/workflow/token-utils.test.ts -t "986" → 5 passed
  • npx vitest run src/lib/workflow/drivers/claude-code.test.ts -t "986" → 3 passed
  • npx vitest run src/commands/stats.test.ts -t "986" → 5 passed
  • npx vitest run src/lib/workflow/execution-config-parity.test.ts → 9 passed
  • md5 -q templates/hooks/capture-tokens.sh .claude/hooks/capture-tokens.sh hooks/capture-tokens.sh | uniq | wc -l → 1
  • AC-1b: after merge, first sequant run on main — jq '[.. | objects | select(has("tokensUsed")) | .tokensUsed] | last' .sequant/metrics.json → > 0, pasted 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

Notes for review

  • Scope. hooks/hooks.json, templates/settings.json, scripts/sync-hooks.sh and src/lib/relay/__tests__/hook-sync.test.ts sit outside the issue's declared "may touch" list. The first two are the registration AC-3's hook promotion requires; the last two are comment-only. src/lib/workflow/drivers/claude-code.ts is also outside it — added in review because the comments in phase-executor.ts and types.ts asserted a failure-path capture that did not happen.
  • cleanup is a real seam, not a flag for its own sake. run reads once at the end and clears (true); the ready gate polls the same directory across QA passes and must not (false) — deleting mid-loop would zero its own budget accounting.
  • costUSD is omitted, never recorded as 0, when no driver reported one. "Absent" and "free" are different claims, and stats renders — rather than $0.00 for pre-fix records.

Known follow-ups (not fixed here)

  • getTokenUsageForRun is now a dead export — no non-test caller remains after AC-4 rerouted both. Worth deleting or deprecating so nobody reintroduces the main-checkout read.
  • The plugin-wide SessionEnd registration (hooks/hooks.json, "matcher": "") means capture-tokens.sh runs an unguarded mkdir -p .sequant in whatever directory a plugin user ends a session in. The obvious guard ([ -d .sequant ] || exit 0) would break a fresh worktree, so this needs a deliberate design choice.
  • Nothing exercises capture-tokens.sh end-to-end under a real SDK query() session, so the issue's open question — whether SessionEnd fires for SDK sessions at all — is still open. The primary modelUsage path masks it.

Closes #986

… token helper (WIP)

Entire-Checkpoint: 9f5ed2867822
…dupe; promote to templates + plugin hooks

Entire-Checkpoint: 6898af7c921d
The is_error, error_max_turns and error_max_budget_usd returns dropped
resultMessage.modelUsage, so failed, capped and over-budget phases reported
zero tokens and zero cost — while PhaseResult.usage's own docs claimed usage
was captured on both the success and failure paths. modelUsage is required on
every SDK result variant, error ones included.

These are the expensive shapes: a capped agent ran to its full turn ceiling,
and a budget-limit failure reporting zero cost is a contradiction in terms.

Entire-Checkpoint: a2bdd68cbe0d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant