package thintest import ( "database/sql" "encoding/json" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/wire" ) func i64(v int64) *int64 { return &v } func held(conns ...wire.HeldConnection) wire.Hello { return wire.Hello{Repos: []string{}, CreateIn: []string{}, Catalog: []wire.RepoInfo{}, Connections: conns, Versions: map[string]string{"runner": "test"}} } // TestContractConnections: the runner's hello records the person's own // connections (never a teammate's); an attempt started in the app goes to // the runner as a durable connect frame, shows the provider's device // code, turns healthy with the runner's name for it and is not // duplicated by the next hello; cancel goes to the runner; a connection // the runner no longer holds is signed out. Every document matches the // shared fixtures, and no secret-shaped field is ever stored. func TestContractConnections(t *testing.T) { r := newRig(t) runner := r.dial(0) r.wait("runner online", func(c *Conversation) bool { return c.Runner.Online }) reset := time.Date(2026, 11, 10, 10, 0, 0, 0, time.UTC) one := 1.0 hello := held(wire.HeldConnection{LocalID: "claude-a", Person: Owner, Provider: "claude", Kind: "subscription", Label: Owner, State: wire.ConnLimited, Headroom: &wire.Headroom{Utilization: &one, ResetsAt: &reset, Windows: []wire.Window{{Name: "seven_day", UsedPercent: 100, Minutes: 10080, ResetsAt: &reset}}}}, wire.HeldConnection{LocalID: "claude-b", Person: "teammate@example.com", Provider: "claude", Kind: "subscription", Label: "teammate@example.com", State: wire.ConnHealthy}) hello.Generation = runner.Welcome.Generation if err := runner.Send(r.ctx, "h1", wire.FrameHello, hello); err != nil { t.Fatal(err) } r.wait("claude-a recorded", func(c *Conversation) bool { return len(c.Connections) == 1 }) list, err := r.client.Connections(r.ctx) if err != nil || len(list.Items) != 1 || list.Items[0].LocalID != "claude-a" || list.Items[0].State != wire.ConnLimited { t.Fatalf("connections %+v %v", list, err) } attempt, err := r.client.Connect(r.ctx, wire.Connect{Provider: "codex", Kind: "subscription"}) if err != nil || attempt.State != wire.ConnConnecting || attempt.LocalID != "" { t.Fatalf("connect %+v %v", attempt, err) } f, body, err := runner.Expect(r.ctx, wire.FrameConnect) if err != nil { t.Fatal(err) } shape(t, "frames/connect.json", runner.Received[len(runner.Received)-1]) cmd := body.(*wire.ConnectCommand) if cmd.Connection != attempt.ID || cmd.Person != Owner || cmd.Provider != "codex" || cmd.SameMachine { t.Fatalf("connect frame %+v", cmd) } if err = runner.Send(r.ctx, "r-ack-c", wire.FrameAck, wire.Ack{ID: f.ID}); err != nil { t.Fatal(err) } // A second Add while one is connecting is the same attempt. again, err := r.client.Connect(r.ctx, wire.Connect{Provider: "codex"}) if err != nil || again.ID != attempt.ID { t.Fatalf("second attempt %+v %v", again, err) } report := wire.ConnectionReport{Connection: attempt.ID, Person: Owner, Provider: "codex", State: wire.ConnConnecting, Prompt: &wire.ConnectPrompt{Kind: wire.PromptDeviceCode, URL: "https://auth.openai.com/codex/device", Code: "ABCD-1234"}} if err = runner.Send(r.ctx, "r-conn-1", wire.FrameConnection, report); err != nil { t.Fatal(err) } r.wait("device code shown", func(c *Conversation) bool { p := c.Connections[attempt.ID].Prompt return p != nil && p.Code == "ABCD-1234" }) got, err := r.client.Connection(r.ctx, attempt.ID) if err != nil { t.Fatal(err) } shape(t, "api/connection-connecting-codex.json", got) done := wire.ConnectionReport{Connection: attempt.ID, Person: Owner, LocalID: "codex-1", Provider: "codex", State: wire.ConnHealthy, Label: Owner, Plan: "pro", Headroom: &wire.Headroom{Windows: []wire.Window{}}} // The hello can arrive before the attempt's report: it is not a second // connection. hello.Connections = append(hello.Connections, wire.HeldConnection{LocalID: "codex-1", Person: Owner, Provider: "codex", Kind: "subscription", Label: Owner, State: wire.ConnHealthy, Plan: "pro"}) if err = runner.Send(r.ctx, "h2", wire.FrameHello, hello); err != nil { t.Fatal(err) } if err = runner.Send(r.ctx, "r-conn-2", wire.FrameConnection, done); err != nil { t.Fatal(err) } shape(t, "frames/connection.json", runner.Sent[len(runner.Sent)-1]) r.wait("codex healthy", func(c *Conversation) bool { v := c.Connections[attempt.ID] return v.State == wire.ConnHealthy && v.LocalID == "codex-1" && v.Prompt == nil }) if err = runner.Send(r.ctx, "h3", wire.FrameHello, hello); err != nil { t.Fatal(err) } time.Sleep(200 * time.Millisecond) list, _ = r.client.Connections(r.ctx) if len(list.Items) != 2 { t.Fatalf("after the hello: %+v", list.Items) } shape(t, "api/connections.json", list) // A late frame for an ended attempt changes nothing. if err = runner.Send(r.ctx, "r-conn-3", wire.FrameConnection, report); err != nil { t.Fatal(err) } if v, _ := r.client.Connection(r.ctx, attempt.ID); v.State != wire.ConnHealthy { t.Fatalf("late frame reopened the attempt: %+v", v) } // Claude, browser elsewhere: the sign-in by a link, starting on the // runner (no link yet). claude, err := r.client.Connect(r.ctx, wire.Connect{Provider: "claude"}) if err != nil || claude.Prompt == nil || claude.Prompt.Kind != wire.PromptAuthorize || claude.Prompt.URL != "" || claude.Prompt.Attempt != 0 || claude.Kind != wire.KindSubscription { t.Fatalf("claude attempt %+v %v", claude, err) } if _, body, err = runner.Expect(r.ctx, wire.FrameConnect); err != nil || body.(*wire.ConnectCommand).SameMachine || body.(*wire.ConnectCommand).Kind != wire.KindSubscription { t.Fatalf("claude connect %+v %v", body, err) } cancelled, err := r.client.CancelConnection(r.ctx, claude.ID) if err != nil || cancelled.State != wire.ConnError || cancelled.Reason != "cancelled" { t.Fatalf("cancel %+v %v", cancelled, err) } if _, body, err = runner.Expect(r.ctx, wire.FrameCancelConnect); err != nil || body.(*wire.CancelConnectCommand).Connection != claude.ID { t.Fatalf("cancel frame %+v %v", body, err) } // A connection the runner no longer holds is signed out. hello.Connections = hello.Connections[:1] if err = runner.Send(r.ctx, "h4", wire.FrameHello, hello); err != nil { t.Fatal(err) } r.wait("codex signed out", func(c *Conversation) bool { return c.Connections[attempt.ID].State == wire.ConnSignedOut }) snap, err := r.client.Snapshot(r.ctx) if err != nil || len(snap.Connections) != 3 { t.Fatalf("snapshot connections %+v %v", snap.Connections, err) } // Nothing secret-shaped was stored. var dump string _ = r.inst.DB.Writer().QueryRow("SELECT group_concat(coalesce(headroom,'') || coalesce(prompt,'') || label || plan, '|') FROM chat_connections").Scan(&dump) for _, bad := range []string{"token", "secret", "password", "/home/"} { if strings.Contains(strings.ToLower(dump), bad) { t.Fatalf("stored %q: %s", bad, dump) } } var _ = sql.ErrNoRows } // TestContractHeldTurnAndSwitch: a turn held for a connection carries the // reason no_connection while it waits and drops it when it goes on; a // failover's new attempt drops the first attempt's draft; the reply // carries the switched line and its usage is recorded. func TestContractHeldTurnAndSwitch(t *testing.T) { r := newRig(t) runner := r.dial(0) r.wait("runner online", func(c *Conversation) bool { return c.Runner.Online }) sent, err := r.client.Send(r.ctx, "hello", "k-held") if err != nil { t.Fatal(err) } f, _, err := runner.Expect(r.ctx, wire.FrameMessage) if err != nil { t.Fatal(err) } runner.Send(r.ctx, "a-1", wire.FrameAck, wire.Ack{ID: f.ID}) turn := sent.Turn.ID runner.Send(r.ctx, "r-hold", wire.FrameTurn, wire.TurnReport{TurnID: turn, Attempt: 1, State: wire.TurnWaiting, Reason: wire.ReasonNoConnection}) r.wait("held", func(c *Conversation) bool { v := c.Turns[turn] return v.State == wire.TurnWaiting && v.Reason == wire.ReasonNoConnection }) // A message sent while it waits joins the queue behind it. later, err := r.client.Send(r.ctx, "still there?", "k-held-2") if err != nil || later.Turn.State != wire.TurnQueued || later.Turn.ID == turn { t.Fatalf("second message %+v %v", later.Turn, err) } page := r.inst.Get(t, "/conversation") if !strings.Contains(page, "data-no-connection") || !strings.Contains(page, "Nothing can answer right now.") || strings.Contains(page, "Send your message again") { t.Fatalf("held card missing from the page") } runner.Send(r.ctx, "r-go", wire.FrameTurn, wire.TurnReport{TurnID: turn, Attempt: 1, State: wire.TurnRunning}) r.wait("going again", func(c *Conversation) bool { v := c.Turns[turn]; return v.State == wire.TurnRunning && v.Reason == "" }) runner.Send(r.ctx, "r-d1", wire.FrameDelta, wire.DeltaReport{TurnID: turn, Attempt: 1, Offset: 0, Text: "Partial"}) r.wait("draft", func(c *Conversation) bool { return c.Drafts[turn] == "Partial" }) // Claude refused on quota: attempt 2 on Codex. runner.Send(r.ctx, "r-retry", wire.FrameTurn, wire.TurnReport{TurnID: turn, Attempt: 2, State: wire.TurnRunning}) r.wait("attempt 2, no draft", func(c *Conversation) bool { return c.Turns[turn].Attempt == 2 && c.Drafts[turn] == "" }) runner.Send(r.ctx, "r-stale", wire.FrameDelta, wire.DeltaReport{TurnID: turn, Attempt: 1, Offset: 7, Text: " old"}) runner.Send(r.ctx, "r-d2", wire.FrameDelta, wire.DeltaReport{TurnID: turn, Attempt: 2, Offset: 0, Text: "Done."}) r.wait("new draft", func(c *Conversation) bool { return c.Drafts[turn] == "Done." }) reset := time.Date(2026, 11, 10, 10, 0, 0, 0, time.UTC) reply := wire.Reply{TurnID: turn, Attempt: 2, Text: "Done.", Usage: []wire.Usage{{Provider: "codex", Connection: "codex-1", Model: "gpt-6-astra", Attempt: 2, Outcome: wire.OutcomeReplied, Complete: true, InputTokens: i64(5120), CachedInputTokens: i64(4096), CacheWriteTokens: i64(0), OutputTokens: i64(88), ReasoningOutputTokens: i64(40)}}, Switched: &wire.Switched{From: "claude", To: "codex", ResetsAt: &reset}} runner.Send(r.ctx, "r-reply", wire.FrameReply, reply) r.wait("replied", func(c *Conversation) bool { return c.Turns[turn].State == wire.TurnReplied && len(c.Replies()) == 1 }) m := r.conv.Replies()[0] if m.Switched == nil || m.Switched.To != "codex" || !m.Switched.ResetsAt.Equal(reset) { t.Fatalf("switched %+v", m.Switched) } if v, _ := r.client.Turn(r.ctx, turn); v.Connection != "codex-1" || v.Attempt != 2 { t.Fatalf("turn %+v", v) } page = r.inst.Get(t, "/conversation") // In the person's zone (Europe/Dublin, UTC in November), no UTC // suffix (paused work, decision 4). if !strings.Contains(page, "Switched to Codex; Claude resets Tue 10:00<") || strings.Contains(page, "10:00 UTC") || strings.Contains(page, "data-no-connection") { t.Fatalf("switched line missing from the page") } var rows, input, cached, reasoning int64 var provider, model, conn, role string err = r.inst.DB.Writer().QueryRow("SELECT count(*), sum(input_tokens), sum(cached_input_tokens), sum(reasoning_output_tokens), max(provider), max(model), max(connection), max(role) FROM chat_usage WHERE turn_id = ?", turn).Scan(&rows, &input, &cached, &reasoning, &provider, &model, &conn, &role) if err != nil || rows != 1 || input != 5120 || cached != 4096 || reasoning != 40 || provider != "codex" || model != "gpt-6-astra" || conn != "codex-1" || role != "coordinator" { 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, 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 README typo", "brief": "The README has teh"}) 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}) 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 // 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": "Fix the README typo", "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) } } 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, steps := 0, 0 for _, k := range tasks.Items { if strings.Contains(k.Title, "typo") || strings.Contains(k.Title, "misspelling") { n++ steps += len(k.Steps) } } 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"}) if !stale.IsError || stale.Code != "turn_ended" { 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) } } // Astra round 2: never by order alone. Attempt 1 records A; attempt 2 // asks for an unrelated B before repeating A: B is made, A's repeat maps // to A. A call that reads like two earlier tasks is refused with both, // so the model names the one it means. func TestContractRecordTaskNeverByOrder(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) a2 := r.call("r2", wire.ToolRecordTask, map[string]any{"repo": "oficina/sample", "title": "Fix the README typo in the install section", "brief": "The install section of the README says teh too.", "separate": true}) if a.IsError || a2.IsError || a2.Replayed { t.Fatalf("attempt 1 %+v %+v", a, a2) } 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 b := r.call("r3", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Add a dark theme toggle", "brief": "Settings needs a switch for the dark theme."}) if b.IsError || b.Replayed || b.Code != "recorded" { t.Fatalf("the unrelated task was not made: %+v", b) } again := r.call("r4", wire.ToolRecordTask, aArgs) if !again.Replayed || again.Text != a.Text { t.Fatalf("A's repeat mapped to %s, want %s", again.Text, a.Text) } both := r.call("r5", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Fix the README typo (teh)", "brief": "The README says teh in two places."}) var listed struct { Earlier []struct{ Task string } } json.Unmarshal([]byte(both.Text), &listed) if !both.IsError || both.Code != "ambiguous" || len(listed.Earlier) != 2 { t.Fatalf("an ambiguous call was not refused with both: %+v", both) } tasks, _ := r.client.Tasks(r.ctx) if len(tasks.Items) != 3 { t.Fatalf("%d tasks, want A, A2 and B", len(tasks.Items)) } }