Repository navigation
Conversation
… token helper (WIP) Entire-Checkpoint: 9f5ed2867822
…dupe; promote to templates + plugin hooks Entire-Checkpoint: 6898af7c921d
Entire-Checkpoint: 6a94b2145daa
Entire-Checkpoint: 383ed0de00d4
Entire-Checkpoint: 0ce01a9f4f8c
… fixtures Entire-Checkpoint: 2d3af5250c58
Entire-Checkpoint: 5940b9330bc5
…ding Entire-Checkpoint: 8ff093e29dbc
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
…cs-tokensused-is-0-on-every-recorded-run-
admarble
deleted the
feature/986-fix-metrics-tokensused-is-0-on-every-recorded-run-
branch
September 8, 2026 06:16
10 tasks
9 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
metrics.tokensUsedwas 0 in 365/365 recorded runs because of two independent defects, either of which alone yields 0:capture-tokens.shread.usagefrom the transcript JSONL; Claude Code carries usage at.message.usage. Every token file the hook ever wrote was all zeros.recordMetricsreadgetTokenUsageForRun(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
modelUsagemap 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 bothrunand the ready gate through one worktree-anchored helper (#833 single-choke-point pattern).sequant statsgrows a phase × model cost table labeled "SDK estimate, not a billing statement".A third defect surfaced in review (
7b8cd82b): the driver returnedmodelUsageonly on the success path. Theis_error,error_max_turnsanderror_max_budget_usdreturns dropped it, so failed, capped and over-budget phases reported zero tokens and zero cost — whilePhaseResult.usage's own docs claimed usage was captured on both paths.modelUsageis 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
modelUsagephase-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)tokensUsed > 0sequant runon main (D14)metrics.phaseUsage[], retries unmergedphaseResultsorder, never keyed by phase name. Verified against the live pipeline, not just the fixture:batch-executor.ts:1397re-runs the whole phase list per quality-loop iteration and:1500pushes each execution.message.usage // .usagetemplates/hooks/capture-tokens.sh; md5 across all three copies →1readWorktreeTokenUsage();grep -c 'getTokenUsageForRun(undefined' run-orchestrator.ts→0; helper used by bothrunandready-gate.tsstatsphase × model cost tablestats.ts:820-853, shown by default (OQ-1).sequant/metrics.json; renders0/—execution-config-parity.test.ts→ 9 passedBeyond 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.idfailed (expected 7 to be 73); restored.Mutation-verified: AC-3 — appended a comment line to
hooks/capture-tokens.shto break three-copy parity;src/lib/workflow/token-utils.test.ts > 986 hook is byte-identical across templates/, .claude/ and the plugin hooks/ dirfailed; restored.Mutation-verified: AC-3 — renamed
"SessionEnd"to"SessionEndX"inhooks/hooks.json;src/lib/workflow/token-utils.test.ts > 986 hook registers SessionEnd on both the plugin and project surfacesfailed; restored.Mutation-verified: AC-4 — restored the pre-fix
getTokenUsageForRun(undefined, true)call inrecordMetrics;src/lib/workflow/run-orchestrator.phase-policy.test.ts > 986 leaves no getTokenUsageForRun(undefined call in recordMetricsfailed, along with the two sibling AC-4 assertions; restored.Mutation-verified: AC-1 — deleted
modelUsage: resultMessage.modelUsagefrom the three failure returns inclaude-code.tswhile keeping the success one; all threesrc/lib/workflow/drivers/claude-code.test.ts > 986 keeps modelUsage ...tests failed (expected undefined to deeply equal); restored.Test plan
npm run build— passesnpm run lint— passes (0 warnings,--max-warnings 0)npm test— 5936 passed, 3 failedorigin/mainin 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 passednpx vitest run src/lib/workflow/token-utils.test.ts -t "986"→ 5 passednpx vitest run src/lib/workflow/drivers/claude-code.test.ts -t "986"→ 3 passednpx vitest run src/commands/stats.test.ts -t "986"→ 5 passednpx vitest run src/lib/workflow/execution-config-parity.test.ts→ 9 passedmd5 -q templates/hooks/capture-tokens.sh .claude/hooks/capture-tokens.sh hooks/capture-tokens.sh | uniq | wc -l→1sequant runon 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 #986Notes for review
hooks/hooks.json,templates/settings.json,scripts/sync-hooks.shandsrc/lib/relay/__tests__/hook-sync.test.tssit 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.tsis also outside it — added in review because the comments inphase-executor.tsandtypes.tsasserted a failure-path capture that did not happen.cleanupis a real seam, not a flag for its own sake.runreads 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.costUSDis omitted, never recorded as0, when no driver reported one. "Absent" and "free" are different claims, andstatsrenders—rather than$0.00for pre-fix records.Known follow-ups (not fixed here)
getTokenUsageForRunis 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.SessionEndregistration (hooks/hooks.json,"matcher": "") meanscapture-tokens.shruns an unguardedmkdir -p .sequantin 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.capture-tokens.shend-to-end under a real SDKquery()session, so the issue's open question — whetherSessionEndfires for SDK sessions at all — is still open. The primarymodelUsagepath masks it.Closes #986