Ledger rules across attempts; reworded writes and fresh reads tested
The per-kind rules hold a later attempt of a turn to what earlier attempts made; within one attempt only an exact repeat replays, so one message may still record two tasks (applying the rules within an attempt folded the review tests' second task into the first). A write enters the ledger only when it made something (record_task answering with similar tasks does not). Contract: a reworded record_task, a paraphrased question, a reworded start and the same add_project are answered replayed with one task, one card and one step; status after add_project is fresh. Headless F2 now rewords every write in the new attempt (three folded by the instance, two answered by the runner's record) and F2b checks the new attempt's status is fresh.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
5 files changed,
+158
−68
internal/equipo/chat/tools.go+52 −39internal/fakeclaude/fake.go+9 −0internal/headless/connections_test.go+17 −7internal/thintest/connections_contract_test.go+62 −20internal/wire/frames.go+18 −2
Intent
diff --git a/internal/equipo/chat/tools.go b/internal/equipo/chat/tools.go| index 54ee8a7e..149a7a62 100644 |
| --- a/internal/equipo/chat/tools.go |
| +++ b/internal/equipo/chat/tools.go |
| @@ -54,11 +54,10 @@ func (t *txn) toolCall(l Lease, v *wire.ToolCall) error { |
| if !errors.Is(err, gorm.ErrRecordNotFound) { |
| return err |
| } |
| - // 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) |
| + // The turn's mutation ledger (spec §3 step 4): a mutation an earlier |
| + // attempt of the turn made is not made again in any wording; its |
| + // stored result answers, replayed. Reads always run fresh. |
| + op, err := t.mutationOp(person, v) |
| if err != nil { |
| return err |
| } |
| @@ -94,8 +93,9 @@ func (t *txn) toolCall(l Lease, v *wire.ToolCall) error { |
| } |
| res.CallID, res.Person = v.CallID, person |
| raw, _ := json.Marshal(res) |
| - if res.IsError { |
| - // A refused write made no mutation: a later attempt may make it. |
| + if res.IsError || !mutated(v.Name, res.Code) { |
| + // A refused write, or one that made nothing (record_task answering |
| + // with similar tasks), is not in the ledger: a later call 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 { |
| @@ -104,48 +104,61 @@ func (t *txn) toolCall(l Lease, v *wire.ToolCall) error { |
| 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) { |
| +// mutationOp is the ledger entry a designated mutation makes, kind and |
| +// target (spec §3 step 4), or "" for any other tool, which runs fresh. |
| +// The rules hold a later attempt of the turn to what earlier attempts |
| +// made, whatever its wording: one question card; the n-th record_task of |
| +// the attempt is the n-th task the turn recorded; start and cancel once |
| +// per task; a project once per name, added or created; the home once per |
| +// person; a finding once per task and normalised text. Within one |
| +// attempt only an exact repeat (the same call id) replays, so one |
| +// message may still record two tasks. |
| +func (t *txn) mutationOp(person string, v *wire.ToolCall) (string, error) { |
| + kind, ok := wire.MutationKinds[v.Name] |
| + if !ok { |
| + return "", nil |
| + } |
| var a struct { |
| Task string `json:"task"` |
| Repo string `json:"repo"` |
| + Text string `json:"text"` |
| } |
| _ = json.Unmarshal(v.Args, &a) |
| - switch v.Name { |
| - case wire.ToolAskPerson: |
| - return "ask", nil |
| - case wire.ToolSetProjectHome: |
| - return "home", nil |
| - case wire.ToolRecordTask: |
| + switch kind { |
| + case "ask": |
| + return kind, nil |
| + case "task_record": |
| 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 |
| + err := t.db.Model(&toolCallRecord{}).Where("turn_id = ? AND attempt = ? AND op LIKE ?", v.TurnID, v.Attempt, "task_record#%").Count(&n).Error |
| + return kind + "#" + strconv.FormatInt(n+1, 10), err |
| + case "home": |
| + return kind + ":" + person, nil |
| + case "task_start", "task_cancel": |
| + return kind + ":" + a.Task, nil |
| + case "project", "project_create": |
| + return "project:" + ProjectName(a.Repo), nil |
| + case "finding": |
| + return kind + ":" + a.Task + ":" + strings.Join(strings.Fields(strings.ToLower(a.Text)), " "), nil |
| } |
| return "", nil |
| } |
| +// madeCodes are the results that show a mutation happened, for the kinds |
| +// whose result can also be "nothing done". |
| +var madeCodes = map[string][]string{ |
| + wire.ToolRecordTask: {"recorded"}, |
| + wire.ToolStartTask: {"started"}, |
| + wire.ToolAskPerson: {"asked"}, |
| + wire.ToolAddFinding: {"finding"}, |
| + wire.ToolCreateProject: {"create"}, |
| + wire.ToolAddProject: {"added", "exists"}, |
| +} |
| + |
| +func mutated(tool, code string) bool { |
| + codes, ok := madeCodes[tool] |
| + return !ok || slices.Contains(codes, code) |
| +} |
| + |
| func argsHash(raw json.RawMessage) string { |
| var v any |
| if json.Unmarshal(raw, &v) == nil { |
diff --git a/internal/fakeclaude/fake.go b/internal/fakeclaude/fake.go| index bef2af89..351e4f90 100644 |
| --- a/internal/fakeclaude/fake.go |
| +++ b/internal/fakeclaude/fake.go |
| @@ -732,6 +732,15 @@ func (f *fake) serve(stdin io.Reader, stdout, stderr io.Writer) int { |
| emit(map[string]any{"type": "stream_event", "session_id": f.session, "parent_tool_use_id": nil, "event": map[string]any{"type": "content_block_start", "index": 0, "content_block": map[string]any{"type": "tool_use", "id": id, "name": "mcp__equipo__" + m[1], "input": map[string]any{}}}, "uuid": fmt.Sprintf("tool-%d-%d", turn, i)}) |
| } |
| input := toolInput(m[1], strings.NewReplacer("$task", f.lastTask, "$similar", f.lastSimilar).Replace(m[2])) |
| + // reword: each account words its writes its own way, as another |
| + // model taking the turn over would. |
| + if strings.Contains(newest, "reword") { |
| + for _, k := range []string{"question", "title", "brief"} { |
| + if v, ok := input[k].(string); ok { |
| + input[k] = v + " (as " + accountEmail() + " puts it)" |
| + } |
| + } |
| + } |
| if m[1] == "write_note" && strings.HasPrefix(strings.TrimSpace(m[2]), "+") { |
| input = f.keepAll(fmt.Sprintf("toolu_fake_%d_%d_read", turn, i), input) |
| } |
diff --git a/internal/headless/connections_test.go b/internal/headless/connections_test.go| index 70ff79b7..d11890ec 100644 |
| --- a/internal/headless/connections_test.go |
| +++ b/internal/headless/connections_test.go |
| @@ -598,7 +598,9 @@ func connQuotaAfterWrites(t *testing.T, env *Env, inst *thintest.Instance, r *lo |
| r.addAccount(t, "claude", "claude-2", second) |
| r.start(t) |
| s := open(t, env) |
| - text := "Please fix the typo.\nlimitafter:" + thintest.Owner + "\ntool:add_project:oficina/sample\ntool:record_task:oficina/sample|Fix the README typo|teh\ntool:start_task:$task|Fix it. reviewsleep:60000 edit:README.md|teh panes|the panes\ntool:ask_person:Which colour?|Red|Blue\ntool:set_project_home:oficina" |
| + // reword: the new attempt words every write differently; status runs |
| + // first and last (F2b: the second attempt's status is fresh). |
| + text := "Please fix the typo. reword\nlimitafter:" + thintest.Owner + "\ntool:status\ntool:add_project:oficina/sample\ntool:record_task:oficina/sample|Fix the README typo|teh\ntool:start_task:$task|Fix it. reviewsleep:60000 edit:README.md|teh panes|the panes\ntool:ask_person:Which colour?|Red|Blue\ntool:set_project_home:oficina\ntool:status" |
| sent := s.send(t, text) |
| m := replyOf(t, s, sent.Turn.ID) |
| turn := s.conv.Turns[sent.Turn.ID] |
| @@ -608,6 +610,11 @@ func connQuotaAfterWrites(t *testing.T, env *Env, inst *thintest.Instance, r *lo |
| if !strings.Contains(m.Text, "(earlier effects in context)") { |
| t.Fatalf("the new attempt was not told what was done: %q", m.Text) |
| } |
| + // F2b: the new attempt's first status is fresh: the project added in |
| + // the first attempt is in it. |
| + if _, after, ok := strings.Cut(m.Text, "[status: "); !ok || !strings.Contains(strings.SplitN(after, "[add_project", 2)[0], `"projects":[{`) { |
| + t.Fatalf("status was not fresh: %q", m.Text) |
| + } |
| time.Sleep(2 * time.Second) |
| snap, err := env.Client.Snapshot(s.ctx) |
| if err != nil { |
| @@ -615,7 +622,7 @@ func connQuotaAfterWrites(t *testing.T, env *Env, inst *thintest.Instance, r *lo |
| } |
| tasks, steps, questions, projects := 0, 0, 0, 0 |
| for _, k := range snap.Tasks { |
| - if k.Title == "Fix the README typo" { |
| + if strings.HasPrefix(k.Title, "Fix the README typo") { |
| tasks++ |
| for _, st := range k.Steps { |
| if st.Specialist == wire.SpecialistEngineering { |
| @@ -630,17 +637,20 @@ func connQuotaAfterWrites(t *testing.T, env *Env, inst *thintest.Instance, r *lo |
| } |
| } |
| for _, p := range snap.Projects { |
| - if p.Repo == "amadan.net/oficina/sample" || strings.HasSuffix(p.Repo, "oficina/sample") { |
| + if strings.HasSuffix(p.Repo, "oficina/sample") { |
| projects++ |
| } |
| } |
| if tasks != 1 || steps != 1 || questions != 1 || projects != 1 { |
| t.Fatalf("effects ran again: %d tasks, %d steps, %d question cards, %d projects", tasks, steps, questions, projects) |
| } |
| - var effects int |
| - _ = inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_tool_calls WHERE turn_id = ? AND name = 'record_task'", sent.Turn.ID).Scan(&effects) |
| - if effects != 1 { |
| - t.Fatalf("record_task reached the instance %d times", effects) |
| + // The reworded writes (record_task, start_task, ask_person) reached |
| + // the instance and were folded there by kind; the identical ones |
| + // (add_project, set_project_home) the runner answered from its record. |
| + var replayed int |
| + _ = inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_tool_calls WHERE turn_id = ? AND attempt = 2 AND result LIKE '%\"replayed\":true%'", sent.Turn.ID).Scan(&replayed) |
| + if replayed != 3 { |
| + t.Fatalf("%d reworded writes were folded by the ledger", replayed) |
| } |
| } |
diff --git a/internal/thintest/connections_contract_test.go b/internal/thintest/connections_contract_test.go| index bb8f1187..ebf16100 100644 |
| --- a/internal/thintest/connections_contract_test.go |
| +++ b/internal/thintest/connections_contract_test.go |
| @@ -2,6 +2,7 @@ package thintest |
| import ( |
| "database/sql" |
| + "encoding/json" |
| "strings" |
| "testing" |
| "time" |
| @@ -210,16 +211,34 @@ func TestContractHeldTurnAndSwitch(t *testing.T) { |
| } |
| // TestContractWritesReplayAcrossAttempts: after a turn moves to a new |
| -// attempt, a write the earlier attempt made (same tool, same canonical |
| -// arguments) is answered with its stored result, marked replayed, and |
| -// does nothing again; a different write runs; a call from the old |
| -// attempt is refused. |
| +// attempt, the instance's mutation ledger holds it to what the earlier |
| +// attempt did, whatever the new wording (spec §3 step 4): a reworded |
| +// record_task attaches to the task already recorded, a paraphrased |
| +// question returns the card already asked, a reworded start of the same |
| +// task starts nothing; each answers with the stored result, replayed. A |
| +// further record_task records anew, a finding with other words is made, |
| +// and reads run fresh: status after add_project sees the project. |
| func TestContractWritesReplayAcrossAttempts(t *testing.T) { |
| r := newToolRig(t) |
| + before := r.call("s1", wire.ToolStatus, map[string]string{}) |
| added := r.call("a1", wire.ToolAddProject, map[string]string{"repo": "oficina/sample"}) |
| recorded := r.call("r1", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Fix the typo", "brief": "teh"}) |
| - if added.IsError || recorded.IsError || added.Replayed || recorded.Replayed { |
| - t.Fatalf("first attempt %+v %+v", added, recorded) |
| + var rec struct{ Task string } |
| + json.Unmarshal([]byte(recorded.Text), &rec) |
| + asked := r.call("q1", wire.ToolAskPerson, map[string]any{"question": "Which colour?", "options": []string{"Red", "Blue"}}) |
| + started := r.call("t1", wire.ToolStartTask, map[string]string{"task": rec.Task, "brief": "Fix teh."}) |
| + for _, res := range []wire.ToolResult{added, recorded, asked, started} { |
| + if res.IsError || res.Replayed { |
| + t.Fatalf("first attempt %+v", res) |
| + } |
| + } |
| + projects := func(text string) int { |
| + var v struct{ Projects []any } |
| + json.Unmarshal([]byte(text), &v) |
| + return len(v.Projects) |
| + } |
| + if projects(before.Text) != 0 { |
| + t.Fatalf("status before add_project already has it: %s", before.Text) |
| } |
| r.runner.Send(r.ctx, "r-wait", wire.FrameTurn, wire.TurnReport{TurnID: r.turn, Attempt: 1, State: wire.TurnWaiting, Reason: "limited"}) |
| r.runner.Send(r.ctx, "r-run2", wire.FrameTurn, wire.TurnReport{TurnID: r.turn, Attempt: 2, State: wire.TurnRunning}) |
| @@ -227,30 +246,53 @@ func TestContractWritesReplayAcrossAttempts(t *testing.T) { |
| return c.Turns[r.turn].Attempt == 2 && c.Turns[r.turn].State == wire.TurnRunning |
| }) |
| r.attempt = 2 |
| - again := r.call("r2", wire.ToolRecordTask, map[string]string{"title": "Fix the typo", "brief": "teh", "repo": "oficina/sample"}) |
| - if !again.Replayed || again.Text != recorded.Text { |
| - t.Fatalf("record_task again %+v", again) |
| - } |
| - addedAgain := r.call("a2", wire.ToolAddProject, map[string]string{"repo": "oficina/sample"}) |
| - if !addedAgain.Replayed || addedAgain.Text != added.Text { |
| - t.Fatalf("add_project again %+v", addedAgain) |
| + // Reads run fresh: status sees the project added in attempt 1. |
| + if after := r.call("s2", wire.ToolStatus, map[string]string{}); after.Replayed || projects(after.Text) != 1 { |
| + t.Fatalf("status was not fresh: %+v", after) |
| + } |
| + for name, call := range map[string]func() wire.ToolResult{ |
| + "record_task reworded": func() wire.ToolResult { |
| + return r.call("r2", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Correct the README misspelling", "brief": "The README says teh."}) |
| + }, |
| + "ask_person paraphrased": func() wire.ToolResult { |
| + return r.call("q2", wire.ToolAskPerson, map[string]any{"question": "What colour would you like?", "options": []string{"Blue", "Red", "Green"}}) |
| + }, |
| + "start_task reworded": func() wire.ToolResult { |
| + return r.call("t2", wire.ToolStartTask, map[string]string{"task": rec.Task, "brief": "Please correct the spelling."}) |
| + }, |
| + "add_project again": func() wire.ToolResult { |
| + return r.call("a2", wire.ToolAddProject, map[string]string{"repo": "oficina/sample"}) |
| + }, |
| + } { |
| + if res := call(); !res.Replayed { |
| + t.Fatalf("%s ran again: %+v", name, res) |
| + } |
| } |
| - other := r.call("r3", wire.ToolRecordTask, map[string]any{"repo": "oficina/sample", "title": "Another problem entirely", "brief": "something else", "separate": true}) |
| - if other.Replayed || other.IsError { |
| - t.Fatalf("a different write was replayed: %+v", other) |
| + var cards int |
| + snap, _ := r.client.Snapshot(r.ctx) |
| + for _, c := range snap.Cards { |
| + if c.Kind == wire.CardQuestion { |
| + cards++ |
| + } |
| } |
| tasks, err := r.client.Tasks(r.ctx) |
| if err != nil { |
| t.Fatal(err) |
| } |
| - n := 0 |
| + n, steps := 0, 0 |
| for _, k := range tasks.Items { |
| - if k.Title == "Fix the typo" { |
| + if strings.Contains(k.Title, "typo") || strings.Contains(k.Title, "misspelling") { |
| n++ |
| + steps += len(k.Steps) |
| } |
| } |
| - if n != 1 { |
| - t.Fatalf("%d tasks for one record_task", n) |
| + if n != 1 || cards != 1 || steps != 1 { |
| + t.Fatalf("%d tasks, %d question cards, %d steps", n, cards, steps) |
| + } |
| + // Beyond what the earlier attempt did, a write is made. |
| + other := r.call("r3", wire.ToolRecordTask, map[string]any{"repo": "oficina/sample", "title": "Another problem entirely", "brief": "something else", "separate": true}) |
| + if other.Replayed || other.IsError { |
| + t.Fatalf("a new write was folded: %+v", other) |
| } |
| r.attempt = 1 |
| stale := r.call("r4", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Third", "brief": "x"}) |
diff --git a/internal/wire/frames.go b/internal/wire/frames.go| index 95795d34..064d01fb 100644 |
| --- a/internal/wire/frames.go |
| +++ b/internal/wire/frames.go |
| @@ -450,8 +450,24 @@ type ToolResult struct { |
| Replayed bool `json:"replayed"` |
| } |
| -// WriteTools change something outside the coordinator's session: a |
| -// later attempt of the same turn never runs one of them twice. |
| +// MutationKinds are the designated mutating tools and the kind of |
| +// operation each makes (Connections spec §3 step 4). The instance keeps |
| +// them in the turn's mutation ledger and holds any later call of the |
| +// turn to them, whatever its wording; every other tool runs fresh. |
| +var MutationKinds = map[string]string{ |
| + ToolAddProject: "project", |
| + ToolCreateProject: "project_create", |
| + ToolSetProjectHome: "home", |
| + ToolRecordTask: "task_record", |
| + ToolStartTask: "task_start", |
| + ToolCancelTask: "task_cancel", |
| + ToolAddFinding: "finding", |
| + ToolAskPerson: "ask", |
| +} |
| + |
| +// WriteTools change something outside the coordinator's session: the |
| +// runner replays an exact repeat of one in a later attempt from its own |
| +// record. |
| var WriteTools = []string{ToolAddProject, ToolCreateProject, ToolSetProjectHome, ToolAskPerson, ToolWriteNote, ToolRecordTask, ToolAddFinding, ToolStartTask, ToolCancelTask, ToolAddReport, ToolProjectCreated} |
| // ActivityReport is what the coordinator started doing: thinking, or a |