package runner import ( "bytes" "context" "encoding/json" "fmt" "io" "os" "os/exec" "path/filepath" "strings" "sync/atomic" "testing" "time" "amadan.net/oficina/equipo/internal/runner/containment" "amadan.net/oficina/equipo/internal/runner/provider" ) type directProcess struct { writable io.WriteCloser input bytes.Buffer out io.ReadCloser errout io.ReadCloser stopped atomic.Bool record containment.Record } type directInput struct{ *bytes.Buffer } func (directInput) Close() error { return nil } func (p *directProcess) ID() string { return p.record.ID } func (p *directProcess) Stdin() io.WriteCloser { if p.writable != nil { return p.writable } return directInput{&p.input} } func (p *directProcess) Stdout() io.ReadCloser { return p.out } func (p *directProcess) Stderr() io.ReadCloser { return p.errout } func (p *directProcess) Wait(context.Context) (provider.Exit, error) { return provider.Exit{}, nil } func (p *directProcess) Contain(context.Context) error { p.stopped.Store(true) p.out.Close() p.errout.Close() return nil } func (p *directProcess) Record() containment.Record { return p.record } func directFixture(t *testing.T, name string) (*Journal, provider.Launch, provider.Session, *directProcess) { t.Helper() j, err := OpenJournal(context.Background(), filepath.Join(t.TempDir(), "private", "journal.db")) mustJournal(t, err) t.Cleanup(func() { j.Close() }) version := "0.165.0" if name == "claude" { version = "2.1.312" } l := provider.Launch{AttemptKey: "attempt", Selection: provider.Selection{Provider: name, AccountID: "account", Family: name, Model: "model", ConnectionID: "connection"}, Binding: provider.Binding{ID: "binding", Provider: name, AccountID: "account", Expected: provider.Identity{ProviderVersion: version}}, Policy: provider.Policy{Hash: "policy", ManifestHash: "44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a", Manifest: json.RawMessage(`{}`)}} s := provider.Session{ID: "session", AttemptKey: l.AttemptKey, Provider: name, AccountID: "account", Family: name, Model: "model"} p := &directProcess{record: containment.Record{ID: strings.Repeat("a", 32), AttemptKey: l.AttemptKey, ManifestHash: "namespace-manifest", PolicyHash: l.Policy.Hash}, out: io.NopCloser(strings.NewReader("")), errout: io.NopCloser(strings.NewReader(""))} mustJournal(t, j.recordDirectLaunch(context.Background(), l, p.record)) return j, l, s, p } func directTurn() provider.Turn { return provider.Turn{ID: "turn", AdmissionID: "admission", Prompt: "hello"} } func directPrompt(name string) []byte { if name == "claude" { return []byte("{\"type\":\"user\",\"session_id\":\"session\",\"message\":{\"role\":\"user\",\"content\":\"hello\"}}\n") } return []byte("{\"id\":1,\"method\":\"turn/start\",\"params\":{\"threadId\":\"session\",\"input\":[{\"type\":\"text\",\"text\":\"hello\"}]}}\n") } func TestDirectCrashBoundaries(t *testing.T) { for _, name := range []string{"claude", "codex"} { for _, stage := range []string{"intent", "before-stdin", "after-stdin", "before-frame", "after-frame", "before-upload", "server-before-ack"} { t.Run(name+"/"+stage, func(t *testing.T) { j, l, s, p := directFixture(t, name) ctx, cancel := context.WithCancel(context.Background()) defer cancel() // Keep stdout open until the simulated crash. r, w := io.Pipe() p.out = r defer w.Close() cap, err := NewCaptureFactory(j).Open(ctx, p, l) mustJournal(t, err) if _, err = cap.Input.Write(directPrompt(name)); err == nil || p.input.Len() != 0 { t.Fatal("prompt bypassed intent") } mustJournal(t, j.BeginTurn(ctx, s, directTurn())) if stage != "intent" && stage != "before-stdin" { _, err = cap.Input.Write(directPrompt(name)) mustJournal(t, err) } if stage == "after-frame" || stage == "before-upload" || stage == "server-before-ack" { mustJournal(t, j.AppendFrame(ctx, l.AttemptKey, p.ID(), 1, []byte(`{"type":"result","session_id":"session","subtype":"success","is_error":false}`))) } cancel() <-cap.Done path := j.path mustJournal(t, j.Close()) reopened, err := OpenJournal(context.Background(), path) mustJournal(t, err) defer reopened.Close() rows, err := reopened.RecoverDirect(context.Background()) mustJournal(t, err) if len(rows) != 1 || rows[0].State != "waiting_for_person" || rows[0].Usage != nil { t.Fatalf("uncertain recovery: %+v", rows) } if reopened.BeginTurn(context.Background(), s, directTurn()) == nil { t.Fatal("restart admitted uncertain prompt again") } }) } } } func TestDirectJournalFailureContains(t *testing.T) { for _, kind := range []string{"torn", "unterminated", "malformed", "duplicate-key", "oversized", "disk-full", "outbox-full", "outbox-crossing", "blocked", "stderr"} { t.Run(kind, func(t *testing.T) { j, l, _, p := directFixture(t, "claude") ctx, cancel := context.WithCancel(context.Background()) defer cancel() raw := "{\"type\":\"system\",\"input_tokens\":9007199254740993,\"authorization\":\"Bearer secret\"}\n" switch kind { case "torn": raw = `{"type":"system"` case "unterminated": raw = `{"type":"system"}` case "malformed": raw = "secret-sentinel\n" case "duplicate-key": raw = "{\"type\":1,\"type\":2}\n" case "oversized": raw = "{\"text\":\"" + strings.Repeat("x", 1<<20) + "\"}\n" case "disk-full": var pages int mustJournal(t, j.db.QueryRow("PRAGMA page_count").Scan(&pages)) _, err := j.db.Exec(fmt.Sprintf("PRAGMA max_page_count=%d", pages)) mustJournal(t, err) raw = "{\"text\":\"" + strings.Repeat("a", 20000) + "\"}\n" case "outbox-full": _, err := j.db.Exec("INSERT INTO journal_events(id,event_key,content_hash,body,size) VALUES('full','full','full','{}',?)", MaxJournalBytes) mustJournal(t, err) case "outbox-crossing": j.maxBytes = 256 raw = "{\"text\":\"" + strings.Repeat("x", 512) + "\"}\n" case "blocked": r, w := io.Pipe() p.out = r defer w.Close() case "stderr": p.errout = io.NopCloser(strings.NewReader(strings.Repeat("x", 70000))) } if kind != "blocked" { p.out = io.NopCloser(strings.NewReader(raw)) } cap, err := NewCaptureFactory(j).Open(ctx, p, l) if err != nil { if !p.stopped.Load() { t.Fatal("open failure did not contain") } return } if kind == "blocked" { cancel() } if kind == "stderr" { for range cap.Frames { } if err = <-cap.Done; err != nil { t.Fatal(err) } var n int mustJournal(t, j.db.QueryRow("SELECT length(diagnostics) FROM direct_attempts").Scan(&n)) if n > 64<<10 { t.Fatal("unbounded stderr") } return } select { case _, ok := <-cap.Frames: if ok { t.Fatal("uncommitted or invalid frame escaped") } case <-time.After(2 * time.Second): t.Fatal("capture blocked") } if err = <-cap.Done; err == nil || !p.stopped.Load() || (kind == "malformed" && (!strings.Contains(err.Error(), "stdout_invalid_json") || strings.Contains(err.Error(), "secret-sentinel"))) { t.Fatalf("not contained or unsafe diagnostic: %v", err) } }) } } func TestDirectJournalCommitBeforeDelivery(t *testing.T) { j, l, _, p := directFixture(t, "claude") p.out = io.NopCloser(strings.NewReader("{\"input_tokens\":9007199254740993,\"authorization\":\"Bearer secret\"}\n")) cap, err := NewCaptureFactory(j).Open(context.Background(), p, l) mustJournal(t, err) for f := range cap.Frames { var b []byte mustJournal(t, j.db.QueryRow("SELECT body FROM direct_frames WHERE stream=? AND sequence=?", p.ID(), f.Sequence).Scan(&b)) if !bytes.Equal(b, f.Bytes) || strings.Contains(string(b), "secret") || !strings.Contains(string(b), "9007199254740993") { t.Fatalf("frame not durably redacted with exact counters: %s", b) } } mustJournal(t, <-cap.Done) } func TestDirectCrashProcess(t *testing.T) { if path := os.Getenv("EQUIPO_TASK7_CRASH_PATH"); path != "" { ctx := context.Background() j, err := OpenJournal(ctx, path) mustJournal(t, err) l := provider.Launch{AttemptKey: "attempt", Selection: provider.Selection{Provider: "codex", AccountID: "account", Family: "gpt", Model: "model"}, Binding: provider.Binding{ID: "binding", Provider: "codex", AccountID: "account", Expected: provider.Identity{ProviderVersion: "0.165.0"}}, Policy: provider.Policy{Hash: "policy", ManifestHash: "44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a", Manifest: json.RawMessage(`{}`)}} s := provider.Session{ID: "session", AttemptKey: "attempt", Provider: "codex", AccountID: "account", Family: "gpt", Model: "model"} r, w := io.Pipe() defer w.Close() input, err := os.OpenFile(path+".stdin", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600) mustJournal(t, err) p := &directProcess{record: containment.Record{ID: strings.Repeat("a", 32), AttemptKey: "attempt", ManifestHash: "manifest", PolicyHash: "policy"}, out: r, errout: io.NopCloser(strings.NewReader("")), writable: input} mustJournal(t, j.recordDirectLaunch(ctx, l, p.record)) cap, err := NewCaptureFactory(j).Open(ctx, p, l) mustJournal(t, err) mustJournal(t, j.BeginTurn(ctx, s, directTurn())) stage := os.Getenv("EQUIPO_TASK7_CRASH_STAGE") if stage == "intent" || stage == "before-stdin" { os.Exit(0) } _, err = cap.Input.Write(directPrompt("codex")) mustJournal(t, err) mustJournal(t, input.Sync()) if stage == "after-stdin" { os.Exit(0) } raw := []byte(`{"method":"turn/completed","params":{"threadId":"session","turn":{"id":"provider-turn","status":"completed"}}}`) if stage == "before-frame" { tx, err := j.db.BeginTx(ctx, nil) mustJournal(t, err) _, err = tx.Exec("INSERT INTO direct_frames(stream,sequence,body) VALUES(?,1,?)", p.ID(), raw) mustJournal(t, err) os.Exit(0) } mustJournal(t, j.AppendFrame(ctx, l.AttemptKey, p.ID(), 1, raw)) if stage == "after-frame" { os.Exit(0) } _, err = j.ObserveDirect(ctx, s, codexUsage("turn", 28254, 142)) mustJournal(t, err) template := journalEvent("ignored", 1) template.ActionID = 1 pump := EventPump{Journal: j, Contain: func(context.Context) error { return nil }} mustJournal(t, pump.AppendDirect(ctx, s, directComplete("turn"), template)) if stage == "server-before-ack" { pending, err := j.Pending(ctx, 1) mustJournal(t, err) raw, _ := json.Marshal(pending[0]) mustJournal(t, os.WriteFile(path+".server", raw, 0600)) } os.Exit(0) } for _, stage := range []string{"intent", "before-stdin", "after-stdin", "before-frame", "after-frame", "before-upload", "server-before-ack"} { t.Run(stage, func(t *testing.T) { path := filepath.Join(t.TempDir(), "private", "journal.db") ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestDirectCrashProcess$") cmd.Env = append(os.Environ(), "EQUIPO_TASK7_CRASH_PATH="+path, "EQUIPO_TASK7_CRASH_STAGE="+stage) if out, err := cmd.CombinedOutput(); err != nil { t.Fatal(err, string(out)) } j, err := OpenJournal(ctx, path) mustJournal(t, err) defer j.Close() rows, err := j.RecoverDirect(ctx) mustJournal(t, err) if len(rows) != 1 { t.Fatalf("missing recovery %+v", rows) } complete := stage == "before-upload" || stage == "server-before-ack" if complete { if rows[0].State != "completed_needs_containment" || rows[0].Usage == nil || rows[0].Usage.InputTokens != 28254 { t.Fatalf("durable completion lost: %+v", rows) } } else if rows[0].State != "waiting_for_person" || rows[0].Usage != nil { t.Fatalf("invented completion: %+v", rows) } var frames int mustJournal(t, j.db.QueryRow("SELECT count(*) FROM direct_frames").Scan(&frames)) want := 0 if stage == "after-frame" || complete { want = 1 } if frames != want { t.Fatal("torn transaction persisted", frames, want) } input, err := os.ReadFile(path + ".stdin") mustJournal(t, err) writes := bytes.Count(input, []byte{'\n'}) expected := 1 if stage == "intent" || stage == "before-stdin" { expected = 0 } if writes != expected { t.Fatal("prompt repeated", writes) } if stage == "server-before-ack" { server, err := os.ReadFile(path + ".server") mustJournal(t, err) pending, err := j.Pending(ctx, 10) mustJournal(t, err) if len(pending) != 1 { t.Fatal("lost upload") } replay, _ := json.Marshal(pending[0]) if !bytes.Equal(server, replay) { t.Fatal("replay changed delivery identity") } } }) } } func TestDirectCrashSingleUseInput(t *testing.T) { j, l, s, p := directFixture(t, "codex") ctx, cancel := context.WithCancel(context.Background()) defer cancel() r, w := io.Pipe() defer w.Close() p.out = r cap, err := NewCaptureFactory(j).Open(ctx, p, l) mustJournal(t, err) mustJournal(t, j.BeginTurn(ctx, s, directTurn())) _, err = cap.Input.Write(directPrompt("codex")) mustJournal(t, err) if _, err = cap.Input.Write(directPrompt("codex")); err == nil { t.Fatal("same prompt sent twice") } if bytes.Count(p.input.Bytes(), []byte{'\n'}) != 1 { t.Fatal("single-use intent reused") } if j.BeginTurn(ctx, s, provider.Turn{ID: "other", AdmissionID: "other-admission", Prompt: "hello"}) == nil { t.Fatal("active turn replaced") } cancel() <-cap.Done } func TestDirectJournalFrameSequence(t *testing.T) { j, l, _, p := directFixture(t, "codex") ctx := context.Background() mustJournal(t, j.AppendFrame(ctx, l.AttemptKey, p.ID(), 2, []byte(`{"n":2}`))) if j.AppendFrame(ctx, l.AttemptKey, p.ID(), 1, []byte(`{"n":1}`)) == nil { t.Fatal("frame order regressed") } if j.AppendFrame(ctx, l.AttemptKey, "other", 3, []byte(`{"n":3}`)) == nil { t.Fatal("stream detached from attempt") } } type shortDirectInput struct{} func (shortDirectInput) Write(b []byte) (int, error) { return len(b) / 2, nil } func (shortDirectInput) Close() error { return nil } func TestDirectJournalShortInput(t *testing.T) { j, l, s, p := directFixture(t, "codex") ctx, cancel := context.WithCancel(context.Background()) defer cancel() r, w := io.Pipe() defer w.Close() p.out = r p.writable = shortDirectInput{} cap, err := NewCaptureFactory(j).Open(ctx, p, l) mustJournal(t, err) mustJournal(t, j.BeginTurn(ctx, s, directTurn())) if _, err = cap.Input.Write(directPrompt("codex")); err == nil { t.Fatal("short stdin write reported success") } if err = <-cap.Done; err == nil || !p.stopped.Load() { t.Fatal("short stdin write was not contained") } rows, err := j.RecoverDirect(context.Background()) mustJournal(t, err) if rows[0].State != "waiting_for_person" { t.Fatal("short write invented outcome") } } func TestDirectJournalInputProtocol(t *testing.T) { j, l, s, p := directFixture(t, "codex") ctx, cancel := context.WithCancel(context.Background()) defer cancel() r, w := io.Pipe() defer w.Close() p.out = r cap, err := NewCaptureFactory(j).Open(ctx, p, l) mustJournal(t, err) for _, raw := range []string{"{\"method\":\"command/exec\",\"params\":{}}\n", "{}\n{}\n", "{\"method\":\"turn/start\",\"params\":{\"threadId\":\"session\",\"input\":[]}}\n"} { if _, err = cap.Input.Write([]byte(raw)); err == nil { t.Fatal("invalid input admitted") } } if p.input.Len() != 0 { t.Fatal("invalid input transmitted") } mustJournal(t, j.BeginTurn(ctx, s, directTurn())) wrong := bytes.ReplaceAll(directPrompt("codex"), []byte("hello"), []byte("different")) if _, err = cap.Input.Write(wrong); err == nil { t.Fatal("prompt differs from admitted intent") } if p.input.Len() != 0 { t.Fatal("unadmitted prompt transmitted") } cancel() <-cap.Done } func TestDirectCrashFullOutbox(t *testing.T) { j, l, s, p := directFixture(t, "codex") ctx, cancel := context.WithCancel(context.Background()) defer cancel() r, w := io.Pipe() defer w.Close() p.out = r cap, err := NewCaptureFactory(j).Open(ctx, p, l) mustJournal(t, err) mustJournal(t, j.BeginTurn(ctx, s, directTurn())) _, err = j.db.Exec("INSERT INTO journal_events(id,event_key,content_hash,body,size) VALUES('full','full','full','{}',?)", MaxJournalBytes) mustJournal(t, err) if _, err = cap.Input.Write(directPrompt("codex")); err == nil || p.input.Len() != 0 { t.Fatal("full outbox admitted stdin") } cancel() <-cap.Done } func TestDirectInterruptedLiveCapture(t *testing.T) { j, l, s, p := directFixture(t, "codex") ctx, cancel := context.WithCancel(context.Background()) defer cancel() r, w := io.Pipe() defer w.Close() p.out = r cap, err := NewCaptureFactory(j).Open(ctx, p, l) mustJournal(t, err) mustJournal(t, j.BeginTurn(ctx, s, directTurn())) _, err = cap.Input.Write(directPrompt("codex")) mustJournal(t, err) _, err = j.db.Exec("INSERT INTO journal_answers VALUES('answer','hash','pending')") mustJournal(t, err) _, err = j.db.Exec("INSERT INTO direct_answer_scopes VALUES('answer',?,?)", s.AttemptKey, "turn") mustJournal(t, err) cancel() <-cap.Done var state string mustJournal(t, j.db.QueryRow("SELECT state FROM direct_turns").Scan(&state)) if state != "waiting_for_person" { t.Fatal("live cancellation left turn dispatchable", state) } mustJournal(t, j.db.QueryRow("SELECT state FROM journal_answers").Scan(&state)) if state != "invalid" { t.Fatal("live cancellation retained pending answers") } late, err := j.ObserveDirect(context.Background(), s, directComplete("turn")) mustJournal(t, err) if late != nil { t.Fatal("late completion erased live cancellation") } }