oficina / equipo Public

Spend review: per-result Claude usage, honest lower bounds, live answers

Astra review of spend-1 (REQUEST CHANGES, three findings), all fixed:

1. ClaudeRows read modelUsage, the session's running total, so every
   later turn of a coordinator process, each answer and each resumed
   fix round counted the earlier turns again (the recorded resume turn
   used 3,987 tokens and recorded 11,847). It now reads
   model_usage_since_last_result, falling back to the result's own
   usage, never the running total. TestClaudeRowsPerResult checks the
   recorded two-turn and resumed transcripts; it failed before.
2. A task's spend called a sum exact when a row's final usage message
   was not seen, its cached figure was missing, or a Claude row lacked
   its cache-write figure. rowSpend marks each as a lower bound;
   TestRowSpend fails when any one condition is removed, and the page
   test shows "at least" for a cancelled fix round.
3. An answer's spend showed only after a reload: the thread now asks
   the page's live regions to refresh when a question ends.
   TestBrowserSpendFollowsAnswers failed before.

Protocol: ProtocolSpend names the feedback-and-turns capability, and
Encode drops those fields below it rather than below the current
protocol, so a later protocol 4 keeps them at 3.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 44c5338a05a57a1ce09e1eafc88e15810e4650ad parent 5b90ead
10 files changed, +164 −21
  • internal/equipo/chat/connections.go +16 −7
  • internal/equipo/chat/spend_test.go +34 −0
  • internal/equipo/static/chat-stream.js +2 −0
  • internal/runner/connect/usage.go +8 −5
  • internal/runner/connect/usage_test.go +39 −2
  • internal/thintest/review_contract_test.go +2 −2
  • internal/thintest/spend_browser_test.go +32 −0
  • internal/thintest/spend_pages_test.go +20 −0
  • internal/wire/runners.go +10 −4
  • internal/wire/runners_test.go +1 −1

CI passed — run details

diff --git a/internal/equipo/chat/connections.go b/internal/equipo/chat/connections.go
index 246d22b6..00e4d61d 100644
--- a/internal/equipo/chat/connections.go
+++ b/internal/equipo/chat/connections.go
@@ -760,7 +760,8 @@ func (s *Store) NoConnection(ctx context.Context, person string) (out []NoConnec
// Spend is what usage rows add up to: every token read or written
// (input, cached or not, and output) and, of them, the cached input.
-// Partial: a row lacked a figure, so the sum is a lower bound.
+// Partial: a row lacked a figure the sum needs, or the harness's final
+// usage message for it was not seen, so the sum is a lower bound.
type Spend struct {
Tokens, Cached int64
Partial bool
@@ -797,12 +798,7 @@ func (s *Store) TaskSpend(ctx context.Context, person, id string) (out TaskSpend
return err
}
for _, r := range rows {
- one := Spend{Partial: r.InputTokens == nil || r.OutputTokens == nil}
- in, cached, written := figure(r.InputTokens), figure(r.CachedInputTokens), figure(r.CacheWriteTokens)
- if r.Provider == "claude" {
- in += cached + written
- }
- one.Tokens, one.Cached = in+figure(r.OutputTokens), cached
+ one := rowSpend(r)
out.Total.add(one)
if r.Role == "ask" {
out.Questions.add(one)
@@ -818,6 +814,19 @@ func (s *Store) TaskSpend(ctx context.Context, person, id string) (out TaskSpend
return out, err
}
+// rowSpend is one usage row's part of a sum. Claude counts cache reads
+// and writes apart from input, so each is a figure of the sum; for Codex
+// the cached figure is part of input, but the cached subtotal needs it.
+func rowSpend(r usageRecord) Spend {
+ one := Spend{Partial: !r.Complete || r.InputTokens == nil || r.OutputTokens == nil || r.CachedInputTokens == nil || r.Provider == "claude" && r.CacheWriteTokens == nil}
+ in, cached, written := figure(r.InputTokens), figure(r.CachedInputTokens), figure(r.CacheWriteTokens)
+ if r.Provider == "claude" {
+ in += cached + written
+ }
+ one.Tokens, one.Cached = in+figure(r.OutputTokens), cached
+ return one
+}
+
func figure(p *int64) int64 {
if p == nil {
return 0
diff --git a/internal/equipo/chat/spend_test.go b/internal/equipo/chat/spend_test.go
new file mode 100644
index 00000000..e3478eee
--- /dev/null
+++ b/internal/equipo/chat/spend_test.go
@@ -0,0 +1,34 @@
+package chat
+
+import "testing"
+
+// Each row's part of a task's spend: Claude's cache reads and writes
+// beside its input, Codex's cached input inside it; a lower bound when
+// any figure the sum needs is missing or the attempt's final usage
+// message was not seen.
+func TestRowSpend(t *testing.T) {
+ n := func(v int64) *int64 { return &v }
+ claude := usageRecord{Provider: "claude", Complete: true, InputTokens: n(2), CachedInputTokens: n(3566), CacheWriteTokens: n(378), OutputTokens: n(3)}
+ codex := usageRecord{Provider: "codex", Complete: true, InputTokens: n(9000), CachedInputTokens: n(4000), OutputTokens: n(1000)}
+ if got := rowSpend(claude); got != (Spend{Tokens: 3949, Cached: 3566}) {
+ t.Fatalf("claude %+v", got)
+ }
+ if got := rowSpend(codex); got != (Spend{Tokens: 10000, Cached: 4000}) {
+ t.Fatalf("codex %+v", got)
+ }
+ for name, r := range map[string]usageRecord{
+ "incomplete": func() usageRecord { r := codex; r.Complete = false; return r }(),
+ "no input": func() usageRecord { r := codex; r.InputTokens = nil; return r }(),
+ "no output": func() usageRecord { r := codex; r.OutputTokens = nil; return r }(),
+ "no cached": func() usageRecord { r := codex; r.CachedInputTokens = nil; return r }(),
+ "claude no cache write": func() usageRecord { r := claude; r.CacheWriteTokens = nil; return r }(),
+ } {
+ if !rowSpend(r).Partial {
+ t.Fatalf("%s: not a lower bound", name)
+ }
+ }
+ // Codex reports no cache-write figure: that alone is no gap.
+ if rowSpend(codex).Partial {
+ t.Fatal("codex without a cache-write figure is partial")
+ }
+}
diff --git a/internal/equipo/static/chat-stream.js b/internal/equipo/static/chat-stream.js
index 773889f0..d7baa8f1 100644
--- a/internal/equipo/static/chat-stream.js
+++ b/internal/equipo/static/chat-stream.js
@@ -576,6 +576,8 @@
if (v.state === "answered" || v.state === "failed" || v.state === "cancelled") {
delete drafts[v.id];
ended[v.id] = true;
+ // What the answer used: the page's spend regions follow.
+ document.dispatchEvent(new CustomEvent("equipo:work", { detail: { type: "question" } }));
}
if (v.state === "running") {
// Its turn came: the waiting line becomes the thinking line.
diff --git a/internal/runner/connect/usage.go b/internal/runner/connect/usage.go
index ee25eaa7..09253fe0 100644
--- a/internal/runner/connect/usage.go
+++ b/internal/runner/connect/usage.go
@@ -184,10 +184,13 @@ func (t *CodexTally) Row() wire.Usage {
}
// ClaudeRows reads a stream-json result: one row per model in
-// modelUsage (or one row from usage when the CLI reported no models),
-// complete because the result is the CLI's final usage message. Claude
-// reports no reasoning figure: null. The result's num_turns goes on the
-// row of the model that wrote most, so each request counts once.
+// model_usage_since_last_result (or one row from usage, this result's
+// own, when the CLI reported no models), complete because the result is
+// the CLI's final usage message. modelUsage is never read: it is the
+// session's running total, so a later turn of a process or a resumed
+// session would count the earlier ones again. Claude reports no
+// reasoning figure: null. The result's num_turns goes on the row of the
+// model that wrote most, so each request counts once.
func ClaudeRows(result []byte) []wire.Usage {
var v struct {
Turns *int64 `json:"num_turns"`
@@ -202,7 +205,7 @@ func ClaudeRows(result []byte) []wire.Usage {
Output *int64 `json:"outputTokens"`
CacheRead *int64 `json:"cacheReadInputTokens"`
CacheCreation *int64 `json:"cacheCreationInputTokens"`
- } `json:"modelUsage"`
+ } `json:"model_usage_since_last_result"`
}
if json.Unmarshal(result, &v) != nil {
return nil
diff --git a/internal/runner/connect/usage_test.go b/internal/runner/connect/usage_test.go
index 171ed771..7b910102 100644
--- a/internal/runner/connect/usage_test.go
+++ b/internal/runner/connect/usage_test.go
@@ -131,7 +131,7 @@ func TestCodexTally(t *testing.T) {
}
func TestClaudeRows(t *testing.T) {
- rows := ClaudeRows([]byte(`{"type":"result","subtype":"success","is_error":false,"usage":{"input_tokens":10,"output_tokens":5,"cache_read_input_tokens":3},"modelUsage":{"claude-opus-5-5":{"inputTokens":8,"outputTokens":4,"cacheReadInputTokens":3,"cacheCreationInputTokens":0},"claude-haiku-5":{"inputTokens":2,"outputTokens":1}}}`))
+ rows := ClaudeRows([]byte(`{"type":"result","subtype":"success","is_error":false,"usage":{"input_tokens":10,"output_tokens":5,"cache_read_input_tokens":3},"modelUsage":{"claude-opus-5-5":{"inputTokens":99,"outputTokens":99}},"model_usage_since_last_result":{"claude-opus-5-5":{"inputTokens":8,"outputTokens":4,"cacheReadInputTokens":3,"cacheCreationInputTokens":0},"claude-haiku-5":{"inputTokens":2,"outputTokens":1}}}`))
if len(rows) != 2 || rows[0].Model != "claude-haiku-5" || get(rows[1].InputTokens) != 8 || rows[0].CachedInputTokens != nil || rows[1].ReasoningOutputTokens != nil || !rows[0].Complete {
t.Fatalf("rows %+v", rows)
}
@@ -147,7 +147,7 @@ func TestClaudeRows(t *testing.T) {
// that wrote most), so a sum over rows counts each request once; a
// result without it leaves turns null, never zero.
func TestClaudeRowsTurns(t *testing.T) {
- rows := ClaudeRows([]byte(`{"type":"result","num_turns":7,"modelUsage":{"claude-opus-5-5":{"inputTokens":8,"outputTokens":40},"claude-haiku-5":{"inputTokens":2,"outputTokens":1}}}`))
+ rows := ClaudeRows([]byte(`{"type":"result","num_turns":7,"model_usage_since_last_result":{"claude-opus-5-5":{"inputTokens":8,"outputTokens":40},"claude-haiku-5":{"inputTokens":2,"outputTokens":1}}}`))
if len(rows) != 2 || rows[0].Turns != nil || get(rows[1].Turns) != 7 {
t.Fatalf("rows %+v", rows)
}
@@ -184,3 +184,40 @@ func TestCodexTallyTurns(t *testing.T) {
t.Fatalf("second turn %+v", r)
}
}
+
+// The recorded CLI's modelUsage is the session's running total (in a
+// resumed session too); each result's own use is
+// model_usage_since_last_result. A row is that, never the running
+// total, so a second turn or a resumed session counts only itself.
+func TestClaudeRowsPerResult(t *testing.T) {
+ for file, want := range map[string][][4]int64{
+ // Two turns in one process: 2+3906 written, then 2+3566 read+378 written.
+ "../provider/claude/testdata/stdout.jsonl": {{2, 3, 0, 3906}, {2, 3, 3566, 378}},
+ // A resumed session's turn: its own figures, not the 6/9 so far.
+ "../provider/claude/testdata/resume-stdout.jsonl": {{2, 3, 3919, 63}},
+ } {
+ raw, err := os.ReadFile(file)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var got [][4]int64
+ for _, line := range strings.Split(string(raw), "\n") {
+ if !strings.Contains(line, `"type":"result"`) {
+ continue
+ }
+ rows := ClaudeRows([]byte(line))
+ if len(rows) != 1 || rows[0].Model != "claude-haiku-5-5" || get(rows[0].Turns) != 1 {
+ t.Fatalf("%s: rows %+v", file, rows)
+ }
+ got = append(got, [4]int64{get(rows[0].InputTokens), get(rows[0].OutputTokens), get(rows[0].CachedInputTokens), get(rows[0].CacheWriteTokens)})
+ }
+ if len(got) != len(want) {
+ t.Fatalf("%s: %v, want %v", file, got, want)
+ }
+ for i := range want {
+ if got[i] != want[i] {
+ t.Fatalf("%s result %d: %v, want %v", file, i, got[i], want[i])
+ }
+ }
+ }
+}
diff --git a/internal/thintest/review_contract_test.go b/internal/thintest/review_contract_test.go
index f3e37c62..706a56f8 100644
--- a/internal/thintest/review_contract_test.go
+++ b/internal/thintest/review_contract_test.go
@@ -412,7 +412,7 @@ func TestContractCannotRunReasonsAreDelivered(t *testing.T) {
// an older runner (protocol 1 or 2, whose strict decoder knows no such
// field) gets the same dispatch as before and runs the round fresh.
func TestContractFixRoundFeedbackByProtocol(t *testing.T) {
- for _, proto := range []int{wire.Protocol1, wire.Protocol2, wire.Protocol3} {
+ for _, proto := range []int{wire.Protocol1, wire.Protocol2, wire.ProtocolSpend} {
t.Run(fmt.Sprint(proto), func(t *testing.T) {
r := newToolRig(t)
if proto > wire.Protocol1 {
@@ -439,7 +439,7 @@ func TestContractFixRoundFeedbackByProtocol(t *testing.T) {
if !strings.Contains(fix.Brief, "Fix round 1 of 2") {
t.Fatalf("brief %q", fix.Brief)
}
- if got := strings.Contains(raw, `"feedback"`); got != (proto >= wire.Protocol3) || got && (!strings.HasPrefix(fix.Feedback, "Fix round 1 of 2") || !strings.HasSuffix(fix.Brief, fix.Feedback) || strings.Contains(fix.Feedback, "Fix the README typo")) {
+ if got := strings.Contains(raw, `"feedback"`); got != (proto >= wire.ProtocolSpend) || got && (!strings.HasPrefix(fix.Feedback, "Fix round 1 of 2") || !strings.HasSuffix(fix.Brief, fix.Feedback) || strings.Contains(fix.Feedback, "Fix the README typo")) {
t.Fatalf("protocol %d: feedback sent %v: %s", proto, got, raw)
}
})
diff --git a/internal/thintest/spend_browser_test.go b/internal/thintest/spend_browser_test.go
new file mode 100644
index 00000000..d83a35b7
--- /dev/null
+++ b/internal/thintest/spend_browser_test.go
@@ -0,0 +1,32 @@
+//go:build browser
+
+package thintest
+
+import (
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// The task page's spend follows an answer live: when a question about
+// the task is answered, the total and the Questions line show what the
+// answer used without a reload.
+func TestBrowserSpendFollowsAnswers(t *testing.T) {
+ r := newToolRig(t)
+ base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40)
+ id, _, _ := r.askableTask("b", base, cand)
+ p := openInner(t, r.inst.URL, r.inst.Cookie(), 1280, 900, false, "light", "no-preference")
+ p.open("/tasks/" + id)
+ p.check(`document.querySelector('[data-spend]')===null && document.querySelector('#task-spend')!==null`, "spend before any usage")
+ q, err := r.client.Ask(r.ctx, id, "What did you change?", "", "k1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ r.expect(wire.FrameAsk)
+ r.answer("b-q-run", wire.AnswerReport{TaskID: id, QuestionID: q.ID, Attempt: 1, State: wire.QuestionRunning})
+ used := []wire.Usage{{Provider: "codex", Connection: "codex-a", Model: "gpt-6-astra", Attempt: 1, Outcome: wire.OutcomeReplied, Complete: true, InputTokens: tokens(9000), CachedInputTokens: tokens(4000), OutputTokens: tokens(1000)}}
+ r.answer("b-q-done", wire.AnswerReport{TaskID: id, QuestionID: q.ID, Attempt: 1, State: wire.QuestionAnswered, Text: "I fixed the typo.", Usage: used})
+ p.wait(`document.querySelector('[data-spend]')?.textContent==='Used 10k tokens (4k cached)'`, "the total after the answer")
+ p.wait(`document.querySelector('[data-spend-step="questions"]')?.textContent==='Questions: 10k tokens (4k cached)'`, "the Questions line after the answer")
+}
diff --git a/internal/thintest/spend_pages_test.go b/internal/thintest/spend_pages_test.go
index 358cb3d5..b53139af 100644
--- a/internal/thintest/spend_pages_test.go
+++ b/internal/thintest/spend_pages_test.go
@@ -58,6 +58,26 @@ func TestPagesTaskSpend(t *testing.T) {
t.Fatalf("%s: step lines %d", who, strings.Count(page, "data-spend-step="))
}
}
+ // What a harness did not report makes the sum a lower bound: a Claude
+ // row without its cache-write figure (counted beside input), and a row
+ // whose final usage message was not seen (a cancelled attempt).
+ fix := r.dispatched(wire.SpecialistEngineering, cand, "", 1)
+ r.step("s-f-run", wire.StepReport{TaskID: id, StepID: fix.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: cand})
+ partial := []wire.Usage{
+ {Provider: "claude", Connection: "claude-a", Model: "claude-opus-5-5", Attempt: 1, Outcome: wire.OutcomeCancelled, Complete: true, InputTokens: tokens(1000), CachedInputTokens: tokens(1000), OutputTokens: tokens(0)},
+ {Provider: "claude", Connection: "claude-a", Model: "claude-haiku-5", Attempt: 1, Outcome: wire.OutcomeCancelled, InputTokens: tokens(500), CachedInputTokens: tokens(0), CacheWriteTokens: tokens(0), OutputTokens: tokens(500)},
+ }
+ r.step("s-f-end", wire.StepReport{TaskID: id, StepID: fix.StepID, Attempt: 1, State: wire.StepCancelled, Reason: "cancelled", BaseSHA: cand, Termination: true, Usage: partial})
+ page := r.get(owner, "/tasks/"+id, 200)
+ for _, want := range []string{
+ `<p equipo-quiet data-spend>Used at least 87k tokens (62k cached)</p>`,
+ `<li data-spend-step="` + d.StepID + `">Engineering: 64k tokens (60k cached)</li>`,
+ `<li data-spend-step="` + fix.StepID + `">Engineering, fix round 1: at least 3k tokens (1k cached)</li>`,
+ } {
+ if !strings.Contains(page, want) {
+ t.Fatalf("task page lacks %q:\n%s", want, page)
+ }
+ }
}
// Migration 0059 over an instance whose usage rows predate it: the rows
diff --git a/internal/wire/runners.go b/internal/wire/runners.go
index cd59d1d3..96f6c9d3 100644
--- a/internal/wire/runners.go
+++ b/internal/wire/runners.go
@@ -22,6 +22,9 @@ const (
Protocol2 = 2
Protocol3 = 3
ProtocolCurrent = Protocol3
+ // ProtocolSpend is the first protocol with a fix round's Feedback and
+ // a usage row's Turns; Encode drops both below it.
+ ProtocolSpend = Protocol3
)
// Runner roles. A person's first runner is the primary: the coordinator,
@@ -360,7 +363,10 @@ func Encode(f Frame, protocol int) (Frame, error) {
if err != nil {
return Frame{}, err
}
- changed := downgrade3(body)
+ changed := false
+ if protocol < ProtocolSpend {
+ changed = downgradeSpend(body)
+ }
if protocol < Protocol2 {
changed = downgrade(body) || changed
}
@@ -375,9 +381,9 @@ func Encode(f Frame, protocol int) (Frame, error) {
return f, nil
}
-// downgrade3 clears a body's protocol 3 fields (omitempty, so absent
-// once zero). It reports whether any was set.
-func downgrade3(body any) bool {
+// downgradeSpend clears a body's ProtocolSpend fields (omitempty, so
+// absent once zero). It reports whether any was set.
+func downgradeSpend(body any) bool {
turns := func(rows []Usage) bool {
set := false
for i := range rows {
diff --git a/internal/wire/runners_test.go b/internal/wire/runners_test.go
index 78e7145f..10209e71 100644
--- a/internal/wire/runners_test.go
+++ b/internal/wire/runners_test.go
@@ -182,7 +182,7 @@ func TestEncodeProtocol2DropsProtocol3Fields(t *testing.T) {
t.Fatal(err)
}
want, _ := wire.NewFrame("f1", c.kind, c.prev)
- if same, err := wire.Encode(f, wire.Protocol3); err != nil || !bytes.Equal(same.Data, f.Data) {
+ if same, err := wire.Encode(f, wire.ProtocolSpend); err != nil || !bytes.Equal(same.Data, f.Data) {
t.Fatalf("%s changed at protocol 3: %v", c.kind, err)
}
for _, p := range []int{wire.Protocol2, wire.Protocol1} {