package runner import ( "context" "encoding/json" "path/filepath" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runnerproto" ) type answerClient struct { responses []provider.PermissionResponse sends int } func (c *answerClient) Respond(_ context.Context, _ provider.Agent, r provider.PermissionResponse) error { c.responses = append(c.responses, r) return nil } func (c *answerClient) Send(_ context.Context, _ provider.Agent, _, _ string) error { c.sends++ return nil } func TestQuestionPermissionID(t *testing.T) { a := provider.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"} q := runnerproto.Question{ID: "q", TaskID: "task", ServerID: "server", AgentID: "agent", SessionID: "session", PermissionID: "original", Kind: "question", Revision: 1, RawRequest: json.RawMessage(`{"id":"original","kind":"question","provider":"claude","name":"AskUserQuestion","input":{"questions":[{"question":"Which?","header":"Which?"}]}}`)} q.ExpiresAt = time.Now().Add(time.Minute) c := &answerClient{} answer := runnerproto.QuestionAnswer{Behavior: "allow", UpdatedInput: json.RawMessage(`{"answers":{"Which?":"Yes"}}`)} if err := DeliverAnswer(context.Background(), c, a, q, answer); err != nil { t.Fatal(err) } if c.sends != 0 || len(c.responses) != 1 || c.responses[0].RequestID != "original" || string(c.responses[0].UpdatedInput) != string(answer.UpdatedInput) { t.Fatal("answer must Respond with original ID and answers") } q.Kind = "unknown" if DeliverAnswer(context.Background(), c, a, q, answer) == nil { t.Fatal("unknown permission approved") } q.Kind = "permission" if DeliverAnswer(context.Background(), c, a, q, answer) == nil { t.Fatal("permission widened policy") } q.Kind = "question" a.ProviderSessionID = "replacement" if DeliverAnswer(context.Background(), c, a, q, answer) == nil { t.Fatal("replaced session answered") } } func TestQuestionFollowupAdmission(t *testing.T) { c := &answerClient{} a := provider.Agent{AgentID: "agent"} if SendFollowup(context.Background(), c, a, "hello", "turn", nil) == nil || c.sends != 0 { t.Fatal("hidden turn without admission") } if SendFollowup(context.Background(), c, a, "hello", "denied", func(context.Context, string) error { return runnerproto.ErrInvalid }) == nil || c.sends != 0 { t.Fatal("turn sent without budget admission") } if err := SendFollowup(context.Background(), c, a, "hello", "turn", func(context.Context, string) error { return nil }); err != nil || c.sends != 1 { t.Fatal("admitted conversational followup did not Send", err) } } func TestQuestionDeliveryReplay(t *testing.T) { j, err := OpenJournal(context.Background(), filepath.Join(t.TempDir(), "private", "journal.db")) mustJournal(t, err) defer j.Close() q := runnerproto.Question{ID: "q", TaskID: "task", ServerID: "server", AgentID: "agent", SessionID: "session", PermissionID: "original", Kind: "question", Attempt: 1, Fence: 1, Revision: 1, ExpiresAt: time.Now().Add(time.Minute), RawRequest: json.RawMessage(`{"id":"original","kind":"question","provider":"claude","name":"AskUserQuestion","input":{"questions":[{"question":"Which?"}]}}`)} c := &answerClient{} current := true relay := QuestionRelay{Journal: j, Client: c, Agent: provider.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"}, Current: func(context.Context, runnerproto.Question) (time.Time, error) { if !current { return time.Time{}, runnerproto.ErrInvalid } return q.ExpiresAt, nil }} answer := runnerproto.QuestionAnswer{Behavior: "deny"} mustJournal(t, relay.Deliver(context.Background(), q, answer)) mustJournal(t, relay.Deliver(context.Background(), q, answer)) if len(c.responses) != 1 { t.Fatal("answer replay duplicated Respond") } answer = runnerproto.QuestionAnswer{Behavior: "allow", UpdatedInput: json.RawMessage(`{"answers":{"Which?":"yes"}}`)} if relay.Deliver(context.Background(), q, answer) == nil { t.Fatal("changed answer replay accepted") } changed := q changed.RawRequest = json.RawMessage(`{"id":"original","kind":"question","title":"Changed request"}`) if relay.Deliver(context.Background(), changed, runnerproto.QuestionAnswer{Behavior: "deny"}) == nil { t.Fatal("changed permission request replay accepted") } current = false if relay.Deliver(context.Background(), q, runnerproto.QuestionAnswer{Behavior: "deny"}) == nil { t.Fatal("stale replay accepted") } } func TestQuestionSanitizedFixtures(t *testing.T) { for _, providerName := range []string{"claude", "codex"} { name := "AskUserQuestion" if providerName == "codex" { name = "request_user_input" } payload := json.RawMessage(`{"request":{"id":"original","kind":"question","provider":"` + providerName + `","name":"` + name + `","input":{"questions":[{"question":"Which?"}],"api_token":"secret-sentinel"}}}`) q, err := QuestionFromEvent(provider.RecordedEvent{PermissionID: "original", ServerID: "server", AgentID: "agent", ProviderSessionID: "session", Payload: payload}, "q", "task", []string{"secret-sentinel"}) mustJournal(t, err) if strings.Contains(string(q.RawRequest), "secret-sentinel") || !strings.Contains(string(q.RawRequest), "Which?") { t.Fatal("sanitization lost request or leaked secret") } } if _, err := QuestionFromEvent(provider.RecordedEvent{PermissionID: "id", Payload: json.RawMessage(`{"request":"unknown"}`)}, "q", "task", nil); err == nil { t.Fatal("unsupported shape answered") } } func TestQuestionExpiredWaitContains(t *testing.T) { j, err := OpenJournal(context.Background(), filepath.Join(t.TempDir(), "private", "journal.db")) mustJournal(t, err) defer j.Close() q := runnerproto.Question{ID: "q", TaskID: "task", ServerID: "server", AgentID: "agent", SessionID: "session", PermissionID: "p", Kind: "question", Attempt: 1, Fence: 1, Revision: 1, ExpiresAt: time.Now().Add(-time.Second), RawRequest: json.RawMessage(`{"id":"p","kind":"question"}`)} c := &answerClient{} r := QuestionRelay{Journal: j, Client: c, Agent: provider.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"}, Current: func(context.Context, runnerproto.Question) (time.Time, error) { return q.ExpiresAt, nil }} contained := 0 if r.Wait(context.Background(), q, func(context.Context) (*runnerproto.QuestionAnswer, error) { t.Fatal("polled expired wait") return nil, nil }, func(context.Context) error { contained++; return nil }) == nil || contained != 1 { t.Fatal("expired wait not contained") } q.ExpiresAt = time.Now().Add(time.Minute) if r.Deliver(context.Background(), q, runnerproto.QuestionAnswer{Behavior: "deny"}) == nil || len(c.responses) != 0 { t.Fatal("expired permission ID revived") } } type uncertainAnswerClient struct{ answerClient } func (c *uncertainAnswerClient) Respond(ctx context.Context, a provider.Agent, r provider.PermissionResponse) error { _ = c.answerClient.Respond(ctx, a, r) return provider.ErrUncertain } func TestQuestionUncertainDelivery(t *testing.T) { path := filepath.Join(t.TempDir(), "private", "journal.db") j, err := OpenJournal(context.Background(), path) mustJournal(t, err) q := runnerproto.Question{ID: "q", TaskID: "task", ServerID: "server", AgentID: "agent", SessionID: "session", PermissionID: "p", Kind: "question", Attempt: 1, Fence: 1, Revision: 1, ExpiresAt: time.Now().Add(time.Minute), RawRequest: json.RawMessage(`{"id":"p","kind":"question"}`)} c := &uncertainAnswerClient{} r := QuestionRelay{Journal: j, Client: c, Agent: provider.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"}, Current: func(context.Context, runnerproto.Question) (time.Time, error) { return q.ExpiresAt, nil }} if r.Deliver(context.Background(), q, runnerproto.QuestionAnswer{Behavior: "deny"}) == nil { t.Fatal("lost response treated as delivered") } mustJournal(t, j.Close()) j, err = OpenJournal(context.Background(), path) mustJournal(t, err) defer j.Close() r.Journal = j if r.Deliver(context.Background(), q, runnerproto.QuestionAnswer{Behavior: "deny"}) == nil || len(c.responses) != 1 { t.Fatal("uncertain response resent after restart") } } func TestQuestionAnswerFormats(t *testing.T) { a := runnerproto.QuestionAnswer{Behavior: "allow", UpdatedInput: json.RawMessage(`{"answers":{"Which?":"yes"}}`)} q := runnerproto.Question{RawRequest: json.RawMessage(`{"provider":"claude","name":"AskUserQuestion","input":{"questions":[{"question":"Which?","header":"Header"}]}}`), Kind: "question"} mustJournal(t, q.ValidateAnswer(a)) for _, raw := range []string{`{"answers":{"unasked":"yes"}}`, `{"answers":{"Which?":"yes"},"permissions":["all"]}`, `{"answers":{"Which?":[]}}`, `{"answers":{"Which?":""}}`, `{"answers":{"Which?":"yes","Which?":"no"}}`} { bad := a bad.UpdatedInput = json.RawMessage(raw) if q.ValidateAnswer(bad) == nil { t.Fatal("unsupported answers accepted", raw) } } q.RawRequest = json.RawMessage(`{"provider":"codex","name":"request_user_input","input":{"questions":[{"question":"Question text","header":"Which?"}]}}`) mustJournal(t, q.ValidateAnswer(a)) q.RawRequest = json.RawMessage(`{"provider":"future","name":"AskUserQuestion","input":{"questions":[{"question":"Which?"}]}}`) if q.ValidateAnswer(a) == nil { t.Fatal("unknown provider shape approved") } for _, kind := range []string{"tool", "plan", "mode", "other"} { if a.Validate(kind) == nil { t.Fatal("permission policy widened", kind) } mustJournal(t, (runnerproto.QuestionAnswer{Behavior: "deny"}).Validate(kind)) } } func TestQuestionRejectsMalformedBeforeSanitizing(t *testing.T) { e := provider.RecordedEvent{PermissionID: "p", ServerID: "server", AgentID: "agent", ProviderSessionID: "session", Payload: json.RawMessage(`{"request":{"id":"p","kind":"unknown","kind":"question"}}`)} if _, err := QuestionFromEvent(e, "q", "task", nil); err == nil { t.Fatal("sanitization hid malformed permission") } } func TestQuestionDeliveryBindingAndExpiry(t *testing.T) { q := runnerproto.Question{ID: "q", TaskID: "task", ServerID: "server", AgentID: "agent", SessionID: "session", PermissionID: "p", Kind: "question", RawRequest: json.RawMessage(`{"id":"p","kind":"question"}`)} a := provider.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"} answer := runnerproto.QuestionAnswer{Behavior: "deny"} for _, field := range []string{"server", "agent", "session", "expiry", "zero_expiry"} { bad := q bad.ExpiresAt = time.Now().Add(time.Minute) switch field { case "server": bad.ServerID = "other" case "agent": bad.AgentID = "other" case "session": bad.SessionID = "other" case "zero_expiry": bad.ExpiresAt = time.Time{} case "expiry": bad.ExpiresAt = time.Now().Add(-time.Second) } if DeliverAnswer(context.Background(), &answerClient{}, a, bad, answer) == nil { t.Fatal("answer binding accepted", field) } } } func TestQuestionWaitRenewedLease(t *testing.T) { j, err := OpenJournal(context.Background(), filepath.Join(t.TempDir(), "private", "journal.db")) mustJournal(t, err) defer j.Close() q := runnerproto.Question{ID: "q", TaskID: "task", ServerID: "server", AgentID: "agent", SessionID: "session", PermissionID: "p", Kind: "question", Attempt: 1, Fence: 1, Revision: 1, ExpiresAt: time.Now().Add(-time.Second), RawRequest: json.RawMessage(`{"id":"p","kind":"question"}`)} c := &answerClient{} live := time.Now().Add(time.Minute) r := QuestionRelay{Journal: j, Client: c, Agent: provider.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"}} // The supervisor has renewed the lease before the earlier bound expired. r.Current = func(context.Context, runnerproto.Question) (time.Time, error) { return live, nil } contained := 0 mustJournal(t, r.Wait(context.Background(), q, func(context.Context) (*runnerproto.QuestionAnswer, error) { return &runnerproto.QuestionAnswer{Behavior: "deny"}, nil }, func(context.Context) error { contained++; return nil })) if len(c.responses) != 1 || contained != 0 { t.Fatal("renewed wait lost answer") } live = time.Now().Add(-time.Second) if r.Wait(context.Background(), q, func(context.Context) (*runnerproto.QuestionAnswer, error) { t.Fatal("polled lost lease") return nil, nil }, func(context.Context) error { contained++; return nil }) == nil || contained != 1 { t.Fatal("lost wait not contained") } live = time.Now().Add(time.Minute) if r.Deliver(context.Background(), q, runnerproto.QuestionAnswer{Behavior: "deny"}) == nil || len(c.responses) != 1 { t.Fatal("lost permission revived") } } func TestQuestionWaitRenewedDuringPoll(t *testing.T) { j, err := OpenJournal(context.Background(), filepath.Join(t.TempDir(), "private", "journal.db")) mustJournal(t, err) defer j.Close() q := runnerproto.Question{ID: "q", TaskID: "task", ServerID: "server", AgentID: "agent", SessionID: "session", PermissionID: "p", Kind: "question", Attempt: 1, Fence: 1, Revision: 1, ExpiresAt: time.Now().Add(200 * time.Millisecond), RawRequest: json.RawMessage(`{"id":"p","kind":"question"}`)} bound := q.ExpiresAt c := &answerClient{} r := QuestionRelay{Journal: j, Client: c, Agent: provider.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"}, Current: func(context.Context, runnerproto.Question) (time.Time, error) { return bound, nil }} polls := 0 err = r.Wait(context.Background(), q, func(ctx context.Context) (*runnerproto.QuestionAnswer, error) { polls++ if polls == 1 { bound = bound.Add(time.Second) <-ctx.Done() return nil, ctx.Err() } return &runnerproto.QuestionAnswer{Behavior: "deny"}, nil }, func(context.Context) error { t.Error("renewal during poll contained live wait"); return nil }) mustJournal(t, err) if len(c.responses) != 1 { t.Fatal("renewal during poll lost answer") } }