oficina / equipo Public

Mutation ledger by kind and target; verified Codex baselines

Astra round 2: the instance holds a later attempt of a turn to the
mutations an earlier attempt completed, whatever their wording: one
question card per turn; the n-th record_task of an attempt is the n-th
task the turn recorded; start, cancel and a report once per task; a
project once per repository; the project home once per turn; a finding
only for the same arguments. Reads and write_note run fresh. The
runner's ledger replays exact repeats only (and reconciles unseen
answers under their call id).

A Codex attempt's usage is complete only on a verified base (a fresh
thread, or the previous turn's last total seen by this process); a
resumed thread's first turn is counted from its first notice and marked
complete: false (no thread token-usage read in 0.165.0).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev e4cc2942c7d8f691f5037a810923361ad6f5e73e parent 5186469
8 files changed, +123 −35
  • internal/equipo/chat/projects.go +8 −4
  • internal/equipo/chat/tools.go +58 −6
  • internal/equipo/migrations/0049_thin_connections.sql +2 −0
  • internal/equipo/migrations/schema.sql +2 −1
  • internal/runner/connect/usage.go +30 −9
  • internal/runner/connect/usage_test.go +14 −6
  • internal/runner/thin/codex.go +1 −1
  • internal/runner/thin/effects.go +8 −8
diff --git a/internal/equipo/chat/projects.go b/internal/equipo/chat/projects.go
index d3f3a7a4..5d961204 100644
--- a/internal/equipo/chat/projects.go
+++ b/internal/equipo/chat/projects.go
@@ -68,12 +68,16 @@ func (cardRecord) TableName() string { return "chat_cards" }
type toolCallRecord struct {
CallID string `gorm:"primaryKey"`
Person string
- TurnID string
+ TurnID string `gorm:"index:chat_tool_call_turn,priority:1"`
// Attempt and ArgsHash bind a replay to the same call: same turn,
// attempt, tool and arguments.
- Attempt int64
- ArgsHash string
- Name string
+ Attempt int64
+ ArgsHash string
+ Name string
+ // Op is the mutation a completed write made, by kind and target
+ // ("ask", "record#2", "start:<task>", "add:<repo>"): the turn's
+ // mutation ledger, which a later attempt of the turn is held to.
+ Op string `gorm:"index:chat_tool_call_turn,priority:2"`
Result string
CreatedAt time.Time
}
diff --git a/internal/equipo/chat/tools.go b/internal/equipo/chat/tools.go
index df1458e1..54ee8a7e 100644
--- a/internal/equipo/chat/tools.go
+++ b/internal/equipo/chat/tools.go
@@ -54,11 +54,17 @@ func (t *txn) toolCall(l Lease, v *wire.ToolCall) error {
if !errors.Is(err, gorm.ErrRecordNotFound) {
return err
}
- // The same write in an earlier attempt of this turn (spec §3 step 4):
- // its stored result, replayed, never a second effect.
- if slices.Contains(wire.WriteTools, v.Name) {
+ // The turn's mutation ledger (spec §3 step 4, Astra round 2): a
+ // mutation an earlier attempt of this turn completed is not made again
+ // in another wording; its stored result answers, replayed. Reads
+ // always run fresh.
+ op, err := t.mutationOp(v)
+ if err != nil {
+ return err
+ }
+ if op != "" {
var earlier toolCallRecord
- err = t.db.Where("turn_id = ? AND person = ? AND name = ? AND args_hash = ? AND attempt < ?", v.TurnID, person, v.Name, args, v.Attempt).Order("created_at").First(&earlier).Error
+ err = t.db.Where("turn_id = ? AND person = ? AND op = ? AND attempt < ?", v.TurnID, person, op, v.Attempt).Order("created_at").First(&earlier).Error
if err == nil {
r, err := t.ownTurn(l, v.TurnID)
if err != nil && !errors.Is(err, ErrNotFound) && !errors.Is(err, ErrForbidden) {
@@ -73,7 +79,7 @@ func (t *txn) toolCall(l Lease, v *wire.ToolCall) error {
}
res.CallID, res.Person = v.CallID, person
raw, _ := json.Marshal(res)
- if err := t.db.Create(&toolCallRecord{CallID: v.CallID, Person: person, TurnID: v.TurnID, Attempt: v.Attempt, ArgsHash: args, Name: v.Name, Result: string(raw), CreatedAt: t.now()}).Error; err != nil {
+ if err := t.db.Create(&toolCallRecord{CallID: v.CallID, Person: person, TurnID: v.TurnID, Attempt: v.Attempt, ArgsHash: args, Name: v.Name, Op: op, Result: string(raw), CreatedAt: t.now()}).Error; err != nil {
return err
}
return t.command(person, wire.FrameToolResult, res)
@@ -88,12 +94,58 @@ func (t *txn) toolCall(l Lease, v *wire.ToolCall) error {
}
res.CallID, res.Person = v.CallID, person
raw, _ := json.Marshal(res)
- if err := t.db.Create(&toolCallRecord{CallID: v.CallID, Person: person, TurnID: v.TurnID, Attempt: v.Attempt, ArgsHash: args, Name: v.Name, Result: string(raw), CreatedAt: t.now()}).Error; err != nil {
+ if res.IsError {
+ // A refused write made no mutation: a later attempt may make it.
+ op = ""
+ }
+ if err := t.db.Create(&toolCallRecord{CallID: v.CallID, Person: person, TurnID: v.TurnID, Attempt: v.Attempt, ArgsHash: args, Name: v.Name, Op: op, Result: string(raw), CreatedAt: t.now()}).Error; err != nil {
return err
}
return t.command(person, wire.FrameToolResult, res)
}
+// mutationOp names the mutation a write makes, by kind and target, so a
+// later attempt of the turn is held to it whatever its wording: one
+// question card per turn; the n-th record_task of an attempt is the n-th
+// task the turn recorded; start, cancel and a report once per task; a
+// project once per repository; the project home once per turn. A finding
+// is held only to the same arguments. Reads, and write_note (it replaces
+// the notebook whole), have none and run every time.
+func (t *txn) mutationOp(v *wire.ToolCall) (string, error) {
+ var a struct {
+ Task string `json:"task"`
+ Repo string `json:"repo"`
+ }
+ _ = json.Unmarshal(v.Args, &a)
+ switch v.Name {
+ case wire.ToolAskPerson:
+ return "ask", nil
+ case wire.ToolSetProjectHome:
+ return "home", nil
+ case wire.ToolRecordTask:
+ var n int64
+ if err := t.db.Model(&toolCallRecord{}).Where("turn_id = ? AND attempt = ? AND op LIKE ?", v.TurnID, v.Attempt, "record#%").Count(&n).Error; err != nil {
+ return "", err
+ }
+ return "record#" + strconv.FormatInt(n+1, 10), nil
+ case wire.ToolStartTask:
+ return "start:" + a.Task, nil
+ case wire.ToolCancelTask:
+ return "cancel:" + a.Task, nil
+ case wire.ToolAddReport:
+ return "report:" + a.Task, nil
+ case wire.ToolAddProject:
+ return "add:" + ProjectName(a.Repo), nil
+ case wire.ToolCreateProject:
+ return "create:" + a.Repo, nil
+ case wire.ToolProjectCreated:
+ return "created:" + a.Repo, nil
+ case wire.ToolAddFinding:
+ return "finding:" + argsHash(v.Args), nil
+ }
+ return "", nil
+}
+
func argsHash(raw json.RawMessage) string {
var v any
if json.Unmarshal(raw, &v) == nil {
diff --git a/internal/equipo/migrations/0049_thin_connections.sql b/internal/equipo/migrations/0049_thin_connections.sql
index dccace2f..e3208141 100644
--- a/internal/equipo/migrations/0049_thin_connections.sql
+++ b/internal/equipo/migrations/0049_thin_connections.sql
@@ -6,3 +6,5 @@ CREATE UNIQUE INDEX chat_usage_key ON chat_usage(turn_id, step_id, attempt, conn
ALTER TABLE chat_messages ADD COLUMN switched text;
ALTER TABLE chat_turns ADD COLUMN connection text;
ALTER TABLE chat_steps ADD COLUMN switched text;
+ALTER TABLE chat_tool_calls ADD COLUMN op text;
+CREATE INDEX chat_tool_call_turn ON chat_tool_calls(turn_id, op);
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql
index 0766edf9..dd7d66ce 100644
--- a/internal/equipo/migrations/schema.sql
+++ b/internal/equipo/migrations/schema.sql
@@ -586,7 +586,8 @@ CREATE TABLE chat_cards (id text PRIMARY KEY, person text, kind text, state text
CREATE INDEX chat_card_person ON chat_cards(person);
CREATE INDEX chat_card_project ON chat_cards(project_id);
CREATE INDEX chat_card_answer ON chat_cards(answer_message);
-CREATE TABLE chat_tool_calls (call_id text PRIMARY KEY, person text, turn_id text, name text, result text, created_at datetime, attempt integer, args_hash text);
+CREATE TABLE chat_tool_calls (call_id text PRIMARY KEY, person text, turn_id text, name text, result text, created_at datetime, attempt integer, args_hash text, op text);
+CREATE INDEX chat_tool_call_turn ON chat_tool_calls(turn_id, op);
CREATE TABLE chat_settings (key text PRIMARY KEY, value text, revision integer, updated_by text, updated_at datetime, unset numeric);
CREATE TABLE chat_coordinators (person text PRIMARY KEY, state text, turn_id text, revision integer, moved_in_at datetime, updated_at datetime);
CREATE TABLE chat_notebooks (person text PRIMARY KEY, entries text, revision integer, updated_at datetime);
diff --git a/internal/runner/connect/usage.go b/internal/runner/connect/usage.go
index 405d4064..c802f707 100644
--- a/internal/runner/connect/usage.go
+++ b/internal/runner/connect/usage.go
@@ -52,12 +52,27 @@ func (b Breakdown) minus(o Breakdown) (Breakdown, bool) {
// seen before it began (the first total after a resume is the baseline),
// so a resent notice changes nothing. A notice for another thread is
// dropped.
+//
+// That baseline is verified only for a fresh thread (zero) or after this
+// process saw the previous turn's last total: the pinned app-server has
+// no read of a thread's token usage, and the first notice after a resume
+// may already include new use (Astra round 2), so an attempt on a resumed
+// thread is recorded complete: false, counted from the first total seen
+// (a lower bound).
type CodexTally struct {
- Thread string
- turn string
- base Breakdown
- cur Breakdown
- seen bool
+ Thread string
+ turn string
+ base Breakdown
+ baseKnown bool
+ verified bool
+ cur Breakdown
+ seen bool
+}
+
+// NewCodexTally starts a tally for a thread: fresh (started here, zero
+// so far) or resumed (its total so far unknown).
+func NewCodexTally(thread string, fresh bool) *CodexTally {
+ return &CodexTally{Thread: thread, baseKnown: fresh, verified: fresh}
}
// CodexNotice decodes a thread/tokenUsage/updated notice.
@@ -81,12 +96,17 @@ func (t *CodexTally) Notice(thread, turn string, total Breakdown) {
return
}
if t.turn != "" && turn == t.turn {
+ if !t.baseKnown {
+ // Nothing before it: this first total is the lower bound's base.
+ t.base, t.baseKnown = total, true
+ }
t.cur, t.seen = total, true
return
}
if !t.seen {
- // Before this attempt's own notices: the thread's running total.
- t.base = total
+ // Before this attempt's own notices (a resume's replay): a base,
+ // not a verified one.
+ t.base, t.baseKnown, t.verified = total, true, false
}
}
@@ -94,7 +114,8 @@ func (t *CodexTally) Notice(thread, turn string, total Breakdown) {
// the total seen so far.
func (t *CodexTally) Begin(turn string) {
if t.seen {
- t.base = t.cur
+ // The previous turn's last total, seen here: a verified base.
+ t.base, t.baseKnown, t.verified = t.cur, true, true
}
t.turn, t.seen, t.cur = turn, false, Breakdown{}
}
@@ -110,7 +131,7 @@ func (t *CodexTally) Row() wire.Usage {
// attempt's own.
d = t.cur
}
- return wire.Usage{InputTokens: d.Input, CachedInputTokens: d.Cached, CacheWriteTokens: d.CacheWrite, OutputTokens: d.Output, ReasoningOutputTokens: d.Reasoning, Complete: true}
+ return wire.Usage{InputTokens: d.Input, CachedInputTokens: d.Cached, CacheWriteTokens: d.CacheWrite, OutputTokens: d.Output, ReasoningOutputTokens: d.Reasoning, Complete: t.verified}
}
// ClaudeRows reads a stream-json result: one row per model in
diff --git a/internal/runner/connect/usage_test.go b/internal/runner/connect/usage_test.go
index 9c327911..7dfec230 100644
--- a/internal/runner/connect/usage_test.go
+++ b/internal/runner/connect/usage_test.go
@@ -41,7 +41,7 @@ func TestCodexTallyRecorded(t *testing.T) {
t.Fatal(err)
}
defer f.Close()
- tally := &CodexTally{Thread: "thread-1"}
+ tally := NewCodexTally("thread-1", true)
tally.Begin("turn-1")
scan := bufio.NewScanner(f)
scan.Buffer(make([]byte, 0, 1<<20), 1<<20)
@@ -66,7 +66,7 @@ func TestCodexTallyRecorded(t *testing.T) {
func TestCodexTally(t *testing.T) {
// A fresh process resumes a thread: the first total after
// thread/resume (the previous turn's) is the baseline.
- tally := &CodexTally{Thread: "th"}
+ tally := NewCodexTally("th", false)
feed(t, tally, notice("th", "old", `{"inputTokens":1000,"outputTokens":100,"cachedInputTokens":800}`))
tally.Begin("t2")
feed(t, tally,
@@ -76,7 +76,7 @@ func TestCodexTally(t *testing.T) {
// A resent frame changes nothing.
notice("th", "t2", `{"inputTokens":1700,"outputTokens":150,"cachedInputTokens":1200}`))
row := tally.Row()
- if get(row.InputTokens) != 700 || get(row.OutputTokens) != 50 || get(row.CachedInputTokens) != 400 || !row.Complete || row.CacheWriteTokens != nil {
+ if get(row.InputTokens) != 700 || get(row.OutputTokens) != 50 || get(row.CachedInputTokens) != 400 || row.Complete || row.CacheWriteTokens != nil {
t.Fatalf("resumed turn %+v", row)
}
// The next turn in the same process starts from that total.
@@ -85,11 +85,19 @@ func TestCodexTally(t *testing.T) {
t.Fatalf("no notice yet: %+v", r)
}
feed(t, tally, notice("th", "t3", `{"inputTokens":1800,"outputTokens":160,"cachedInputTokens":1250}`))
- if r := tally.Row(); get(r.InputTokens) != 100 || get(r.OutputTokens) != 10 {
- t.Fatalf("next turn %+v", r)
+ if r := tally.Row(); get(r.InputTokens) != 100 || get(r.OutputTokens) != 10 || !r.Complete {
+ t.Fatalf("next turn (verified base) %+v", r)
+ }
+ // Resumed with no notice before the turn: counted from its first
+ // notice, a lower bound, never the thread's whole total.
+ cold := NewCodexTally("th", false)
+ cold.Begin("t9")
+ feed(t, cold, notice("th", "t9", `{"inputTokens":14054,"outputTokens":96}`), notice("th", "t9", `{"inputTokens":28254,"outputTokens":142}`))
+ if r := cold.Row(); get(r.InputTokens) != 14200 || r.Complete {
+ t.Fatalf("resumed without a base %+v", r)
}
// A total that went back is the attempt's own.
- fresh := &CodexTally{Thread: "new"}
+ fresh := NewCodexTally("new", true)
feed(t, fresh, notice("new", "x", `{"inputTokens":5000,"outputTokens":5}`))
fresh.Begin("y")
feed(t, fresh, notice("new", "y", `{"inputTokens":40,"outputTokens":4}`))
diff --git a/internal/runner/thin/codex.go b/internal/runner/thin/codex.go
index c4e89ab7..3e6d28c2 100644
--- a/internal/runner/thin/codex.go
+++ b/internal/runner/thin/codex.go
@@ -470,7 +470,7 @@ func (c *codexCoordinator) start(ctx context.Context) (err error) {
return errors.Join(provider.ErrPolicy, err)
}
}
- p.tally = &connect.CodexTally{Thread: p.thread}
+ p.tally = connect.NewCodexTally(p.thread, p.fresh)
c.proc = p
return nil
}
diff --git a/internal/runner/thin/effects.go b/internal/runner/thin/effects.go
index 8b130e93..1091458d 100644
--- a/internal/runner/thin/effects.go
+++ b/internal/runner/thin/effects.go
@@ -62,9 +62,10 @@ func (s *State) endEffect(ctx context.Context, turn string, attempt, seq int64,
}
// earlierEffect claims the write an earlier attempt of the turn made that
-// this call repeats: the same tool with the same arguments, else the
-// earliest unclaimed one of that tool. It is claimed for this attempt,
-// so each recorded write answers one call.
+// this call repeats exactly (the same tool, the same canonical
+// arguments). It is claimed for this attempt, so each recorded write
+// answers one call. A write in other words goes to the instance, whose
+// mutation ledger holds the turn to what it already did.
func (s *State) earlierEffect(ctx context.Context, turn string, attempt int64, name string, args json.RawMessage) (effect, bool, error) {
var out effect
found := false
@@ -83,17 +84,16 @@ func (s *State) earlierEffect(ctx context.Context, turn string, attempt int64, n
all = append(all, e)
}
rows.Close()
- if len(all) == 0 {
- return nil
- }
- out, found = all[0], true
want := canonArgs(args)
for _, e := range all {
if e.Args == want {
- out = e
+ out, found = e, true
break
}
}
+ if !found {
+ return nil
+ }
_, err = t.Exec("UPDATE turn_effects SET replayed_in=? WHERE turn_id=? AND attempt=? AND seq=?", attempt, turn, out.Attempt, out.Seq)
return err
})