Gate 1c: stickiness as a rule, replay by name and args, waiting steps
The choice keeps the session's connection while it is eligible (across a restart too, from the connection that answered last); otherwise the most reported headroom, unknown headroom after any figure. The instance answers a write an earlier attempt of the turn made (same tool, same canonical arguments) with its stored result, replayed: true, behind the runner's own ledger. An Engineering step with no eligible connection waits in the queue and goes on when one returns. A reply from another connection than the last one carries the switched line, whether the turn moved or waited. Headless F2 (a limit straight after add_project, record_task, start_task, ask_person and set_project_home: one of each, the new attempt told what was done; failing with both guards removed) and F5 (cancel while waiting); a contract test for the instance replay (failing without it). The migration is 0049 (ux1 takes 0048).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
14 files changed,
+220
−25
internal/equipo/chat/tools.go+28 −0internal/equipo/migrations/{0048_thin_connections.sql => 0049_thin_connections.sql}+0 −0internal/fakeclaude/fake.go+9 −0internal/headless/connections_test.go+66 −0internal/runner/connect/choose.go+17 −13internal/runner/connect/choose_test.go+4 −4internal/runner/thin/effects.go+3 −4internal/runner/thin/engineer.go+8 −1internal/runner/thin/failover.go+11 −0internal/runner/thin/run.go+11 −1internal/thintest/connections_contract_test.go+50 −0internal/thintest/tools_contract_test.go+4 −1internal/wire/frames.go+8 −0internal/wire/wiretest/testdata/frames/tool_result.json+1 −1
CI failed — run details
Intent
diff --git a/internal/equipo/chat/tools.go b/internal/equipo/chat/tools.go| index b41d6ef5..df1458e1 100644 |
| --- a/internal/equipo/chat/tools.go |
| +++ b/internal/equipo/chat/tools.go |
| @@ -54,6 +54,34 @@ 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) { |
| + 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 |
| + if err == nil { |
| + r, err := t.ownTurn(l, v.TurnID) |
| + if err != nil && !errors.Is(err, ErrNotFound) && !errors.Is(err, ErrForbidden) { |
| + return err |
| + } |
| + res := refused("turn_ended", toolTurnEnded) |
| + if err == nil && !wire.Terminal(r.State) && v.Attempt == r.Attempt { |
| + if err := json.Unmarshal([]byte(earlier.Result), &res); err != nil { |
| + return err |
| + } |
| + res.Replayed = true |
| + } |
| + 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 { |
| + return err |
| + } |
| + return t.command(person, wire.FrameToolResult, res) |
| + } |
| + if !errors.Is(err, gorm.ErrRecordNotFound) { |
| + return err |
| + } |
| + } |
| res, err := t.runTool(l, v) |
| if err != nil { |
| return err |
diff --git a/internal/equipo/migrations/0048_thin_connections.sql b/internal/equipo/migrations/0049_thin_connections.sql| similarity index 100% |
| rename from internal/equipo/migrations/0048_thin_connections.sql |
| rename to internal/equipo/migrations/0049_thin_connections.sql |
diff --git a/internal/fakeclaude/fake.go b/internal/fakeclaude/fake.go| index 9f9bd174..bef2af89 100644 |
| --- a/internal/fakeclaude/fake.go |
| +++ b/internal/fakeclaude/fake.go |
| @@ -754,6 +754,14 @@ func (f *fake) serve(stdin io.Reader, stdout, stderr io.Writer) int { |
| } |
| reply += fmt.Sprintf(" [%s: %s]", m[1], text) |
| } |
| + // limitafter:<email>: the tools ran, then the limit hit. |
| + if m := limitAfterWord.FindStringSubmatch(newest); m != nil && m[1] == accountEmail() { |
| + refuse() |
| + continue |
| + } |
| + if strings.Contains(prompt, "Already done in this turn") { |
| + reply += " (earlier effects in context)" |
| + } |
| if m := pauseWord.FindStringSubmatch(newest); m != nil { |
| ms, _ := strconv.Atoi(m[1]) |
| time.Sleep(time.Duration(ms) * time.Millisecond) |
| @@ -793,6 +801,7 @@ var moveInPause = regexp.MustCompile(`movein-pause:([0-9]+)`) |
| // limitWord is limit:<email>. |
| var limitWord = regexp.MustCompile(`\blimit:([^\s|]+@[^\s|]+[a-z])`) |
| +var limitAfterWord = regexp.MustCompile(`\blimitafter:([^\s|]+@[^\s|]+[a-z])`) |
| var noResetWord = regexp.MustCompile(`\blimitnoreset:([^\s|]+@[^\s|]+[a-z])`) |
| var authWord = regexp.MustCompile(`\bauthrefused:([^\s|]+@[^\s|]+[a-z])`) |
diff --git a/internal/headless/connections_test.go b/internal/headless/connections_test.go| index 85b01fe2..95a3ec2f 100644 |
| --- a/internal/headless/connections_test.go |
| +++ b/internal/headless/connections_test.go |
| @@ -104,6 +104,7 @@ func TestHeadlessConnections(t *testing.T) { |
| {"C1_claude_failover", connClaudeFailover}, |
| {"A6_A7_failure_kinds", connFailureKinds}, |
| {"A5_cancel_and_sign_out", connCancelAndSignOut}, |
| + {"F2_quota_after_writes", connQuotaAfterWrites}, |
| {"C2_codex_coordinator", connCodexCoordinator}, |
| {"C3_codex_device_code", connCodexDeviceCode}, |
| {"C4_claude_sign_in", connClaudeSignIn}, |
| @@ -203,6 +204,8 @@ func connCodexCoordinator(t *testing.T, env *Env, inst *thintest.Instance, r *lo |
| func connCodexDeviceCode(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { |
| r.start(t) |
| s := open(t, env) |
| + // Claude answers first: the conversation is on Claude. |
| + replyOf(t, s, s.send(t, "Hello first.").Turn.ID) |
| approve := filepath.Join(r.root, "accounts", ".fake-device.json") |
| os.Remove(approve) |
| c, err := env.Client.Connect(s.ctx, wire.Connect{Provider: "codex"}) |
| @@ -361,6 +364,14 @@ func connEngineeringFailover(t *testing.T, env *Env, inst *thintest.Instance, r |
| func connNoConnection(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { |
| r.start(t) |
| s := open(t, env) |
| + replyOf(t, s, s.send(t, "Hello first.").Turn.ID) |
| + // F5: a cancel while the turn waits ends it, cancelled. |
| + first := s.send(t, "Hello. limit:"+thintest.Owner) |
| + s.wait(t, "first waits", time.Minute, func(cv *thintest.Conversation) bool { return cv.Turns[first.Turn.ID].State == wire.TurnWaiting }) |
| + if _, err := env.Client.Cancel(s.ctx, first.Turn.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + s.waitTurn(t, first.Turn.ID, wire.TurnCancelled) |
| sent := s.send(t, "Hello. limit:"+thintest.Owner) |
| s.wait(t, "held", time.Minute, func(cv *thintest.Conversation) bool { |
| v := cv.Turns[sent.Turn.ID] |
| @@ -577,3 +588,58 @@ func connCancelAndSignOut(t *testing.T, env *Env, inst *thintest.Instance, r *lo |
| t.Fatal("signed out, but the binding or home stayed") |
| } |
| } |
| + |
| +// F2: the limit hits straight after the turn's writes (add_project, |
| +// record_task, start_task, ask_person, set_project_home). The new attempt |
| +// on the other account is told what was done, its repeats are answered |
| +// from the record, and there is one project, one task, one step and one |
| +// question card. |
| +func connQuotaAfterWrites(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { |
| + 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" |
| + sent := s.send(t, text) |
| + m := replyOf(t, s, sent.Turn.ID) |
| + turn := s.conv.Turns[sent.Turn.ID] |
| + if turn.Attempt != 2 || turn.Connection != "claude-2" || m.Switched == nil { |
| + t.Fatalf("turn %+v switched %+v", turn, m.Switched) |
| + } |
| + if !strings.Contains(m.Text, "(earlier effects in context)") { |
| + t.Fatalf("the new attempt was not told what was done: %q", m.Text) |
| + } |
| + time.Sleep(2 * time.Second) |
| + snap, err := env.Client.Snapshot(s.ctx) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + tasks, steps, questions, projects := 0, 0, 0, 0 |
| + for _, k := range snap.Tasks { |
| + if k.Title == "Fix the README typo" { |
| + tasks++ |
| + for _, st := range k.Steps { |
| + if st.Specialist == wire.SpecialistEngineering { |
| + steps++ |
| + } |
| + } |
| + } |
| + } |
| + for _, c := range snap.Cards { |
| + if c.Kind == wire.CardQuestion { |
| + questions++ |
| + } |
| + } |
| + for _, p := range snap.Projects { |
| + if p.Repo == "amadan.net/oficina/sample" || 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) |
| + } |
| +} |
diff --git a/internal/runner/connect/choose.go b/internal/runner/connect/choose.go| index 708446f0..3f908080 100644 |
| --- a/internal/runner/connect/choose.go |
| +++ b/internal/runner/connect/choose.go |
| @@ -27,7 +27,6 @@ const ( |
| const ( |
| StateHealthy = "healthy" |
| StateLimited = "limited" |
| - lowHeadroom = 0.9 |
| coolOff = 15 * time.Minute |
| coolOffLonger = time.Hour |
| ) |
| @@ -74,13 +73,14 @@ type Choice struct { |
| } |
| // Choose picks one connection for role from the person's own candidates |
| -// (in the runner's configured order): capable of the role, usable now, not |
| -// in avoid; then the one with headroom left (reported use under 90%, or |
| -// unreported) before one nearly spent; ties go to current (the |
| -// connection that ran this session last, so sessions do not hop for |
| -// nothing), then to the configured order. Reported use is compared in |
| -// those two bands only, so a few points' difference never moves a |
| -// conversation to a fresh session. ok is false when nothing can run it. |
| +// (in the runner's configured order), spec §3: capable of the role, |
| +// usable now (healthy, or limited with its reset passed; never one |
| +// connecting or unchecked), not in avoid. The current binding, when it is |
| +// eligible, is kept: stickiness is a rule, a session leaves its |
| +// connection only on failure. Otherwise the one with the most reported |
| +// headroom, a connection whose provider reported nothing ranking below |
| +// any with a figure, then the configured order. ok is false when nothing |
| +// can run it. |
| func Choose(cs []Candidate, role, current string, avoid []string, now time.Time) (Choice, bool) { |
| var usable []Candidate |
| for _, c := range cs { |
| @@ -94,19 +94,23 @@ func Choose(cs []Candidate, role, current string, avoid []string, now time.Time) |
| if len(usable) == 1 { |
| return Choice{ID: usable[0].ID, Reason: ReasonOnlyOption}, true |
| } |
| - spent := func(c Candidate) bool { return c.Known && c.Used >= lowHeadroom } |
| + for _, c := range usable { |
| + if c.ID == current { |
| + return Choice{ID: c.ID, Reason: ReasonHeadroom}, true |
| + } |
| + } |
| best := usable[0] |
| for _, c := range usable[1:] { |
| switch { |
| - case spent(best) && !spent(c): |
| + case c.Known && !best.Known: |
| best = c |
| - case spent(best) == spent(c) && c.ID == current && best.ID != current: |
| + case c.Known && best.Known && c.Used < best.Used: |
| best = c |
| } |
| } |
| reason := ReasonHeadroom |
| - if current != "" && best.ID != current { |
| - // The connection that ran this last cannot (or should not) now. |
| + if current != "" { |
| + // The connection that ran this last cannot now. |
| reason = ReasonFailover |
| } |
| return Choice{ID: best.ID, Reason: reason}, true |
diff --git a/internal/runner/connect/choose_test.go b/internal/runner/connect/choose_test.go| index bb737935..ca5c1f82 100644 |
| --- a/internal/runner/connect/choose_test.go |
| +++ b/internal/runner/connect/choose_test.go |
| @@ -28,15 +28,15 @@ func TestChoose(t *testing.T) { |
| {"one", []Candidate{claude}, RoleCoordinator, "", nil, "claude-a", ReasonOnlyOption}, |
| {"none", []Candidate{limited(claude, now.Add(time.Hour))}, RoleCoordinator, "claude-a", nil, "", ""}, |
| {"configured order first", []Candidate{claude, codex}, RoleCoordinator, "", nil, "claude-a", ReasonHeadroom}, |
| + {"reported headroom before unknown", []Candidate{claude, used(codex, 0.8)}, RoleCoordinator, "", nil, "codex-1", ReasonHeadroom}, |
| + {"most headroom", []Candidate{used(claude, 0.5), used(claude2, 0.2), used(codex, 0.4)}, RoleCoordinator, "", nil, "claude-2", ReasonHeadroom}, |
| {"sticky", []Candidate{claude, codex}, RoleCoordinator, "codex-1", nil, "codex-1", ReasonHeadroom}, |
| {"failover from limited", []Candidate{limited(claude, now.Add(time.Hour)), codex}, RoleCoordinator, "claude-a", nil, "codex-1", ReasonOnlyOption}, |
| {"failover among several", []Candidate{limited(claude, now.Add(time.Hour)), claude2, codex}, RoleCoordinator, "claude-a", nil, "claude-2", ReasonFailover}, |
| {"reset passed", []Candidate{limited(claude, now.Add(-time.Minute)), codex}, RoleCoordinator, "claude-a", nil, "claude-a", ReasonHeadroom}, |
| {"limited without reset never by itself", []Candidate{limited(claude, time.Time{})}, RoleCoordinator, "", nil, "", ""}, |
| - {"nearly spent gives way", []Candidate{used(claude, 0.95), used(codex, 0.2)}, RoleCoordinator, "claude-a", nil, "codex-1", ReasonFailover}, |
| - {"small differences keep the session", []Candidate{used(claude, 0.6), used(codex, 0.1)}, RoleCoordinator, "claude-a", nil, "claude-a", ReasonHeadroom}, |
| - {"unknown headroom counts as room", []Candidate{used(claude, 0.97), codex}, RoleCoordinator, "claude-a", nil, "codex-1", ReasonFailover}, |
| - {"all spent still answers", []Candidate{used(claude, 0.97), used(codex, 0.99)}, RoleCoordinator, "codex-1", nil, "codex-1", ReasonHeadroom}, |
| + {"stickiness is a rule", []Candidate{used(claude, 0.97), used(codex, 0.1)}, RoleCoordinator, "claude-a", nil, "claude-a", ReasonHeadroom}, |
| + {"failover to the most headroom", []Candidate{limited(claude, now.Add(time.Hour)), used(claude2, 0.7), used(codex, 0.2)}, RoleCoordinator, "claude-a", nil, "codex-1", ReasonFailover}, |
| {"engineering skips codex", []Candidate{limited(claude, now.Add(time.Hour)), codex}, RoleEngineering, "", nil, "", ""}, |
| {"avoid", []Candidate{claude, claude2}, RoleEngineering, "", []string{"claude-a"}, "claude-2", ReasonOnlyOption}, |
| {"signed out never", []Candidate{{ID: "claude-a", Provider: "claude", State: "sign_in_again"}, codex}, RoleCoordinator, "claude-a", nil, "codex-1", ReasonOnlyOption}, |
diff --git a/internal/runner/thin/effects.go b/internal/runner/thin/effects.go| index ad817b0c..8b130e93 100644 |
| --- a/internal/runner/thin/effects.go |
| +++ b/internal/runner/thin/effects.go |
| @@ -8,6 +8,8 @@ import ( |
| "fmt" |
| "slices" |
| "strings" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| ) |
| // Exactly-once across attempts. A turn that moves to another connection |
| @@ -23,10 +25,7 @@ const effectSchema = ` |
| CREATE TABLE IF NOT EXISTS turn_effects (turn_id TEXT NOT NULL, attempt INTEGER NOT NULL, seq INTEGER NOT NULL, name TEXT NOT NULL, args TEXT NOT NULL, call_id TEXT NOT NULL, done INTEGER NOT NULL DEFAULT 0, result TEXT NOT NULL DEFAULT '', is_error INTEGER NOT NULL DEFAULT 0, replayed_in INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (turn_id, attempt, seq)); |
| ` |
| -// writeTools change something outside the model's session. |
| -var writeTools = []string{"add_project", "create_project", "set_project_home", "ask_person", "write_note", "record_task", "add_finding", "start_task", "cancel_task", "add_report"} |
| - |
| -func writeTool(name string) bool { return slices.Contains(writeTools, name) } |
| +func writeTool(name string) bool { return slices.Contains(wire.WriteTools, name) } |
| // effect is one recorded write. |
| type effect struct { |
diff --git a/internal/runner/thin/engineer.go b/internal/runner/thin/engineer.go| index 4caa40bf..c3a30f91 100644 |
| --- a/internal/runner/thin/engineer.go |
| +++ b/internal/runner/thin/engineer.go |
| @@ -113,6 +113,12 @@ func (e *Engineer) Exec(ctx context.Context, r stepRow, progress func(wire.StepR |
| rep.State, rep.Reason, rep.Termination = wire.StepCancelled, "cancelled", true |
| return rep |
| } |
| + // Nothing can run Engineering now: the step waits, queued, and goes on |
| + // its own when a connection returns (spec §3); the queue moves on. |
| + if _, err := e.engineerOn(ctx, r.Person, nil); errors.Is(err, ErrNoConnection) && !r.Republish { |
| + rep.State = stepDeferred |
| + return rep |
| + } |
| if r.Republish { |
| // Retry of a failed push: the commit an earlier attempt recorded is |
| // published again; the specialist does not run. |
| @@ -186,7 +192,8 @@ func (e *Engineer) Exec(ctx context.Context, r stepRow, progress func(wire.StepR |
| var err error |
| if b, err = e.engineerOn(ctx, r.Person, avoid); err != nil { |
| if errors.Is(err, ErrNoConnection) { |
| - return fail(wire.ReasonNoConnection, true) |
| + // Every connection that could take it over is refused now. |
| + return fail(firstNonEmpty(res.reason, wire.ReasonNoConnection), true) |
| } |
| return fail("account_unavailable", true) |
| } |
diff --git a/internal/runner/thin/failover.go b/internal/runner/thin/failover.go| index 1cd7ead5..1487e497 100644 |
| --- a/internal/runner/thin/failover.go |
| +++ b/internal/runner/thin/failover.go |
| @@ -27,6 +27,9 @@ const heldRecheck = time.Minute |
| func (e *Engine) converse(ctx context.Context, person string, w *worker, r *run, act func(kind, tool string)) TurnResult { |
| var switched *wire.Switched |
| held := false |
| + // The connection that answered the person last: a reply from another |
| + // one says so, whether this turn moved or waited for it. |
| + last, _ := e.State.meta(ctx, "conn:"+person) |
| for { |
| b, choice, err := e.choose(ctx, person, w.connID) |
| if errors.Is(err, ErrNoConnection) { |
| @@ -92,6 +95,9 @@ func (e *Engine) converse(ctx context.Context, person string, w *worker, r *run, |
| e.log("runner session", e.State.setMeta(context.WithoutCancel(ctx), "conn:"+person, b.ID)) |
| } |
| + if switched == nil && res.Reason == "" && last != "" && last != b.ID && e.Conns != nil { |
| + switched = e.Conns.LimitedFrom(last) |
| + } |
| if switched != nil && res.Reason == "" { |
| switched.To = b.Provider |
| res.Switched = switched |
| @@ -156,6 +162,11 @@ func (e *Engine) choose(ctx context.Context, person, current string) (runner.Acc |
| if e.Conns == nil { |
| return runner.AccountBinding{}, connect.Choice{Reason: connect.ReasonOnlyOption}, nil |
| } |
| + if current == "" { |
| + // After a restart the session's connection is the one that |
| + // answered last: stickiness holds across processes. |
| + current, _ = e.State.meta(ctx, "conn:"+person) |
| + } |
| return e.Conns.Choose(ctx, person, connect.RoleCoordinator, current, nil) |
| } |
diff --git a/internal/runner/thin/run.go b/internal/runner/thin/run.go| index de9d129f..2a1ffcb4 100644 |
| --- a/internal/runner/thin/run.go |
| +++ b/internal/runner/thin/run.go |
| @@ -11,6 +11,7 @@ import ( |
| "golang.org/x/sys/unix" |
| "sync" |
| + "sync/atomic" |
| "time" |
| "amadan.net/oficina/equipo/internal/runner" |
| @@ -133,7 +134,14 @@ func Run(ctx context.Context, c runner.Config, o Options) error { |
| } |
| return OpenClaude(o.Claude, person, b) |
| }} |
| - conns.Changed = func() { engine.ConnectionsChanged(); link.HelloSoon() } |
| + var wakeSteps atomic.Pointer[func()] |
| + conns.Changed = func() { |
| + engine.ConnectionsChanged() |
| + link.HelloSoon() |
| + if wake := wakeSteps.Load(); wake != nil { |
| + (*wake)() |
| + } |
| + } |
| link.Engine = engine |
| if o.AccountsRoot == "" { |
| o.AccountsRoot = DefaultAccountsRoot() |
| @@ -211,6 +219,8 @@ func Run(ctx context.Context, c runner.Config, o Options) error { |
| } |
| steps := &StepEngine{State: state, Exec: engineer.Exec, Ask: engineer.ask, Notify: link.Notify, Logger: o.Logger, Sweep: func(ctx context.Context) { engineer.Sweep(ctx, state); engineer.sweepKept(ctx, state) }, Verify: func(ctx context.Context, id string) bool { return verifiedExit(ctx, manager, id) }} |
| link.Steps = steps |
| + wake := steps.Wake |
| + wakeSteps.Store(&wake) |
| if err = steps.Start(ctx); err != nil { |
| return err |
| } |
diff --git a/internal/thintest/connections_contract_test.go b/internal/thintest/connections_contract_test.go| index 0be35899..bb8f1187 100644 |
| --- a/internal/thintest/connections_contract_test.go |
| +++ b/internal/thintest/connections_contract_test.go |
| @@ -208,3 +208,53 @@ func TestContractHeldTurnAndSwitch(t *testing.T) { |
| t.Fatalf("usage %d %d %d %d %s %s %s %s %v", rows, input, cached, reasoning, provider, model, conn, role, err) |
| } |
| } |
| + |
| +// 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. |
| +func TestContractWritesReplayAcrossAttempts(t *testing.T) { |
| + r := newToolRig(t) |
| + 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) |
| + } |
| + 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}) |
| + r.wait("attempt 2", func(c *Conversation) bool { |
| + 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) |
| + } |
| + 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) |
| + } |
| + tasks, err := r.client.Tasks(r.ctx) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + n := 0 |
| + for _, k := range tasks.Items { |
| + if k.Title == "Fix the typo" { |
| + n++ |
| + } |
| + } |
| + if n != 1 { |
| + t.Fatalf("%d tasks for one record_task", n) |
| + } |
| + r.attempt = 1 |
| + stale := r.call("r4", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Third", "brief": "x"}) |
| + if !stale.IsError || stale.Code != "turn_ended" { |
| + t.Fatalf("a call from the old attempt ran: %+v", stale) |
| + } |
| +} |
diff --git a/internal/thintest/tools_contract_test.go b/internal/thintest/tools_contract_test.go| index ff10e9af..47d86d99 100644 |
| --- a/internal/thintest/tools_contract_test.go |
| +++ b/internal/thintest/tools_contract_test.go |
| @@ -16,6 +16,8 @@ type toolRig struct { |
| runner *FakeRunner |
| turn string |
| seq int |
| + // attempt is the turn attempt calls belong to (0: 1). |
| + attempt int64 |
| // held are frames other than tool results that arrived during a call, |
| // for expect. |
| held []heldFrame |
| @@ -57,7 +59,8 @@ func (r *toolRig) call(id, name string, args any) wire.ToolResult { |
| raw, _ := json.Marshal(args) |
| r.seq++ |
| frame := "r-tc-" + id + "-" + itoa(r.seq) |
| - if err := r.runner.Send(r.ctx, frame, wire.FrameToolCall, wire.ToolCall{CallID: r.turn + "/1/" + id, TurnID: r.turn, Attempt: 1, Name: name, Args: raw}); err != nil { |
| + attempt := max(r.attempt, 1) |
| + if err := r.runner.Send(r.ctx, frame, wire.FrameToolCall, wire.ToolCall{CallID: r.turn + "/" + itoa(int(attempt)) + "/" + id, TurnID: r.turn, Attempt: attempt, Name: name, Args: raw}); err != nil { |
| r.t.Fatal(err) |
| } |
| for { |
diff --git a/internal/wire/frames.go b/internal/wire/frames.go| index b7d4dbc5..95795d34 100644 |
| --- a/internal/wire/frames.go |
| +++ b/internal/wire/frames.go |
| @@ -444,8 +444,16 @@ type ToolResult struct { |
| Code string `json:"code"` |
| Repo string `json:"repo"` |
| Text string `json:"text"` |
| + // Replayed: an earlier attempt of the turn already made this call |
| + // (same tool, same arguments); this is its stored result, and nothing |
| + // ran again. |
| + 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. |
| +var WriteTools = []string{ToolAddProject, ToolCreateProject, ToolSetProjectHome, ToolAskPerson, ToolWriteNote, ToolRecordTask, ToolAddFinding, ToolStartTask, ToolCancelTask, ToolAddReport, ToolProjectCreated} |
| + |
| // ActivityReport is what the coordinator started doing: thinking, or a |
| // tool by name. Sent once, never acked, like a delta. |
| type ActivityReport struct { |
diff --git a/internal/wire/wiretest/testdata/frames/tool_result.json b/internal/wire/wiretest/testdata/frames/tool_result.json| index 40f4ff22..dbc581b9 100644 |
| --- a/internal/wire/wiretest/testdata/frames/tool_result.json |
| +++ b/internal/wire/wiretest/testdata/frames/tool_result.json |
| @@ -1 +1 @@ |
| -{"id":"c17","type":"tool_result","data":{"call_id":"t_0001/toolu_01","person":"owner@example.com","is_error":false,"code":"added","repo":"amadan.net/oficina/sample","text":"Added oficina/sample."}} |
| +{"id":"c17","type":"tool_result","data":{"call_id":"t_0001/toolu_01","person":"owner@example.com","is_error":false,"code":"added","repo":"amadan.net/oficina/sample","text":"Added oficina/sample.","replayed":false}} |