package runner import ( "context" "encoding/json" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runnerproto" ) type approvalAPI struct{ values []runnerproto.Question } func (a *approvalAPI) Call(_ context.Context, _ string, _ runnerproto.RunnerRequest, out any) error { *out.(*[]runnerproto.Question) = a.values return nil } func TestDirectStaleAnswerNativeCurrent(t *testing.T) { q := runnerproto.Question{ID: "q", TaskID: "task", Attempt: 1, Fence: 7, AgentID: "agent", SessionID: "session", PermissionID: "7", Revision: 1, AnsweredBy: "person", RawRequest: json.RawMessage(`{"command":"printf hello"}`), Answer: &runnerproto.QuestionAnswer{Behavior: "allow"}} for _, change := range []string{"removed", "person", "payload", "answer", "fence", "attempt", "task", "revision"} { t.Run(change, func(t *testing.T) { saved := q api := &approvalAPI{values: []runnerproto.Question{saved}} switch change { case "removed": api.values = nil case "person": api.values[0].AnsweredBy = "other" case "payload": api.values[0].RawRequest = json.RawMessage(`{"command":"changed"}`) case "answer": api.values[0].Answer = &runnerproto.QuestionAnswer{Behavior: "deny"} case "fence": api.values[0].Fence++ case "attempt": api.values[0].Attempt++ case "task": api.values[0].TaskID = "other" case "revision": api.values[0].Revision++ } s := &Supervisor{api: api} if _, err := s.currentDirectQuestion(context.Background(), &attemptState{}, q, func(context.Context) error { return nil }); err == nil { t.Fatal("stale answer accepted", change) } }) } } type nativeAnswerLauncher struct { directAnswerLauncher event provider.Event change func(provider.Event) provider.Event sent int before func() } func (l *nativeAnswerLauncher) Respond(ctx context.Context, _ provider.Session, a provider.Answer) error { if l.before != nil { l.before() } if a.Behavior == "allow" { if a.Authorize == nil { return provider.ErrPolicy } ev := l.event if l.change != nil { ev = l.change(ev) } if err := a.Authorize(ctx, ev); err != nil { return err } } l.sent++ return nil } func TestCodexApprovalJournalAndExactRequest(t *testing.T) { for _, change := range []string{"none", "id", "item", "turn", "session", "command", "cwd", "revoked", "redacted"} { t.Run(change, func(t *testing.T) { b := directToolFixture(t) ctx := context.Background() ev := provider.Event{Kind: "request", RequestID: "7", SessionID: b.Session.ID, TurnID: b.TurnID, Payload: json.RawMessage(`{"id":7,"method":"item/commandExecution/requestApproval","params":{"threadId":"session","turnId":"provider-turn","itemId":"item","command":"printf hello","cwd":"/workspace"}}`)} if change == "redacted" { ev.Payload = json.RawMessage(strings.Replace(string(ev.Payload), "printf hello", "printf Bearer secret-token-value", 1)) } l := &nativeAnswerLauncher{event: ev} l.before = func() { var records []runnerproto.Question mustJournal(t, b.Journal.readStates(ctx, "profile-approval", &records)) if len(records) == 0 || records[0].AnsweredBy != "person@example.com" { t.Fatal("approval was not durable before provider I/O") } } current := true l.change = func(ev provider.Event) provider.Event { switch change { case "id": ev.RequestID = "8" case "turn": ev.TurnID = "other" case "session": ev.SessionID = "other" case "item": ev.Payload = json.RawMessage(strings.Replace(string(ev.Payload), `"itemId":"item"`, `"itemId":"other"`, 1)) case "command": ev.Payload = json.RawMessage(strings.Replace(string(ev.Payload), "printf hello", "printf changed", 1)) case "cwd": ev.Payload = json.RawMessage(strings.Replace(string(ev.Payload), "/workspace", "/elsewhere", 1)) case "revoked": current = false } return ev } person := "person@example.com" relay := DirectQuestionRelay{Binding: b, Launcher: l, Answerer: func(context.Context, runnerproto.Question) (string, error) { return person, nil }, Current: func(context.Context, runnerproto.Question) (time.Time, error) { if !current { return time.Time{}, provider.ErrPolicy } return b.LeaseDeadline, nil }} asks := 0 ask := func(context.Context, runnerproto.Question) (runnerproto.QuestionAnswer, error) { asks++ return runnerproto.QuestionAnswer{Behavior: "allow"}, nil } err := relay.Handle(ctx, ev, ask) if change != "none" { if err == nil || l.sent != 0 { t.Fatal("changed or revoked request approved", change) } return } mustJournal(t, err) ev.RequestID = "8" ev.Payload = json.RawMessage(strings.Replace(string(ev.Payload), `"id":7`, `"id":8`, 1)) l.event = ev mustJournal(t, relay.Handle(ctx, ev, ask)) if asks != 2 || l.sent != 2 { t.Fatal("later identical request reused approval", asks, l.sent) } var saved []runnerproto.Question mustJournal(t, b.Journal.readStates(ctx, "profile-approval", &saved)) if len(saved) != 2 { t.Fatal("durable approval absent", len(saved)) } for _, q := range saved { if q.AnsweredBy != "person@example.com" || !strings.Contains(string(q.RawRequest), "printf hello") || !strings.Contains(string(q.RawRequest), "provider-turn") || q.Answer == nil || q.Answer.Behavior != "allow" { t.Fatal("journal lost request or allowing person", q) } } person = "other@example.com" if relay.Handle(ctx, ev, ask) == nil { t.Fatal("changed allowing person replay accepted") } }) } } func TestCodexApprovalJournalWriteFailure(t *testing.T) { b := directToolFixture(t) ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() ev := provider.Event{Kind: "request", RequestID: "7", SessionID: b.Session.ID, TurnID: b.TurnID, Payload: json.RawMessage(`{"id":7,"method":"item/commandExecution/requestApproval","params":{"threadId":"session","turnId":"provider-turn","itemId":"item","command":"printf hello","cwd":"/workspace"}}`)} q, err := DirectQuestionFromEvent(ev, b) mustJournal(t, err) q.AnsweredBy = "person@example.com" _, err = b.Journal.db.Exec("CREATE TRIGGER reject_approval BEFORE INSERT ON journal_supervisor WHEN NEW.kind='profile-approval' BEGIN SELECT RAISE(ABORT,'approval write refused'); END") mustJournal(t, err) client := &answerClient{} relay := QuestionRelay{Journal: b.Journal, Client: client, Agent: b.Agent, DirectSession: b.Session, TurnID: b.TurnID, Current: func(context.Context, runnerproto.Question) (time.Time, error) { return b.LeaseDeadline, nil }} err = relay.Deliver(ctx, q, runnerproto.QuestionAnswer{Behavior: "allow"}) if err == nil || len(client.responses) != 0 { t.Fatal("approval sent without durable evidence", err) } if ctx.Err() != nil { t.Fatal("journal failure waited for the request deadline instead of releasing the write transaction") } if b.Journal.AdmissionAllowed(context.Background()) == nil { t.Fatal("journal failure did not fence admission") } var count int mustJournal(t, b.Journal.db.QueryRow("SELECT count(*) FROM journal_answers").Scan(&count)) if count != 0 { t.Fatal("partial approval transaction persisted") } } func TestClaudeApprovalJournalBeyondProfile(t *testing.T) { b := directToolFixture(t) j, _, session, _ := directFixture(t, "claude") ctx := context.Background() mustJournal(t, j.BeginTurn(ctx, session, directTurn())) mustJournal(t, j.consumeTurn(ctx, session.AttemptKey, session.ID, "hello")) b.Journal = j b.Session = session b.Agent.Provider = "claude" b.Agent.AgentID = session.AttemptKey b.Agent.ProviderSessionID = session.ID ev := provider.Event{Kind: "request", RequestID: "permission:write", SessionID: session.ID, TurnID: b.TurnID, Payload: json.RawMessage(`{"tool_name":"Write","tool_use_id":"write","input":{"file_path":"/outside/file","content":"x"}}`)} l := &nativeAnswerLauncher{event: ev} relay := DirectQuestionRelay{Binding: b, Launcher: l, Current: func(context.Context, runnerproto.Question) (time.Time, error) { return b.LeaseDeadline, nil }, Answerer: func(context.Context, runnerproto.Question) (string, error) { return "person@example.com", nil }} mustJournal(t, relay.Handle(ctx, ev, func(_ context.Context, q runnerproto.Question) (runnerproto.QuestionAnswer, error) { if q.ValidateAnswer(runnerproto.QuestionAnswer{Behavior: "allow"}) != nil || q.ValidateAnswer(runnerproto.QuestionAnswer{Behavior: "deny"}) != nil { t.Fatal("missing Allow once/Deny") } return runnerproto.QuestionAnswer{Behavior: "allow"}, nil })) var records []runnerproto.Question mustJournal(t, j.readStates(ctx, "profile-approval", &records)) if len(records) != 1 { t.Fatal("out-of-profile approval not journaled") } }