Repository navigation
Description
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
- Parser reads the wrong path.
.claude/hooks/capture-tokens.sh:38-39extracts[.[] | .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 readinput_tokens: 0, output_tokens: 0. - Producer and consumer disagree on the directory. The hook writes
.sequant/.token-usage-<sid>.jsonrelative to the session cwd — for phase agents, the worktree.run-orchestrator.ts:1729readsgetTokenUsageForRun(undefined, true)→ the main checkout's.sequant/. Worktree.sequant/dirs contain no token files at all (so eitherSessionEndnever fires for SDKquery()sessions, or the file dies with the worktree).ready-gate.ts:642reads fromworktreePath— 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
- Primary source = driver
modelUsage, per phase execution. Normalize into ausage: { model, inputTokens, outputTokens, cacheReadTokens, cacheCreationTokens, costUSD }[]on the phase result; the orchestrator aggregates it into the existingmetrics.tokensUsed / inputTokens / outputTokens / cacheTokens, addsmetrics.costUSD, and records a per-phase breakdownphaseUsage: { phase, model, …tokens, costUSD }[]. Extendmetrics-schema.tsadditively — existing records stay valid. - Hook path becomes the fallback for drivers that report no
modelUsage(aider / subprocess). Fix its jq to.message.usage // .usage, and makerunandreadyread fallback files through one helper anchored at the worktree (fix(cli): bare parseInt on run --timeout lets a malformed value abort every phase instantly (sibling of #818) #833 single-choke-point pattern). sequant statsrenders non-zero totals plus a phase × model table with cost, labeled "SDK estimate, not a billing statement" (the SDK's own wording forcostUSD).readygets the same fields when feat(ready): sequant ready never records run metrics — no visibility into escalation, iteration counts, or gate outcomes #929 lands — not duplicated here.
Non-Goals
- No cost-based routing decisions — 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 consume this number; this issue only produces it.
- No reconciliation against console billing.
- No change to what the phase agents are allowed to do; observability only.
Scope (graph plan 2026-09)
- may touch:
src/lib/workflow/metrics-schema.ts(append-only),src/lib/workflow/token-utils.ts,src/lib/workflow/run-orchestrator.ts(metrics assembly region ~:1729 only),src/lib/workflow/phase-executor.ts(usage normalization beside the feat(config): model roles — semantic indirection between phase policy/ladders and concrete model strings #975resolvedModelextraction ~:1381),src/lib/workflow/drivers/agent-driver.ts(type themodelUsagemap),src/lib/workflow/ready-gate.ts(default ofreadTokensUsedonly),src/commands/ready.ts,src/lib/workflow/batch-executor.ts(the onereadTokensUsedwiring),src/commands/stats.ts,templates/hooks/capture-tokens.sh+.claude/hooks/capture-tokens.sh+hooks/capture-tokens.sh, tests beside each, fixtures: one recorded real SDKresultmessage, one real transcript excerpt, one pre-fixmetrics.jsonrecord - not in scope: routing decisions; billing reconciliation;
readymetrics (feat(ready): sequant ready never records run metrics — no visibility into escalation, iteration counts, or gate outcomes #929); feat(run): model escalation ladder on capability-bound non-convergence #971 (node 11)'s escalation columns.
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 realresultmessage fixture with two model entries and assertsmetrics.tokensUsed/inputTokens/outputTokens/cacheTokens/costUSDequal the sums. - AC-1b (real run, runner-verified post-merge, D14): after the first
sequant runon 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 twoqaexecutions asserts two rows. - AC-3: hook parses
.message.usage // .usage— Verify:bash templates/hooks/capture-tokens.shagainst a fixture transcript with known totals writes matching numbers (test insrc/lib/workflow/token-utils.test.ts -t "986 hook"); PR body carriesMutation-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), andready-gate.ts's defaultreadTokensUsedcalls the same helper (grep -n '<helperName>' src/lib/workflow/ready-gate.ts src/lib/workflow/run-orchestrator.ts→ both files). - AC-5:
sequant statsphase × model table with cost, labeledSDK 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 fixturemetrics.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(nocostUSD/phaseUsage) renders without throwing and shows0/—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 runon the claude-code driver records non-zerometrics.tokensUsed,inputTokens,outputTokens,cacheTokens, andcostUSDsourced from the SDKmodelUsagemap; a unit test with a mockedresultmessage asserts the aggregate equals the sum of the mocked per-model entries. - AC-2:
metrics.phaseUsagerecords{ 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.shsums.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:
runandreadyread hook-fallback files through one shared helper anchored at the worktree; a grep gate asserts nogetTokenUsageForRun(undefinedcall remains inrun-orchestrator.ts. - AC-5:
sequant statsrenders a phase × model table with tokens and cost and labels cost as an SDK estimate; snapshot test against a fixturemetrics.json. - AC-6: pre-fix
metrics.jsonrecords (nocostUSD/phaseUsage) still load and render — test loads a fixture copied from a current real record.
Human decisions required
- Whether
costUSDshows instatsby default or behind a--costflag.
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
docs(plan): 2026-09 backlog graph (16 nodes, /graph-run ready) (#998)
admarble commentedon Sep 8, 2026
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) anddocs/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 backgroundnpm test); prefer the node file's targeted-tcommands 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-producerExecutionConfigand routedready.tsthroughresolveRunOptions; the ready gate reads tokens through the injectedreadTokensUsedcallback (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 theMutation-verified:format.admarble commentedon Sep 8, 2026
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-1bparses asAC-8.extractAcceptanceCriteriadoes not recognise the-1bsuffix and remaps it to a trailing sequential ID. Anysequant state update accall must useAC-8, notAC-1b. (AC-8 is runner-verified post-merge per D14 — not satisfiable in the PR.)verificationMethod: "manual"because they useVerify:rather than a declaredEvidence:clause. The#938testgen detector therefore sees zero unit/integration ACs. In substance every AC is a vitest command — see Recommended Workflow for whytestgenis still the right skip.Scope Assessment
Non-Goals: found (3) — no cost-based routing (#944/#971), no billing reconciliation, observability only.
Verdict: ❌ SCOPE_SPLIT_RECOMMENDED — do not split. The red is a keyword-clustering artifact: the detector bucketed ACs into
auth/ui/configfrom 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)jq -s '[.[]|.usage//empty]|length'→ 0;.message.usage→ 35.sequant/metrics.jsonnow 164 records, latest still"tokensUsed":0run-orchestrator.ts:1815getTokenUsageForRun(undefined, true)(baselinegrep -c= 1, AC-4's gate)ready-gate.ts:350 defaultReadTokensUsed→path.join(worktreePath, TOKEN_USAGE_DIR)drivers/claude-code.ts:265returnsmodelUsage;phase-executor.ts:1384takes onlyObject.keys(...)[0]phasePolicies.qa.resolvedModel: "claude-opus-5"— #975 already provesPhaseResult→recordMetricsdelivers driver-derived data. Tokens ride the same wire.Two corrections to the issue's scope list, both load-bearing:
batch-executor.tshas noreadTokensUsedwiring.grep -rn readTokensUsed src/returns onlyready-gate.ts(3 sites) and its two test files. No production caller injects the callback, sodefaultReadTokensUsedis the only live path. Dropbatch-executor.tsandsrc/commands/ready.tsfrom the touch list unless something else pulls them in.worktreeMapis already in scope at the metrics site.RunOrchestrator.recordMetrics(config, mergedOptions, results, worktreeMap, …)(:1760) already doesworktreeMap.get(result.issueNumber)at:1797for 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 TestGiven a recorded real
resultmessage with two model entries → When a phase executes andrecordMetricsruns → Thenmetrics.tokensUsed/inputTokens/outputTokens/cacheTokens/costUSDequal the per-model sums.Assumption:
costUSDis a float.RunMetricsSchema's existing token fields are allz.number().int()—costUSDmust bez.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 runcompletes → Thenjq '[..|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 TestGiven two
qaexecutions in one issue'sphaseResults→ When flattened → Then two rows, not one merged row.Assumption: rows are emitted in
phaseResultsorder with no keying by phase name — grouping is what would silently merge retries.ready-gateQA passes do not enterphaseResults, so they are out of scope here (#929).AC-3 — hook parses
.message.usage // .usage· Integration Test + gateGiven a fixture transcript with known totals → When
capture-tokens.shruns → 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
cleanupflag — see Design Review Q4, the two callers disagree about it.AC-5 —
sequant statsphase × model table · Unit Test (snapshot)Given a fixture
metrics.jsonwithphaseUsage→ Whenstatsrenders → Then a phase × model table with cost, labeledSDK 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.jsonrecord (nocostUSD/phaseUsage) → Whenstatsrenders → Then no throw,0/—for missing fields.Note:
stats.ts:725already gates the Token Usage panel ontotal*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 touchesExecutionConfig; this is a regression guard on #863.Implementation Plan
Phase 1 — capture at the driver (AC-1, AC-2)
drivers/agent-driver.ts:117-122— replacemodelUsage?: Record<string, unknown>with a typedRecord<string, ModelUsageEntry>(inputTokens,outputTokens,cacheReadInputTokens,cacheCreationInputTokens,costUSD). Keep it optional — aider/subprocess don't populate it.phase-executor.ts:1381-1403— beside the feat(config): model roles — semantic indirection between phase policy/ladders and concrete model strings #975resolvedModelextraction, normalize the whole map intousage: PhaseUsage[](one row per model key) and attach toPhaseResulton both the success and failure paths — a failed phase still burned tokens. Addusage?: PhaseUsage[]toPhaseResultintypes.ts.resultmessage 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 thephasePolicies/effortEscalationsconvention). Privacy contract holds: phase enums, model IDs, numbers — no paths, no content.5. Thread both fields through
createMetricRun. Itsmetrics:block copies fields one by one; a field added to the schema but not to that copy is silently dropped and lands asundefined/0. This is the same shape as the bug being fixed.6.
metrics-writer.ts:152— widen therecordRunmetricsparam.7.
run-orchestrator.ts recordMetrics(~:1793-1880) — inside the existingfor (const result of results)loop, flattenresult.phaseResults[].usageintophaseUsagerows 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— addreadWorktreeTokenUsage(worktreePath, { cleanup }), the single choke point (#833 pattern). It joinsworktreePathwithTOKEN_USAGE_DIR; no bare-relative default survives.9.
ready-gate.ts:350—defaultReadTokensUseddelegates withcleanup: 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 usingworktreeMap.get(result.issueNumber)?.path,cleanup: true. AC-4's grep goes to0.11. Sibling site (do not skip): today's
cleanup: trueruns against the main checkout, so everysequant rundeletes 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) — rollphaseUsageup 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 theSDK estimate, not a billing statementlabel.Design Review
phase-executor(the only place holding a driver result and its phase identity); aggregation atrun-orchestrator.recordMetrics(the only place holding all results plusworktreeMap); presentation entirely instats.ts.token-utils.tsowns the fallback and becomes the only module that knows where token files live.PhaseResult→recordMetrics.resolvedModelreaching 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); aphaseUsagemap keyed by phase (cannot express AC-2's retry rows); repairing only the hook (the SDK numbers are strictly better and already in hand).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.cleanupflag — 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;runreads 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
AC-3's mirror clause is unsatisfiable as written, and contradicts a documented decision.
capture-tokens.shexists only in.claude/hooks/.templates/hooks/capture-tokens.shandhooks/capture-tokens.shdo not exist — sobash templates/hooks/capture-tokens.shcannot run andmd5 -q … | uniq | wc -lcannot return1. This is deliberate:scripts/sync-hooks.sh:8says "Local-only files (e.g. capture-tokens.sh) are left untouched" andhook-sync.test.ts:11-13says ".claude/hooks/ MAY contain extra files … e.g. capture-tokens.sh, which is sequant-specific and intentionally local." Separately,hooks/hooks.jsonregisters onlyPreToolUse/PostToolUse— dropping a file intohooks/without aSessionEndentry ships a script nothing ever calls.Recommendation: promote it —
templates/hooks/becomes the source of truth,npm run sync-hooksregenerates.claude/hooks/,hooks/capture-tokens.shplus aSessionEndentry inhooks.jsongives 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.The naive sum double-counts. On a live transcript: 35 lines carry
.message.usage, all 35 have uniqueuuid, but only 13 uniquemessage.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 honest0we 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.costUSDdefault-on is already decided. The issue lists "default vs--costflag" 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.Ready-gate QA passes produce no
phaseUsagerows. They don't flow throughphaseResults. Recommendation: leave it —readymetrics 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/qadoesn't read the gap as a miss.Coordination Risk
No in-flight conflicts today: the
862/916/919worktrees are all zero commits ahead oforigin/main. But node 12 (#862, opencode driver) also touchesdrivers/agent-driver.ts— this issue's typedmodelUsagemap 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 additiveModelUsageEntryinterface keeps that conflict trivial.Recommended Workflow
Phases: exec → qa
Quality Loop: enabled
Reasoning:
buglabel, no UI, no browser test.testgenskipped: the #938 detector reads 0 declared-evidence and 0 inferred unit/integration ACs (all 8 useVerify:, notEvidence:), 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)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.git checkout <file>wipes uncommitted edits.Label Review
Current:
bug,graph-2026-09Recommended: add
plannedReason: phase marker; no
ui(no.tsx/.jsxin scope), nocomplex(8 ACs, one causal chain).Quality Loop: auto-enabled by SCOPE_SPLIT_RECOMMENDED.
admarble commentedon Sep 8, 2026
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(undefinedgrep 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.docs(#986): restore CHANGELOG section boundary split by the Added hea…
fix(#986): keep modelUsage on every driver failure path
admarble commentedon Sep 8, 2026
QA Verdict: AC_MET_BUT_NOT_A_PLUS
AC coverage: 7/8 met
Gaps:
Suggestions:
resolvedModelside effect, or a test pinning it, so feat(config): model roles — semantic indirection between phase policy/ladders and concrete model strings #975's behavior isn't silently redefined.message.id" differs from the spec's 35/13. Both plausible from different transcripts; naming the sample would make the number auditable.admarble commentedon Sep 8, 2026
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'd7b8cd82b, and the targeted set re-run at43b1ac88(merge ofmainincl. #935/#862):npx vitest run src/lib/workflow/phase-executor.test.ts src/lib/workflow/run-orchestrator.phase-policy.test.ts -t "986"modelUsagefixture sums; twoqaexecutions → twophaseUsagerows)src/lib/workflow/token-utils.test.ts -t "986 hook";md5 -qover the threecapture-tokens.shcopies.message.usage // .usagegrep -c 'getTokenUsageForRun(undefined' src/lib/workflow/run-orchestrator.tsready-gate.tsdefaultreadTokensUseddelegates to the shared helpersrc/commands/stats.test.ts -t "986"0/—)execution-config-parity.test.tssequant runon main that includes this fixRun 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 2AC_MET_BUT_NOT_A_PLUS. Sequant's post-run step then rebased the worktree ontomain; the PR branch was instead synced by mergingmain(no conflict).Merging on the owner's standing instruction once CI is green.
fix(#986): source token and cost metrics from the SDK modelUsage map (#…
admarble commentedon Sep 8, 2026
AC-1b — runner-verified post-merge (PLAN D14)
First
sequant runonmainthat includes this fix: the #993 re-dispatch (exec,qawith quality loop, 3 iterations, 06:17Z–06:52Z on 2026-09-08, dist rebuilt at0f278b40).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 readtokensUsed: 0, which is the expected boundary.AC-1b met (
> 0).