package plan3test import ( "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/equipo/conversation" "amadan.net/oficina/equipo/internal/equipo/kernel" "amadan.net/oficina/equipo/internal/equipo/team" "amadan.net/oficina/equipo/internal/runnerproto" "context" "encoding/json" "fmt" "gorm.io/gorm" "strings" "testing" ) func TestCoordinatorConnectionWaiting(t *testing.T) { f, x, p, b := coordinatorFixture(t) first := queueCoordinator(t, f, "first", "first") c, err := x.ClaimCoordinator(ctx, p, first.ID, first.Revision) must(t, err) // A claimed specialist holds the same home until its namespace is contained. f.exec(t, "UPDATE coordinator_turns SET state='delivered' WHERE id=?", first.ID) f.exec(t, `INSERT INTO runner_assignments(id,task_id,person,state,attempt_id,selection) VALUES('blocking','blocking-task',?,'claimed',?,?)`, owner.Address, c.Handle.Attempt, `{"ConnectionID":"claude"}`) second := queueCoordinator(t, f, "second", "second") // The first coordinator no longer owns pending containment; the specialist does. f.exec(t, "UPDATE coordinator_turns SET attempt_id=0 WHERE id=?", first.ID) turns, err := x.PollCoordinator(ctx, p) must(t, err) if len(turns) != 0 { t.Fatal("coordinator overlapped shared home") } status, err := f.Store.Coordinator(ctx, owner) must(t, err) if status.WaitingTaskID != "blocking-task" || status.WaitingTaskURL != "/tasks/blocking-task" { t.Fatal("waiting card omitted task link", status) } page, err := f.Store.Conversation(ctx, owner, "", 50) must(t, err) found := false for _, card := range page.Cards { if card.Kind == "coordinator" && card.Thinking && card.ConnectionLabel == "claude" { found = true } } if !found { t.Fatal("conversation omitted live waiting bubble") } if f.count(t, "SELECT count(*) FROM admission_tickets") != 1 { t.Fatal("waiting dispatched a provider") } if _, err = x.ClaimCoordinator(ctx, p, second.ID, second.Revision); err == nil { t.Fatal("claim ignored occupied home") } f.exec(t, "UPDATE runner_assignments SET state='contained' WHERE id='blocking'") f.exec(t, "UPDATE attempts SET containment='contained' WHERE id=?", c.Handle.Attempt) turns, err = x.PollCoordinator(ctx, p) must(t, err) if len(turns) != 1 || turns[0].ID != second.ID { t.Fatal("released home lost queued turn") } status, err = f.Store.Coordinator(ctx, owner) must(t, err) if status.WaitingTaskID != "" || f.count(t, "SELECT count(*) FROM conversation_requests WHERE operation='coordinator.waiting'") != 0 { t.Fatal("released task retained waiting record before claim") } next, err := x.ClaimCoordinator(ctx, p, second.ID, second.Revision) must(t, err) if next.Handle.Attempt == c.Handle.Attempt || next.Binding.ID != b.ID { t.Fatal("waiting redispatched old turn") } x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }}) must(t, x.ContainCoordinator(ctx, p, next, runnerproto.ContainmentProof{Scope: next.Scope, Handle: next.Handle})) action, err := x.Core.GetAction(ctx, next.Scope, next.Admission.Dispatch.Action) must(t, err) if action.State != team.ActionUncertain { t.Fatal("unknown charge lost") } } func TestCoordinatorContextBounds(t *testing.T) { f, x, p, _ := coordinatorFixture(t) for i := 0; i < 60; i++ { _, err := f.Store.SendMessage(ctx, owner, "", strings.Repeat("x", 16384), equipo.Mutation{RequestID: fmt.Sprint(i)}) must(t, err) } turn := queueCoordinator(t, f, "latest request", "latest") c, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) must(t, err) if c.Context.Hash == "" || c.Context.Hash != c.Turn.ContextHash || c.Context.Hash != runnerproto.CoordinatorContextHash(c.Context) { t.Fatal("claim snapshot hash mismatch") } if len(c.Context.Recent) != 2 || c.Context.Recent[1].ID != turn.MessageID { t.Fatal("long history did not trim oldest first", len(c.Context.Recent)) } if len(c.Context.ConfirmedPreferences) != 0 || len(c.Context.ConfirmedDecisions) != 0 { t.Fatal("history promoted to confirmed context") } _, err = runnerproto.CoordinatorPrompt(c.Context) must(t, err) again, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) must(t, err) if runnerproto.EventHash(c) != runnerproto.EventHash(again) { t.Fatal("claim replay rebuilt snapshot") } } func TestCoordinatorContextSourceRevocation(t *testing.T) { f, x, p, _ := coordinatorFixture(t) var project int64 must(t, f.DB.Writer().QueryRow("SELECT id FROM projects LIMIT 1").Scan(&project)) msg, err := f.Store.SendMessage(ctx, owner, "", "restricted older message", equipo.Mutation{RequestID: "old"}) must(t, err) _, err = f.Store.QueueCoordinatorTurn(ctx, owner, msg.ID, project, equipo.Mutation{RequestID: "old"}) must(t, err) f.exec(t, "UPDATE coordinator_turns SET state='superseded'") f.exec(t, `UPDATE connection_choices SET connection_ids_json='["codex"]',pinned_id='codex'`) turn := queueCoordinator(t, f, "general request", "general") c, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) must(t, err) raw, err := runnerproto.CoordinatorPrompt(c.Context) must(t, err) if strings.Contains(raw, "restricted older message") || len(c.Context.Retrieved) != 0 { t.Fatal("revoked source survived fresh snapshot") } } func TestCoordinatorSessionTrustedReceipt(t *testing.T) { f, x, p, c := claimTools(t) validators := runnerproto.ReportValidators(runnerproto.ReportErrors{Invalid: equipo.ErrInvalid, Forbidden: equipo.ErrForbidden, Conflict: equipo.ErrConflict}, func(context.Context, string, []string) ([]json.RawMessage, error) { t.Fatal("delivery used a remote or unbounded validator") return nil, nil }) x.SetRunnerValidators(validators) out := toolCall(t, x, p, c, "post", "post_message", map[string]any{"body": "delivered once", "source_refs": []team.SourceRef{}}) event := coordinatorEvent(c, "coordinator.delivery") event.SessionID = "fixture-session" event.Payload = []byte(`{"request_id":"post","resource_id":"` + out.ResourceID + `"}`) if err := x.CompleteCoordinator(ctx, p, c, event); err == nil { t.Fatal("delivery accepted before receipt") } terminal := coordinatorEvent(c, "turn.completed") terminal.SessionID = event.SessionID terminal.Payload = []byte(`{"usage":{"calls":1,"input_tokens":11,"output_tokens":3,"cost_unavailable":true}}`) raw, _ := runnerproto.Marshal(terminal) q := runnerproto.RunnerRequest{Version: 2, AssignmentID: c.Turn.ID, Scope: c.Scope, Handle: c.Handle, ActionID: terminal.ActionID, Event: raw} a := runnerproto.Assignment{ID: c.Turn.ID, Selection: c.Brief.Selection} if err := validators.Events(ctx, a, q); err != nil { t.Fatalf("event validator: %v; event %s", err, raw) } if _, err := validators.Receipt(ctx, a, q); err != nil { t.Fatalf("receipt validator: %v", err) } must(t, x.CoordinatorEvent(ctx, p, c, terminal)) must(t, x.CoordinatorEvent(ctx, p, c, terminal)) must(t, x.CompleteCoordinator(ctx, p, c, event)) must(t, x.CompleteCoordinator(ctx, p, c, event)) action, err := x.Core.GetAction(ctx, c.Scope, c.Admission.Dispatch.Action) must(t, err) if action.Receipt == nil || action.Receipt.Usage == nil || action.Receipt.Usage.InputTokens != 11 { t.Fatal("trusted receipt missing") } if f.count(t, "SELECT count(*) FROM conversation_messages WHERE body='delivered once'") != 1 { t.Fatal("delivery duplicated tool effect") } } func TestCoordinatorContextFixturePreferences(t *testing.T) { f, x, p, _ := coordinatorFixture(t) turn := queueCoordinator(t, f, "history", "prefs") c, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) must(t, err) deleted := false snapshot := func() runnerproto.CoordinatorContext { var out runnerproto.CoordinatorContext must(t, x.Write(ctx, func(tx *gorm.DB) error { cs := conversation.New(tx, conversation.Dependencies{Authorize: func(tx *gorm.DB, a kernel.Actor) (string, error) { var n int64 err := tx.Table("members").Where("address=? AND active=1", a.Address).Count(&n).Error if err != nil { return "", err } if n != 1 { return "", equipo.ErrForbidden } return f.TeamID, nil }, ContextSource: func(context.Context, *gorm.DB, runnerproto.CoordinatorClaim) ([]runnerproto.ContextRef, []runnerproto.ContextRef, []runnerproto.ContextRef, []runnerproto.ContextRef, error) { rule := runnerproto.ContextRef{Source: team.SourceRef{Kind: "team_rule", ID: "rule", Revision: 1, Hash: team.ContentDigest([]byte("required team rule"))}, Text: "required team rule"} var prefs []runnerproto.ContextRef if !deleted { prefs = []runnerproto.ContextRef{{Source: team.SourceRef{Kind: "preference", ID: "confirmed", Revision: 2, Hash: team.ContentDigest([]byte("confirmed preference"))}, Text: "confirmed preference"}} } return []runnerproto.ContextRef{rule}, nil, prefs, nil, nil }}) var err error out, err = cs.CoordinatorContext(ctx, c) return err })) return out } before := snapshot() deleted = true after := snapshot() if len(before.ConfirmedPreferences) != 1 || len(after.ConfirmedPreferences) != 0 || before.Hash == after.Hash || len(after.Instructions) != 1 { t.Fatal("deleted preference survived or team rule disappeared") } } func TestCoordinatorContextConfirmedAnswer(t *testing.T) { f, x, p, c := claimTools(t) question := toolCall(t, x, p, c, "question", "ask_person", map[string]any{"message_id": c.Turn.MessageID, "question": "Choose a direction", "options": []any{}}) toolCall(t, x, p, c, "suggestion", "suggest_preference", map[string]any{"source_message_id": c.Turn.MessageID, "text": "unconfirmed suggestion"}) must(t, f.Store.AnswerClarification(ctx, owner, question.ResourceID, "", "explicit person decision", equipo.Mutation{RequestID: "answer", Revision: 1})) must(t, x.Core.Record(ctx, c.Scope, c.Admission.Dispatch.Action, team.Receipt{ID: "receipt", Outcome: team.OutcomeSuccess})) event := coordinatorEvent(c, "coordinator.delivery") event.SessionID = "fixture-session" event.Payload = []byte(`{"request_id":"question","resource_id":"` + question.ResourceID + `"}`) must(t, x.CompleteCoordinator(ctx, p, c, event)) x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }}) must(t, x.ContainCoordinator(ctx, p, c, runnerproto.ContainmentProof{Scope: c.Scope, Handle: c.Handle})) turns, err := x.PollCoordinator(ctx, p) must(t, err) if len(turns) != 1 { t.Fatal(turns) } next, err := x.ClaimCoordinator(ctx, p, turns[0].ID, turns[0].Revision) must(t, err) if len(next.Context.ConfirmedDecisions) != 1 || next.Context.ConfirmedDecisions[0].Text != "explicit person decision" || len(next.Context.ConfirmedPreferences) != 0 { t.Fatal("confirmed context inferred from assistant text", next.Context) } } func TestCoordinatorSessionUnboundRunner(t *testing.T) { f, x, p, _ := coordinatorFixture(t) f.exec(t, "DELETE FROM coordinator_bindings") turns, err := x.PollCoordinator(ctx, p) must(t, err) if len(turns) != 0 { t.Fatal("unbound runner acquired coordinator work") } }