oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package codex
2
3import (
4 "bufio"
5 "bytes"
6 "context"
7 "crypto/sha256"
8 "encoding/hex"
9 "encoding/json"
10 "errors"
11 "fmt"
12 "io"
13 "os"
14 "path/filepath"
15 "reflect"
16 "strings"
17 "sync"
18 "testing"
19 "time"
20
21 "amadan.net/oficina/equipo/internal/runner/provider"
22)
23
24type fakeProcess struct {
25 exitCode int
26 in *io.PipeWriter
27 out *io.PipeReader
28 done chan struct{}
29}
30
31func (p *fakeProcess) Stdin() io.WriteCloser { return p.in }
32func (p *fakeProcess) Stdout() io.ReadCloser { return p.out }
33func (p *fakeProcess) Stderr() io.ReadCloser { return io.NopCloser(strings.NewReader("diagnostic")) }
34func (p *fakeProcess) ID() string { return "fake" }
35func (p *fakeProcess) Wait(ctx context.Context) (provider.Exit, error) {
36 select {
37 case <-p.done:
38 return provider.Exit{Code: p.exitCode}, nil
39 case <-ctx.Done():
40 return provider.Exit{}, ctx.Err()
41 }
42}
43
44type fakeHost struct {
45 sessionID string
46 startupFrames []json.RawMessage
47 startupSessionOnly bool
48 startupMethod string
49 mu sync.Mutex
50 mode string
51 calls []string
52 requests []json.RawMessage
53 launches []provider.Launch
54 processes []*fakeProcess
55}
56
57func (h *fakeHost) set(mode string) { h.mu.Lock(); h.mode = mode; h.mu.Unlock() }
58func (h *fakeHost) count(method string) int {
59 h.mu.Lock()
60 defer h.mu.Unlock()
61 n := 0
62 for _, m := range h.calls {
63 if m == method {
64 n++
65 }
66 }
67 return n
68}
69func (h *fakeHost) Start(ctx context.Context, l provider.Launch, args []string) (provider.Process, error) {
70 if _, e := provider.AttestLaunch(l, args); e != nil {
71 return nil, e
72 }
73 in, writer := io.Pipe()
74 reader, out := io.Pipe()
75 p := &fakeProcess{in: writer, out: reader, done: make(chan struct{})}
76 h.mu.Lock()
77 h.launches = append(h.launches, l)
78 h.processes = append(h.processes, p)
79 h.mu.Unlock()
80 go func() { <-ctx.Done(); in.CloseWithError(ctx.Err()); out.CloseWithError(ctx.Err()) }()
81 go func() {
82 defer close(p.done)
83 defer in.Close()
84 defer out.Close()
85 // Simulate an app-server writing only its constructed home.
86 os.WriteFile(filepath.Join(l.Binding.Home, "history.jsonl"), []byte("# private fake config\n"), 0600)
87 scan := bufio.NewScanner(in)
88 scan.Buffer(make([]byte, 4096), MaxFrameBytes)
89 send := func(v any) {
90 raw, _ := json.Marshal(v)
91 if h.sessionID != "" {
92 raw = bytes.ReplaceAll(raw, []byte("thread-1"), []byte(h.sessionID))
93 }
94 out.Write(append(raw, '\n'))
95 }
96 turn := 0
97 startupSent := false
98 for scan.Scan() {
99 var req struct {
100 ID json.RawMessage
101 Method string
102 Params map[string]json.RawMessage
103 }
104 if json.Unmarshal(scan.Bytes(), &req) != nil {
105 return
106 }
107 h.mu.Lock()
108 mode := h.mode
109 h.calls = append(h.calls, req.Method)
110 h.requests = append(h.requests, bytes.Clone(scan.Bytes()))
111 h.mu.Unlock()
112 noticeMethod := h.startupMethod
113 if noticeMethod == "" {
114 noticeMethod = "initialized"
115 }
116 if !startupSent && req.Method == noticeMethod && (!h.startupSessionOnly || !strings.HasPrefix(l.AttemptKey, "codex-preflight-")) {
117 startupSent = true
118 frames := h.startupFrames
119 if frames == nil && mode != "account-event" {
120 frames = []json.RawMessage{json.RawMessage(startupAccountFrame)}
121 }
122 send(json.RawMessage(startupRemoteFrame))
123 for _, frame := range frames {
124 send(frame)
125 }
126 }
127 if req.Method == "initialized" {
128 continue
129 }
130 var result any = map[string]any{}
131 switch req.Method {
132 case "initialize":
133 version := Version
134 if mode == "version" {
135 version = "0.164.0"
136 }
137 result = recordedReply(tFixturePath, 1)
138 if mode == "version" {
139 result.(map[string]any)["userAgent"] = "equipo/" + version + " (Linux)"
140 }
141 send(recordedNotification())
142 case "account/read":
143 email := "account@example.invalid"
144 if mode == "identity" {
145 email = "other@example.invalid"
146 }
147 result = map[string]any{"account": map[string]any{"type": "chatgpt", "email": email, "planType": "pro"}, "requiresOpenaiAuth": true}
148 case "config/read":
149 if mode == "resume-race" {
150 os.WriteFile(filepath.Join(l.Binding.CredentialHome, "auth.json"), []byte(`{"fake":"changed"}`), 0600)
151 }
152 var config map[string]any
153 json.Unmarshal(l.Policy.Settings, &config)
154 if mode == "profile" {
155 config["permissions"].(map[string]any)["equipo"].(map[string]any)["filesystem"].(map[string]any)["/egress"] = "read"
156 }
157 if mode == "config-extra" {
158 config["hooks"] = map[string]any{"enabled": true}
159 }
160 if mode == "apps" {
161 config["features"].(map[string]any)["apps"] = true
162 }
163 if mode == "mcp" {
164 config["mcp_servers"] = map[string]any{"inherited": map[string]any{"command": "evil"}}
165 }
166 if mode == "extra-mcp" {
167 config["mcp_servers"].(map[string]any)["other"] = map[string]any{"command": "other"}
168 }
169 if mode == "network" {
170 config["permissions"].(map[string]any)["equipo"].(map[string]any)["network"].(map[string]any)["enabled"] = true
171 }
172 result = recordedConfig(config)
173 if mode == "origin" {
174 result.(map[string]any)["origins"].(map[string]any)["model"] = map[string]any{"name": map[string]any{"type": "enterpriseManaged"}, "version": "fake"}
175 }
176
177 case "thread/start", "thread/resume":
178 if req.Method == "thread/resume" && strings.HasPrefix(mode, "resume-usage") {
179 raw, _ := os.ReadFile("testdata/probe.jsonl")
180 var snapshot map[string]any
181 for _, line := range bytes.Split(bytes.TrimSpace(raw), []byte("\n")) {
182 var frame map[string]any
183 json.Unmarshal(line, &frame)
184 if frame["method"] == "thread/tokenUsage/updated" {
185 snapshot = frame
186 }
187 }
188 if mode == "resume-usage-changed" {
189 snapshot["params"].(map[string]any)["tokenUsage"].(map[string]any)["total"].(map[string]any)["inputTokens"] = 99999
190 }
191 send(snapshot)
192 }
193 if mode == "unpersisted" && req.Method == "thread/resume" && turn == 0 {
194 send(map[string]any{"id": req.ID, "error": map[string]any{"code": -32600, "message": "no rollout found for thread id thread-1"}})
195 continue
196 }
197 if mode == "turn-race" {
198 os.WriteFile(filepath.Join(l.Binding.CredentialHome, "auth.json"), []byte(`{"fake":"changed"}`), 0600)
199 }
200 profile := "equipo"
201 if mode == "active-profile" {
202 profile = "other"
203 }
204 approval := "on-request"
205 reviewer := "user"
206 if mode == "approval" {
207 approval = "never"
208 }
209 if mode == "reviewer" {
210 reviewer = "guardian_subagent"
211 }
212 result = map[string]any{"thread": map[string]any{"id": "thread-1"}, "model": "gpt-6-luna", "modelProvider": "openai", "cwd": "/workspace", "approvalPolicy": approval, "approvalsReviewer": reviewer, "activePermissionProfile": map[string]any{"id": profile, "extends": nil}, "runtimeWorkspaceRoots": []string{"/workspace"}, "sandbox": map[string]any{"type": "workspaceWrite", "networkAccess": false}}
213 case "turn/start":
214 if mode == "exit" {
215 p.exitCode = 7
216 }
217 turn++
218 tid := "turn-" + string(rune('0'+turn))
219 if mode == "account-event" {
220 send(map[string]any{"method": "account/updated", "params": map[string]any{"authMode": "chatgpt", "planType": "pro"}})
221 }
222 if mode == "source-active" {
223 os.WriteFile(filepath.Join(l.Binding.CredentialHome, "auth.json"), []byte(`{"fake":"changed-active"}`), 0600)
224 }
225 send(map[string]any{"method": "turn/started", "params": map[string]any{"threadId": "thread-1", "turn": map[string]any{"id": tid, "status": "inProgress"}}})
226 result = map[string]any{"turn": map[string]any{"id": tid, "status": "inProgress"}}
227 send(map[string]any{"id": req.ID, "result": result})
228 if mode == "eof" {
229 return
230 }
231 if mode == "hang" {
232 continue
233 }
234 raw, _ := os.ReadFile("testdata/probe.jsonl")
235 for _, line := range bytes.Split(bytes.TrimSpace(raw), []byte("\n")) {
236 if mode == "session-event" {
237 line = bytes.ReplaceAll(line, []byte("thread-1"), []byte("wrong-thread"))
238 }
239 if mode == "turn-event" {
240 line = bytes.ReplaceAll(line, []byte("turn-1"), []byte("wrong-turn"))
241 }
242 if h.sessionID != "" {
243 line = bytes.ReplaceAll(line, []byte("thread-1"), []byte(h.sessionID))
244 }
245 out.Write(append(bytes.ReplaceAll(line, []byte("turn-1"), []byte(tid)), '\n'))
246 }
247 continue
248 }
249 send(map[string]any{"id": req.ID, "result": result})
250 }
251 }()
252 return p, nil
253}
254
255type fakeCapture struct{}
256
257func (fakeCapture) Open(ctx context.Context, p provider.Process, l provider.Launch) (*provider.Capture, error) {
258 frames := make(chan provider.Frame)
259 done := make(chan error, 1)
260 go func() {
261 defer p.Stdout().Close()
262 scan := bufio.NewScanner(p.Stdout())
263 scan.Buffer(make([]byte, 4096), MaxFrameBytes+1)
264 var seq int64
265 for scan.Scan() {
266 seq++
267 select {
268 case frames <- provider.Frame{Sequence: seq, Bytes: bytes.Clone(scan.Bytes())}:
269 case <-ctx.Done():
270 close(frames)
271 done <- ctx.Err()
272 close(done)
273 return
274 }
275 }
276 close(frames)
277 done <- scan.Err()
278 close(done)
279 }()
280 return &provider.Capture{Input: p.Stdin(), Frames: frames, Done: done}, nil
281}
282
283type fixture struct {
284 l *Launcher
285 host *fakeHost
286 lease *provider.AccountLease
287 launch provider.Launch
288 inputs provider.PolicyInputs
289 interactive string
290}
291
292func fixtureFor(t *testing.T) *fixture {
293 t.Helper()
294 root := t.TempDir()
295 source := filepath.Join(root, "dedicated")
296 os.Mkdir(source, 0700)
297 id := provider.Identity{AccountID: "account@example.invalid", HomeID: "equipo-home", ProviderVersion: Version}
298 raw, _ := json.Marshal(id)
299 os.WriteFile(filepath.Join(source, provider.IdentityFile), raw, 0600)
300 os.WriteFile(filepath.Join(source, "auth.json"), []byte(`{"fake":"login"}`), 0600)
301 lease, e := provider.OpenAccount(context.Background(), provider.Binding{ID: "binding", Home: source, AccountID: id.AccountID, Provider: "codex", Expected: id, RuntimeRoot: filepath.Join(root, "homes")})
302 if e != nil {
303 t.Fatal(e)
304 }
305 t.Cleanup(func() { lease.Close() })
306 work, scratch := filepath.Join(root, "workspace"), filepath.Join(root, "scratch")
307 os.Mkdir(work, 0700)
308 os.Mkdir(scratch, 0700)
309 files := []provider.Mount{}
310 for _, name := range []string{"codex", "codex-code-mode-host", "equipo-tool-proxy"} {
311 p := filepath.Join(root, name)
312 os.WriteFile(p, []byte(name), 0700)
313 files = append(files, provider.Mount{Source: p, Target: "/opt/" + name, ReadOnly: true})
314 }
315 in := provider.PolicyInputs{RuntimeFiles: files, Workspace: work, Scratch: scratch, AuthHost: "auth.openai.com", EgressHosts: []string{"chatgpt.com", "auth.openai.com"}, LauncherVersion: "2", BwrapVersion: "0.11.0", DeniedPaths: []string{"/alias/login", "/private/state"}}
316 in, e = PolicyInputs(lease.Binding(), in, "gpt-6-luna")
317 if e != nil {
318 t.Fatal(e)
319 }
320 policy, e := provider.BuildPolicy(lease.Binding(), in)
321 if e != nil {
322 t.Fatal(e)
323 }
324 host := &fakeHost{}
325 l, e := New(host, fakeCapture{})
326 if e != nil {
327 t.Fatal(e)
328 }
329 for name, dst := range map[string]*string{"codex": &l.digest, "codex-code-mode-host": &l.hostDigest} {
330 sum := sha256.Sum256([]byte(name))
331 *dst = hex.EncodeToString(sum[:])
332 }
333 interactive := filepath.Join(root, "interactive")
334 os.Mkdir(interactive, 0700)
335 os.WriteFile(filepath.Join(interactive, "config.toml"), []byte("# keep byte-identical\nmodel = \"interactive\"\n"), 0600)
336 t.Cleanup(func() {
337 host.mu.Lock()
338 defer host.mu.Unlock()
339 for _, p := range host.processes {
340 p.in.Close()
341 p.out.Close()
342 select {
343 case <-p.done:
344 case <-time.After(time.Second):
345 t.Error("fake server leaked")
346 }
347 }
348 })
349 return &fixture{l, host, lease, provider.Launch{AttemptKey: "attempt", Workspace: work, Binding: lease.Binding(), Policy: policy, Selection: provider.Selection{ConnectionID: "connection", Provider: "codex", Family: "gpt", Model: "gpt-6-luna", AccountID: id.AccountID}}, in, interactive}
350}
351func openFixture(t *testing.T, f *fixture) (provider.Session, <-chan provider.Event) {
352 t.Helper()
353 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
354 t.Cleanup(cancel)
355 s, e := f.l.Open(ctx, f.launch)
356 if e != nil {
357 t.Fatal(e)
358 }
359 t.Cleanup(func() { f.l.Close(context.Background(), s) })
360 events, e := f.l.Events(ctx, s)
361 if e != nil {
362 t.Fatal(e)
363 }
364 return s, events
365}
366func terminal(t *testing.T, ch <-chan provider.Event) provider.Event {
367 t.Helper()
368 for {
369 select {
370 case ev, ok := <-ch:
371 if !ok {
372 t.Fatal("missing terminal")
373 }
374 if ev.Kind == "turn.completed" || ev.Kind == "turn.failed" {
375 return ev
376 }
377 case <-time.After(2 * time.Second):
378 t.Fatal("terminal timeout")
379 }
380 }
381}
382func TestCodexAppServerPolicy(t *testing.T) {
383 t.Parallel()
384 f := fixtureFor(t)
385 before, _ := os.ReadFile(filepath.Join(f.interactive, "config.toml"))
386 s, events := openFixture(t, f)
387 if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "local-1", AdmissionID: "a1", Prompt: "hello"}); e != nil {
388 t.Fatal(e)
389 }
390 if ev := terminal(t, events); ev.Kind != "turn.completed" || ev.TurnID != "local-1" {
391 t.Fatal(ev)
392 }
393 if e := f.l.Close(context.Background(), s); e != nil {
394 t.Fatal(e)
395 }
396 f.launch.AttemptKey = "resume"
397 f.launch.ResumeSessionID = s.ID
398 s2, events2 := openFixture(t, f)
399 if e := f.l.StartTurn(context.Background(), s2, provider.Turn{ID: "local-2", AdmissionID: "a2", Prompt: "again"}); e != nil {
400 t.Fatal(e)
401 }
402 terminal(t, events2)
403 after, _ := os.ReadFile(filepath.Join(f.interactive, "config.toml"))
404 if !bytes.Equal(before, after) {
405 t.Fatal("interactive config changed")
406 }
407 if f.host.count("thread/resume") != 2 {
408 t.Fatal("resume not used")
409 }
410 f.host.mu.Lock()
411 defer f.host.mu.Unlock()
412 for _, launch := range f.host.launches {
413 in, _, e := policyInputs(launch.Policy)
414 if e != nil {
415 t.Fatal(e)
416 }
417 if len(in.Argv) < 5 || !reflect.DeepEqual(in.Argv[:5], []string{"/opt/codex", "app-server", "--strict-config", "--listen", "stdio://"}) {
418 t.Fatal("strict app-server launch missing", in.Argv)
419 }
420 if len(launch.Policy.Manifest) == 0 || !bytes.Contains(launch.Policy.Manifest, []byte(`"ThreadPolicy"`)) || !bytes.Contains(launch.Policy.ThreadPolicy, []byte(`"approvalsReviewer":"user"`)) {
421 t.Fatal("RPC policy missing from manifest")
422 }
423 }
424 for i, method := range f.host.calls {
425 var req struct{ Params map[string]any }
426 json.Unmarshal(f.host.requests[i], &req)
427 switch method {
428 case "initialize":
429 if req.Params["capabilities"].(map[string]any)["experimentalApi"] != true {
430 t.Fatal("experimental API missing")
431 }
432 case "thread/start", "thread/resume":
433 for k, v := range map[string]any{"approvalPolicy": "on-request", "approvalsReviewer": "user", "permissions": "equipo"} {
434 if req.Params[k] != v {
435 t.Fatal(method, k, req.Params)
436 }
437 }
438 case "turn/start":
439 for _, k := range []string{"permissions", "sandboxPolicy", "approvalPolicy", "approvalsReviewer"} {
440 if _, ok := req.Params[k]; ok {
441 t.Fatal("turn override", k)
442 }
443 }
444 }
445 }
446}
447func TestCodexNoLegacyPolicyOverride(t *testing.T) {
448 t.Parallel()
449 for _, change := range []string{"strict", "ignore", "sandbox", "sandboxPolicy", "deny-home", "deny-egress", "deny-tool", "deny-alias", "code-host", "digest", "approval", "reviewer", "turn", "hash", "version"} {
450 t.Run(change, func(t *testing.T) {
451 f := fixtureFor(t)
452 in := f.inputs
453 switch change {
454 case "strict":
455 in.Argv = append([]string{}, in.Argv...)
456 for i, a := range in.Argv {
457 if a == "--strict-config" {
458 in.Argv = append(in.Argv[:i], in.Argv[i+1:]...)
459 break
460 }
461 }
462 case "ignore":
463 in.Argv = append(in.Argv, "--ignore-user-config")
464 case "code-host":
465 in.RuntimeFiles = in.RuntimeFiles[:1]
466 case "digest":
467 os.WriteFile(in.RuntimeFiles[1].Source, []byte("wrong binary"), 0700)
468 case "version":
469 in.ProviderVersion = "0.164.0"
470 case "turn":
471 in.TurnPolicy = json.RawMessage(`{"permissions":"other"}`)
472 case "hash":
473 f.launch.Policy.Hash = "wrong"
474 default:
475 var settings map[string]any
476 json.Unmarshal(in.Settings, &settings)
477 if strings.HasPrefix(change, "deny-") {
478 path := map[string]string{"deny-home": f.launch.Binding.CredentialHome, "deny-egress": "/egress", "deny-tool": "/tool", "deny-alias": "/alias/login"}[change]
479 delete(settings["permissions"].(map[string]any)["equipo"].(map[string]any)["filesystem"].(map[string]any), path)
480 in.Settings, _ = json.Marshal(settings)
481 } else {
482 var tp map[string]any
483 json.Unmarshal(in.ThreadPolicy, &tp)
484 key := change
485 value := "read-only"
486 if change == "approval" {
487 key = "approvalPolicy"
488 value = "never"
489 }
490 if change == "reviewer" {
491 key = "approvalsReviewer"
492 value = "guardian_subagent"
493 }
494 tp[key] = value
495 in.ThreadPolicy, _ = json.Marshal(tp)
496 }
497 }
498 if change != "hash" {
499 p, e := provider.BuildPolicy(f.launch.Binding, in)
500 if e != nil {
501 return
502 }
503 f.launch.Policy = p
504 }
505 if _, e := f.l.Open(context.Background(), f.launch); e == nil {
506 t.Fatal("unsafe policy accepted", change)
507 }
508 if f.host.count("turn/start") != 0 {
509 t.Fatal("spent before rejection")
510 }
511 })
512 }
513}
514func TestCodexUnexpectedPolicyChange(t *testing.T) {
515 t.Parallel()
516 for _, mode := range []string{"profile", "network", "origin", "identity", "active-profile", "approval", "reviewer", "version", "config-extra", "apps", "mcp"} {
517 t.Run("startup-"+mode, func(t *testing.T) {
518 t.Parallel()
519 f := fixtureFor(t)
520 f.host.set(mode)
521 if _, e := f.l.Open(context.Background(), f.launch); e == nil {
522 t.Fatal("bad readback accepted")
523 }
524 if f.host.count("turn/start") != 0 {
525 t.Fatal("prompt sent")
526 }
527 })
528 }
529 for _, mode := range []string{"profile", "active-profile", "approval", "reviewer", "origin", "identity", "source-file", "source-active", "account-event", "session-event", "turn-event", "eof"} {
530 t.Run("between-"+mode, func(t *testing.T) {
531 t.Parallel()
532 f := fixtureFor(t)
533 s, ch := openFixture(t, f)
534 if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "initial", AdmissionID: "initial", Prompt: "ready"}); e != nil {
535 t.Fatal(e)
536 }
537 terminal(t, ch)
538 f.host.set(mode)
539 if mode == "source-file" {
540 os.WriteFile(f.inputs.RuntimeFiles[1].Source, []byte("tampered"), 0700)
541 }
542 e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "local-1", AdmissionID: "a1", Prompt: "hello"})
543 if mode == "source-active" || mode == "account-event" || mode == "session-event" || mode == "turn-event" || mode == "eof" {
544 if e == nil && terminal(t, ch).Kind != "turn.failed" {
545 t.Fatal("active change completed")
546 }
547 } else if e == nil {
548 t.Fatal("changed policy accepted")
549 }
550 count := f.host.count("turn/start")
551 if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "local-2", AdmissionID: "a2", Prompt: "again"}); e == nil {
552 t.Fatal("contained step resumed")
553 }
554 if count != f.host.count("turn/start") {
555 t.Fatal("contained step wrote prompt")
556 }
557 })
558 }
559}
560func TestCodexRefreshAndAdmission(t *testing.T) {
561 t.Parallel()
562 f := fixtureFor(t)
563 s, ch := openFixture(t, f)
564 turn := provider.Turn{ID: "l1", AdmissionID: "a1", Prompt: "hello"}
565 if e := f.l.StartTurn(context.Background(), s, turn); e != nil {
566 t.Fatal(e)
567 }
568 terminal(t, ch)
569 checks := f.host.count("account/read")
570 os.WriteFile(filepath.Join(f.launch.Binding.Home, "auth.json"), []byte(`{"fake":"refreshed"}`), 0600)
571 if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "l2", AdmissionID: "a2", Prompt: "again"}); !errors.Is(e, provider.ErrAccountMaintenance) {
572 t.Fatal("runtime refresh did not require sign-in", e)
573 }
574 if f.host.count("account/read") != checks {
575 t.Fatal("refresh ran an identity probe")
576 }
577 raw, _ := os.ReadFile(filepath.Join(f.launch.Binding.CredentialHome, "auth.json"))
578 if string(raw) == `{"fake":"refreshed"}` {
579 t.Fatal("runtime credentials committed")
580 }
581
582 if e := f.l.StartTurn(context.Background(), s, turn); e == nil {
583 t.Fatal("admission replayed")
584 }
585 if e := f.l.Respond(context.Background(), s, provider.Answer{Behavior: "allow"}); e == nil {
586 t.Fatal("automatic approval")
587 }
588}
589func TestCodexPolicyHashIncludesRPC(t *testing.T) {
590 t.Parallel()
591 f := fixtureFor(t)
592 for _, field := range []string{"thread", "turn"} {
593 in := f.inputs
594 if field == "thread" {
595 in.ThreadPolicy = json.RawMessage(`{"permissions":"other"}`)
596 } else {
597 in.TurnPolicy = json.RawMessage(`{"effort":"high"}`)
598 }
599 p, e := provider.BuildPolicy(f.launch.Binding, in)
600 if e != nil {
601 t.Fatal(e)
602 }
603 if p.Hash == f.launch.Policy.Hash || p.ManifestHash == f.launch.Policy.ManifestHash {
604 t.Fatal("RPC policy omitted from hash")
605 }
606 }
607}
608func TestCodexIdentityWithoutHomeEcho(t *testing.T) {
609 t.Parallel()
610 f := fixtureFor(t)
611 id, e := f.l.Preflight(context.Background(), f.launch.Binding, f.launch.Policy)
612 if e != nil {
613 t.Fatal(e)
614 }
615 if id.HomeID != "" || id.AccountID != f.launch.Binding.Expected.AccountID {
616 t.Fatal("invented identity", id)
617 }
618 if e = f.lease.ValidatePolicy(context.Background()); e != nil {
619 t.Fatal(e)
620 }
621 f.host.set("identity")
622 _, e = f.l.Preflight(context.Background(), f.launch.Binding, f.launch.Policy)
623 if !errors.Is(e, provider.ErrIdentity) {
624 t.Fatal(e)
625 }
626}
627func TestCodexConstructor(t *testing.T) {
628 t.Parallel()
629 if _, e := New(nil, fakeCapture{}); e == nil {
630 t.Fatal("nil host")
631 }
632 if _, e := New(&fakeHost{}, nil); e == nil {
633 t.Fatal("nil capture")
634 }
635}
636
637func TestCodexThreadConfigPinned(t *testing.T) {
638 t.Parallel()
639 f := fixtureFor(t)
640 s, ch := openFixture(t, f)
641 if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "l", AdmissionID: "a", Prompt: "hello"}); e != nil {
642 t.Fatal(e)
643 }
644 terminal(t, ch)
645 f.host.mu.Lock()
646 defer f.host.mu.Unlock()
647 for i, method := range f.host.calls {
648 if method != "thread/start" && method != "thread/resume" {
649 continue
650 }
651 var req struct{ Params map[string]json.RawMessage }
652 json.Unmarshal(f.host.requests[i], &req)
653 if !sameJSON(req.Params["config"], f.launch.Policy.Settings) {
654 t.Fatal("saved thread can retain a different profile definition", method)
655 }
656 }
657}
658func TestCodexLifecycle(t *testing.T) {
659 t.Parallel()
660 t.Run("attach-and-identity", func(t *testing.T) {
661 f := fixtureFor(t)
662 ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
663 defer cancel()
664 s, e := f.l.Open(ctx, f.launch)
665 if e != nil {
666 t.Fatal(e)
667 }
668 defer f.l.Close(context.Background(), s)
669 if e = f.l.StartTurn(ctx, s, provider.Turn{ID: "t", AdmissionID: "a", Prompt: "hello"}); e == nil {
670 t.Fatal("turn without event capture")
671 }
672 bad := s
673 bad.AccountID = "other"
674 if _, e = f.l.Events(ctx, bad); e == nil {
675 t.Fatal("forged session accepted")
676 }
677 if _, e = f.l.Events(ctx, s); e != nil {
678 t.Fatal(e)
679 }
680 if _, e = f.l.Events(ctx, s); e == nil {
681 t.Fatal("duplicate consumer")
682 }
683 })
684 t.Run("interrupt", func(t *testing.T) {
685 f := fixtureFor(t)
686 s, ch := openFixture(t, f)
687 f.host.set("hang")
688 if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "t", AdmissionID: "a", Prompt: "hello"}); e != nil {
689 t.Fatal(e)
690 }
691 f.l.Interrupt(context.Background(), s)
692 if terminal(t, ch).Kind != "turn.failed" {
693 t.Fatal("interruption reported completion")
694 }
695 if f.host.count("turn/interrupt") != 1 {
696 t.Fatal("missing graceful interrupt")
697 }
698 if e := f.l.Close(context.Background(), s); e == nil {
699 t.Fatal("uncertain attempt clean")
700 }
701 f.launch.AttemptKey = "resume"
702 f.launch.ResumeSessionID = s.ID
703 if _, e := f.l.Open(context.Background(), f.launch); e == nil {
704 t.Fatal("uncertain resume")
705 }
706 })
707 t.Run("attempt-context", func(t *testing.T) {
708 f := fixtureFor(t)
709 ctx, cancel := context.WithCancel(context.Background())
710 s, e := f.l.Open(ctx, f.launch)
711 if e != nil {
712 t.Fatal(e)
713 }
714 ch, _ := f.l.Events(ctx, s)
715 cancel()
716 if terminal(t, ch).Kind != "turn.failed" {
717 t.Fatal("attempt lifetime ignored")
718 }
719 f.l.Close(context.Background(), s)
720 })
721 t.Run("per-turn-tamper", func(t *testing.T) {
722 f := fixtureFor(t)
723 s, _ := openFixture(t, f)
724 state, _ := f.l.state(s)
725 state.launch.Policy.TurnPolicy = json.RawMessage(`{"approvalPolicy":"never"}`)
726 count := len(f.host.calls)
727 if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "t", AdmissionID: "a", Prompt: "hello"}); e == nil {
728 t.Fatal("per-turn override accepted")
729 }
730 if len(f.host.calls) != count {
731 t.Fatal("override reached stdin")
732 }
733 })
734}
735func TestCodexGeneratedSchema(t *testing.T) {
736 t.Parallel()
737 f := fixtureFor(t)
738 for _, name := range []string{"ThreadStartParams", "ThreadResumeParams", "TurnStartParams"} {
739 raw, e := os.ReadFile("testdata/schema-" + name + ".json")
740 if e != nil {
741 t.Fatal(e)
742 }
743 var schema struct{ Properties map[string]json.RawMessage }
744 if e = json.Unmarshal(raw, &schema); e != nil {
745 t.Fatal(e)
746 }
747 policy := f.launch.Policy.ThreadPolicy
748 if name == "TurnStartParams" {
749 policy = f.launch.Policy.TurnPolicy
750 }
751 var fields map[string]json.RawMessage
752 json.Unmarshal(policy, &fields)
753 if name == "ThreadResumeParams" {
754 fields = threadParams(policy, "thread/resume", "fixture")
755 }
756 for key := range fields {
757 if _, ok := schema.Properties[key]; !ok {
758 t.Fatal("field absent from pinned schema", name, key)
759 }
760 }
761 }
762}
763
764func TestCodexPolicyShape(t *testing.T) {
765 if Version != "0.165.0" || ExecutableSHA256 != "c06a67fd8ac76508dc78bd99ce20c9f317b8d568beda59485f3f4134df9962d5" || CodeModeHostSHA256 != "522935d4392ec9674fab60b239b5495992c6a93e4deb65113a216b6f5451ccd4" {
766 t.Fatal("pinned runtime changed")
767 }
768 t.Parallel()
769 f := fixtureFor(t)
770 var config map[string]any
771 json.Unmarshal(f.inputs.Settings, &config)
772 for key, want := range map[string]any{"approval_policy": "on-request", "approvals_reviewer": "user", "default_permissions": "equipo", "model": "gpt-6-luna", "model_provider": "openai"} {
773 if config[key] != want {
774 t.Fatal(key, config[key])
775 }
776 }
777 profiles, ok := config["permissions"].(map[string]any)
778 if !ok || len(profiles) != 1 {
779 t.Fatal("named profile missing")
780 }
781 profile, ok := profiles["equipo"].(map[string]any)
782 if !ok {
783 t.Fatal("equipo profile missing")
784 }
785 fs := profile["filesystem"].(map[string]any)
786 for _, path := range []string{f.launch.Binding.CredentialHome, f.launch.Binding.Home, "/home/runner", "/egress", "/tool", "/config", "/proc", "/alias/login", "/private/state"} {
787 if fs[path] != "deny" {
788 t.Fatal("missing deny", path)
789 }
790 }
791 if fs["/workspace"] != "write" || profile["network"].(map[string]any)["enabled"] != false {
792 t.Fatal("workspace/network profile changed")
793 }
794 features := config["features"].(map[string]any)
795 for _, key := range []string{"apps", "multi_agent", "remote_control"} {
796 if features[key] != false {
797 t.Fatal("feature enabled", key)
798 }
799 }
800 if servers := config["mcp_servers"].(map[string]any); len(servers) != 1 || servers["equipo"] == nil {
801 t.Fatal("inherited MCP")
802 }
803}
804func TestCodexResumeRechecksLease(t *testing.T) {
805 t.Parallel()
806 f := fixtureFor(t)
807 s, _ := openFixture(t, f)
808 f.host.set("resume-race")
809 before := f.host.count("thread/resume")
810 if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "t", AdmissionID: "a", Prompt: "hello"}); e == nil {
811 t.Fatal("resume accepted stale lease")
812 }
813 if f.host.count("thread/resume") != before {
814 t.Fatal("thread/resume sent after source changed")
815 }
816}
817func TestCodexTurnRechecksLease(t *testing.T) {
818 t.Parallel()
819 f := fixtureFor(t)
820 s, events := openFixture(t, f)
821 if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "initial", AdmissionID: "initial", Prompt: "ready"}); e != nil {
822 t.Fatal(e)
823 }
824 terminal(t, events)
825 f.host.set("turn-race")
826 if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "t", AdmissionID: "a", Prompt: "hello"}); e == nil {
827 t.Fatal("turn accepted stale lease")
828 }
829 if f.host.count("turn/start") != 1 {
830 t.Fatal("turn/start sent after source changed")
831 }
832}
833func TestCodexRefreshRejectsChangedIdentity(t *testing.T) {
834 t.Parallel()
835 f := fixtureFor(t)
836 s, ch := openFixture(t, f)
837 if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "t", AdmissionID: "a", Prompt: "hello"}); e != nil {
838 t.Fatal(e)
839 }
840 terminal(t, ch)
841 os.WriteFile(filepath.Join(f.launch.Binding.Home, "auth.json"), []byte(`{"fake":"other login"}`), 0600)
842 f.host.set("identity")
843 if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "t2", AdmissionID: "a2", Prompt: "again"}); e == nil {
844 t.Fatal("wrong identity refreshed")
845 }
846 if e := f.lease.Validate(context.Background()); !errors.Is(e, provider.ErrRefreshPending) {
847 t.Fatal("runtime login did not remain pending sign-in", e)
848 }
849 raw, _ := os.ReadFile(filepath.Join(f.launch.Binding.CredentialHome, "auth.json"))
850 if bytes.Contains(raw, []byte("other login")) {
851 t.Fatal("wrong identity committed")
852 }
853}
854
855func TestCodexProcessExit(t *testing.T) {
856 t.Parallel()
857 f := fixtureFor(t)
858 s, ch := openFixture(t, f)
859 f.host.set("exit")
860 if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "t", AdmissionID: "a", Prompt: "hello"}); e != nil {
861 t.Fatal(e)
862 }
863 terminal(t, ch)
864 if e := f.l.Close(context.Background(), s); e == nil {
865 t.Fatal("nonzero exit accepted")
866 }
867 f.launch.AttemptKey = "resume"
868 f.launch.ResumeSessionID = s.ID
869 if _, e := f.l.Open(context.Background(), f.launch); e == nil {
870 t.Fatal("nonzero exit authorized resume")
871 }
872}
873
874type brokenCapture struct{ invalid bool }
875
876func (f brokenCapture) Open(context.Context, provider.Process, provider.Launch) (*provider.Capture, error) {
877 if f.invalid {
878 return &provider.Capture{}, nil
879 }
880 return nil, io.ErrUnexpectedEOF
881}
882func TestCodexCaptureRequired(t *testing.T) {
883 t.Parallel()
884 for _, invalid := range []bool{false, true} {
885 f := fixtureFor(t)
886 f.l.captures = brokenCapture{invalid: invalid}
887 if _, e := f.l.Open(context.Background(), f.launch); e == nil {
888 t.Fatal("missing capture accepted")
889 }
890 if f.host.count("turn/start") != 0 {
891 t.Fatal("prompt bypassed capture")
892 }
893 }
894}
895
896func TestCodexClosedTurnCannotRestart(t *testing.T) {
897 t.Parallel()
898 f := fixtureFor(t)
899 session, ch := openFixture(t, f)
900 if e := f.l.StartTurn(context.Background(), session, provider.Turn{ID: "t", AdmissionID: "a", Prompt: "hello"}); e != nil {
901 t.Fatal(e)
902 }
903 terminal(t, ch)
904 if e := f.l.Close(context.Background(), session); e != nil {
905 t.Fatal(e)
906 }
907 s, _ := f.l.state(session)
908 if e := s.beginTurn(context.Background(), provider.Turn{ID: "late", AdmissionID: "late-admission", Prompt: "late"}); e == nil {
909 t.Fatal("close raced with begin and reopened the lease")
910 }
911 if e := f.lease.BeginTurn(context.Background()); e != nil {
912 t.Fatal("closed session left lease active", e)
913 }
914 f.lease.EndTurn(context.Background())
915}
916
917func TestCodexTypedNilConstructor(t *testing.T) {
918 var host *fakeHost
919 var capture *fakeCapture
920 if _, e := New(host, fakeCapture{}); e == nil {
921 t.Fatal("typed nil host accepted")
922 }
923 if _, e := New(&fakeHost{}, capture); e == nil {
924 t.Fatal("typed nil capture accepted")
925 }
926}
927
928type directGuardCapture struct {
929 inner provider.CaptureFactory
930 fail bool
931 bound, turns int
932}
933type directGuardInput struct {
934 io.WriteCloser
935 owner *directGuardCapture
936}
937
938func (c *directGuardCapture) Open(ctx context.Context, p provider.Process, l provider.Launch) (*provider.Capture, error) {
939 cap, e := c.inner.Open(ctx, p, l)
940 if e == nil {
941 cap.Input = &directGuardInput{cap.Input, c}
942 }
943 return cap, e
944}
945func (w *directGuardInput) BindSession(context.Context, provider.Session) error {
946 w.owner.bound++
947 return nil
948}
949func (w *directGuardInput) BeginTurn(context.Context, provider.Session, provider.Turn) error {
950 w.owner.turns++
951 if w.owner.fail {
952 return io.ErrClosedPipe
953 }
954 return nil
955}
956
957func TestDirectJournalAdapterBarrier(t *testing.T) {
958 for _, fail := range []bool{false, true} {
959 t.Run(fmt.Sprint(fail), func(t *testing.T) {
960 f := fixtureFor(t)
961 guard := &directGuardCapture{inner: f.l.captures, fail: fail}
962 f.l.captures = guard
963 session, ch := openFixture(t, f)
964 if guard.bound != 1 {
965 t.Fatal("session not durably bound")
966 }
967 err := f.l.StartTurn(context.Background(), session, provider.Turn{ID: "direct-turn", AdmissionID: "direct-admission", Prompt: "hello"})
968 if fail {
969 if err == nil {
970 t.Fatal("failed journal barrier ignored")
971 }
972 if f.host.count("turn/start") != 0 {
973 t.Fatal("failed barrier sent input")
974 }
975 } else {
976 if err != nil {
977 t.Fatal(err)
978 }
979 event := terminal(t, ch)
980 if event.Sequence <= 0 {
981 t.Fatal("capture sequence lost before projection")
982 }
983 }
984 if guard.turns != 1 {
985 t.Fatal("journal turn barrier not called")
986 }
987 })
988 }
989}
990
991func TestRefreshWithoutCertifiedHostFailsClosed(t *testing.T) {
992 f := fixtureFor(t)
993 in, _, err := policyInputs(f.launch.Policy)
994 if err != nil {
995 t.Fatal(err)
996 }
997 in.AuthHost = ""
998 in.EgressHosts = []string{"chatgpt.com"}
999 f.launch.Policy, err = provider.BuildPolicy(f.launch.Binding, in)
1000 if err != nil {
1001 t.Fatal(err)
1002 }
1003 s, _ := openFixture(t, f)
1004 if err = os.WriteFile(filepath.Join(f.launch.Binding.Home, "auth.json"), []byte(`{"fake":"refreshed"}`), 0600); err != nil {
1005 t.Fatal(err)
1006 }
1007 t.Setenv("EQUIPO_AUTH_HOST", "auth.openai.com")
1008 if err = f.l.StartTurn(context.Background(), s, provider.Turn{ID: "no-refresh", AdmissionID: "no-refresh", Prompt: "never sent"}); !errors.Is(err, provider.ErrAccountMaintenance) {
1009 t.Fatalf("uncertified refresh: %v", err)
1010 }
1011}
1012