package runner import ( "context" "encoding/json" "net" "strings" "sync/atomic" "testing" "time" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runnerproto" ) // Accelerate any idle deadline installed by the production reader. type shortDeadlineConn struct{ net.Conn } func (c shortDeadlineConn) SetReadDeadline(d time.Time) error { if !d.IsZero() { d = time.Now().Add(20 * time.Millisecond) } return c.Conn.SetReadDeadline(d) } func TestToolProxyIdleConnection(t *testing.T) { b := directToolFixture(t) p, e := OpenToolProxy(context.Background(), b) mustJournal(t, e) defer p.Close() server, client := net.Pipe() defer client.Close() done := make(chan error, 1) go func() { defer server.Close() done <- serveTools(context.Background(), &proxyReader{conn: shortDeadlineConn{server}}, server, func() (toolCapability, error) { return p.broker.capability, nil }, func(q toolRequest) (any, error) { return nil, p.submit(context.Background(), q.Name, q.RequestID, q.Arguments) }, nil) }() defer func() { client.Close(); <-done }() mustJournal(t, client.SetDeadline(time.Now().Add(2*time.Second))) enc, dec := json.NewEncoder(client), json.NewDecoder(client) rpc := func(raw string) { t.Helper() mustJournal(t, enc.Encode(json.RawMessage(raw))) var reply mcpResponse mustJournal(t, dec.Decode(&reply)) if reply.Error != nil { t.Fatal(reply.Error) } } rpc(`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{}}}`) time.Sleep(80 * time.Millisecond) rpc(`{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"submit_candidate","arguments":{"request_id":"idle","commit":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}}`) rows, e := b.Journal.ToolSubmissions(context.Background(), 10) mustJournal(t, e) if len(rows) != 1 { t.Fatal("idle call not recorded", rows) } } func TestToolProxyIdleAuthority(t *testing.T) { b := directToolFixture(t) var calls atomic.Int32 b.Current = func(context.Context) error { calls.Add(1); return nil } p, e := OpenToolProxy(context.Background(), b) mustJournal(t, e) defer p.Close() before := calls.Load() time.Sleep(350 * time.Millisecond) if got := calls.Load() - before; got != 0 { t.Fatalf("idle ticker made %d authority calls", got) } } func TestToolProxyAuthorityLock(t *testing.T) { for _, change := range []string{"unchanged", "invalidated", "turn", "session", "agent", "expired", "cancelled"} { t.Run(change, func(t *testing.T) { b := directToolFixture(t) entered, release := make(chan struct{}), make(chan struct{}) var calls atomic.Int32 b.Current = func(context.Context) error { if calls.Add(1) == 2 { close(entered) <-release } return nil } p, e := OpenToolProxy(context.Background(), b) mustJournal(t, e) defer p.Close() done := make(chan error, 1) ctx, cancel := context.WithCancel(context.Background()) defer cancel() go func() { if change == "unchanged" { done <- p.submit(ctx, "ask_person", "r", json.RawMessage(`{"question":"Which?"}`)) return } p.broker.mu.Lock() err := p.broker.authorityLocked(ctx) p.broker.mu.Unlock() done <- err }() defer func() { close(release) err := <-done if change == "unchanged" && err != nil { t.Error(err) } if change != "unchanged" && err == nil { t.Error("changed binding accepted after authority check") } }() select { case <-entered: case <-time.After(time.Second): t.Fatal("authority did not start") } // A second tool call must acquire the lock even while the first waits remotely. concurrent := make(chan error, 1) go func() { concurrent <- p.submit(context.Background(), "publish", "bad", json.RawMessage(`{}`)) }() select { case err := <-concurrent: if err == nil { t.Fatal("unscoped tool accepted") } case <-time.After(300 * time.Millisecond): t.Fatal("remote authority holds broker lock") } p.broker.mu.Lock() switch change { case "invalidated": p.broker.invalidateLocked() case "turn": p.broker.binding.TurnID = "replacement" case "session": p.broker.binding.Session.ID = "replacement" case "agent": p.broker.binding.Agent.AgentID = "replacement" case "cancelled": cancel() case "expired": p.broker.binding.LeaseDeadline = time.Now().Add(-time.Second) } p.broker.mu.Unlock() }) } } func TestCodexApprovalResponseInvalidRelay(t *testing.T) { for _, change := range []string{"fence", "attempt", "tool", "arguments", "stale", "stale-after-check", "revoked-after-check"} { t.Run(change, func(t *testing.T) { b := directToolFixture(t) p, e := OpenToolProxy(context.Background(), b) mustJournal(t, e) defer p.Close() relayBinding := b tool, args := "submit_candidate", `{"request_id":"r","commit":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}` switch change { case "fence": relayBinding.Fence++ case "attempt": relayBinding.Attempt++ case "tool": tool = "publish" case "stale-after-check", "revoked-after-check": var checks int relayBinding.Current = func(ctx context.Context) error { checks++ if checks == 2 { if change == "revoked-after-check" { return runnerproto.ErrInvalid } return b.Journal.interruptDirect(ctx, b.Session.AttemptKey, false) } return nil } args = `{"request_id":"r","commit":"bad"}` case "arguments": args = `{"request_id":"r","commit":"bad"}` case "stale": mustJournal(t, b.Journal.interruptDirect(context.Background(), b.Session.AttemptKey, false)) } payload, _ := json.Marshal(map[string]any{"id": 7, "method": "mcpServer/elicitation/request", "params": map[string]any{"threadId": b.Session.ID, "turnId": "provider-turn", "tool": tool, "arguments": json.RawMessage(args)}}) ev := pinnedRunnerMCP(provider.Event{Kind: "request", SessionID: b.Session.ID, TurnID: b.TurnID, RequestID: "7", Payload: payload}) l := &directAnswerLauncher{} r := DirectQuestionRelay{Binding: relayBinding, Proxy: p, Launcher: l} err := r.Handle(context.Background(), ev, nil) if strings.Contains(change, "after-check") || change == "stale" { if err == nil || len(l.answers) != 0 { t.Fatal("stale request answered") } return } if err != nil || len(l.answers) != 1 || l.answers[0].Behavior != "deny" || l.answers[0].RequestID != "7" { t.Fatalf("invalid %s approval was not declined: %v %+v", change, err, l.answers) } }) } } func TestClaudePermissionResponseToolUseIDRelay(t *testing.T) { b := directToolFixture(t) b.Session.Provider = "claude" ev := provider.Event{Kind: "request", SessionID: b.Session.ID, TurnID: b.TurnID, RequestID: "permission:r", Payload: json.RawMessage(`{"tool_name":"Write","input":{"file_path":"/workspace/a","content":"hi"},"tool_use_id":"toolu_fixture"}`)} q, e := DirectQuestionFromEvent(ev, b) mustJournal(t, e) if !strings.Contains(string(q.RawRequest), "toolu_fixture") { t.Fatal("original request lost") } ev.Payload = json.RawMessage(`{"tool_name":"Write","input":{},"tool_use_id":"toolu_fixture","permissions":{}}`) if _, e = DirectQuestionFromEvent(ev, b); e == nil { t.Fatal("unknown permission field accepted") } } func TestClaudePermissionResponseAdvertisedSchema(t *testing.T) { var out strings.Builder in := `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}` + "\n" + `{"jsonrpc":"2.0","id":2,"method":"tools/list"}` + "\n" e := serveTools(context.Background(), strings.NewReader(in), &out, func() (toolCapability, error) { return toolCapability{}, nil }, nil, func(context.Context, json.RawMessage) (json.RawMessage, error) { return nil, runnerproto.ErrInvalid }) mustJournal(t, e) var reply struct { Result struct { Tools []struct { Name string InputSchema struct { Properties map[string]json.RawMessage AdditionalProperties bool } } } } mustJournal(t, json.Unmarshal([]byte(strings.Split(strings.TrimSpace(out.String()), "\n")[1]), &reply)) for _, tool := range reply.Result.Tools { if tool.Name == "permission" { if string(tool.InputSchema.Properties["tool_use_id"]) != `{"type":"string"}` || len(tool.InputSchema.Properties) != 3 || tool.InputSchema.AdditionalProperties { t.Fatal("permission schema differs from pinned input", tool) } return } } t.Fatal("permission schema missing") }