package runner import ( "bufio" "context" "encoding/json" "fmt" "os" "os/exec" "path/filepath" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo/team" "amadan.net/oficina/equipo/internal/runner/containment" "amadan.net/oficina/equipo/internal/testci" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runnerproto" ) func directToolFixture(t *testing.T) ToolBinding { t.Helper() j, _, s, _ := directFixture(t, "codex") mustJournal(t, j.BeginTurn(context.Background(), s, directTurn())) mustJournal(t, j.consumeTurn(context.Background(), s.AttemptKey, s.ID, "hello")) return ToolBinding{Journal: j, Session: s, TurnID: "turn", InstanceID: "instance", TaskID: "task", Attempt: 1, Fence: 7, Tools: []string{"ask_person", "submit_candidate", "submit_review", "submit_reproduction"}, LeaseDeadline: time.Now().Add(time.Minute), Agent: provider.Agent{Provider: "codex", ServerID: "direct", AgentID: s.AttemptKey, ProviderSessionID: s.ID}, Isolation: team.IsolationSnapshot{Status: "confined"}, Copy: ToolCopy{Accepted: "accepted", Rejected: "rejected"}, Current: func(context.Context) error { return nil }} } func TestDirectToolScope(t *testing.T) { b := directToolFixture(t) p, e := OpenToolProxy(context.Background(), b) mustJournal(t, e) defer p.Close() binary := filepath.Join(t.TempDir(), "equipo-tool-proxy") build := exec.Command("go", "build", "-o", binary, "../../cmd/equipo-tool-proxy") build.Env = append(os.Environ(), "CGO_ENABLED=0") testci.GoCommand(t, build) if out, e := build.CombinedOutput(); e != nil { t.Fatalf("build: %v %s", e, out) } ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() cmd := exec.CommandContext(ctx, binary, "--socket", p.SocketPath) cmd.Env = []string{"PATH=/usr/bin:/bin"} in, e := cmd.StdinPipe() mustJournal(t, e) out, e := cmd.StdoutPipe() mustJournal(t, e) mustJournal(t, cmd.Start()) t.Cleanup(func() { if cmd.ProcessState == nil { cmd.Process.Kill() cmd.Wait() } }) enc := json.NewEncoder(in) scan := bufio.NewScanner(out) rpc := func(id int, method string, params any) map[string]any { t.Helper() mustJournal(t, enc.Encode(map[string]any{"jsonrpc": "2.0", "id": id, "method": method, "params": params})) if !scan.Scan() { t.Fatal("no helper reply", scan.Err()) } var v map[string]any mustJournal(t, json.Unmarshal(scan.Bytes(), &v)) return v } if rpc(1, "initialize", map[string]any{"protocolVersion": "2025-06-18", "capabilities": map[string]any{}, "clientInfo": map[string]any{}})["error"] != nil { t.Fatal("initialize") } tools := fmt.Sprint(rpc(2, "tools/list", map[string]any{})) if strings.Contains(tools, "publish") || strings.Contains(tools, "attest") { t.Fatal(tools) } args := []string{`{"request_id":"a","question":"Which?"}`, `{"request_id":"b","commit":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}`, `{"request_id":"c","candidate":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","decision":"approve","findings":[]}`, `{"request_id":"d","expected_symptom":"fails","files":[{"path":"x_test.go","bytes":"eA=="}],"test_names":[{"package":"./x","name":"TestX"}]}`} for i, name := range b.Tools { if v := rpc(3+i, "tools/call", map[string]any{"name": name, "arguments": json.RawMessage(args[i])}); v["error"] != nil { t.Fatal(name, v) } rows, e := b.Journal.ToolSubmissions(ctx, 10) mustJournal(t, e) if len(rows) != 1 || rows[0].Fence != 7 || rows[0].Agent.ProviderSessionID != b.Session.ID { t.Fatal(rows) } mustJournal(t, b.Journal.AckTool(ctx, rows[0])) } for i, name := range []string{"read_file", "publish", "attest_check", "ask_person"} { a := json.RawMessage(`{"request_id":"evil","path":"/etc/passwd"}`) if v := rpc(20+i, "tools/call", map[string]any{"name": name, "arguments": a}); v["error"] == nil { t.Fatal("host authority", name) } } in.Close() mustJournal(t, cmd.Wait()) } func TestToolProxyCannotExposeSecrets(t *testing.T) { b := directToolFixture(t) p, e := OpenToolProxy(context.Background(), b) mustJournal(t, e) want := `{"mcpServers":{"equipo":{"type":"stdio","command":"/opt/equipo-tool-proxy","args":["--socket","/tool/equipo.sock"]}}}` if string(p.MCP()) != want { t.Fatal("unexpected tool proxy MCP configuration") } if strings.Contains(string(p.MCP()), b.Journal.path) || strings.Contains(string(p.MCP()), "capability") { t.Fatal("host secret exposed") } // A long host address is dialled through the verified parent fd by the helper. if len(p.SocketPath) <= 107 { t.Log("fixture address is short; separate long-path case covers fd binding") } mustJournal(t, p.Close()) mustJournal(t, p.Close()) if _, e := os.Stat(p.SocketPath); !os.IsNotExist(e) { t.Fatal("proxy survived close", e) } } func TestToolProxyLongPath(t *testing.T) { b := directToolFixture(t) path := filepath.Join(t.TempDir(), strings.Repeat("long", 30), "journal.db") j, e := OpenJournal(context.Background(), path) mustJournal(t, e) defer j.Close() // Proxy storage location is independent of the authenticated attempt journal. p, e := openToolProxy(context.Background(), b, filepath.Dir(path)) mustJournal(t, e) defer p.Close() var out strings.Builder input := `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{}}}` + "\n" mustJournal(t, ServeToolProxy(context.Background(), strings.NewReader(input), &out, p.SocketPath)) if !strings.Contains(out.String(), "serverInfo") { t.Fatal(out.String()) } } func TestCodexApprovalResponseBroker(t *testing.T) { for _, change := range []string{"ok", "fence", "attempt", "tool", "arguments", "lost-lease", "execute-revalidate"} { t.Run(change, func(t *testing.T) { b := directToolFixture(t) current := true b.Current = func(context.Context) error { if !current { return runnerproto.ErrInvalid } return nil } p, e := OpenToolProxy(context.Background(), b) mustJournal(t, e) defer p.Close() q := ToolSubmission{InstanceID: b.InstanceID, TaskID: b.TaskID, Attempt: b.Attempt, Fence: b.Fence, Agent: b.Agent, Name: "ask_person", RequestID: "r", Arguments: json.RawMessage(`{"question":"Which?"}`)} switch change { case "fence": q.Fence++ case "attempt": q.Attempt++ case "tool": q.Name = "publish" case "arguments": q.Arguments = json.RawMessage(`{"question":"Which?","command":"cat /etc/passwd"}`) case "lost-lease": current = false } e = p.ValidateApproval(context.Background(), q) if change == "ok" || change == "execute-revalidate" { mustJournal(t, e) } else if e == nil { t.Fatal("invalid approval", change) } if change == "execute-revalidate" { current = false if p.submit(context.Background(), q.Name, q.RequestID, q.Arguments) == nil { t.Fatal("execution did not revalidate") } } }) } } func TestDirectStaleAnswer(t *testing.T) { for _, change := range []string{"cancel", "restart", "replaced-turn", "revoked-member", "replayed-changed-payload"} { t.Run(change, func(t *testing.T) { b := directToolFixture(t) c := &answerClient{} current := true r := QuestionRelay{Journal: b.Journal, Client: c, Agent: b.Agent, DirectSession: b.Session, TurnID: b.TurnID, Current: func(context.Context, runnerproto.Question) (time.Time, error) { if !current { return time.Time{}, runnerproto.ErrInvalid } return b.LeaseDeadline, nil }} q := runnerproto.Question{ID: "q", TaskID: b.TaskID, Attempt: b.Attempt, Fence: b.Fence, ServerID: b.Agent.ServerID, AgentID: b.Agent.AgentID, SessionID: b.Session.ID, PermissionID: "r", Kind: "person", Revision: 1, ExpiresAt: b.LeaseDeadline, RawRequest: json.RawMessage(`{"id":"r","kind":"person","question":"Which?"}`)} a := runnerproto.QuestionAnswer{Behavior: "deny"} switch change { case "cancel": mustJournal(t, b.Journal.interruptDirect(context.Background(), b.Session.AttemptKey, false)) case "restart": _, e := b.Journal.RecoverDirect(context.Background()) mustJournal(t, e) case "replaced-turn": r.TurnID = "other" case "revoked-member": current = false case "replayed-changed-payload": mustJournal(t, r.Deliver(context.Background(), q, a)) q.RawRequest = json.RawMessage(`{"id":"r","kind":"person","question":"Changed?"}`) } before := len(c.responses) if r.Deliver(context.Background(), q, a) == nil || len(c.responses) != before { t.Fatal("stale answer delivered", change) } }) } } func TestDirectStaleAnswerCancelIsAttemptScoped(t *testing.T) { b := directToolFixture(t) ctx := context.Background() var launchRaw, recordRaw []byte mustJournal(t, b.Journal.db.QueryRow("SELECT launch,record FROM direct_attempts WHERE attempt='attempt'").Scan(&launchRaw, &recordRaw)) var launch provider.Launch var record containment.Record mustJournal(t, json.Unmarshal(launchRaw, &launch)) mustJournal(t, json.Unmarshal(recordRaw, &record)) launch.AttemptKey = "B" record.AttemptKey = "B" record.ID = strings.Repeat("b", 32) mustJournal(t, b.Journal.recordDirectLaunch(ctx, launch, record)) sessionB := b.Session sessionB.AttemptKey = "B" sessionB.ID = "session-B" turnB := provider.Turn{ID: "turn", AdmissionID: "admission-B", Prompt: "hello"} mustJournal(t, b.Journal.BeginTurn(ctx, sessionB, turnB)) mustJournal(t, b.Journal.consumeTurn(ctx, "B", sessionB.ID, "hello")) for _, a := range []string{"attempt", "B"} { _, e := b.Journal.db.ExecContext(ctx, "INSERT INTO journal_answers VALUES(?,?,'pending')", a, "hash") mustJournal(t, e) _, e = b.Journal.db.ExecContext(ctx, "INSERT INTO direct_answer_scopes(answer_key,attempt,turn) VALUES(?,?,?)", a, a, "turn") mustJournal(t, e) } mustJournal(t, b.Journal.interruptDirect(ctx, "attempt", false)) mustJournal(t, b.Journal.currentDirectTurn(ctx, sessionB, "turn")) var state string mustJournal(t, b.Journal.db.QueryRow("SELECT state FROM journal_answers WHERE answer_key='B'").Scan(&state)) if state != "pending" { t.Fatal("attempt B answer invalidated by A", state) } mustJournal(t, b.Journal.db.QueryRow("SELECT state FROM journal_answers WHERE answer_key='attempt'").Scan(&state)) if state != "invalid" { t.Fatal("A answer survived", state) } } func TestDirectToolAnswerCapture(t *testing.T) { j, l, s, p := directFixture(t, "codex") ctx := context.Background() mustJournal(t, j.BeginTurn(ctx, s, directTurn())) mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, "hello")) input := &captureInput{journal: j, launch: l, input: p.Stdin(), ctx: ctx, fail: func(error) {}} wire := []byte("{\"id\":7,\"result\":{\"decision\":\"decline\"}}\n") if _, e := input.Write(wire); e == nil { t.Fatal("ordinary stdin accepted uncorrelated reply") } if _, e := input.WriteAnswer(ctx, s, "turn", wire); e != nil { t.Fatal("correlated answer rejected", e) } before := p.input.Len() if _, e := input.WriteAnswer(ctx, s, "turn", wire); e == nil || p.input.Len() != before { t.Fatal("answer replay transmitted") } for _, raw := range []string{"{\"id\":8,\"method\":\"turn/start\",\"params\":{}}\n", "{\"id\":8,\"result\":{\"decision\":{\"acceptWithExecpolicyAmendment\":{}}}}\n"} { if _, e := input.WriteAnswer(ctx, s, "turn", []byte(raw)); e == nil { t.Fatal("hidden turn or policy amendment", raw) } } mustJournal(t, j.interruptDirect(ctx, s.AttemptKey, false)) if _, e := input.WriteAnswer(ctx, s, "turn", []byte("{\"id\":8,\"result\":{\"decision\":\"decline\"}}\n")); e == nil { t.Fatal("cancelled answer sent") } } type directAnswerLauncher struct { provider.Launcher answers []provider.Answer } func (l *directAnswerLauncher) Respond(ctx context.Context, s provider.Session, a provider.Answer) error { l.answers = append(l.answers, a) return nil } func TestCodexApprovalResponseRouting(t *testing.T) { b := directToolFixture(t) p, e := OpenToolProxy(context.Background(), b) mustJournal(t, e) defer p.Close() l := &directAnswerLauncher{} relay := DirectQuestionRelay{Binding: b, Proxy: p, Launcher: l, Current: func(context.Context, runnerproto.Question) (time.Time, error) { return b.LeaseDeadline, nil }} for i, method := range []string{"mcpServer/elicitation/request", "item/commandExecution/requestApproval", "item/fileChange/requestApproval"} { ev := provider.Event{Kind: "request", SessionID: b.Session.ID, TurnID: b.TurnID, RequestID: fmt.Sprint(i), Payload: json.RawMessage(fmt.Sprintf(`{"id":%d,"method":%q,"params":{"threadId":"session","turnId":"provider-turn","server":"equipo","tool":"ask_person","arguments":{"request_id":"r","question":"Which?"}}}`, i, method))} ev = pinnedRunnerMCP(ev) asked := 0 mustJournal(t, relay.Handle(context.Background(), ev, func(ctx context.Context, q runnerproto.Question) (runnerproto.QuestionAnswer, error) { asked++ if q.Validate() != nil || q.RawRequest == nil { t.Fatal(q) } return runnerproto.QuestionAnswer{Behavior: "deny"}, nil })) if i == 0 { if asked != 0 || l.answers[i].Behavior != "allow" || l.answers[i].Authorize == nil { t.Fatal("Equipo MCP not validated", asked, l.answers) } } else if asked != 1 || l.answers[i].Behavior != "deny" { t.Fatal("non-Equipo approval not relayed", asked, l.answers) } } } func TestToolProxyLifecycle(t *testing.T) { for _, cause := range []string{"cancel", "lease", "restart", "pending", "invalid"} { t.Run(cause, func(t *testing.T) { b := directToolFixture(t) ctx, cancel := context.WithCancel(context.Background()) defer cancel() saved := b.Session if cause == "pending" { b.Session = provider.Session{} b.TurnID = "" } p, e := OpenToolProxy(ctx, b) mustJournal(t, e) defer p.Close() if cause == "pending" { if p.submit(ctx, "ask_person", "r", json.RawMessage(`{"question":"Hi?"}`)) == nil { t.Fatal("unbound attempt accepted") } mustJournal(t, p.BindTurn(saved, "turn")) mustJournal(t, p.submit(ctx, "ask_person", "r", json.RawMessage(`{"question":"Hi?"}`))) return } switch cause { case "cancel": cancel() case "invalid": p.broker.Invalidate() case "lease": p.broker.mu.Lock() p.broker.binding.LeaseDeadline = time.Now().Add(-time.Second) p.broker.mu.Unlock() case "restart": _, e = b.Journal.RecoverDirect(ctx) mustJournal(t, e) } deadline := time.Now().Add(2 * time.Second) for time.Now().Before(deadline) { if _, e = os.Stat(p.SocketPath); os.IsNotExist(e) { return } time.Sleep(10 * time.Millisecond) } t.Fatal("invalid endpoint remained live", cause) }) } } func TestCodexApprovalResponseChangedOriginal(t *testing.T) { b := directToolFixture(t) p, e := OpenToolProxy(context.Background(), b) mustJournal(t, e) defer p.Close() l := &directAnswerLauncher{} relay := DirectQuestionRelay{Binding: b, Proxy: p, Launcher: l} ev := provider.Event{Kind: "request", SessionID: b.Session.ID, TurnID: b.TurnID, RequestID: "7", Payload: json.RawMessage(`{"id":7,"method":"mcpServer/elicitation/request","params":{"threadId":"session","turnId":"provider-turn","server":"equipo","tool":"ask_person","arguments":{"request_id":"r","question":"Original?"}}}`)} ev = pinnedRunnerMCP(ev) mustJournal(t, relay.Handle(context.Background(), ev, nil)) changed := ev changed.Payload = json.RawMessage(strings.Replace(string(ev.Payload), "Original?", "Changed?", 1)) changed.ToolCall = json.RawMessage(strings.Replace(string(ev.ToolCall), "Original?", "Changed?", 1)) if l.answers[0].Authorize(context.Background(), changed) == nil { t.Fatal("changed arguments approved") } } func TestToolProxyCannotExposeSecretsHostileFrames(t *testing.T) { b := directToolFixture(t) p, e := OpenToolProxy(context.Background(), b) mustJournal(t, e) defer p.Close() for _, params := range []string{`{"name":"read_file","arguments":{"path":"/etc/passwd"}}`, `{"name":"publish","arguments":{"request_id":"r"}}`, `{"name":"ask_person","arguments":{"request_id":"r","question":"Hi?","fence":8}}`, `{"name":"ask_person","arguments":{"request_id":"r","question":"Hi?"},"capability":"steal"}`} { var out strings.Builder input := `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{}}}` + "\n" + `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":` + params + "}\n" mustJournal(t, ServeToolProxy(context.Background(), strings.NewReader(input), &out, p.SocketPath)) if !strings.Contains(out.String(), `"error"`) || strings.Contains(out.String(), p.broker.capability.Secret) || strings.Contains(out.String(), b.Journal.path) { t.Fatal("host authority leaked", out.String()) } } } func TestDirectStaleAnswerTurnAssociation(t *testing.T) { b := directToolFixture(t) ctx := context.Background() c := &answerClient{} r := QuestionRelay{Journal: b.Journal, Client: c, Agent: b.Agent, DirectSession: b.Session, TurnID: b.TurnID, Current: func(context.Context, runnerproto.Question) (time.Time, error) { return b.LeaseDeadline, nil }} q := runnerproto.Question{ID: "q", TaskID: b.TaskID, Attempt: b.Attempt, Fence: b.Fence, ServerID: b.Agent.ServerID, AgentID: b.Agent.AgentID, SessionID: b.Session.ID, PermissionID: "same-id", Kind: "person", Revision: 1, ExpiresAt: b.LeaseDeadline, RawRequest: json.RawMessage(`{"id":"same-id","kind":"person","question":"Hi?"}`)} mustJournal(t, r.Deliver(ctx, q, runnerproto.QuestionAnswer{Behavior: "deny"})) _, e := b.Journal.db.Exec("UPDATE direct_turns SET state='completed'") mustJournal(t, e) turn := provider.Turn{ID: "next", AdmissionID: "next", Prompt: "next"} mustJournal(t, b.Journal.BeginTurn(ctx, b.Session, turn)) mustJournal(t, b.Journal.consumeTurn(ctx, b.Session.AttemptKey, b.Session.ID, "next")) r.TurnID = "next" if r.Deliver(ctx, q, runnerproto.QuestionAnswer{Behavior: "deny"}) == nil { t.Fatal("previous turn answer reused in replacement turn") } } func pinnedRunnerMCP(ev provider.Event) provider.Event { var v map[string]any _ = json.Unmarshal(ev.Payload, &v) if v["method"] != "mcpServer/elicitation/request" { return ev } p := v["params"].(map[string]any) ev.ToolCall, _ = json.Marshal(map[string]any{"method": "item/started", "params": map[string]any{"threadId": p["threadId"], "turnId": p["turnId"], "item": map[string]any{"id": "item", "type": "mcpToolCall", "server": "equipo", "tool": p["tool"], "arguments": p["arguments"], "status": "inProgress"}}}) v["params"] = map[string]any{"threadId": p["threadId"], "turnId": p["turnId"], "serverName": "equipo", "mode": "form", "message": "fixture", "requestedSchema": map[string]any{"type": "object", "properties": map[string]any{}}, "_meta": map[string]any{"codex_approval_kind": "mcp_tool_call", "tool_params": p["arguments"]}} ev.Payload, _ = json.Marshal(v) return ev } func TestDirectToolScopedAskAnswer(t *testing.T) { b := directToolFixture(t) asked := 0 b.Ask = func(ctx context.Context, bound ToolBinding, id string, args json.RawMessage) (json.RawMessage, error) { relay := DirectQuestionRelay{Binding: bound, Current: func(context.Context, runnerproto.Question) (time.Time, error) { return bound.LeaseDeadline, nil }} return relay.Ask(ctx, id, args, func(_ context.Context, q runnerproto.Question) (runnerproto.QuestionAnswer, error) { asked++ if q.Kind != "person" || q.SessionID != bound.Session.ID { t.Fatal(q) } return runnerproto.QuestionAnswer{Behavior: "allow", UpdatedInput: json.RawMessage(`{"answers":{"answer":"blue"}}`)}, nil }) } p, e := OpenToolProxy(context.Background(), b) mustJournal(t, e) defer p.Close() input := `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{}}}` + "\n" + `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"ask_person","arguments":{"request_id":"ask-1","question":"Which colour?"}}}` + "\n" var out strings.Builder mustJournal(t, ServeToolProxy(context.Background(), strings.NewReader(input), &out, p.SocketPath)) if !strings.Contains(out.String(), "blue") || asked != 1 { t.Fatal("scoped answer not returned", out.String(), asked) } } func TestToolProxyBindBeforeDispatch(t *testing.T) { b := directToolFixture(t) saved := b.Session _, e := b.Journal.db.Exec("UPDATE direct_turns SET state='completed'") mustJournal(t, e) b.Session = provider.Session{} b.TurnID = "" p, e := OpenToolProxy(context.Background(), b) mustJournal(t, e) defer p.Close() mustJournal(t, p.BindTurn(saved, "next")) turn := provider.Turn{ID: "next", AdmissionID: "next", Prompt: "next"} mustJournal(t, b.Journal.BeginTurn(context.Background(), saved, turn)) mustJournal(t, b.Journal.consumeTurn(context.Background(), saved.AttemptKey, saved.ID, "next")) mustJournal(t, p.submit(context.Background(), "ask_person", "r", json.RawMessage(`{"question":"Hi?"}`))) } func TestCodexApprovalResponseIdempotency(t *testing.T) { b := directToolFixture(t) p, e := OpenToolProxy(context.Background(), b) mustJournal(t, e) defer p.Close() ctx := context.Background() args := json.RawMessage(`{"question":"Original?"}`) mustJournal(t, p.submit(ctx, "ask_person", "r", args)) q := ToolSubmission{InstanceID: b.InstanceID, TaskID: b.TaskID, Attempt: b.Attempt, Fence: b.Fence, Agent: b.Agent, Name: "ask_person", RequestID: "r", Arguments: args} mustJournal(t, p.ValidateApproval(ctx, q)) q.Arguments = json.RawMessage(`{"question":"Changed?"}`) if p.ValidateApproval(ctx, q) == nil { t.Fatal("changed replay arguments approved") } } func TestToolProxyBindingIdentity(t *testing.T) { for _, field := range []string{"account", "model", "provider", "session"} { t.Run(field, func(t *testing.T) { b := directToolFixture(t) switch field { case "account": b.Session.AccountID = "other" case "model": b.Session.Model = "other" case "provider": b.Session.Provider = "claude" b.Agent.Provider = "claude" case "session": b.Agent.ProviderSessionID = "other" } p, e := OpenToolProxy(context.Background(), b) mustJournal(t, e) defer p.Close() if p.submit(context.Background(), "ask_person", "r", json.RawMessage(`{"question":"Hi?"}`)) == nil { t.Fatal("mismatched bound identity", field) } }) } } func TestCodexApprovalResponseToolAllowlist(t *testing.T) { b := directToolFixture(t) b.Tools = []string{"ask_person"} p, e := OpenToolProxy(context.Background(), b) mustJournal(t, e) defer p.Close() q := ToolSubmission{InstanceID: b.InstanceID, TaskID: b.TaskID, Attempt: b.Attempt, Fence: b.Fence, Agent: b.Agent, Name: "submit_candidate", RequestID: "r", Arguments: json.RawMessage(`{"commit":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}`)} if p.ValidateApproval(context.Background(), q) == nil { t.Fatal("valid but unscoped tool approved") } } func TestToolProxyRenewedLease(t *testing.T) { b := directToolFixture(t) b.LeaseDeadline = time.Now().Add(150 * time.Millisecond) p, e := OpenToolProxy(context.Background(), b) mustJournal(t, e) defer p.Close() mustJournal(t, p.RenewLease(context.Background(), time.Now().Add(time.Second))) time.Sleep(200 * time.Millisecond) mustJournal(t, p.submit(context.Background(), "ask_person", "r", json.RawMessage(`{"question":"Hi?"}`))) mustJournal(t, p.Close()) if p.RenewLease(context.Background(), time.Now().Add(time.Minute)) == nil { t.Fatal("closed lease revived") } } func TestDirectAnswerProtocolError(t *testing.T) { j, l, s, p := directFixture(t, "codex") ctx := context.Background() mustJournal(t, j.BeginTurn(ctx, s, directTurn())) mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, "hello")) c := &captureInput{journal: j, launch: l, process: p, input: p.Stdin(), ctx: ctx} raw := []byte("{\"id\":7,\"error\":{\"code\":-32000,\"message\":\"provider_policy_rejected\"}}\n") if _, err := c.WriteAnswer(ctx, s, "turn", raw); err != nil { t.Fatal("protocol refusal cannot pass durable capture", err) } }