package thin import ( "context" "database/sql" "encoding/json" "errors" "fmt" "slices" "strings" "amadan.net/oficina/equipo/internal/wire" ) // 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. 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)); ` func writeTool(name string) bool { return slices.Contains(wire.WriteTools, name) } func canonArgs(raw json.RawMessage) string { var v any if json.Unmarshal(raw, &v) == nil { raw, _ = json.Marshal(v) } return string(raw) } // startEffect records a write before it runs. func (s *State) startEffect(ctx context.Context, turn string, attempt int64, name string, args json.RawMessage, callID string) (int64, error) { var seq int64 err := s.tx(ctx, func(t *sql.Tx) error { if err := t.QueryRow("SELECT coalesce(max(seq),0)+1 FROM turn_effects WHERE turn_id=? AND attempt=?", turn, attempt).Scan(&seq); err != nil { return err } _, err := t.Exec("INSERT INTO turn_effects(turn_id, attempt, seq, name, args, call_id) VALUES(?,?,?,?,?,?)", turn, attempt, seq, name, canonArgs(args), callID) return err }) return seq, err } // endEffect records a write's result. func (s *State) endEffect(ctx context.Context, turn string, attempt, seq int64, result string, isError bool) error { _, err := s.db.ExecContext(context.WithoutCancel(ctx), "UPDATE turn_effects SET done=1, result=?, is_error=? WHERE turn_id=? AND attempt=? AND seq=?", result, isError, turn, attempt, seq) return 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 { rows, err := s.db.QueryContext(ctx, "SELECT name, done, result, is_error FROM turn_effects WHERE turn_id=? AND attempt