Repository navigation
feat(cli): non-overlapping waste attribution + session waste rollup (#84) - #136
Merged
Merged
Conversation
) Findings no longer double-book the same tokens: every claim books through a documented type priority (failed_call > loop_streak > duplicate_call > probe_no_progress > oversized_output for per-call sources; cache_dead > stall_streak > wait_loop > cycle_motif for per-round sources) instead of severity+size, so a call fitting several types books once, in the top-priority category. context_spike becomes an observation (books 0), long_turn carries its observation status explicitly; every finding gets kind: waste | observation and the precision sampler skips observations. The session report prints one waste line — "waste (non-overlapping): N tok ~$X of $Y (Z%)" — and --json / session:sums carry a waste block { tokensWasted, wastedUsd?, wasteShare?, wasteUsdPartial }. The corpus invariants gain wasted-usd-le-cost: fully priced non-overlapping waste cannot exceed the session cost (#79 invariants extended). Co-Authored-By: Claude Code <noreply@anthropic.com>
axisrow
commented
Oct 13, 2026
axisrow
left a comment
Owner
Author
There was a problem hiding this comment.
Вердикт: approve (изменений не требую)
Ревью по диффу против main (head d3a654b): src/cli (analyzeSession, corpus, precision, sessionSums), тесты, SKILL.md, CHANGELOG, пересобранный dist-cli.
Что проверено
- Аллокация. Сортировка заменена на документированный
WASTE_TYPE_PRIORITY(экспортирован), внутри одного типа — severity, затем размер;Array.sortстабилен, детерминизм сохранён. Claimant’ы result-семейства и round-семейства не пересекаются по owner-ключам, поэтому порядок между семействами на аллокацию не влияет — распределение однозначно при любом порядке чтения. Тест «один вызов, четыре типа — бронируется один раз в топ-приоритете» арифметически сходится (4 × (args + result), паттерн-findings остаются с 0). sessionWasteTotals. Разделение priced/partial корректно (tokensWasted > 0 && wastedUsd === undefined→ partial);wasteShareтолько при priced иcost > 0; в--no-costблок строится из неочищенных findings до strip’аwastedUsd, ложный partial не появляется. В text-режиме строка гейтится на cost-режим,wastedUsd!под non-null assertion безопасен (wasteShare ⇒ priced).- Инвариант
wasted-usd-le-cost. Условие пропуска полное (нет priced суммы, partial, нет costUsd); epsilon 1e-6 адекватен float-суммированию долларовых долей; при нулевых ставках waste-$ = 0 и ложного трипа не будет. Ставки claim’ов берутся те же, по которым раунды биллились (premiumRates для cache_dead — только надбавка), так что гарантия ≤ cost содержательно обоснована. - Precision sampler. Наблюдения отсекаются до stratifiedSample, идентификаторы семпла (
:${i}) остаются стабильными. - Тесты. Новые кейсы покрывают ключевое поведение: типовой приоритет, spike/cache_dead на одном раунде, totals с partial и без доллара, trip/skip инварианта, пропуск наблюдений в семпле, waste-блок session:sums (priced и unpriced). Флип duplicate/probe в analyzeSession.test.ts согласован с fixture: dup занимает b2, probe — оставшийся b1, суммарный total не меняется.
meta()/ai()расширены обратно совместимо. - dist-cli/session-audit.js пересобран: в бандле есть
WASTE_TYPE_PRIORITY,kind: "waste", строка отчётаwaste (non-overlapping); session-inventory не тронут обоснованно (findings не использует),session:sumsидёт через tsx из src и в бандл не входит. - Документация. SKILL.md и CHANGELOG согласованы с реализацией (kind, наблюдения, формат строки, JSON-блок,
--no-cost).
Наблюдения — не требуют изменений
- «Non-overlapping» — гарантия per-source. Аллокатор (#124) дедуплицирует внутри одного owner’а; физическое пересечение между семействами owner’ов осталось: токены
result:<id>входят и вcontextSizeпоследующих раундов, поэтомуoversized_output/duplicate_call+cache_dead/stall_streakна тех же раундах посчитают один токен дважды — релевантно для роутеров без кэша, где cache_dead массовый. Инвариантwasted-le-billedтакой overlap ловит не всегда (overlap может укладываться в billed). Формулировки в SKILL.md/CHANGELOG («no token is booked twice») чуть сильнее механики — можно со временем смягчить до «each source books at most once». - Знаменатель
wasteShare—costUsdуже исключает unpriced раунды (costPartial), а строка помечает только частичность числителя; в смешанной сессии доля завышается. Можно рядом с est. cost помечать и partial-знаменатель. - Ставка ровно $0 (бесплатные роуты): гейт
usd > 0в allocateWaste не выставляетwastedUsd, и totals помечаются partial («unpriced») при фактически проставленной нулю цене. Консервативно и чисто косметически.
Итог: изменения согласованы, намеренные семантические сдвиги задокументированы, тесты написаны под новое поведение, артефакты пересобраны — approve.
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.
Non-overlapping waste attribution + one waste number per session
Implements #84. Findings used to book tokens independently: the same tool
call fitting several finding types (failed + duplicated + looping) had its
tokens counted in each category, so summing a session's
tokensWastedovercounted. Observations were mixed into the same list as loss claims.
What changes
Type-priority booking. Every claim books through a documented
WASTE_TYPE_PRIORITY(exported) instead of severity+size ordering:per-call sources (
result:<toolUseId>) —failed_call>loop_streak>duplicate_call>probe_no_progress>oversized_output; per-roundsources (
round:<index>) —cache_dead>stall_streak>wait_loop>cycle_motif. The claim-allocator (#124) books each source at most once,so a call fitting four types books once, in the top-priority category
(test: one call fitting four types books once, in the top-priority
category). Undersupplied findings stay at 0 rather than overbooking.
kind: 'waste' | 'observation'.
context_spikebecomes an observation:it reports the growth (summary unchanged) but books nothing — a big growth
is often a legitimately needed large file, so recording it as loss
inflated waste.
long_turnkeeps its previous 0-booking semantics withthe kind now explicit. Observations sort last, claim nothing, carry no
dollars, and the precision sampler (#81) skips them — labeling them
"not waste" would measure the definition, not detection quality.
One waste number per session. New
sessionWasteTotals()(shared bythe text report,
--jsonandsession:sums) returns{ tokensWasted, wastedUsd?, wasteShare?, wasteUsdPartial }wherewasteShare = wastedUsd / ledger.totals.costUsd. Text:waste (non-overlapping): 1,835,952 tok ~$0.0134 of $5.80 (0.2%) (partial — unpriced waste excluded)(golden fixture run, CLI built from this branch).
--jsoncarries theblock under
waste;--no-costleaves onlytokensWasted.context_spikeandlong_turnnever enter the rollup.Invariant.
checkInvariantsgainswasted-usd-le-cost: fully pricednon-overlapping waste cannot exceed the session cost — the claimed
tokens' rates are exactly what those rounds billed. Skipped when the
waste sum is partial (unpriced findings present).
Semantic changes (intentional, coherent)
priority: failed vs streak now gives the money to
failed_call;cache_deadalways beatswait_loop(previously tick-countdependent); duplicate vs probe now deterministically favors
duplicate_call(the scoping test inanalyzeSession.test.tsflipsaccordingly — total unchanged).
context_spikesnapshots change: previously each spike booked itsdelta as loss, now it books 0 (regenerate
pnpm corpus:snapshotifyou keep local snapshots; none are committed).
mutator that the new priority keeps every exact-booking expectation.
Tests
Tests written first (12 failing before implementation): allocation
(one call, four types, books once in top priority; spike books 0;
long_turn observation), waste/observation split and session totals,
session:sums waste block incl. unpriced partial, corpus invariant
(
wasted-usd-le-costtrips above cost, skipped when partial), precisionsampler skips observations.
pnpm test1144 passed,pnpm typecheckclean,
pnpm lint0 errors,dist-clirebuilt.Closes #84
🤖 Generated with Claude Code