package runner import ( "context" "encoding/json" "errors" "fmt" "path/filepath" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo/team" "amadan.net/oficina/equipo/internal/runner/containment" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runnerproto" ) type coordinatorAPIStub struct { events []string delivery bool c runnerproto.CoordinatorClaim crash string polled bool } type waitingCoordinatorAPI struct { polled chan struct{} claims int } func (a *waitingCoordinatorAPI) CoordinatorCall(ctx context.Context, op string, _ runnerproto.CoordinatorRequest, _ any) error { if op != "poll" { a.claims++ return provider.ErrContract } select { case a.polled <- struct{}{}: default: } return nil } func TestCoordinatorConnectionWaitingService(t *testing.T) { api := &waitingCoordinatorAPI{polled: make(chan struct{}, 1)} service := &Service{Coordinator: &CoordinatorService{API: api}} ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() if err := service.withCoordinatorWaiting(ctx, func() error { select { case <-api.polled: return nil case <-ctx.Done(): return ctx.Err() } }); err != nil { t.Fatal("specialist prevented waiting status", err) } if api.claims != 0 { t.Fatal("waiting observer dispatched coordinator") } } func (a *coordinatorAPIStub) CoordinatorCall(_ context.Context, op string, q runnerproto.CoordinatorRequest, out any) error { switch op { case "poll": if !a.polled { *out.(*[]runnerproto.CoordinatorTurn) = []runnerproto.CoordinatorTurn{a.c.Turn} a.polled = true } case "claim", "recover": *out.(*runnerproto.CoordinatorClaim) = a.c case "renew": *out.(*time.Time) = time.Now().Add(time.Minute) case "event": if q.Event.Kind == "coordinator.delivery" && a.delivery { return nil } a.events = append(a.events, q.Event.Kind) if q.Event.Kind == "coordinator.delivery" { if len(a.events) < 2 || a.events[len(a.events)-2] != "turn.completed" { return errors.New("delivery before receipt") } a.delivery = true if a.crash == "ack" { a.crash = "" return ErrTransient } } case "tool", "tool_result": *out.(*runnerproto.CoordinatorToolResult) = runnerproto.CoordinatorToolResult{ResourceID: "message", Revision: 1, Value: json.RawMessage(`{"tool":"post_message"}`)} case "containment": default: return fmt.Errorf("unexpected op %s", op) } return nil } type coordinatorFixtureLauncher struct { j *Journal launch provider.Launch session provider.Session proxy *ToolProxy events chan provider.Event starts int hold bool started chan struct{} crash string } func (l *coordinatorFixtureLauncher) Preflight(_ context.Context, b provider.Binding, _ provider.Policy) (provider.Identity, error) { return b.Expected, nil } func (l *coordinatorFixtureLauncher) Open(ctx context.Context, v provider.Launch) (provider.Session, error) { l.launch = v l.session = provider.Session{ID: v.AttemptKey + "-session", AttemptKey: v.AttemptKey, Provider: v.Selection.Provider, AccountID: v.Selection.AccountID, Family: v.Selection.Family, Model: v.Selection.Model} l.events = make(chan provider.Event, 4) return l.session, l.j.BindSession(ctx, l.session) } func (l *coordinatorFixtureLauncher) Events(context.Context, provider.Session) (<-chan provider.Event, error) { return l.events, nil } func (l *coordinatorFixtureLauncher) StartTurn(ctx context.Context, s provider.Session, t provider.Turn) error { if l.crash == "before-intent" { return provider.ErrUncertain } if err := l.j.BeginTurn(ctx, s, t); err != nil { return err } if l.crash == "intent" { return provider.ErrUncertain } if err := l.j.consumeTurn(ctx, s.AttemptKey, s.ID, t.Prompt); err != nil { return err } l.starts++ if l.crash == "stdin" { return provider.ErrUncertain } _, err := l.proxy.CallCoordinatorTool(ctx, runnerproto.CoordinatorToolCall{RequestID: "post", Name: "post_message", Arguments: json.RawMessage(`{"body":"answer","source_refs":[]}`)}) if err != nil { return err } if l.crash == "tool" { return provider.ErrUncertain } if l.hold { if l.started != nil { close(l.started) } return nil } l.events <- provider.Event{Sequence: 1, SessionID: s.ID, TurnID: t.ID, Kind: "turn.completed", Payload: json.RawMessage(`{"usage":{"input_tokens":2,"cache_read_input_tokens":0,"cache_creation_input_tokens":0,"output_tokens":3}}`)} return nil } func (l *coordinatorFixtureLauncher) Respond(context.Context, provider.Session, provider.Answer) error { return nil } func (l *coordinatorFixtureLauncher) Interrupt(context.Context, provider.Session) error { return nil } func (l *coordinatorFixtureLauncher) Close(context.Context, provider.Session) error { return nil } func coordinatorServiceFixture(t *testing.T) (*CoordinatorService, *coordinatorAPIStub, *coordinatorFixtureLauncher, runnerproto.CoordinatorClaim) { t.Helper() ctx := context.Background() j, err := OpenJournal(ctx, filepath.Join(t.TempDir(), "private", "journal.db")) mustJournal(t, err) t.Cleanup(func() { j.Close() }) c := runnerproto.CoordinatorClaim{Binding: runnerproto.CoordinatorBinding{ID: "binding", Person: "person", Generation: 1}, Turn: runnerproto.CoordinatorTurn{ID: "turn", Revision: 1, Generation: 1}, Scope: team.Scope{Account: "team", Job: 1}, Handle: team.Handle{Attempt: 1, Fence: 1, Runner: "runner"}, LeaseDeadline: time.Now().Add(time.Minute), AttemptDeadline: time.Now().Add(time.Minute)} c.Brief.Selection = runnerproto.Selection{Provider: "claude", Family: "claude", AccountID: "account", Model: "model", Isolation: team.IsolationSnapshot{Status: "confined"}} c.Context, err = runnerproto.BoundCoordinatorContext(runnerproto.CoordinatorContext{ConversationID: "conversation", Revision: 1, Recent: []runnerproto.MessageRef{{ID: "message", AuthorKind: "person", Body: "hello", Sequence: 1, Revision: 1}}}) mustJournal(t, err) c.Turn.ContextHash = c.Context.Hash c.Admission = team.AdmissionTicket{Scope: c.Scope, Handle: c.Handle, Dispatch: team.Dispatch{Action: 1}, ExpiresAt: time.Now().Add(5 * time.Second), Incarnation: 1} a := &coordinatorAPIStub{c: c} l := &coordinatorFixtureLauncher{j: j} s := &CoordinatorService{Journal: j, API: a, Launchers: map[string]provider.Launcher{"claude": l}} s.Contain = func(ctx context.Context, c runnerproto.CoordinatorClaim) (runnerproto.ContainmentProof, error) { _, err := s.Journal.db.ExecContext(ctx, "UPDATE direct_attempts SET contained=1") return runnerproto.ContainmentProof{Version: 2, Scope: c.Scope, Handle: c.Handle, CheckedAt: time.Now()}, err } s.OpenLaunch = func(ctx context.Context, c runnerproto.CoordinatorClaim, p *ToolProxy) (provider.Launch, func() error, error) { l.proxy = p v := provider.Launch{AttemptKey: c.Turn.ID, Binding: provider.Binding{Provider: "claude", AccountID: "account", Expected: provider.Identity{ProviderVersion: "2.1.312"}}, Selection: provider.Selection{Provider: "claude", Family: "claude", AccountID: "account", Model: "model"}, Policy: provider.Policy{Hash: "policy", Manifest: json.RawMessage(`{"Action":"coordinate"}`)}} v.Policy.ManifestHash = team.ContentDigest(v.Policy.Manifest) err := s.Journal.recordDirectLaunch(ctx, v, containment.Record{ID: c.Turn.ID, AttemptKey: v.AttemptKey, ManifestHash: "namespace", PolicyHash: v.Policy.Hash}) return v, func() error { return nil }, err } return s, a, l, c } func TestCoordinatorSessionService(t *testing.T) { s, a, l, c := coordinatorServiceFixture(t) mustJournal(t, s.Poll(context.Background())) if !a.delivery || l.starts != 1 { t.Fatal("service did not deliver admitted turn", a.events) } var n int mustJournal(t, s.Journal.db.QueryRow("SELECT count(*) FROM coordinator_tools").Scan(&n)) if n != 0 { t.Fatal("delivery ACK did not retire tool journal") } if err := s.RunTurn(context.Background(), c); !errors.Is(err, provider.ErrUncertain) { t.Fatal("saved turn redispatched", err) } } func TestCoordinatorSessionProductionWiring(t *testing.T) { c := directRuntimeFixture(t) r, err := openRuntime(context.Background(), c) mustJournal(t, err) defer r.Close() mustJournal(t, r.wire(context.Background())) if r.service.Coordinator == nil || r.service.Coordinator.Journal != r.journal || r.service.Coordinator.OpenLaunch == nil || len(r.service.Coordinator.Launchers) != 2 { t.Fatal("production service omitted coordinator") } } func TestCoordinatorCrashNeverRedispatches(t *testing.T) { for _, phase := range []string{"before-intent", "intent", "stdin", "tool", "ack"} { t.Run(phase, func(t *testing.T) { s, a, l, c := coordinatorServiceFixture(t) if phase == "ack" { a.crash = phase } else { l.crash = phase } _ = s.RunTurn(context.Background(), c) before := l.starts path := s.Journal.path mustJournal(t, s.Journal.Close()) j, err := OpenJournal(context.Background(), path) mustJournal(t, err) defer j.Close() s.Journal = j l.j = j // Finished cleanup is already contained; a runner restart must still refuse dispatch. mustJournal(t, s.Recover(context.Background())) if err = s.RunTurn(context.Background(), c); err == nil || l.starts != before { t.Fatal("uncertain turn resent") } if phase != "ack" && a.delivery { t.Fatal("partial turn reported delivered") } }) } } func TestCoordinatorUsageOnce(t *testing.T) { ctx := context.Background() j, l, s, _ := directFixture(t, "codex") path := j.path for i := 0; i < 3; i++ { if i > 0 { mustJournal(t, j.Close()) var err error j, err = OpenJournal(ctx, path) mustJournal(t, err) defer j.Close() l.AttemptKey = fmt.Sprint(i) s.AttemptKey = l.AttemptKey s.ID = fmt.Sprint(i) mustJournal(t, j.recordDirectLaunch(ctx, l, containment.Record{ID: s.ID, AttemptKey: l.AttemptKey, ManifestHash: "manifest", PolicyHash: l.Policy.Hash})) } turn := directTurn() turn.AdmissionID = fmt.Sprint(i) mustJournal(t, j.BeginTurn(ctx, s, turn)) mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, turn.Prompt)) if i < 2 { ev := codexUsage(turn.ID, 100, 20) ev.SessionID = s.ID _, err := j.ObserveDirect(ctx, s, ev) mustJournal(t, err) } ev := directComplete(turn.ID) ev.SessionID = s.ID u, err := j.ObserveDirect(ctx, s, ev) mustJournal(t, err) again, err := j.ObserveDirect(ctx, s, ev) mustJournal(t, err) if i < 2 && (u == nil || u.InputTokens != 100 || again == nil || *u != *again) { t.Fatal("usage reused another session baseline", u) } if i == 2 && (u != nil || again != nil) { t.Fatal("missing usage became zero") } } } func TestCoordinatorContextDurableIntent(t *testing.T) { j, l, s, _ := directFixture(t, "claude") l.Policy.Manifest = json.RawMessage(`{"Action":"coordinate"}`) l.Policy.ManifestHash = team.ContentDigest(l.Policy.Manifest) _, err := j.db.Exec("UPDATE direct_attempts SET launch=? WHERE attempt=?", marshal(l), l.AttemptKey) mustJournal(t, err) for _, prompt := range []string{strings.Repeat("x", (48<<10)+1), strings.Repeat("\x00", 48<<10)} { turn := directTurn() turn.Prompt = prompt if err = j.BeginTurn(context.Background(), s, turn); err == nil { t.Fatal("durable intent bypassed prompt cap") } } } func TestCoordinatorContextDispatch(t *testing.T) { j, l, s, _ := directFixture(t, "claude") l.Policy.Manifest = json.RawMessage(`{"Action":"coordinate"}`) l.Policy.ManifestHash = team.ContentDigest(l.Policy.Manifest) _, err := j.db.Exec("UPDATE direct_attempts SET launch=? WHERE attempt=?", marshal(l), l.AttemptKey) mustJournal(t, err) prompt := strings.Repeat("x", (48<<10)+1) _, err = j.db.Exec("INSERT INTO direct_turns(turn_key,attempt,session,turn,admission,prompt_hash,state) VALUES('key',?,?,'turn','admission',?,'intent')", s.AttemptKey, s.ID, runnerproto.EventHash(prompt)) mustJournal(t, err) if err = j.consumeTurn(context.Background(), s.AttemptKey, s.ID, prompt); err == nil { t.Fatal("dispatch bypassed coordinator prompt cap") } } func TestCoordinatorCrashRecordedBoundaries(t *testing.T) { for _, phase := range []string{"claim", "intent", "stdin", "tool-commit", "frame", "completed-frame", "server-ack"} { t.Run(phase, func(t *testing.T) { ctx := context.Background() s, a, l, c := coordinatorServiceFixture(t) launch, _, err := s.OpenLaunch(ctx, c, nil) mustJournal(t, err) session := provider.Session{ID: "session", AttemptKey: launch.AttemptKey, Provider: "claude", Family: "claude", AccountID: "account", Model: "model"} mustJournal(t, s.Journal.BindSession(ctx, session)) r := coordinatorState{Claim: c, Session: session} mustJournal(t, s.Journal.saveState(ctx, "coordinator", c.Turn.ID, r)) if phase != "claim" { turn := provider.Turn{ID: c.Turn.ID, AdmissionID: c.Turn.ID, Prompt: "hello"} mustJournal(t, s.Journal.BeginTurn(ctx, session, turn)) if phase != "intent" { mustJournal(t, s.Journal.consumeTurn(ctx, session.AttemptKey, session.ID, turn.Prompt)) } } if phase == "tool-commit" || phase == "frame" || phase == "completed-frame" || phase == "server-ack" { call := runnerproto.CoordinatorToolCall{RequestID: "post", Name: "post_message", Arguments: json.RawMessage(`{"body":"answer","source_refs":[]}`)} mustJournal(t, s.Journal.submitCoordinatorTool(ctx, c, session, call)) // The instance committed, but no response reached the local tool journal. } if phase == "frame" { mustJournal(t, s.Journal.AppendFrame(ctx, launch.AttemptKey, c.Turn.ID, 1, json.RawMessage(`{"type":"result","session_id":"session"}`))) } if phase == "completed-frame" || phase == "server-ack" { pump := EventPump{Journal: s.Journal, Contain: func(context.Context) error { return nil }} mustJournal(t, pump.AppendDirect(ctx, session, provider.Event{SessionID: session.ID, TurnID: c.Turn.ID, Kind: "turn.completed", Payload: json.RawMessage(`{}`)}, s.template(r))) } if phase == "server-ack" { mustJournal(t, s.reconcileTools(ctx, r)) a.crash = "ack" if err = s.finishDelivery(ctx, r); err == nil { t.Fatal("lost server ACK not injected") } } path := s.Journal.path mustJournal(t, s.Journal.Close()) j, err := OpenJournal(ctx, path) mustJournal(t, err) defer j.Close() s.Journal = j l.j = j mustJournal(t, s.Recover(ctx)) mustJournal(t, s.Recover(ctx)) if l.starts != 0 { t.Fatal("crash recovery redispatched prompt") } want := phase == "completed-frame" || phase == "server-ack" if a.delivery != want { t.Fatalf("recovery outcome %s: delivered %v", phase, a.delivery) } pending, err := j.Pending(ctx, 128) mustJournal(t, err) if len(pending) != 0 { t.Fatal("coordinator events leaked to task uploader") } }) } } func TestCoordinatorStopContains(t *testing.T) { s, _, l, c := coordinatorServiceFixture(t) l.crash = "stdin" released := false contained := false open := s.OpenLaunch s.OpenLaunch = func(ctx context.Context, c runnerproto.CoordinatorClaim, p *ToolProxy) (provider.Launch, func() error, error) { v, _, err := open(ctx, c, p) return v, func() error { if !contained { t.Error("account lease released before every namespace stopped") } released = true return nil }, err } contain := s.Contain s.Contain = func(context.Context, runnerproto.CoordinatorClaim) (runnerproto.ContainmentProof, error) { return runnerproto.ContainmentProof{}, provider.ErrContainment } if err := s.RunTurn(context.Background(), c); err == nil || released { t.Fatal("unknown namespace released account lease") } s.Contain = func(ctx context.Context, c runnerproto.CoordinatorClaim) (runnerproto.ContainmentProof, error) { contained = true return contain(ctx, c) } mustJournal(t, s.Recover(context.Background())) if !released { t.Fatal("contained turn retained account lease") } if err := s.Journal.currentDirectTurn(context.Background(), l.session, c.Turn.ID); err == nil { t.Fatal("late answer accepted after stop") } var usage []byte mustJournal(t, s.Journal.db.QueryRow("SELECT usage FROM direct_turns WHERE turn=?", c.Turn.ID).Scan(&usage)) if len(usage) != 0 { t.Fatal("unknown usage became known on stop") } }