Skip to content

feat(cli): non-overlapping waste attribution + session waste rollup (#84) - #136

Merged
axisrow merged 1 commit into
mainfrom
ao/claude-devtools-57/waste-attribution
Oct 13, 2026
Merged

axisrow merged 1 commit into
mainfrom
ao/claude-devtools-57/waste-attribution

Conversation

@axisrow

@axisrow axisrow commented Oct 13, 2026

Copy link
Copy Markdown
Owner

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 tokensWasted
overcounted. 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-round
sources (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_spike becomes 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_turn keeps its previous 0-booking semantics with
the 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 by
the text report, --json and session:sums) returns
{ tokensWasted, wastedUsd?, wasteShare?, wasteUsdPartial } where
wasteShare = 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). --json carries the
block under waste; --no-cost leaves only tokensWasted.
context_spike and long_turn never enter the rollup.

Invariant. checkInvariants gains wasted-usd-le-cost: fully priced
non-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)

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-cost trips above cost, skipped when partial), precision
sampler skips observations. pnpm test 1144 passed, pnpm typecheck
clean, pnpm lint 0 errors, dist-cli rebuilt.

Closes #84

🤖 Generated with Claude Code

)

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 axisrow left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вердикт: 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).

Наблюдения — не требуют изменений

  1. «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».
  2. Знаменатель wasteShare — costUsd уже исключает unpriced раунды (costPartial), а строка помечает только частичность числителя; в смешанной сессии доля завышается. Можно рядом с est. cost помечать и partial-знаменатель.
  3. Ставка ровно $0 (бесплатные роуты): гейт usd > 0 в allocateWaste не выставляет wastedUsd, и totals помечаются partial («unpriced») при фактически проставленной нулю цене. Консервативно и чисто косметически.

Итог: изменения согласованы, намеренные семантические сдвиги задокументированы, тесты написаны под новое поведение, артефакты пересобраны — approve.

@axisrow
axisrow merged commit 40af3ee into main Oct 13, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Non-overlapping waste attribution and session waste share; split observations from waste

1 participant