package coordinator import ( "context" "encoding/json" "errors" "fmt" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo/team" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runnerproto" ) func contextFixture() runnerproto.CoordinatorContext { return runnerproto.CoordinatorContext{ConversationID: "conversation", Revision: 1, ConfirmedDecisions: []runnerproto.ContextRef{{Source: team.SourceRef{Kind: "answer", ID: "answer", Revision: 1, Hash: team.ContentDigest([]byte("keep decision"))}, Text: "keep decision"}}} } func TestCoordinatorContextBounds(t *testing.T) { c := contextFixture() for i := 0; i < 100; i++ { c.Recent = append(c.Recent, runnerproto.MessageRef{ID: fmt.Sprint(i), AuthorKind: "person", Body: strings.Repeat("x", 16384), Sequence: int64(i + 1), Revision: 1}) } bounded, err := runnerproto.BoundCoordinatorContext(c) if err != nil { t.Fatal(err) } if len(bounded.Recent) != 2 || bounded.Recent[0].ID != "98" || bounded.Recent[1].ID != "99" { t.Fatal("history did not trim oldest first") } if bounded.Hash == "" || bounded.Hash != runnerproto.CoordinatorContextHash(bounded) { t.Fatal("snapshot hash mismatch") } prompt, err := runnerproto.CoordinatorPrompt(bounded) if err != nil { t.Fatal(err) } if !strings.Contains(prompt, "keep decision") { t.Fatal("required decision trimmed") } if _, err = runnerproto.CoordinatorTurnIntentPayload("claude", "model", prompt); err != nil { t.Fatal(err) } for _, text := range []string{strings.Repeat("a", 48<<10), strings.Repeat("\x00", 15000)} { if _, err = runnerproto.CoordinatorTurnIntentPayload("claude", "model", text); err != nil && len(text) == 48<<10 { t.Fatal("48 KiB boundary rejected", err) } } if _, err = runnerproto.CoordinatorTurnIntentPayload("claude", "model", strings.Repeat("a", (48<<10)+1)); err == nil { t.Fatal("raw cap bypassed") } if _, err = runnerproto.CoordinatorTurnIntentPayload("claude", "model", strings.Repeat("\x00", 48<<10)); err == nil { t.Fatal("escaped frame cap bypassed") } for _, n := range []int{9556, 9557} { _, err := runnerproto.CoordinatorTurnIntentPayload("claude", "model", strings.Repeat("\x00", n)) if (err != nil) != (n == 9557) { t.Fatal("frame boundary incorrect", n, err) } } c = contextFixture() c.Instructions = []runnerproto.ContextRef{{Text: strings.Repeat("x", 49<<10)}} if _, err = runnerproto.BoundCoordinatorContext(c); !errors.Is(err, runnerproto.ErrPromptTooLarge) { t.Fatal("oversized required content accepted", err) } c = contextFixture() c.Recent = []runnerproto.MessageRef{{Body: strings.Repeat("\x00", 16000)}} bounded, err = runnerproto.BoundCoordinatorContext(c) if !errors.Is(err, runnerproto.ErrPromptTooLarge) { t.Fatal("escaped admitted request was trimmed", err) } c = contextFixture() c.Retrieved = []runnerproto.ContextRef{{Text: strings.Repeat("x", 48<<10)}} bounded, err = runnerproto.BoundCoordinatorContext(c) if err != nil || len(bounded.Retrieved) != 0 { t.Fatal("optional retrieval blocked turn", err) } } type runtimeTools struct{} func (runtimeTools) Call(context.Context, CoordinatorToolCall) (CoordinatorToolResult, error) { return CoordinatorToolResult{}, nil } type runtimeLauncher struct { opens, starts, preflights, closes int events chan provider.Event launch provider.Launch hold bool attached bool } func (l *runtimeLauncher) Preflight(_ context.Context, b provider.Binding, _ provider.Policy) (provider.Identity, error) { l.preflights++ return b.Expected, nil } func (l *runtimeLauncher) Open(_ context.Context, v provider.Launch) (provider.Session, error) { l.opens++ l.launch = v l.events = make(chan provider.Event, 4) return provider.Session{ID: fmt.Sprint(l.opens), AttemptKey: v.AttemptKey, Provider: v.Selection.Provider, Model: v.Selection.Model, AccountID: v.Selection.AccountID, Family: v.Selection.Family}, nil } func (l *runtimeLauncher) Events(context.Context, provider.Session) (<-chan provider.Event, error) { l.attached = true return l.events, nil } func (l *runtimeLauncher) StartTurn(_ context.Context, s provider.Session, v provider.Turn) error { if !l.attached { return provider.ErrContract } l.starts++ if !l.hold { l.events <- provider.Event{SessionID: s.ID, TurnID: v.ID, Kind: "turn.completed", Payload: json.RawMessage(`{}`)} } return nil } func (l *runtimeLauncher) Respond(context.Context, provider.Session, provider.Answer) error { return nil } func (l *runtimeLauncher) Interrupt(context.Context, provider.Session) error { return nil } func (l *runtimeLauncher) Close(context.Context, provider.Session) error { l.closes++; return nil } func runtimeClaim(t *testing.T) runnerproto.CoordinatorClaim { t.Helper() c, err := runnerproto.BoundCoordinatorContext(contextFixture()) if err != nil { t.Fatal(err) } return runnerproto.CoordinatorClaim{Binding: runnerproto.CoordinatorBinding{ID: "binding", Generation: 1}, Turn: runnerproto.CoordinatorTurn{ID: "turn", Generation: 1, ContextHash: c.Hash}, Context: c, Brief: runnerproto.RunnerBrief{Selection: runnerproto.Selection{Provider: "claude", AccountID: "account", Family: "claude", Model: "model"}}, Admission: team.AdmissionTicket{}, AttemptDeadline: time.Now().Add(time.Minute)} } func runtimeLaunch(c runnerproto.CoordinatorClaim) provider.Launch { s := c.Brief.Selection return provider.Launch{AttemptKey: c.Turn.ID, Selection: provider.Selection{Provider: s.Provider, Family: s.Family, AccountID: s.AccountID, Model: s.Model}, Binding: provider.Binding{Provider: s.Provider, AccountID: s.AccountID, Expected: provider.Identity{AccountID: s.AccountID}}, Policy: provider.Policy{Hash: "policy", Manifest: json.RawMessage(`{"Action":"coordinate"}`), ManifestHash: team.ContentDigest([]byte(`{"Action":"coordinate"}`))}} } func TestCoordinatorFreshTurnRevalidates(t *testing.T) { for _, change := range []string{"resume", "model", "provider", "identity", "policy", "tool-policy", "revoked", "generation", "hash"} { t.Run(change, func(t *testing.T) { c := runtimeClaim(t) l := &runtimeLauncher{} r, err := New(Config{Launcher: l, Tools: runtimeTools{}, OpenLaunch: func(_ context.Context, c runnerproto.CoordinatorClaim) (provider.Launch, error) { v := runtimeLaunch(c) if change == "revoked" { return v, provider.ErrIdentity } switch change { case "tool-policy": v.Policy.Manifest = json.RawMessage(`{"Action":"implement"}`) v.Policy.ManifestHash = team.ContentDigest(v.Policy.Manifest) case "policy": v.Policy.Hash = "" case "resume": v.ResumeSessionID = "old" case "model": v.Selection.Model = "other" case "provider": v.Selection.Provider = "codex" case "identity": v.Binding.AccountID = "other" } return v, nil }, Record: func(context.Context, provider.Event) error { return nil }}) if err != nil { t.Fatal(err) } if change == "generation" { c.Turn.Generation++ } if change == "hash" { c.Context.Hash = "forged" } if err = r.RunTurn(context.Background(), c); err == nil || l.starts != 0 || l.opens != 0 { t.Fatal("changed authority dispatched", err) } }) } l := &runtimeLauncher{} r, _ := New(Config{Launcher: l, Tools: runtimeTools{}, OpenLaunch: func(_ context.Context, c runnerproto.CoordinatorClaim) (provider.Launch, error) { return runtimeLaunch(c), nil }, Record: func(context.Context, provider.Event) error { return nil }}) for i := 0; i < 2; i++ { c := runtimeClaim(t) c.Turn.ID = fmt.Sprint(i) if err := r.RunTurn(context.Background(), c); err != nil { t.Fatal(err) } } if l.preflights != 2 || l.closes != 2 || l.starts != 2 { t.Fatal("fresh turn reused validation or session", l) } }