oficina / equipo Public

Astra round 1: one mutation ledger, held within an attempt too

The instance is the one authority: the runner sends every write to it
and keeps its own record only to tell a new attempt what was done. A
question card, the home and a finding are made once per turn and target
within an attempt too; record_task maps a later attempt's call back to
the task it reads like (same words, then title or brief, then order),
and within an attempt keeps its similar-task answer.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 7a044c1f08813f51c4d6374639cd27a74f5444ce parent 84c3df0
4 files changed, +185 −95
  • internal/equipo/chat/tools.go +113 −18
  • internal/headless/connections_test.go +5 −4
  • internal/runner/thin/effects.go +10 −73
  • internal/thintest/connections_contract_test.go +57 −0
diff --git a/internal/equipo/chat/tools.go b/internal/equipo/chat/tools.go
index 149a7a62..0279fdcf 100644
--- a/internal/equipo/chat/tools.go
+++ b/internal/equipo/chat/tools.go
@@ -62,8 +62,7 @@ func (t *txn) toolCall(l Lease, v *wire.ToolCall) error {
return err
}
if op != "" {
- var earlier toolCallRecord
- err = t.db.Where("turn_id = ? AND person = ? AND op = ? AND attempt < ?", v.TurnID, person, op, v.Attempt).Order("created_at").First(&earlier).Error
+ earlier, err := t.earlierOp(person, v, op)
if err == nil {
r, err := t.ownTurn(l, v.TurnID)
if err != nil && !errors.Is(err, ErrNotFound) && !errors.Is(err, ErrForbidden) {
@@ -106,33 +105,30 @@ func (t *txn) toolCall(l Lease, v *wire.ToolCall) 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.
+// The rules hold a call to what the turn already made, whatever its
+// wording: one question card per turn, the home once per namespace and a
+// finding once per task and normalised text, in any attempt; start and
+// cancel once per task and a project once per name, added or created,
+// against earlier attempts (the tools refuse a second within one). record_task may make several tasks in one turn
+// (the person reported several things): a call is the same task as one
+// the turn recorded when its title or brief reads like it (earlierOp).
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"`
+ Task string `json:"task"`
+ Repo string `json:"repo"`
+ Text string `json:"text"`
+ Namespace string `json:"namespace"`
}
_ = json.Unmarshal(v.Args, &a)
switch kind {
- case "ask":
+ case "ask", "task_record":
return kind, nil
- case "task_record":
- var n int64
- 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
+ return kind + ":" + strings.ToLower(strings.TrimSpace(a.Namespace)), nil
case "task_start", "task_cancel":
return kind + ":" + a.Task, nil
case "project", "project_create":
@@ -143,6 +139,105 @@ func (t *txn) mutationOp(person string, v *wire.ToolCall) (string, error) {
return "", nil
}
+// earlierOp is the call of the turn that already made this mutation, in
+// any attempt. For record_task it is the task the turn recorded with the
+// same arguments; else, from an earlier attempt, the best title or brief
+// match by the rule similar open tasks use, else the first an earlier
+// attempt recorded that this attempt has not matched yet. Within one
+// attempt record_task's own similar-task answer keeps one thing one task,
+// and separate: true makes another on purpose.
+func (t *txn) earlierOp(person string, v *wire.ToolCall, op string) (toolCallRecord, error) {
+ var earlier toolCallRecord
+ if op != "task_record" {
+ q := t.db.Where("turn_id = ? AND person = ? AND op = ?", v.TurnID, person, op)
+ if !onceInAttempt(op) {
+ // The tool holds this attempt to once itself (a second start
+ // of a task is refused): the ledger answers later attempts.
+ q = q.Where("attempt < ?", v.Attempt)
+ }
+ err := q.Order("created_at").First(&earlier).Error
+ return earlier, err
+ }
+ var rows []toolCallRecord
+ if err := t.db.Where("turn_id = ? AND person = ? AND op = ?", v.TurnID, person, op).Order("created_at").Find(&rows).Error; err != nil {
+ return earlier, err
+ }
+ var in struct {
+ Title string `json:"title"`
+ Brief string `json:"brief"`
+ }
+ _ = json.Unmarshal(v.Args, &in)
+ args := argsHash(v.Args)
+ nt, nb := significant(in.Title), significant(in.Title+" "+in.Brief)
+ best := -1.0
+ for _, r := range rows {
+ if r.ArgsHash == args {
+ return r, nil
+ }
+ if r.Attempt >= v.Attempt {
+ // Within an attempt, a task like an open one is answered by
+ // record_task itself (similar tasks, or separate on purpose).
+ continue
+ }
+ task := madeTask(r)
+ if task == "" {
+ continue
+ }
+ k, err := t.loadTask(task)
+ if errors.Is(err, ErrNotFound) {
+ continue
+ }
+ if err != nil {
+ return earlier, err
+ }
+ ts, tn := overlap(nt, significant(k.Title))
+ bs, bn := overlap(nb, significant(k.Title+" "+k.Brief))
+ if score := max(ts, bs*0.9); (ts >= 0.6 && tn >= 2 || bs >= 0.5 && bn >= 3) && score > best {
+ earlier, best = r, score
+ }
+ }
+ if best >= 0 {
+ return earlier, nil
+ }
+ // A later attempt records again what the turn already recorded, in
+ // its own words, in order: the first task earlier attempts recorded
+ // that no call of this attempt has matched yet.
+ if v.Attempt > 1 {
+ claimed := map[string]bool{}
+ for _, r := range rows {
+ if task := madeTask(r); r.Attempt == v.Attempt && task != "" {
+ claimed[task] = true
+ }
+ }
+ for _, r := range rows {
+ if task := madeTask(r); r.Attempt < v.Attempt && task != "" && !claimed[task] {
+ return r, nil
+ }
+ }
+ }
+ return earlier, gorm.ErrRecordNotFound
+}
+
+// onceInAttempt: kinds the ledger also holds to once within an attempt
+// (one open question card per turn; the home and a finding once per
+// target), since the tool alone would make them again.
+func onceInAttempt(op string) bool {
+ kind, _, _ := strings.Cut(op, ":")
+ return kind == "ask" || kind == "home" || kind == "finding"
+}
+
+// madeTask is the task a record_task call recorded (or replayed).
+func madeTask(r toolCallRecord) string {
+ var res wire.ToolResult
+ var made struct {
+ Task string `json:"task"`
+ }
+ if json.Unmarshal([]byte(r.Result), &res) != nil || json.Unmarshal([]byte(res.Text), &made) != nil {
+ return ""
+ }
+ return made.Task
+}
+
// madeCodes are the results that show a mutation happened, for the kinds
// whose result can also be "nothing done".
var madeCodes = map[string][]string{
diff --git a/internal/headless/connections_test.go b/internal/headless/connections_test.go
index a8cc77a9..8838ab3b 100644
--- a/internal/headless/connections_test.go
+++ b/internal/headless/connections_test.go
@@ -735,12 +735,13 @@ func connQuotaAfterWrites(t *testing.T, env *Env, inst *thintest.Instance, r *lo
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)
}
- // 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.
+ // Every write of attempt 2 reached the instance, the one ledger, and
+ // was folded there: the reworded ones (record_task, start_task,
+ // ask_person) by kind, the identical ones (add_project,
+ // set_project_home) too.
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 {
+ if replayed != 5 {
t.Fatalf("%d reworded writes were folded by the ledger", replayed)
}
}
diff --git a/internal/runner/thin/effects.go b/internal/runner/thin/effects.go
index 1091458d..e18b842a 100644
--- a/internal/runner/thin/effects.go
+++ b/internal/runner/thin/effects.go
@@ -14,12 +14,12 @@ import (
// Exactly-once across attempts. A turn that moves to another connection
// runs again as a new attempt in a new session, and that model may call
-// the same tools again. Every write tool's effect is recorded here before
-// it runs and with its result after; in a later attempt of the same turn
-// a call of a tool the turn already ran is answered from that record and
-// never runs twice. A recorded call whose result the runner never saw is
-// reconciled by sending it again under its own call id: the instance
-// answers a call id it has seen with its stored result.
+// the same tools again. The instance's mutation ledger is the one
+// authority on what the turn already did: every call goes to it, and it
+// answers a repeat, exact or reworded, from what the turn made (Astra
+// round 1: a second ledger here, answering exact repeats locally, could
+// disagree with it about which task is which). The runner records each
+// write here only to tell a new attempt what earlier ones did.
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));
@@ -27,13 +27,6 @@ CREATE TABLE IF NOT EXISTS turn_effects (turn_id TEXT NOT NULL, attempt INTEGER
func writeTool(name string) bool { return slices.Contains(wire.WriteTools, name) }
-// effect is one recorded write.
-type effect struct {
- Turn, Name, Args, CallID, Result string
- Attempt, Seq int64
- Done, IsError bool
-}
-
func canonArgs(raw json.RawMessage) string {
var v any
if json.Unmarshal(raw, &v) == nil {
@@ -61,45 +54,6 @@ func (s *State) endEffect(ctx context.Context, turn string, attempt, seq int64,
return err
}
-// earlierEffect claims the write an earlier attempt of the turn made that
-// 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
- err := s.tx(ctx, func(t *sql.Tx) error {
- rows, err := t.Query("SELECT attempt, seq, name, args, call_id, done, result, is_error FROM turn_effects WHERE turn_id=? AND attempt<? AND name=? AND replayed_in=0 ORDER BY attempt, seq", turn, attempt, name)
- if err != nil {
- return err
- }
- var all []effect
- for rows.Next() {
- e := effect{Turn: turn}
- if err = rows.Scan(&e.Attempt, &e.Seq, &e.Name, &e.Args, &e.CallID, &e.Done, &e.Result, &e.IsError); err != nil {
- rows.Close()
- return err
- }
- all = append(all, e)
- }
- rows.Close()
- want := canonArgs(args)
- for _, e := range all {
- if e.Args == want {
- 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
- })
- return out, found, err
-}
-
// doneEarlier lists what earlier attempts of the turn already did, for
// the new attempt's prompt.
func (s *State) doneEarlier(ctx context.Context, turn string, attempt int64) []string {
@@ -130,34 +84,17 @@ func (s *State) doneEarlier(ctx context.Context, turn string, attempt int64) []s
// errNotRecorded: an effect could not be recorded, so it does not run.
var errNotRecorded = errors.New("tool effect not recorded")
-// ledgered runs a write tool once per turn across attempts: a repeat in
-// a later attempt is answered from the record (or, when the earlier
-// result was never seen, by the instance from its own record under the
-// earlier call id); a new write is recorded before and after it runs.
+// ledgered runs a write tool through the instance, which holds the turn
+// to what it already did, and records it before and after it runs so a
+// later attempt is told.
func (b *bridge) ledgered(ctx context.Context, turn string, attempt int64, name, base string, args json.RawMessage, run func(base string, args json.RawMessage) (string, bool)) (string, bool) {
- prior, ok, err := b.State.earlierEffect(ctx, turn, attempt, name, args)
- if err != nil {
- b.log("tool effect", err)
- return toolTimeout, true
- }
- if ok {
- if prior.Done {
- return prior.Result, prior.IsError
- }
- // Sent before, answer unseen: the same call id again.
- text, isError := run(prior.CallID, json.RawMessage(prior.Args))
- if !(isError && text == toolTimeout) {
- b.log("tool effect", b.State.endEffect(ctx, turn, prior.Attempt, prior.Seq, text, isError))
- }
- return text, isError
- }
seq, err := b.State.startEffect(ctx, turn, attempt, name, args, base)
if err != nil {
b.log("tool effect", fmt.Errorf("%w: %v", errNotRecorded, err))
return toolTimeout, true
}
text, isError := run(base, args)
- // No answer is not a result: the next attempt reconciles it.
+ // No answer is not a result: the instance's ledger answers a repeat.
if !(isError && text == toolTimeout) {
b.log("tool effect", b.State.endEffect(ctx, turn, attempt, seq, text, isError))
}
diff --git a/internal/thintest/connections_contract_test.go b/internal/thintest/connections_contract_test.go
index ebf16100..65463d34 100644
--- a/internal/thintest/connections_contract_test.go
+++ b/internal/thintest/connections_contract_test.go
@@ -300,3 +300,60 @@ func TestContractWritesReplayAcrossAttempts(t *testing.T) {
t.Fatalf("a call from the old attempt ran: %+v", stale)
}
}
+
+// Astra round 1, finding 1: the per-kind rules hold within one attempt
+// too. A second question in other words is the same card; the home and a
+// finding are made once per target; record_task makes two tasks for two
+// different things and one for the same thing reworded.
+func TestContractWritesOncePerTurnWithinAnAttempt(t *testing.T) {
+ r := newToolRig(t)
+ r.call("a1", wire.ToolAddProject, map[string]string{"repo": "oficina/sample"})
+ asked := r.call("q1", wire.ToolAskPerson, map[string]any{"question": "Which colour?", "options": []string{"Red", "Blue"}})
+ again := r.call("q2", wire.ToolAskPerson, map[string]any{"question": "And which size?", "options": []string{"Small", "Large"}})
+ if asked.IsError || asked.Replayed || !again.Replayed {
+ t.Fatalf("questions %+v %+v", asked, again)
+ }
+ a := r.call("r1", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Fix the README typo", "brief": "The README says teh panes."})
+ b := r.call("r2", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Add a dark theme toggle", "brief": "Settings needs a switch for the dark theme."})
+ a2 := r.call("r3", wire.ToolRecordTask, map[string]any{"repo": "oficina/sample", "title": "Fix the README typo", "brief": "The README says teh panes."})
+ if a.IsError || b.IsError || a.Replayed || b.Replayed || !a2.Replayed || a2.Text != a.Text {
+ t.Fatalf("tasks %+v %+v %+v", a, b, a2)
+ }
+ var task struct{ Task string }
+ json.Unmarshal([]byte(a.Text), &task)
+ f1 := r.call("f1", wire.ToolAddFinding, map[string]string{"task": task.Task, "text": "The docs say teh too."})
+ f2 := r.call("f2", wire.ToolAddFinding, map[string]string{"task": task.Task, "text": "the docs say TEH too."})
+ if f1.IsError || !f2.Replayed {
+ t.Fatalf("findings %+v %+v", f1, f2)
+ }
+ var cards int
+ snap, _ := r.client.Snapshot(r.ctx)
+ for _, c := range snap.Cards {
+ if c.Kind == wire.CardQuestion {
+ cards++
+ }
+ }
+ tasks, _ := r.client.Tasks(r.ctx)
+ if cards != 1 || len(tasks.Items) != 2 {
+ t.Fatalf("%d question cards, %d tasks", cards, len(tasks.Items))
+ }
+}
+
+// Finding 2, one ledger: attempt 1 records A and B; attempt 2 calls B in
+// other words first, then A exactly. Each maps back to its own task.
+func TestContractRecordTaskMapsBackAcrossAttempts(t *testing.T) {
+ r := newToolRig(t)
+ r.call("a1", wire.ToolAddProject, map[string]string{"repo": "oficina/sample"})
+ aArgs := map[string]string{"repo": "oficina/sample", "title": "Fix the README typo", "brief": "The README says teh panes."}
+ a := r.call("r1", wire.ToolRecordTask, aArgs)
+ b := r.call("r2", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Add a dark theme toggle", "brief": "Settings needs a switch for the dark theme."})
+ 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 })
+ r.attempt = 2
+ b2 := r.call("r3", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Dark theme: add the toggle (as the second account puts it)", "brief": "A switch in Settings for the dark theme (as the second account puts it)."})
+ a2 := r.call("r4", wire.ToolRecordTask, aArgs)
+ if !b2.Replayed || b2.Text != b.Text || !a2.Replayed || a2.Text != a.Text {
+ t.Fatalf("attempt 2 mapped B to %s and A to %s (want %s, %s)", b2.Text, a2.Text, b.Text, a.Text)
+ }
+}