package runner import ( "context" "encoding/json" "fmt" "net/http/httptest" "os" "os/exec" "path/filepath" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo/team" "amadan.net/oficina/equipo/internal/runner/provider" ) var journalCtx = context.Background() func journalEvent(id string, seq int64) Event { return Event{Version: 2, ID: id, TaskID: "task", AssignmentID: "assignment", ServerID: "server", AgentID: "agent", SessionID: "session", Epoch: "epoch", Kind: "timeline", Sequence: &seq, Scope: team.Scope{Account: "team", Job: 1}, Handle: team.Handle{Attempt: 1, Fence: 1, Runner: "runner"}, Payload: json.RawMessage(`{"text":"hello"}`), SourceTime: time.Date(2026, 11, 2, 0, 0, 0, 0, time.UTC)} } func mustJournal(t *testing.T, err error) { t.Helper() if err != nil { t.Fatal(err) } } func TestRunnerJournalCrashBoundaries(t *testing.T) { path := filepath.Join(t.TempDir(), "private", "journal.db") j, err := OpenJournal(journalCtx, path) mustJournal(t, err) pending, err := j.Pending(journalCtx, 10) mustJournal(t, err) if len(pending) != 0 { t.Fatal("effect before append") } e := journalEvent("event", 1) mustJournal(t, j.Append(journalCtx, e)) mustJournal(t, j.Close()) for i := 0; i < 2; i++ { j, err = OpenJournal(journalCtx, path) mustJournal(t, err) pending, err = j.Pending(journalCtx, 10) mustJournal(t, err) if len(pending) != 1 { t.Fatal("lost durable event", len(pending)) } mustJournal(t, j.Append(journalCtx, e)) mustJournal(t, j.Close()) } j, err = OpenJournal(journalCtx, path) mustJournal(t, err) defer j.Close() e.Payload = json.RawMessage(`{"text":"changed"}`) if j.Append(journalCtx, e) == nil { t.Fatal("changed duplicate accepted") } mustJournal(t, j.Ack(journalCtx, "event")) mustJournal(t, j.Close()) j, err = OpenJournal(journalCtx, path) mustJournal(t, err) defer j.Close() pending, err = j.Pending(journalCtx, 10) mustJournal(t, err) if len(pending) != 0 { t.Fatal("ACK did not survive reopen") } info, err := os.Stat(path) mustJournal(t, err) if info.Mode().Perm() != 0600 { t.Fatal("journal is not private") } intent := provider.Intent{Kind: "agent", Key: "creation", RequestHash: "hash", Request: json.RawMessage(`{"idempotency_key":"creation"}`)} mustJournal(t, j.RecordIntent(journalCtx, intent)) mustJournal(t, j.RecordIntent(journalCtx, intent)) intent.RequestHash = "changed" if j.RecordIntent(journalCtx, intent) == nil { t.Fatal("creation key changed") } } func TestBufferFullStopsWork(t *testing.T) { j, err := OpenJournal(journalCtx, filepath.Join(t.TempDir(), "private", "journal.db")) mustJournal(t, err) defer j.Close() j.maxBytes = 1 stopped := 0 p := EventPump{Journal: j, Contain: func(context.Context) error { stopped++; return nil }} acked := false if p.Append(journalCtx, journalEvent("full", 1), func() error { acked = true; return nil }) == nil { t.Fatal("full journal accepted") } if stopped != 1 || acked { t.Fatal("buffer full did not stop admission and contain", stopped, acked) } j.maxBytes = MaxJournalBytes if j.AdmissionAllowed(journalCtx) != nil { t.Fatal("drained budget remained latched") } mustJournal(t, j.Close()) if p.Append(journalCtx, journalEvent("closed", 2), nil) == nil || stopped != 2 { t.Fatal("disk failure did not contain") } } func TestRunnerEventReplay(t *testing.T) { j, err := OpenJournal(journalCtx, filepath.Join(t.TempDir(), "private", "journal.db")) mustJournal(t, err) defer j.Close() p := EventPump{Journal: j, Contain: func(context.Context) error { return nil }} mustJournal(t, p.Append(journalCtx, journalEvent("event", 1), func() error { rows, err := j.Pending(journalCtx, 10) if err != nil || len(rows) != 1 { t.Fatal("ACK before append") } return nil })) calls := 0 p.Upload = func(context.Context, Event) error { calls++ if calls == 1 { return provider.ErrUncertain } return nil } if p.Flush(journalCtx, 10) == nil { t.Fatal("lost upload was ACKed") } mustJournal(t, p.Flush(journalCtx, 10)) rows, err := j.Pending(journalCtx, 10) mustJournal(t, err) if len(rows) != 0 || calls != 2 { t.Fatal("replay failed") } } func TestTimelineEpochReplacement(t *testing.T) { j, err := OpenJournal(journalCtx, filepath.Join(t.TempDir(), "private", "journal.db")) mustJournal(t, err) defer j.Close() a := provider.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"} if _, err = j.Cursor(journalCtx, a); err != nil { t.Fatal(err) } if j.Ready(journalCtx, a) == nil { t.Fatal("live before refetch") } mustJournal(t, j.Append(journalCtx, journalEvent("old", 1))) mustJournal(t, j.BeginReplay(journalCtx, a)) mustJournal(t, j.Recovered(journalCtx, a, provider.Cursor{Epoch: "epoch", Sequence: 1})) mustJournal(t, j.Ready(journalCtx, a)) mustJournal(t, j.BeginReplay(journalCtx, a)) if j.Ready(journalCtx, a) == nil { t.Fatal("reconnect retained readiness") } e := journalEvent("replacement", 1) e.Epoch = "new" reset := e reset.ID = "reset" reset.Kind = "timeline_replacement" reset.Sequence = nil mustJournal(t, j.Append(journalCtx, reset)) mustJournal(t, j.BeginReplay(journalCtx, a)) mustJournal(t, j.Append(journalCtx, e)) mustJournal(t, j.Recovered(journalCtx, a, provider.Cursor{Epoch: "new", Sequence: 1})) c, err := j.Cursor(journalCtx, a) mustJournal(t, err) if c.Epoch != "new" { t.Fatal("epoch did not replace projection") } rows, err := j.Pending(journalCtx, 10) mustJournal(t, err) if len(rows) != 3 { t.Fatal("epoch deleted accounting evidence") } mustJournal(t, j.Close()) j, err = OpenJournal(journalCtx, j.path) mustJournal(t, err) defer j.Close() if j.Ready(journalCtx, a) == nil { t.Fatal("restart trusted old live readiness") } } func TestRunnerJournalCursorCannotSkip(t *testing.T) { j, err := OpenJournal(journalCtx, filepath.Join(t.TempDir(), "private", "journal.db")) mustJournal(t, err) defer j.Close() a := provider.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"} mustJournal(t, j.BeginReplay(journalCtx, a)) if j.Recovered(journalCtx, a, provider.Cursor{Epoch: "epoch", Sequence: 9}) == nil { t.Fatal("cursor skipped unjournaled events") } mustJournal(t, j.Append(journalCtx, journalEvent("saved", 1))) if j.Recovered(journalCtx, a, provider.Cursor{Epoch: "epoch", Sequence: 2}) == nil { t.Fatal("cursor advanced beyond durable event") } } func TestRunnerJournalSecretsAndLog(t *testing.T) { path := filepath.Join(t.TempDir(), "private", "journal.db") j, err := OpenJournal(journalCtx, path) mustJournal(t, err) defer j.Close() e := journalEvent("secret", 1) e.Payload = json.RawMessage(`{"authorization":"Bearer credential-value","text":"Bearer credential-value Authorization: Basic eDpnaXQtY2FuYXJ5 ","inputTokens":2}`) mustJournal(t, j.Append(journalCtx, e)) rows, err := j.Pending(journalCtx, 10) mustJournal(t, err) if strings.Contains(string(rows[0].Payload), "credential-value") || strings.Contains(string(rows[0].Payload), "eDpnaXQtY2FuYXJ5") || !strings.Contains(string(rows[0].Payload), "inputTokens") { t.Error("redaction lost accounting or leaked secret", string(rows[0].Payload)) } intent := provider.Intent{Kind: "agent", Key: "secret-intent", RequestHash: "hash", Request: json.RawMessage(`{"env":{"EQUIPO_TOOL_TOKEN":"private-key-value"}}`)} mustJournal(t, j.RecordIntent(journalCtx, intent)) var raw []byte mustJournal(t, j.db.QueryRow("SELECT body FROM journal_intents").Scan(&raw)) if strings.Contains(string(raw), "private-key-value") { t.Fatal("intent persisted credential") } w := httptest.NewRecorder() DownloadLog(w, []byte(` Bearer credential-value Authorization: Basic eDpnaXQtY2FuYXJ5`), []string{"secret"}) if strings.Contains(w.Body.String(), "