diff --git a/cmd/agentop/README.md b/cmd/agentop/README.md index 44e9a6832..fe096d4d8 100644 --- a/cmd/agentop/README.md +++ b/cmd/agentop/README.md @@ -787,12 +787,13 @@ ran before you installed Cortex, or that did not go through it. agentop import # every supported agent agentop import --agent claude-code --since 30d agentop import --agent bob # Bob's tasks, from ~/.bob/db/bob.db +agentop import --agent codex # Codex's rollouts, from ~/.codex/sessions agentop import --since 2026-10-01 --dry-run # count only, write nothing ``` | Flag | Meaning | |---|---| -| `--agent` | `claude-code`, `bob`, `codex`, `opencode` or `pi`. Only `claude-code` and `bob` are supported now: the proxy answers the others with an error that names the supported agents. #1873 to #1875 add them. `bob` needs the `sqlite3` program on `PATH` | +| `--agent` | `claude-code`, `bob`, `codex`, `opencode` or `pi`. Only `claude-code`, `bob` and `codex` are supported now: the proxy answers the others with an error that names the supported agents. #1874 and #1875 add them. `bob` needs the `sqlite3` program on `PATH` | | `--since` | skip a transcript file last changed before this time: `YYYY-MM-DD` (local midnight) or `d` (N days ago) | | `--dry-run` | count what an import would do, and write nothing | | `--endpoint` | the session API, as for `agentop cost` | diff --git a/cmd/cortex/main.go b/cmd/cortex/main.go index 5d868841d..31c2d17a8 100644 --- a/cmd/cortex/main.go +++ b/cmd/cortex/main.go @@ -52,6 +52,7 @@ import ( "github.com/rossoctl/cortex/core/session/importer" bobimport "github.com/rossoctl/cortex/core/session/importer/bob" claudeimport "github.com/rossoctl/cortex/core/session/importer/claude" + codeximport "github.com/rossoctl/cortex/core/session/importer/codex" "github.com/rossoctl/cortex/core/sessionapi" "github.com/rossoctl/cortex/core/spiffe" "github.com/rossoctl/cortex/core/tlsbridge" @@ -1280,7 +1281,7 @@ func main() { sessionapi.WithLoopbackOnly(cfg.Listener.BindLoopbackOnly), // POST /v1/import, only with the archive on and loopback-only; else no route. sessionapi.WithImport(sessionapi.Import{Rates: pricingRegistry, - Sources: []importer.Source{claudeimport.New(""), bobimport.New("")}}), + Sources: []importer.Source{claudeimport.New(""), bobimport.New(""), codeximport.New("")}}), }, ingestOpts...)..., ) sessionLn := listeners.take("session-api") diff --git a/core/session/importer/codex/codex.go b/core/session/importer/codex/codex.go new file mode 100644 index 000000000..01dc460d4 --- /dev/null +++ b/core/session/importer/codex/codex.go @@ -0,0 +1,361 @@ +// Package codex is the importer source for Codex. It reads the rollout files under +// /sessions and makes one importer.Session from the root rollout of a session +// and the rollouts of its subagents. It does not write a file. +package codex + +import ( + "bufio" + "cmp" + "encoding/json" + "errors" + "io" + "io/fs" + "iter" + "log/slog" + "os" + "path/filepath" + "slices" + "strings" + "time" + + "github.com/klauspost/compress/zstd" + + "github.com/rossoctl/cortex/core/model" + "github.com/rossoctl/cortex/core/session/importer" +) + +const agentName = "codex" + +type source struct{ home string } + +// New returns the source. home "" resolves $CODEX_HOME, else ~/.codex, when Sessions runs. +func New(home string) importer.Source { return source{home: home} } + +func (source) Agent() string { return agentName } + +// PricingHost is the OpenAI host: the bundled table prices the GPT models under every host, +// and a rollout does not say if Codex used an API key or a ChatGPT login. +func (source) PricingHost() string { return "api.openai.com" } + +// rollout is one rollout file, from its session_meta line. +type rollout struct { + path, thread, session string + forkedFrom string // the thread id this rollout forks, or "" + mod time.Time + size int64 +} + +// openRollout opens a rollout file. The listing and the parse both use it, so a test can +// make an open fail. +var openRollout = openFile + +// openFile opens path, and reads it through zstd when its name ends with .zst. +func openFile(path string) (io.ReadCloser, error) { + f, err := os.Open(path) + if err != nil || !strings.HasSuffix(path, ".zst") { + return f, err + } + d, err := zstd.NewReader(f) + if err != nil { + f.Close() + return nil, err + } + return zstdFile{d, f}, nil +} + +type zstdFile struct { + *zstd.Decoder + f *os.File +} + +func (z zstdFile) Close() error { + z.Decoder.Close() + return z.f.Close() +} + +func (s source) dir() (string, error) { + if s.home != "" { + return s.home, nil + } + if h := os.Getenv("CODEX_HOME"); h != "" { + return h, nil + } + h, err := os.UserHomeDir() + if err != nil { + return "", err + } + return filepath.Join(h, ".codex"), nil +} + +func (s source) Sessions(since time.Time, skip func(id string, updated time.Time) bool, progress func(done, total int)) iter.Seq2[importer.Session, error] { + return func(yield func(importer.Session, error) bool) { + dir, err := s.dir() + if err != nil { + yield(importer.Session{}, err) + return + } + files, unopened := list(filepath.Join(dir, "sessions")) + groups := group(files) + // A fork's parent can be archived. The source does not import an archived rollout, but + // the ledger can already hold its turns. + threads := map[string]rollout{} + archived, _ := list(filepath.Join(dir, "archived_sessions")) + for _, f := range archived { + threads[f.thread] = f + } + for _, files := range groups { + for _, f := range files { + threads[f.thread] = f + } + } + sids := make([]string, 0, len(groups)) + newest := map[string]time.Time{} + for id, files := range groups { + sids = append(sids, id) + for _, f := range files { + if f.mod.After(newest[id]) { + newest[id] = f.mod + } + } + } + slices.SortFunc(sids, func(a, b string) int { + return cmp.Or(newest[b].Compare(newest[a]), strings.Compare(a, b)) + }) + total := len(unopened) + len(sids) + // A rollout that cannot be opened names no session, so it is counted on its own. + for i, mod := range unopened { + progress(i, total) + if (since.IsZero() || !mod.Before(since)) && !yield(importer.Session{Unreadable: true}, nil) { + return + } + } + home, _ := os.UserHomeDir() + for i, id := range sids { + progress(len(unopened)+i, total) + // Codex writes each line when it happens, so no line is newer than its file. + if !since.IsZero() && newest[id].Before(since) { + continue + } + if skip(id, newest[id]) { + continue + } + // The mtime is always after the newest event, so only this time lets Rule 2 skip an + // unchanged session before the slow parse. + if at, ok := newestAt(groups[id]); ok && skip(id, at) { + continue + } + if !yield(readSession(id, groups[id], threads, home), nil) { + return + } + } + progress(total, total) + } +} + +// list finds the rollout files under dir at all depths and reads the first line of each. +// unopened is the mtime of each file that cannot be opened or read. A missing dir gives none. +func list(dir string) (out []rollout, unopened []time.Time) { + // An error in one directory must not stop the others, so the walk ignores it. + _ = filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error { + if err != nil { + if d != nil && d.IsDir() && path != dir { + return fs.SkipDir + } + return nil + } + name := d.Name() + if !d.Type().IsRegular() || !strings.HasPrefix(name, "rollout-") || + !(strings.HasSuffix(name, ".jsonl") || strings.HasSuffix(name, ".jsonl.zst")) { + return nil + } + fi, err := d.Info() + if err != nil { + return nil + } + r, err := readMeta(path) + if err != nil { + slog.Warn("importer: cannot list a Codex rollout", "path", path, "error", err) + if !errors.Is(err, errNoMeta) && !errors.Is(err, io.EOF) { + unopened = append(unopened, fi.ModTime()) + } + return nil + } + r.path, r.mod, r.size = path, fi.ModTime(), fi.Size() + out = append(out, r) + return nil + }) + return out, unopened +} + +// errNoMeta is the error of a rollout whose first line is not a session_meta line. +var errNoMeta = errors.New("the first line is not a session_meta line") + +// readMeta gives the thread id, the session id and the forked thread id from the first line +// of a rollout. +func readMeta(path string) (rollout, error) { + f, err := openRollout(path) + if err != nil { + return rollout{}, err + } + defer f.Close() + raw, err := bufio.NewReader(f).ReadBytes('\n') + if err != nil && len(raw) == 0 { + return rollout{}, err + } + var l struct { + Type string `json:"type"` + Payload struct { + ID string `json:"id"` + SessionID string `json:"session_id"` + ForkedFromID string `json:"forked_from_id"` + } `json:"payload"` + } + if json.Unmarshal(raw, &l) != nil || l.Type != "session_meta" || l.Payload.ID == "" { + return rollout{}, errNoMeta + } + // Codex sends session_id as the Session-Id header; when it is absent it reads it as id. + return rollout{thread: l.Payload.ID, session: cmp.Or(l.Payload.SessionID, l.Payload.ID), forkedFrom: l.Payload.ForkedFromID}, nil +} + +// newestAt reads each rollout of a session fast and gives a time that is not before the At of +// any event that the parse makes: the newest token record that closes an open turn, or the +// newest model output. ok is false when a file cannot be read, so that the parse reports it. +// shortcut: it trusts that the lines of a rollout are in time order, as Codex writes them. +func newestAt(files []rollout) (newest time.Time, ok bool) { + for _, f := range files { + t, err := newestInFile(f.path) + if err != nil { + return time.Time{}, false + } + if t.After(newest) { + newest = t + } + } + return newest, true +} + +func newestInFile(path string) (time.Time, error) { + f, err := openRollout(path) + if err != nil { + return time.Time{}, err + } + defer f.Close() + var newest time.Time + open := false // a model output came after the last close; see parser.file + r := bufio.NewReader(f) + for { + raw, rerr := r.ReadBytes('\n') + var l line + var it struct { + Type string `json:"type"` + Role string `json:"role"` + Info json.RawMessage `json:"info"` + } + if json.Unmarshal(raw, &l) == nil && json.Unmarshal(l.Payload, &it) == nil { + switch { + case l.Type == "response_item" && (outputTypes[it.Type] || (it.Type == "message" && it.Role == "assistant")): + open, newest = true, maxTime(newest, l.Timestamp) + case l.Type == "compacted", + // The parse skips an item that it refuses, and the turn stays open. + l.Type == "response_item" && open && !toolOutputTypes[it.Type] && validItem(l.Payload): + open = false + case open && (l.Type == "token_usage_record" || + (l.Type == "event_msg" && it.Type == "token_count" && len(it.Info) > 0 && string(it.Info) != "null")): + open, newest = false, maxTime(newest, l.Timestamp) + } + } + if rerr != nil { + if errors.Is(rerr, io.EOF) { + return newest, nil + } + return time.Time{}, rerr + } + } +} + +func maxTime(a, b time.Time) time.Time { + if b.After(a) { + return b + } + return a +} + +// group puts the rollouts by session id. Of two rollouts with one thread id the newer wins: +// a reverted thread, or a .jsonl and its .jsonl.zst during compression. +func group(files []rollout) map[string][]rollout { + byThread := map[string]rollout{} + for _, f := range files { + if prev, dup := byThread[f.thread]; dup && !f.mod.After(prev.mod) { + continue + } + byThread[f.thread] = f + } + out := map[string][]rollout{} + for _, f := range byThread { + out[f.session] = append(out[f.session], f) + } + for _, rs := range out { + // The root first, so that on a tie of At its events stay before the subagents' events. + slices.SortFunc(rs, func(a, b rollout) int { + return cmp.Or(cmp.Compare(isChild(a), isChild(b)), strings.Compare(a.path, b.path)) + }) + } + return out +} + +func isChild(f rollout) int { + if f.thread == f.session { + return 0 + } + return 1 +} + +// readSession parses the rollouts of one session. threads gives a fork's parent rollout. +func readSession(id string, files []rollout, threads map[string]rollout, home string) importer.Session { + p := parser{home: home, projects: map[string]string{}, parents: map[string][]usage{}} + s := importer.Session{ID: id} + for _, f := range files { + subagent := "" + if f.thread != id { + subagent = f.thread + } + r, err := p.file(f.path, f.thread, subagent, p.copied(f, threads), false) + if err != nil { + if subagent == "" { + slog.Warn("importer: cannot read a Codex rollout", "path", f.path, "error", err) + return importer.Session{ID: id, Unreadable: true} + } + s.Skipped++ + continue + } + s.Events = append(s.Events, r.events...) + s.Skipped += r.skipped + s.SizeHint += f.size + } + // Stable: on a tie the root stays first, and a request stays before its response. + slices.SortStableFunc(s.Events, func(a, b model.SessionEvent) int { return a.At.Compare(b.At) }) + for _, e := range s.Events { + if e.At.After(s.Updated) { + s.Updated = e.At + } + } + return s +} + +// copied gives the usages of the turns of f's parent, which a fork's rollout starts with a +// copy of. It gives none when f is not a fork or its parent rollout cannot be read. +func (p *parser) copied(f rollout, threads map[string]rollout) []usage { + parent, ok := threads[f.forkedFrom] + if f.forkedFrom == "" || !ok { + return nil + } + if u, done := p.parents[parent.path]; done { + return u + } + r, err := p.file(parent.path, parent.thread, "", nil, true) + if err != nil { + r.usages = nil + } + p.parents[parent.path] = r.usages + return r.usages +} diff --git a/core/session/importer/codex/codex_test.go b/core/session/importer/codex/codex_test.go new file mode 100644 index 000000000..fd7766401 --- /dev/null +++ b/core/session/importer/codex/codex_test.go @@ -0,0 +1,359 @@ +package codex + +import ( + "bufio" + "bytes" + "encoding/json" + "errors" + "io" + "io/fs" + "os" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "github.com/klauspost/compress/zstd" + + "github.com/rossoctl/cortex/core/model" + "github.com/rossoctl/cortex/core/project" + "github.com/rossoctl/cortex/core/session/importer" +) + +const ( + plainID = "11111111-1111-4111-8111-111111111111" + toolsID = "22222222-2222-4222-8222-222222222222" + subID = "33333333-3333-4333-8333-333333333333" + + plainFile = "sessions/2026/11/02/rollout-2026-11-02T10-00-00-" + plainID + ".jsonl" + toolsFile = "sessions/2026/11/03/rollout-2026-11-03T09-00-00-" + toolsID + ".jsonl" +) + +// fixtures copies testdata to a temporary Codex home. Git does not keep mtimes, so it sets +// the mtime of each file to the timestamp of its last JSON line. +func fixtures(t *testing.T) string { + t.Helper() + dir := t.TempDir() + if err := os.CopyFS(dir, os.DirFS("testdata")); err != nil { + t.Fatal(err) + } + err := filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error { + if err != nil || d.IsDir() { + return err + } + at := lastTimestamp(t, path) + return os.Chtimes(path, at, at) + }) + if err != nil { + t.Fatal(err) + } + return dir +} + +func lastTimestamp(t *testing.T, path string) time.Time { + t.Helper() + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + var last time.Time + sc := bufio.NewScanner(bytes.NewReader(data)) + for sc.Scan() { + var l struct { + Timestamp time.Time `json:"timestamp"` + } + if json.Unmarshal(sc.Bytes(), &l) == nil && !l.Timestamp.IsZero() { + last = l.Timestamp + } + } + return last +} + +func readAll(t *testing.T, src importer.Source, since time.Time) []importer.Session { + t.Helper() + var out []importer.Session + done, total := -1, -1 + progress := func(d, n int) { done, total = d, n } + for s, err := range src.Sessions(since, func(string, time.Time) bool { return false }, progress) { + if err != nil { + t.Fatal(err) + } + out = append(out, s) + } + if done != total || total < len(out) { + t.Fatalf("last progress = %d of %d, want all of at least %d", done, total, len(out)) + } + return out +} + +func ids(ss []importer.Session) []string { + var out []string + for _, s := range ss { + out = append(out, s.ID) + } + return out +} + +func sessionByID(t *testing.T, dir, id string) importer.Session { + t.Helper() + for _, s := range readAll(t, New(dir), time.Time{}) { + if s.ID == id { + return s + } + } + t.Fatalf("no session %s", id) + return importer.Session{} +} + +func phase(s importer.Session, p model.SessionPhase, agent string) []model.SessionEvent { + var out []model.SessionEvent + for _, e := range s.Events { + if e.Phase == p && e.Subagent == agent { + out = append(out, e) + } + } + return out +} + +func label(t *testing.T, cwd string) string { + t.Helper() + home, _ := os.UserHomeDir() + return project.Label(project.Root(cwd, home), home) +} + +// failOpens makes openRollout fail when fail gives true for the path and its open count. +func failOpens(t *testing.T, fail func(path string, n int) bool) { + t.Helper() + orig := openRollout + counts := map[string]int{} + openRollout = func(path string) (io.ReadCloser, error) { + counts[filepath.Base(path)]++ + if fail(path, counts[filepath.Base(path)]) { + return nil, errors.New("injected open failure") + } + return orig(path) + } + t.Cleanup(func() { openRollout = orig }) +} + +func TestSource_AgentAndHost(t *testing.T) { + src := New(t.TempDir()) + if src.Agent() != "codex" || src.PricingHost() != "api.openai.com" { + t.Fatalf("Agent %q, PricingHost %q", src.Agent(), src.PricingHost()) + } +} + +func TestSource_NoSessionsDirYieldsNothing(t *testing.T) { + if got := readAll(t, New(t.TempDir()), time.Time{}); len(got) != 0 { + t.Fatalf("got %d sessions, want 0", len(got)) + } +} + +func TestSource_HonoursCodexHome(t *testing.T) { + t.Setenv("CODEX_HOME", fixtures(t)) + if got := ids(readAll(t, New(""), time.Time{})); !slices.Equal(got, []string{toolsID, plainID}) { + t.Fatalf("ids = %v", got) + } +} + +func TestSource_PlainSession(t *testing.T) { + s := sessionByID(t, fixtures(t), plainID) + if len(s.Events) != 2 || s.Events[0].RequestID != plainID+":1" || s.Events[1].RequestID != plainID+":1" { + t.Fatalf("events = %+v", s.Events) + } + if s.Skipped != 1 { + t.Errorf("Skipped = %d, want 1", s.Skipped) + } + req, resp := s.Events[0], s.Events[1] + if req.Phase != model.SessionRequest || resp.Phase != model.SessionResponse { + t.Fatalf("phases %v %v", req.Phase, resp.Phase) + } + if req.Inference.Model != "gpt-5-codex" { + t.Errorf("Model = %q", req.Inference.Model) + } + var roles []string + for _, m := range req.Inference.Messages { + roles = append(roles, m.Role) + } + if !slices.Equal(roles, []string{"developer", "user"}) { + t.Errorf("roles = %v", roles) + } + in := resp.Inference + if in.Completion != "hi" || in.InputTokens != 200 || in.CacheReadTokens != 1000 || + in.CompletionTokens != 50 || in.ReasoningTokens != 20 || in.TotalTokens != 1250 { + t.Errorf("response = %+v", in) + } + if in.ResponseThinking == nil || in.ResponseThinking.Blocks != 1 { + t.Errorf("ResponseThinking = %+v", in.ResponseThinking) + } + for _, e := range s.Events { + if e.Client == nil || e.Client.Name != "codex" || e.Client.Version != "0.169.0" { + t.Errorf("Client = %+v", e.Client) + } + if e.Project != label(t, "/tmp/demo") { + t.Errorf("Project = %q", e.Project) + } + if e.Inference.AgentRole != model.AgentRoleMain { + t.Errorf("AgentRole = %q", e.Inference.AgentRole) + } + if e.Direction != model.Outbound { + t.Errorf("Direction = %v", e.Direction) + } + } + if !req.At.Equal(time.Date(2026, 11, 2, 10, 0, 3, 0, time.UTC)) || !resp.At.Equal(time.Date(2026, 11, 2, 10, 0, 8, 0, time.UTC)) { + t.Errorf("At = %v, %v", req.At, resp.At) + } + if !s.Updated.Equal(resp.At) { + t.Errorf("Updated = %v", s.Updated) + } +} + +func TestSource_DuplicateTokenCountIsIgnored(t *testing.T) { + s := sessionByID(t, fixtures(t), plainID) + if n := len(phase(s, model.SessionResponse, "")); n != 1 { + t.Fatalf("%d responses, want 1", n) + } +} + +func TestSource_ToolCallsAndResults(t *testing.T) { + s := sessionByID(t, fixtures(t), toolsID) + reqs, resps := phase(s, model.SessionRequest, ""), phase(s, model.SessionResponse, "") + if len(reqs) != 2 || len(resps) != 2 { + t.Fatalf("%d requests, %d responses", len(reqs), len(resps)) + } + calls := resps[0].Inference.ToolCalls + if len(calls) != 2 || calls[0].ID != "c1" || calls[0].Name != "shell" || calls[0].Arguments != `{"command":["ls"]}` || + calls[1].ID != "c2" || calls[1].Name != "apply_patch" { + t.Errorf("ToolCalls = %+v", calls) + } + var tools []string + for _, tool := range reqs[0].Inference.Tools { + tools = append(tools, tool.Name) + } + if !slices.Equal(tools, []string{"shell"}) { + t.Errorf("Tools = %v", tools) + } + var results []string + for _, r := range reqs[1].Inference.ToolResults { + results = append(results, r.ToolUseID) + } + if !slices.Equal(results, []string{"c1", "c2"}) { + t.Errorf("ToolResults = %v", results) + } + last := resps[1].Inference + if last.Completion != "listed" || last.TotalTokens != 0 || last.InputTokens != 0 || last.OutputTokens != 0 { + t.Errorf("second response = %+v", last) + } + if resps[0].RequestID != toolsID+":1" || resps[1].RequestID != toolsID+":2" { + t.Errorf("RequestIDs %q %q", resps[0].RequestID, resps[1].RequestID) + } +} + +func TestSource_SubagentInRootSession(t *testing.T) { + all := readAll(t, New(fixtures(t)), time.Time{}) + if slices.Contains(ids(all), subID) { + t.Fatalf("subagent is its own session: %v", ids(all)) + } + s := sessionByID(t, fixtures(t), toolsID) + sub := append(phase(s, model.SessionRequest, subID), phase(s, model.SessionResponse, subID)...) + if len(sub) != 2 { + t.Fatalf("%d subagent events, want 2", len(sub)) + } + for _, e := range sub { + if e.Inference.AgentRole != model.AgentRoleSubagent || e.Project != label(t, "/tmp/tools") { + t.Errorf("subagent event AgentRole %q, Project %q", e.Inference.AgentRole, e.Project) + } + } + if !slices.IsSortedFunc(s.Events, func(a, b model.SessionEvent) int { return a.At.Compare(b.At) }) { + t.Error("events are not in time order") + } +} + +func TestSource_NewestFirstSinceAndSkip(t *testing.T) { + dir := fixtures(t) + if got := ids(readAll(t, New(dir), time.Time{})); !slices.Equal(got, []string{toolsID, plainID}) { + t.Fatalf("ids = %v", got) + } + since := lastTimestamp(t, filepath.Join(dir, plainFile)).Add(time.Second) + if got := ids(readAll(t, New(dir), since)); !slices.Equal(got, []string{toolsID}) { + t.Fatalf("since: ids = %v", got) + } + full := sessionByID(t, dir, toolsID) + var got time.Time + var out []string + for s, err := range New(dir).Sessions(time.Time{}, func(id string, at time.Time) bool { + if id == toolsID { + got = at + return true + } + return false + }, func(int, int) {}) { + if err != nil { + t.Fatal(err) + } + out = append(out, s.ID) + } + if !slices.Equal(out, []string{plainID}) { + t.Fatalf("skip: ids = %v", out) + } + if got.Before(full.Updated) { + t.Errorf("skip time %v is before Updated %v", got, full.Updated) + } +} + +func TestSource_CompressedRollout(t *testing.T) { + dir := fixtures(t) + want := sessionByID(t, dir, plainID) + path := filepath.Join(dir, plainFile) + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + f, err := os.Create(path + ".zst") + if err != nil { + t.Fatal(err) + } + w, err := zstd.NewWriter(f) + if err != nil { + t.Fatal(err) + } + if _, err := w.Write(data); err != nil { + t.Fatal(err) + } + if err := w.Close(); err != nil { + t.Fatal(err) + } + if err := f.Close(); err != nil { + t.Fatal(err) + } + if err := os.Remove(path); err != nil { + t.Fatal(err) + } + got := sessionByID(t, dir, plainID) + if len(got.Events) != len(want.Events) || got.Events[1].Inference.Completion != want.Events[1].Inference.Completion { + t.Fatalf("compressed read = %+v, want %+v", got.Events, want.Events) + } +} + +func TestSource_UnreadableRootIsReported(t *testing.T) { + dir := fixtures(t) + // The opens are the listing, the fast scan and the parse. Only the parse fails. + failOpens(t, func(path string, n int) bool { return strings.Contains(path, toolsID) && n == 3 }) + s := sessionByID(t, dir, toolsID) + if !s.Unreadable { + t.Fatalf("session = %+v, want Unreadable", s) + } +} + +func TestSource_UnlistableFileIsLeftOut(t *testing.T) { + dir := fixtures(t) + failOpens(t, func(path string, _ int) bool { return strings.Contains(path, plainID) }) + all := readAll(t, New(dir), time.Time{}) + if got := ids(all); !slices.Equal(got, []string{"", toolsID}) || !all[0].Unreadable { + t.Fatalf("ids = %v, want an unreadable entry then %s", got, toolsID) + } + if len(all[1].Events) != 6 { + t.Errorf("tools session has %d events, want 6", len(all[1].Events)) + } +} diff --git a/core/session/importer/codex/decisions_test.go b/core/session/importer/codex/decisions_test.go new file mode 100644 index 000000000..fa2c52d6b --- /dev/null +++ b/core/session/importer/codex/decisions_test.go @@ -0,0 +1,305 @@ +package codex + +import ( + "fmt" + "os" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "github.com/rossoctl/cortex/core/model" +) + +const ( + meta = `{"timestamp":"2026-11-04T08:00:00Z","type":"session_meta","payload":{"id":"` + plainID + `","cwd":"/tmp/demo","cli_version":"0.169.0"}}` + ctx = `{"timestamp":"2026-11-04T08:00:01Z","type":"turn_context","payload":{"model":"gpt-5-codex"}}` +) + +func user(sec int, text string) string { + return `{"timestamp":"2026-11-04T08:00:` + pad(sec) + `Z","type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"` + text + `"}]}}` +} + +func assistant(sec int, text string) string { + return `{"timestamp":"2026-11-04T08:00:` + pad(sec) + `Z","type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"` + text + `"}]}}` +} + +func pad(sec int) string { return fmt.Sprintf("%02d", sec) } + +// writeRollout writes lines as a rollout file under home/sessions and sets its mtime. +func writeRollout(t *testing.T, home, name string, mod time.Time, lines ...string) string { + t.Helper() + path := filepath.Join(home, "sessions", name) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(strings.Join(lines, "\n")+"\n"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.Chtimes(path, mod, mod); err != nil { + t.Fatal(err) + } + return path +} + +func contents(e model.SessionEvent) []string { + var out []string + for _, m := range e.Inference.Messages { + out = append(out, m.Role+":"+m.Content) + } + return out +} + +// An input item closes an open turn with no usage; compacted closes one with no usage and +// replaces the conversation; token_usage_record closes one with its usage. +func TestSource_TurnBoundaries(t *testing.T) { + home := t.TempDir() + writeRollout(t, home, "rollout-a-"+plainID+".jsonl", time.Date(2026, 11, 4, 8, 1, 0, 0, time.UTC), + meta, ctx, + user(2, "q1"), assistant(3, "a1"), + user(4, "q2"), assistant(5, "a2"), + `{"timestamp":"2026-11-04T08:00:06Z","type":"compacted","payload":{"message":"","replacement_history":[{"type":"message","role":"user","content":[{"type":"input_text","text":"summary"}]}]}}`, + user(7, "q3"), assistant(8, "a3"), + `{"timestamp":"2026-11-04T08:00:09Z","type":"token_usage_record","payload":{"usage":{"input_tokens":300,"cached_input_tokens":100,"output_tokens":7,"reasoning_output_tokens":2,"total_tokens":307}}}`, + ) + s := sessionByID(t, home, plainID) + reqs, resps := phase(s, model.SessionRequest, ""), phase(s, model.SessionResponse, "") + if len(reqs) != 3 || len(resps) != 3 { + t.Fatalf("%d requests, %d responses, want 3 and 3", len(reqs), len(resps)) + } + for i, want := range []string{"a1", "a2", "a3"} { + if resps[i].Inference.Completion != want { + t.Errorf("response %d Completion = %q, want %q", i, resps[i].Inference.Completion, want) + } + } + // (c) q2 closes turn 1 with no usage, at its last output line. + if r := resps[0]; r.Inference.TotalTokens != 0 || !r.At.Equal(time.Date(2026, 11, 4, 8, 0, 3, 0, time.UTC)) { + t.Errorf("turn 1 = TotalTokens %d at %v", r.Inference.TotalTokens, r.At) + } + if got := contents(reqs[1]); !slices.Equal(got, []string{"user:q1", "assistant:a1", "user:q2"}) { + t.Errorf("turn 2 input = %v", got) + } + // (a) compacted closes turn 2 with no usage and replaces the conversation. + if resps[1].Inference.TotalTokens != 0 { + t.Errorf("turn 2 TotalTokens = %d, want 0", resps[1].Inference.TotalTokens) + } + if got := contents(reqs[2]); !slices.Equal(got, []string{"user:summary", "user:q3"}) { + t.Errorf("turn 3 input = %v, want the replacement history and q3", got) + } + // (b) token_usage_record closes turn 3 with its usage. + in := resps[2].Inference + if in.TotalTokens != 307 || in.InputTokens != 200 || in.CacheReadTokens != 100 || in.CompletionTokens != 7 || in.ReasoningTokens != 2 { + t.Errorf("turn 3 usage = %+v", in) + } + if !resps[2].At.Equal(time.Date(2026, 11, 4, 8, 0, 9, 0, time.UTC)) { + t.Errorf("turn 3 At = %v", resps[2].At) + } +} + +// Codex 0.142.3 writes a turn's token_count after its tool results, and no token_usage_record. +// The tool results do not close the turn, so the turn keeps its usage. +func TestSource_TokenCountAfterToolResults(t *testing.T) { + home := t.TempDir() + tokenCount := func(sec, total int) string { + return `{"timestamp":"2026-11-04T08:00:` + pad(sec) + `Z","type":"event_msg","payload":{"type":"token_count","info":{"last_token_usage":{"input_tokens":` + + fmt.Sprint(total-1) + `,"output_tokens":1,"total_tokens":` + fmt.Sprint(total) + `}}}}` + } + writeRollout(t, home, "rollout-a-"+plainID+".jsonl", time.Date(2026, 11, 4, 8, 1, 0, 0, time.UTC), + meta, ctx, + user(2, "q"), + `{"timestamp":"2026-11-04T08:00:03Z","type":"response_item","payload":{"type":"function_call","name":"shell","arguments":"{}","call_id":"c1"}}`, + `{"timestamp":"2026-11-04T08:00:04Z","type":"response_item","payload":{"type":"function_call_output","call_id":"c1","output":"ok"}}`, + tokenCount(5, 100), + assistant(6, "done"), + tokenCount(7, 200), + ) + s := sessionByID(t, home, plainID) + reqs, resps := phase(s, model.SessionRequest, ""), phase(s, model.SessionResponse, "") + if len(reqs) != 2 || len(resps) != 2 { + t.Fatalf("%d requests, %d responses, want 2 and 2", len(reqs), len(resps)) + } + if n := len(resps[0].Inference.ToolCalls); n != 1 || resps[0].Inference.TotalTokens != 100 { + t.Errorf("turn 1 = %d tool calls, TotalTokens %d, want 1 and 100", n, resps[0].Inference.TotalTokens) + } + if r := reqs[1].Inference.ToolResults; len(r) != 1 || r[0].ToolUseID != "c1" { + t.Errorf("turn 2 ToolResults = %+v, want c1", r) + } + if !reqs[1].At.Equal(time.Date(2026, 11, 4, 8, 0, 5, 0, time.UTC)) { + t.Errorf("turn 2 request At = %v, want the end of turn 1", reqs[1].At) + } + if resps[1].Inference.TotalTokens != 200 { + t.Errorf("turn 2 TotalTokens = %d, want 200", resps[1].Inference.TotalTokens) + } +} + +// An output item that the response decoder refuses costs that item only: the turn keeps its +// usage and its other outputs, and the next turn still has the item in its input. +func TestSource_OffSpecOutputItemKeepsTheTurn(t *testing.T) { + tokenCount := func(sec, total int) string { + return `{"timestamp":"2026-11-04T08:00:` + pad(sec) + `Z","type":"event_msg","payload":{"type":"token_count","info":{"last_token_usage":{"input_tokens":` + + fmt.Sprint(total-1) + `,"output_tokens":1,"total_tokens":` + fmt.Sprint(total) + `}}}}` + } + for name, bad := range map[string]string{ + "tool_search_call object arguments": `{"type":"tool_search_call","call_id":"s1","execution":"client","arguments":{"query":"calendar create","limit":1}}`, + "custom_tool_call object input": `{"type":"custom_tool_call","call_id":"s1","name":"apply_patch","input":{"a":1}}`, + "reasoning numeric id": `{"type":"reasoning","id":7,"summary":[]}`, + } { + t.Run(name, func(t *testing.T) { + home := t.TempDir() + writeRollout(t, home, "rollout-a-"+plainID+".jsonl", time.Date(2026, 11, 4, 8, 1, 0, 0, time.UTC), + meta, ctx, + user(2, "q"), + `{"timestamp":"2026-11-04T08:00:03Z","type":"response_item","payload":`+bad+`}`, + `{"timestamp":"2026-11-04T08:00:04Z","type":"response_item","payload":{"type":"function_call","name":"shell","arguments":"{}","call_id":"c1"}}`, + `{"timestamp":"2026-11-04T08:00:05Z","type":"response_item","payload":{"type":"function_call_output","call_id":"c1","output":"ok"}}`, + tokenCount(6, 100), + assistant(7, "done"), + tokenCount(8, 200), + ) + s := sessionByID(t, home, plainID) + reqs, resps := phase(s, model.SessionRequest, ""), phase(s, model.SessionResponse, "") + if len(reqs) != 2 || len(resps) != 2 { + t.Fatalf("%d requests, %d responses, want 2 and 2", len(reqs), len(resps)) + } + if c := resps[0].Inference.ToolCalls; len(c) != 1 || c[0].ID != "c1" || resps[0].Inference.TotalTokens != 100 { + t.Errorf("turn 1 = tool calls %+v, TotalTokens %d; want c1 and 100", c, resps[0].Inference.TotalTokens) + } + if resps[1].Inference.TotalTokens != 200 || resps[1].Inference.Completion != "done" { + t.Errorf("turn 2 = TotalTokens %d, Completion %q", resps[1].Inference.TotalTokens, resps[1].Inference.Completion) + } + }) + } +} + +// A provider that sends no usage writes token_count with info null. An output after held tool +// results is the next model call, so it closes the open turn. +func TestSource_OutputAfterToolResultsIsANewCall(t *testing.T) { + home := t.TempDir() + call := func(sec int, id string) string { + return `{"timestamp":"2026-11-04T08:00:` + pad(sec) + `Z","type":"response_item","payload":{"type":"function_call","name":"shell","arguments":"{}","call_id":"` + id + `"}}` + } + result := func(sec int, id string) string { + return `{"timestamp":"2026-11-04T08:00:` + pad(sec) + `Z","type":"response_item","payload":{"type":"function_call_output","call_id":"` + id + `","output":"ok"}}` + } + noInfo := func(sec int) string { + return `{"timestamp":"2026-11-04T08:00:` + pad(sec) + `Z","type":"event_msg","payload":{"type":"token_count","info":null}}` + } + writeRollout(t, home, "rollout-a-"+plainID+".jsonl", time.Date(2026, 11, 4, 8, 1, 0, 0, time.UTC), + meta, ctx, + user(2, "q"), + call(3, "c1"), result(4, "c1"), noInfo(5), + call(6, "c2"), result(7, "c2"), noInfo(8), + assistant(9, "done"), + ) + s := sessionByID(t, home, plainID) + reqs, resps := phase(s, model.SessionRequest, ""), phase(s, model.SessionResponse, "") + if len(reqs) != 3 || len(resps) != 3 { + t.Fatalf("%d requests, %d responses, want 3 and 3", len(reqs), len(resps)) + } + for i, want := range []string{"c1", "c2"} { + if c := resps[i].Inference.ToolCalls; len(c) != 1 || c[0].ID != want { + t.Errorf("turn %d ToolCalls = %+v, want %s only", i+1, c, want) + } + } + if r := reqs[2].Inference.ToolResults; len(r) != 2 || r[1].ToolUseID != "c2" { + t.Errorf("turn 3 ToolResults = %+v, want c1 and c2 in order", r) + } +} + +// Of two rollouts with one thread id, the newer mtime wins, whatever the path order. +func TestSource_NewerRolloutOfAThreadWins(t *testing.T) { + home := t.TempDir() + old, newer := time.Date(2026, 11, 4, 8, 1, 0, 0, time.UTC), time.Date(2026, 11, 4, 9, 0, 0, 0, time.UTC) + // The newer file sorts first, so a "last listed wins" rule would keep the older one. + writeRollout(t, home, "a/rollout-a-"+plainID+".jsonl", newer, meta, ctx, user(2, "q"), assistant(3, "new")) + writeRollout(t, home, "b/rollout-b-"+plainID+".jsonl", old, meta, ctx, user(2, "q"), assistant(3, "old")) + all := readAll(t, New(home), time.Time{}) + if len(all) != 1 { + t.Fatalf("got %d sessions, want 1", len(all)) + } + if r := phase(all[0], model.SessionResponse, ""); len(r) != 1 || r[0].Inference.Completion != "new" { + t.Fatalf("responses = %+v, want one from the newer file", r) + } +} + +// A child rollout that cannot be read counts as one skipped line; the session stays readable. +func TestSource_UnreadableChildIsSkipped(t *testing.T) { + dir := fixtures(t) + base := sessionByID(t, dir, toolsID) + // The opens are the listing, the fast scan and the parse. Only the parse fails. + failOpens(t, func(path string, n int) bool { return strings.Contains(path, subID) && n == 3 }) + s := sessionByID(t, dir, toolsID) + if s.Unreadable || s.Skipped != base.Skipped+1 { + t.Fatalf("Unreadable %v, Skipped %d, want false and %d", s.Unreadable, s.Skipped, base.Skipped+1) + } + if n := len(phase(s, model.SessionRequest, subID)); n != 0 || len(s.Events) != len(base.Events)-2 { + t.Errorf("%d subagent requests, %d events, want 0 and %d", n, len(s.Events), len(base.Events)-2) + } +} + +// A session whose root rollout is gone still yields its subagents' events. +func TestSource_ChildOnlySessionIsYielded(t *testing.T) { + dir := fixtures(t) + if err := os.Remove(filepath.Join(dir, toolsFile)); err != nil { + t.Fatal(err) + } + s := sessionByID(t, dir, toolsID) + if s.Unreadable || len(s.Events) != 2 || len(phase(s, model.SessionResponse, subID)) != 1 { + t.Fatalf("session = %+v, want the 2 subagent events", s) + } +} + +// An item that the live Responses decoder refuses costs that item, not the later turns. +func TestSource_OffSpecItemIsSkipped(t *testing.T) { + item := func(sec int, payload string) string { + return `{"timestamp":"2026-11-04T08:00:` + pad(sec) + `Z","type":"response_item","payload":` + payload + `}` + } + compacted := func(sec int, history string) string { + return `{"timestamp":"2026-11-04T08:00:` + pad(sec) + `Z","type":"compacted","payload":{"replacement_history":[` + history + `]}}` + } + for name, bad := range map[string]string{ + "string payload": item(3, `"x"`), + "numeric call_id": item(3, `{"type":"function_call_output","call_id":7,"output":"x"}`), + "string tools": item(3, `{"type":"message","role":"user","tools":"x","content":"x"}`), + "object role": item(3, `{"type":"message","role":{"a":1},"content":"x"}`), + "compacted item": compacted(3, `{"type":"message","role":"user","content":"kept"},{"type":"message","role":{"a":1},"content":"x"}`), + } { + t.Run(name, func(t *testing.T) { + home := t.TempDir() + writeRollout(t, home, "rollout-a-"+plainID+".jsonl", time.Date(2026, 11, 4, 8, 1, 0, 0, time.UTC), + meta, ctx, user(2, "q1"), bad, assistant(4, "a1"), user(5, "q2"), assistant(6, "a2"), user(7, "q3"), assistant(8, "a3")) + s := sessionByID(t, home, plainID) + if r := phase(s, model.SessionResponse, ""); len(r) != 3 || r[2].Inference.Completion != "a3" { + t.Fatalf("got %d responses, want 3 ending in a3", len(r)) + } + if s.Skipped != 1 { + t.Errorf("Skipped = %d, want 1", s.Skipped) + } + }) + } +} + +// A rollout that cannot be opened is in no session, but the report counts it. A file whose +// first line is not session_meta, and a file older than since, are not counted. +func TestSource_UnopenableFileIsCountedUnreadable(t *testing.T) { + home := t.TempDir() + mod := time.Date(2026, 11, 4, 8, 1, 0, 0, time.UTC) + writeRollout(t, home, "rollout-a-"+plainID+".jsonl", mod, meta, ctx, user(2, "q"), assistant(3, "a")) + writeRollout(t, home, "rollout-b-broken.jsonl", mod, ctx) + writeRollout(t, home, "rollout-c-broken.jsonl", mod.Add(-time.Hour), meta) + writeRollout(t, home, "rollout-d-broken.jsonl", mod, meta) + failOpens(t, func(path string, _ int) bool { + return strings.Contains(path, "-c-broken") || strings.Contains(path, "-d-broken") + }) + all := readAll(t, New(home), mod.Add(-time.Minute)) + unreadable := 0 + for _, s := range all { + if s.Unreadable { + unreadable++ + } + } + if unreadable != 1 || len(all) != 2 { + t.Fatalf("got %d sessions, %d unreadable; want 2 and 1", len(all), unreadable) + } +} diff --git a/core/session/importer/codex/fork_test.go b/core/session/importer/codex/fork_test.go new file mode 100644 index 000000000..825dae981 --- /dev/null +++ b/core/session/importer/codex/fork_test.go @@ -0,0 +1,144 @@ +package codex + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/rossoctl/cortex/core/model" +) + +const ( + parentID = "44444444-4444-4444-8444-444444444444" + forkID = "55555555-5555-4555-8555-555555555555" +) + +// parentLines is a rollout with a tool-call turn and an answer turn, both with usage. +var parentLines = []string{ + `{"type":"session_meta","payload":{"id":"` + parentID + `","cwd":"/tmp/demo","cli_version":"0.169.0"}}`, + `{"type":"turn_context","payload":{"cwd":"/tmp/demo","model":"gpt-5-codex"}}`, + `{"type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"list"}]}}`, + `{"type":"response_item","payload":{"type":"reasoning","summary":[],"encrypted_content":"x"}}`, + `{"type":"response_item","payload":{"type":"function_call","name":"shell","arguments":"{}","call_id":"c1"}}`, + `{"type":"event_msg","payload":{"type":"token_count","info":{"last_token_usage":{"input_tokens":500,"output_tokens":30,"total_tokens":530}}}}`, + `{"type":"response_item","payload":{"type":"function_call_output","call_id":"c1","output":"a.txt"}}`, + `{"type":"response_item","payload":{"type":"message","role":"assistant","phase":"final_answer","content":[{"type":"output_text","text":"listed"}]}}`, + `{"type":"event_msg","payload":{"type":"token_count","info":{"last_token_usage":{"input_tokens":800,"cached_input_tokens":500,"output_tokens":10,"total_tokens":810}}}}`, +} + +// kept is Codex's filter for a fork without its tool calls (keep_forked_rollout_item). +func kept(l string) bool { + var v struct { + Type string `json:"type"` + Payload struct { + Type, Role, Phase string + } `json:"payload"` + } + _ = json.Unmarshal([]byte(l), &v) + if v.Type != "response_item" { + return true + } + p := v.Payload + return p.Type == "message" && (p.Role != "assistant" || p.Phase == "final_answer") +} + +// stampRollout writes lines as the rollout of thread under dir/sub, each stamped at at. +func stampRollout(t *testing.T, dir, sub, thread string, at time.Time, lines []string) { + t.Helper() + var b strings.Builder + for _, l := range lines { + at = at.Add(time.Second) + b.WriteString(`{"timestamp":"` + at.Format(time.RFC3339) + `",` + l[1:] + "\n") + } + path := filepath.Join(dir, sub, "2026/11/04/rollout-2026-11-04T08-00-00-"+thread+".jsonl") + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(b.String()), 0o644); err != nil { + t.Fatal(err) + } + if err := os.Chtimes(path, at, at); err != nil { + t.Fatal(err) + } +} + +// writeFork writes a fork of parentLines the way Codex does: its session_meta, then the copy +// of the parent's lines (session_meta included) that copy picks, then one turn of its own. +func writeFork(t *testing.T, dir, session string, copy func([]string) []string) { + t.Helper() + lines := []string{`{"type":"session_meta","payload":{"id":"` + forkID + `","session_id":"` + session + + `","forked_from_id":"` + parentID + `","cwd":"/tmp/demo","cli_version":"0.169.0"}}`} + lines = append(lines, copy(parentLines)...) + lines = append(lines, + `{"type":"event_msg","payload":{"type":"thread_settings_applied"}}`, + `{"type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"again"}]}}`, + `{"type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"forked"}]}}`, + `{"type":"event_msg","payload":{"type":"token_count","info":{"last_token_usage":{"input_tokens":900,"output_tokens":7,"total_tokens":907}}}}`) + stampRollout(t, dir, "sessions", forkID, time.Date(2026, 11, 4, 9, 0, 0, 0, time.UTC), lines) +} + +// A fork's copy of its parent's turns is conversation, not turns: the fork has only its own +// turn, and the parent keeps its two. +func TestSource_ForkDoesNotRepeatParentTurns(t *testing.T) { + all := func(l []string) []string { return l } + filtered := func(l []string) []string { + var out []string + for _, s := range l { + if kept(s) { + out = append(out, s) + } + } + return out + } + // The parent was in its tool call when it forked: no token_count closes that turn. + midTurn := func(l []string) []string { + return append(append([]string{}, l[:5]...), `{"type":"event_msg","payload":{"type":"turn_aborted"}}`) + } + for _, tc := range []struct { + name, session, subagent, parentDir string + copy func([]string) []string + }{ + {"thread fork", forkID, "", "sessions", all}, + {"forked subagent", parentID, forkID, "sessions", all}, + {"fork without tool calls", forkID, "", "sessions", filtered}, + {"fork in the middle of a turn", parentID, forkID, "sessions", midTurn}, + {"archived parent", forkID, "", "archived_sessions", all}, + } { + t.Run(tc.name, func(t *testing.T) { + dir := t.TempDir() + stampRollout(t, dir, tc.parentDir, parentID, time.Date(2026, 11, 4, 8, 0, 0, 0, time.UTC), parentLines) + writeFork(t, dir, tc.session, tc.copy) + sameNewest(t, dir) + fork := sessionByID(t, dir, tc.session) + resps := phase(fork, model.SessionResponse, tc.subagent) + if len(resps) != 1 || resps[0].Inference.Completion != "forked" { + var got []string + for _, r := range resps { + got = append(got, r.RequestID+"="+r.Inference.Completion) + } + t.Fatalf("fork responses = %v, want only the new turn", got) + } + reqs := phase(fork, model.SessionRequest, tc.subagent) + if msgs := reqs[0].Inference.Messages; len(msgs) == 0 || msgs[0].Role != "user" { + t.Errorf("fork request messages = %+v, want the copied conversation first", msgs) + } + if tc.parentDir == "sessions" { + if n := len(phase(sessionByID(t, dir, parentID), model.SessionResponse, "")); n != 2 { + t.Errorf("parent has %d responses, want 2", n) + } + } + }) + } +} + +// With no parent rollout to compare, the fork's turns are the only copy, so they stay. +func TestSource_ForkWithoutParentKeepsItsTurns(t *testing.T) { + dir := t.TempDir() + writeFork(t, dir, forkID, func(l []string) []string { return l }) + if n := len(phase(sessionByID(t, dir, forkID), model.SessionResponse, "")); n != 3 { + t.Errorf("%d responses, want 3", n) + } +} diff --git a/core/session/importer/codex/newest_test.go b/core/session/importer/codex/newest_test.go new file mode 100644 index 000000000..0953b0f40 --- /dev/null +++ b/core/session/importer/codex/newest_test.go @@ -0,0 +1,100 @@ +package codex + +import ( + "io/fs" + "os" + "path/filepath" + "slices" + "testing" + "time" +) + +// sameNewest checks that the fast scan of each session gives the Updated of its parse. Rule 2 +// can then skip an unchanged session before the parse. +func sameNewest(t *testing.T, dir string) { + t.Helper() + files, _ := list(filepath.Join(dir, "sessions")) + groups := group(files) + for _, s := range readAll(t, New(dir), time.Time{}) { + if at, ok := newestAt(groups[s.ID]); !ok || !at.Equal(s.Updated) { + t.Errorf("session %s: newestAt = %v, %v; want Updated %v", s.ID, at, ok, s.Updated) + } + } +} + +// Codex writes a line after it takes the line's timestamp, so the mtime of a rollout is after +// its newest event. A second import must still skip each unchanged session before the parse. +func TestSource_UnchangedSessionIsNotParsedAgain(t *testing.T) { + dir := fixtures(t) + now := time.Now() + err := filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error { + if err != nil || d.IsDir() { + return err + } + return os.Chtimes(path, now, now) + }) + if err != nil { + t.Fatal(err) + } + sameNewest(t, dir) + archived := map[string]time.Time{} + for _, s := range readAll(t, New(dir), time.Time{}) { + archived[s.ID] = s.Updated + } + parsed := func() []string { + var out []string + for s, err := range New(dir).Sessions(time.Time{}, func(id string, at time.Time) bool { + return !at.After(archived[id]) // Rule 2, as importer.Run applies it + }, func(int, int) {}) { + if err != nil { + t.Fatal(err) + } + out = append(out, s.ID) + } + return out + } + if got := parsed(); len(got) != 0 { + t.Fatalf("parsed again: %v, want none", got) + } + + f, err := os.OpenFile(filepath.Join(dir, plainFile), os.O_APPEND|os.O_WRONLY, 0) + if err != nil { + t.Fatal(err) + } + _, err = f.WriteString(`{"timestamp":"2026-11-02T10:00:20Z","type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"q2"}]}}` + "\n" + + `{"timestamp":"2026-11-02T10:00:21Z","type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"a2"}]}}` + "\n") + if cerr := f.Close(); err == nil { + err = cerr + } + if err != nil { + t.Fatal(err) + } + if got := parsed(); !slices.Equal(got, []string{plainID}) { + t.Fatalf("parsed again after a new turn: %v, want %s", got, plainID) + } +} + +// The scan closes a turn where the parse closes it. +func TestSource_NewestAtFollowsTheParse(t *testing.T) { + tokenCount := func(sec int) string { + return `{"timestamp":"2026-11-04T08:00:` + pad(sec) + `Z","type":"event_msg","payload":{"type":"token_count","info":{"last_token_usage":{"input_tokens":9,"output_tokens":1,"total_tokens":10}}}}` + } + call := `{"timestamp":"2026-11-04T08:00:03Z","type":"response_item","payload":{"type":"function_call","name":"shell","arguments":"{}","call_id":"c1"}}` + result := `{"timestamp":"2026-11-04T08:00:04Z","type":"response_item","payload":{"type":"function_call_output","call_id":"c1","output":"ok"}}` + refused := `{"timestamp":"2026-11-04T08:00:05Z","type":"response_item","payload":{"type":"message","role":"user","tools":"x","content":"x"}}` + for name, lines := range map[string][]string{ + "usage after the tool results": {user(2, "q"), call, result, tokenCount(6)}, + "refused item in an open turn": {user(2, "q"), assistant(3, "a"), refused, tokenCount(6)}, + "usage with no open turn": {user(2, "q"), assistant(3, "a"), tokenCount(4), tokenCount(6)}, + "open turn at the end": {user(2, "q"), call, result}, + "input after the output": {user(2, "q"), assistant(3, "a"), user(6, "q2")}, + "input closes, usage comes late": {user(2, "q"), assistant(3, "a"), user(4, "q2"), tokenCount(6)}, + } { + t.Run(name, func(t *testing.T) { + home := t.TempDir() + writeRollout(t, home, "rollout-a-"+plainID+".jsonl", time.Date(2026, 11, 4, 8, 1, 0, 0, time.UTC), + append([]string{meta, ctx}, lines...)...) + sameNewest(t, home) + }) + } +} diff --git a/core/session/importer/codex/testdata/sessions/2026/11/02/rollout-2026-11-02T10-00-00-11111111-1111-4111-8111-111111111111.jsonl b/core/session/importer/codex/testdata/sessions/2026/11/02/rollout-2026-11-02T10-00-00-11111111-1111-4111-8111-111111111111.jsonl new file mode 100644 index 000000000..aa74453ef --- /dev/null +++ b/core/session/importer/codex/testdata/sessions/2026/11/02/rollout-2026-11-02T10-00-00-11111111-1111-4111-8111-111111111111.jsonl @@ -0,0 +1,11 @@ +{"timestamp":"2026-11-02T10:00:00Z","type":"session_meta","payload":{"id":"11111111-1111-4111-8111-111111111111","timestamp":"2026-11-02T10:00:00Z","cwd":"/tmp/demo","originator":"codex_cli_rs","cli_version":"0.169.0","source":"cli","model_provider":"openai"}} +{"timestamp":"2026-11-02T10:00:01Z","type":"turn_context","payload":{"cwd":"/tmp/demo","model":"gpt-5-codex","turn_id":"t1","effort":"medium"}} +{"timestamp":"2026-11-02T10:00:02Z","type":"response_item","payload":{"type":"message","role":"developer","content":[{"type":"input_text","text":"You are Codex."}]}} +{"timestamp":"2026-11-02T10:00:03Z","type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"hello codex"}]}} +{"timestamp":"2026-11-02T10:00:04Z","type":"event_msg","payload":{"type":"user_message","message":"hello codex"}} +{"timestamp":"2026-11-02T10:00:05Z","type":"event_msg","payload":{"type":"token_count","info":null,"rate_limits":null}} +{"timestamp":"2026-11-02T10:00:06Z","type":"response_item","payload":{"type":"reasoning","summary":[{"type":"summary_text","text":"thinking"}],"content":null,"encrypted_content":"abc"}} +{"timestamp":"2026-11-02T10:00:07Z","type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"hi"}]}} +{"timestamp":"2026-11-02T10:00:08Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":1200,"cached_input_tokens":1000,"output_tokens":50,"reasoning_output_tokens":20,"total_tokens":1250},"last_token_usage":{"input_tokens":1200,"cached_input_tokens":1000,"output_tokens":50,"reasoning_output_tokens":20,"total_tokens":1250},"model_context_window":272000},"rate_limits":null}} +{"timestamp":"2026-11-02T10:00:09Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":1200,"cached_input_tokens":1000,"output_tokens":50,"reasoning_output_tokens":20,"total_tokens":1250},"last_token_usage":{"input_tokens":1200,"cached_input_tokens":1000,"output_tokens":50,"reasoning_output_tokens":20,"total_tokens":1250},"model_context_window":272000},"rate_limits":null}} +not json diff --git a/core/session/importer/codex/testdata/sessions/2026/11/03/rollout-2026-11-03T09-00-00-22222222-2222-4222-8222-222222222222.jsonl b/core/session/importer/codex/testdata/sessions/2026/11/03/rollout-2026-11-03T09-00-00-22222222-2222-4222-8222-222222222222.jsonl new file mode 100644 index 000000000..4fc066b6c --- /dev/null +++ b/core/session/importer/codex/testdata/sessions/2026/11/03/rollout-2026-11-03T09-00-00-22222222-2222-4222-8222-222222222222.jsonl @@ -0,0 +1,10 @@ +{"timestamp":"2026-11-03T09:00:00Z","type":"session_meta","payload":{"id":"22222222-2222-4222-8222-222222222222","session_id":"22222222-2222-4222-8222-222222222222","timestamp":"2026-11-03T09:00:00Z","cwd":"/tmp/tools","originator":"codex_cli_rs","cli_version":"0.169.0","source":"cli","model_provider":"openai"}} +{"timestamp":"2026-11-03T09:00:01Z","type":"turn_context","payload":{"cwd":"/tmp/tools","model":"gpt-5-codex","turn_id":"t1","effort":"medium"}} +{"timestamp":"2026-11-03T09:00:02Z","type":"response_item","payload":{"type":"additional_tools","role":"developer","tools":[{"type":"namespace","name":"functions","tools":[{"type":"function","name":"shell","description":"Run a command","parameters":{"type":"object"}}]}]}} +{"timestamp":"2026-11-03T09:00:03Z","type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"list the files"}]}} +{"timestamp":"2026-11-03T09:00:04Z","type":"response_item","payload":{"type":"function_call","name":"shell","arguments":"{\"command\":[\"ls\"]}","call_id":"c1"}} +{"timestamp":"2026-11-03T09:00:05Z","type":"response_item","payload":{"type":"custom_tool_call","name":"apply_patch","input":"*** Begin Patch","call_id":"c2"}} +{"timestamp":"2026-11-03T09:00:06Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":500,"cached_input_tokens":0,"output_tokens":30,"reasoning_output_tokens":0,"total_tokens":530},"last_token_usage":{"input_tokens":500,"cached_input_tokens":0,"output_tokens":30,"reasoning_output_tokens":0,"total_tokens":530},"model_context_window":272000},"rate_limits":null}} +{"timestamp":"2026-11-03T09:00:07Z","type":"response_item","payload":{"type":"function_call_output","call_id":"c1","output":"a.txt"}} +{"timestamp":"2026-11-03T09:00:08Z","type":"response_item","payload":{"type":"custom_tool_call_output","call_id":"c2","output":"Done"}} +{"timestamp":"2026-11-03T09:00:09Z","type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"listed"}]}} diff --git a/core/session/importer/codex/testdata/sessions/2026/11/03/rollout-2026-11-03T09-05-00-33333333-3333-4333-8333-333333333333.jsonl b/core/session/importer/codex/testdata/sessions/2026/11/03/rollout-2026-11-03T09-05-00-33333333-3333-4333-8333-333333333333.jsonl new file mode 100644 index 000000000..5afd516e8 --- /dev/null +++ b/core/session/importer/codex/testdata/sessions/2026/11/03/rollout-2026-11-03T09-05-00-33333333-3333-4333-8333-333333333333.jsonl @@ -0,0 +1,5 @@ +{"timestamp":"2026-11-03T09:05:00Z","type":"session_meta","payload":{"id":"33333333-3333-4333-8333-333333333333","session_id":"22222222-2222-4222-8222-222222222222","timestamp":"2026-11-03T09:05:00Z","cwd":"/tmp/tools","originator":"codex_cli_rs","cli_version":"0.169.0","source":{"subagent":{"thread_spawn":{"parent_thread_id":"22222222-2222-4222-8222-222222222222","depth":1,"agent_role":"explorer"}}},"model_provider":"openai","agent_role":"explorer","parent_thread_id":"22222222-2222-4222-8222-222222222222"}} +{"timestamp":"2026-11-03T09:05:01Z","type":"turn_context","payload":{"cwd":"/tmp/tools","model":"gpt-5-codex","turn_id":"s1","effort":"medium"}} +{"timestamp":"2026-11-03T09:05:02Z","type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"find the config"}]}} +{"timestamp":"2026-11-03T09:05:03Z","type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"found"}]}} +{"timestamp":"2026-11-03T09:05:04Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":100,"cached_input_tokens":0,"output_tokens":10,"reasoning_output_tokens":0,"total_tokens":110},"last_token_usage":{"input_tokens":100,"cached_input_tokens":0,"output_tokens":10,"reasoning_output_tokens":0,"total_tokens":110},"model_context_window":272000},"rate_limits":null}} diff --git a/core/session/importer/codex/timeline_test.go b/core/session/importer/codex/timeline_test.go new file mode 100644 index 000000000..7e4f27b0a --- /dev/null +++ b/core/session/importer/codex/timeline_test.go @@ -0,0 +1,36 @@ +package codex + +import ( + "testing" + "time" + + "github.com/rossoctl/cortex/core/model" + "github.com/rossoctl/cortex/core/session/timeline" +) + +func TestTimeline_ImportedSessionShowsToolsAndSubagent(t *testing.T) { + s := sessionByID(t, fixtures(t), toolsID) + events := s.Events + for i := range events { + events[i].Seq = uint64(i + 1) + events[i].Source = model.ImportedSource("codex") // as importer.Run sets it + } + tl := timeline.Build(toolsID, events, time.Date(2026, 11, 4, 0, 0, 0, 0, time.UTC)) + + tools := map[string]bool{} + for _, tool := range tl.Tools { + tools[tool.Name] = true + } + for _, name := range []string{"shell", "apply_patch"} { + if !tools[name] { + t.Errorf("no tool %q in %+v", name, tl.Tools) + } + } + var sub bool + for _, a := range tl.Agents { + sub = sub || a.ID == subID + } + if !sub { + t.Fatalf("no subagent row in %+v", tl.Agents) + } +} diff --git a/core/session/importer/codex/turns.go b/core/session/importer/codex/turns.go new file mode 100644 index 000000000..5de04e192 --- /dev/null +++ b/core/session/importer/codex/turns.go @@ -0,0 +1,344 @@ +package codex + +import ( + "bufio" + "bytes" + "cmp" + "encoding/json" + "errors" + "io" + "slices" + "strconv" + "time" + + "github.com/rossoctl/cortex/core/model" + "github.com/rossoctl/cortex/core/parse/inference" + "github.com/rossoctl/cortex/core/project" + "github.com/rossoctl/cortex/core/session" +) + +// responsesPath is the path the live parser reads a Codex (Responses API) body for. +const responsesPath = "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/v1/responses" + +// line is one rollout line. +type line struct { + Timestamp time.Time `json:"timestamp"` + Type string `json:"type"` + Payload json.RawMessage `json:"payload"` +} + +// usage is Codex's TokenUsage. input_tokens includes cached_input_tokens. +type usage struct { + InputTokens int `json:"input_tokens"` + CachedInputTokens int `json:"cached_input_tokens"` + CacheWriteInputTokens int `json:"cache_write_input_tokens"` + OutputTokens int `json:"output_tokens"` + ReasoningOutputTokens int `json:"reasoning_output_tokens"` + TotalTokens int `json:"total_tokens"` +} + +// outputTypes are the response_item types that the model makes. A "message" is output only +// when its role is assistant. +var outputTypes = map[string]bool{ + "reasoning": true, "function_call": true, "custom_tool_call": true, "local_shell_call": true, + "web_search_call": true, "tool_search_call": true, "image_generation_call": true, +} + +// toolOutputTypes are the response_item types of a tool result. Codex 0.142.3 writes the +// token_count of a turn after the results of its tool calls, and writes no token_usage_record. +// So a tool result does not close an open turn: the turn waits for its usage. +var toolOutputTypes = map[string]bool{ + "function_call_output": true, "custom_tool_call_output": true, "tool_search_output": true, +} + +type fileResult struct { + events []model.SessionEvent + skipped int + usages []usage // the usage of each turn of the file that has usage, in order +} + +// parser holds what the rollouts of one session share. +type parser struct { + home string + projects map[string]string // cwd -> project label + in session.Interner // interns each event when it is made, as the claude source does + parents map[string][]usage // parent rollout path -> its turns' usages; see copied +} + +// file parses one rollout. thread is the file's thread id; subagent is "" for the root. +// copied is the usages of the parent's turns when the file is a fork. The fork starts with a +// copy of the parent's lines, with new timestamps and maybe without its tool calls, but with +// its token_count lines. So while each turn with usage has the next usage of copied, in +// order, the turns are the copy: they are conversation and make no events. A turn with no +// usage there is the copy of a turn that was open at the fork. usagesOnly gives only usages. +func (p *parser) file(path, thread, subagent string, copied []usage, usagesOnly bool) (fileResult, error) { + f, err := openRollout(path) + if err != nil { + return fileResult{}, err + } + defer f.Close() + var res fileResult + role := model.AgentRoleMain + if subagent != "" { + role = model.AgentRoleSubagent + } + + conv := []json.RawMessage{} + var out, held []json.RawMessage // held: the tool results that came after out; see toolOutputTypes + var mdl, cwd, version string + var inAt, heldAt, prevAt, firstOutAt, lastOutAt time.Time + n := 1 + matching := len(copied) > 0 // no turn so far is the fork's own + + closeTurn := func(at time.Time, u *usage) { + if len(out) == 0 { + return + } + if at.IsZero() { + at = lastOutAt + } + turnOut, turnHeld := out, held + out, held = nil, nil + // keep adds the turn to the conversation of the turns after it. + keep := func() { + conv = append(append(conv, turnOut...), turnHeld...) + if len(turnHeld) > 0 { + inAt = heldAt + } + n++ + } + if u != nil { + res.usages = append(res.usages, *u) + } + if matching && u != nil { + if i := slices.Index(copied, *u); i >= 0 { + copied = copied[i+1:] + } else { + matching = false + } + } + if usagesOnly || matching { + keep() + return + } + reqBody, _ := json.Marshal(struct { + Model string `json:"model"` + Input []json.RawMessage `json:"input"` + }{mdl, conv}) + req := inference.ParseRequest(responsesPath, nil, reqBody) + if req == nil { + res.skipped++ + return + } + req.AgentRole = role + respBody, _ := json.Marshal(struct { + Model string `json:"model"` + Output []json.RawMessage `json:"output"` + Usage *responsesUsage `json:"usage,omitempty"` + }{mdl, slices.DeleteFunc(slices.Clone(turnOut), invalidOutput), toResponsesUsage(u)}) + resp := *req + inference.ReadResponse(responsesPath, false, respBody, &resp) + if th := thinking(turnOut); th.Blocks > 0 { + resp.ResponseThinking = &th + } + + reqAt := inAt + if reqAt.IsZero() { + reqAt = firstOutAt + } + if reqAt.Before(prevAt) { + reqAt = prevAt + } + rid := thread + ":" + strconv.Itoa(n) + client := func() *model.EventClient { return &model.EventClient{Name: agentName, Version: version} } + proj := p.project(cwd) + res.events = append(res.events, + model.SessionEvent{At: reqAt, Direction: model.Outbound, Phase: model.SessionRequest, RequestID: rid, + Inference: req, Client: client(), Project: proj, Subagent: subagent}, + model.SessionEvent{At: at, Direction: model.Outbound, Phase: model.SessionResponse, RequestID: rid, + Inference: &resp, Client: client(), Project: proj, Subagent: subagent}) + for i := len(res.events) - 2; i < len(res.events); i++ { + p.in.InternEvent(&res.events[i]) + } + prevAt = at + keep() + } + + r := bufio.NewReader(f) + for { + raw, rerr := r.ReadBytes('\n') + if raw = bytes.TrimSpace(raw); len(raw) > 0 { + var l line + if json.Unmarshal(raw, &l) != nil || l.Type == "" { + res.skipped++ + } else { + switch l.Type { + case "session_meta": + var m struct { + Cwd string `json:"cwd"` + CLIVersion string `json:"cli_version"` + } + _ = json.Unmarshal(l.Payload, &m) + cwd, version = m.Cwd, m.CLIVersion + case "turn_context": + var c struct { + Model string `json:"model"` + Cwd string `json:"cwd"` + } + _ = json.Unmarshal(l.Payload, &c) + mdl, cwd = cmp.Or(c.Model, mdl), cmp.Or(c.Cwd, cwd) + case "response_item": + if !validItem(l.Payload) { + res.skipped++ + break + } + var it struct { + Type string `json:"type"` + Role string `json:"role"` + } + _ = json.Unmarshal(l.Payload, &it) + if outputTypes[it.Type] || (it.Type == "message" && it.Role == "assistant") { + if len(held) > 0 { + closeTurn(time.Time{}, nil) + } + if len(out) == 0 { + firstOutAt = l.Timestamp + } + out = append(out, l.Payload) + lastOutAt = l.Timestamp + break + } + if len(out) > 0 && toolOutputTypes[it.Type] { + held = append(held, l.Payload) + heldAt = l.Timestamp + break + } + closeTurn(time.Time{}, nil) + conv = append(conv, l.Payload) + inAt = l.Timestamp + case "event_msg": + var e struct { + Type string `json:"type"` + Info *struct { + LastTokenUsage *usage `json:"last_token_usage"` + } `json:"info"` + } + // A token_count with no info, or with no open turn (a rate-limit update, or a + // second one for the same turn), makes no turn. + if json.Unmarshal(l.Payload, &e) == nil && e.Type == "token_count" && e.Info != nil { + closeTurn(l.Timestamp, e.Info.LastTokenUsage) + } + case "token_usage_record": + var rec struct { + Usage *usage `json:"usage"` + } + if json.Unmarshal(l.Payload, &rec) == nil { + closeTurn(l.Timestamp, rec.Usage) + } + case "compacted": + closeTurn(time.Time{}, nil) + var c struct { + ReplacementHistory []json.RawMessage `json:"replacement_history"` + } + _ = json.Unmarshal(l.Payload, &c) + conv = []json.RawMessage{} + for _, item := range c.ReplacementHistory { + if !validItem(item) { + res.skipped++ + continue + } + conv = append(conv, item) + } + } + } + } + if rerr != nil { + closeTurn(time.Time{}, nil) + if errors.Is(rerr, io.EOF) { + return res, nil + } + return res, rerr + } + } +} + +// validItem reports whether the live parser decodes item. It refuses a whole input array +// for one item it cannot decode, so one such item in conv would cost every later turn. +func validItem(item json.RawMessage) bool { + return inference.ParseRequest(responsesPath, nil, slices.Concat([]byte(`{"input":[`), item, []byte(`]}`))) != nil +} + +// invalidOutput reports whether the live parser refuses item as an output. It refuses a whole +// response body for one such item, and the turn then loses its usage. +func invalidOutput(item json.RawMessage) bool { + var ext model.InferenceExtension + inference.ReadResponse(responsesPath, false, slices.Concat([]byte(`{"status":"ok","output":[`), item, []byte(`]}`)), &ext) + return ext.FinishReason != "ok" +} + +// responsesUsage is the usage block of a Responses API response. +type responsesUsage struct { + InputTokens int `json:"input_tokens"` + InputTokensDetails struct { + CachedTokens int `json:"cached_tokens"` + CacheWriteTokens int `json:"cache_write_tokens"` + } `json:"input_tokens_details"` + OutputTokens int `json:"output_tokens"` + OutputTokensDetails struct { + ReasoningTokens int `json:"reasoning_tokens"` + } `json:"output_tokens_details"` + TotalTokens int `json:"total_tokens"` +} + +func toResponsesUsage(u *usage) *responsesUsage { + if u == nil { + return nil + } + r := &responsesUsage{InputTokens: u.InputTokens, OutputTokens: u.OutputTokens, TotalTokens: u.TotalTokens} + r.InputTokensDetails.CachedTokens = u.CachedInputTokens + r.InputTokensDetails.CacheWriteTokens = u.CacheWriteInputTokens + r.OutputTokensDetails.ReasoningTokens = u.ReasoningOutputTokens + return r +} + +// thinking counts the reasoning items of one turn's output. +func thinking(out []json.RawMessage) model.InferenceThinking { + var th model.InferenceThinking + for _, raw := range out { + var it struct { + Type string `json:"type"` + Summary []struct { + Text string `json:"text"` + } `json:"summary"` + Content []struct { + Text string `json:"text"` + } `json:"content"` + EncryptedContent string `json:"encrypted_content"` + } + _ = json.Unmarshal(raw, &it) + if it.Type != "reasoning" { + continue + } + text := 0 + for _, s := range it.Summary { + text += len(s.Text) + } + for _, c := range it.Content { + text += len(c.Text) + } + th.Add("thinking", text, len(it.EncryptedContent), 0) + } + return th +} + +func (p *parser) project(cwd string) string { + if cwd == "" { + return "" + } + label, ok := p.projects[cwd] + if !ok { + label = project.Label(project.Root(cwd, p.home), p.home) + p.projects[cwd] = label + } + return label +} diff --git a/core/session/importer/importer.go b/core/session/importer/importer.go index 812a68647..512f02938 100644 --- a/core/session/importer/importer.go +++ b/core/session/importer/importer.go @@ -172,7 +172,8 @@ func count(r *AgentReport, replace bool) { } // priorTurns is what the archived copy of a replaced session holds: the request ids of its -// responses, and the time of its oldest event. +// priced responses, and the time of its oldest event. A response with no price is left out, so +// that a later import records the turn when its usage is on disk. type priorTurns struct { ids map[string]bool oldest time.Time @@ -182,7 +183,7 @@ type priorTurns struct { func readPrior(ctx context.Context, a *archive.Archive, id string) (*priorTurns, error) { p := &priorTurns{ids: map[string]bool{}} _, _, _, err := a.Find(ctx, id, func(e *model.SessionEvent) bool { - if e.Phase == model.SessionResponse { + if _, priced := event.Record(e); priced && e.Phase == model.SessionResponse { p.ids[e.RequestID] = true } if p.oldest.IsZero() || e.At.Before(p.oldest) { @@ -193,8 +194,8 @@ func readPrior(ctx context.Context, a *archive.Archive, id string) (*priorTurns, return p, err } -// toLedger records each response of s that is not before the ledger's retention cutoff, and -// whose request id is not in sent. It adds the ids it records to sent: a fork copies its +// toLedger records each priced response of s that is not before the ledger's retention cutoff, +// and whose request id is not in sent. It adds the ids it records to sent: a fork copies its // parent's turns with their request ids, and one run must count them one time. // // On a replace (prior not nil) it records only the responses whose request id is not in prior: @@ -226,6 +227,9 @@ func toLedger(ctx context.Context, w *ledger.Writer, s Session, prior *priorTurn requestAt[e.RequestID] = e.At case model.SessionResponse: at, ok := requestAt[e.RequestID] + if _, priced := event.Record(e); !priced { + continue + } if !ok || e.At.Before(cutoff) || (e.RequestID != "" && sent[e.RequestID]) { continue } diff --git a/core/session/importer/importer_test.go b/core/session/importer/importer_test.go index 102a2745b..989fff341 100644 --- a/core/session/importer/importer_test.go +++ b/core/session/importer/importer_test.go @@ -390,6 +390,28 @@ func TestRun_LedgerGetsOnlyNewTurnsOnReplace(t *testing.T) { } } +// A turn that an import read before its usage was written (Codex writes the usage after the +// tool results) gets its row from a later import. +func TestRun_LedgerGetsTurnWhoseUsageCameLater(t *testing.T) { + a := openArchive(t) + w := openLedger(t) + o := Options{Archive: a, Ledger: w, Rates: testRates(t)} + early := fakeSession("s1", start, 2) + early.Events[3].Inference = &model.InferenceExtension{Model: "claude-sonnet-4-5"} + Run(context.Background(), &fakeSource{sessions: []Session{early}}, o) + if req, _ := sumRows(ledgerRows(t, w)); req != 1 { + t.Fatalf("ledger has %d requests after the first import, want 1: a turn with no usage has no row", req) + } + later := fakeSession("s1", start, 2) + later.Updated = later.Updated.Add(time.Second) + if r := Run(context.Background(), &fakeSource{sessions: []Session{later}}, o); r.Replaced != 1 { + t.Fatalf("report = %+v, want 1 replaced", r) + } + if req, tok := sumRows(ledgerRows(t, w)); req != 2 || tok != 2200 { + t.Fatalf("ledger has %d requests, %d tokens; want 2, 2200", req, tok) + } +} + func TestRun_LedgerSkipsTurnsPastCutoff(t *testing.T) { a := openArchive(t) w := openLedger(t, ledger.WithRetentionDays(3)) diff --git a/docs/laptop-service.md b/docs/laptop-service.md index 9dd6b1354..7c1462e4b 100644 --- a/docs/laptop-service.md +++ b/docs/laptop-service.md @@ -599,13 +599,14 @@ more than 256 MB of them waited for the writer. ### Importing history from before Cortex `agentop import` adds the sessions that Claude Code keeps in -`~/.claude/projects` (or under `CLAUDE_CONFIG_DIR`), and the tasks that Bob -keeps in `~/.bob/db/bob.db`, to this history and to the cost ledger. Bob needs +`~/.claude/projects` (or under `CLAUDE_CONFIG_DIR`), the tasks that Bob +keeps in `~/.bob/db/bob.db`, and the sessions that Codex keeps in +`~/.codex/sessions` (or under `CODEX_HOME`), to this history and to the cost ledger. Bob needs the `sqlite3` program on `PATH`. Use it for the sessions that ran before you installed Cortex. `agentop import --since 30d --dry-run` counts first and writes nothing. The import skips every session that Cortex captured live, and never changes one. -Each imported session is marked `(*)` in agentop. A Claude Code turn is priced -at today's rates. A Bob turn keeps Bob's own cost. LAST 1H shows imported turns +Each imported session is marked `(*)` in agentop. A Claude Code turn and a Codex +turn are priced at today's rates. A Bob turn keeps Bob's own cost. LAST 1H shows imported turns only after the next restart. The import stops at 90% of `max_bytes`. A session that you erased, or that a limit removed, comes back in full on the next import. Its forget record tells the import which turns the cost ledger already holds. diff --git a/docs/session-api.md b/docs/session-api.md index 77190ac79..2315f8482 100644 --- a/docs/session-api.md +++ b/docs/session-api.md @@ -482,10 +482,15 @@ only another session of the same project made a row in that minute. `source`. The session summary has the mark only while all its events are imported. - The `cost` record of an imported turn has `source: "transcript"`. Cortex - prices a Claude Code turn at today's rates. A Bob turn keeps Bob's own cost - (see **Sources**). A turn with no usage has no `cost` record. + prices a Claude Code turn and a Codex turn at today's rates. A Bob turn + keeps Bob's own cost (see **Sources**). A turn with no usage has no `cost` + record. - The ledger row of an imported turn has `source: "transcript"`. A live row has no `source`. +- An imported turn with no `cost` record has no ledger row, from every source. + The live proxy records such a turn as one request at $0, so the request count + and the priced share of an import can be lower than those of live traffic. + When a later import finds the usage of the turn, that import adds the row. - A turn before the ledger's retention cutoff goes to the archive only. - An imported segment is kept for `retention_days` from its newest event. A session older than that is skipped (`skippedExpired`). The Claude Code source checks @@ -501,9 +506,9 @@ only another session of the same project made a row in that minute. - LAST 1H and the usage pane's hour windows show imported turns only after the next proxy restart. The import does not feed them. -**Sources.** Claude Code (`claude-code`) and Bob (`bob`) are supported now. -#1873 to #1875 add the other agents (`codex`, `opencode`, `pi`). The proxy -answers the others with an error that names the supported agents. +**Sources.** Claude Code (`claude-code`), Bob (`bob`) and Codex (`codex`) are +supported now. #1874 and #1875 add the other agents (`opencode`, `pi`). The +proxy answers the others with an error that names the supported agents. The Claude Code source reads `~/.claude/projects//.jsonl`, or the same path under @@ -543,6 +548,24 @@ agents continue. When `bob.db` does not exist, the source imports nothing. `~/.bob/tmp/*/chats/*.json` files or the IDE's `globalStorage/ibm.bob-code/tasks`. +The Codex source reads `~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`, or the +same path under `CODEX_HOME` when that variable is set. It also reads a +rollout that Codex compressed to `.jsonl.zst`. It does not import a rollout from +`archived_sessions/`. When the `sessions/` directory does not exist, the +source imports nothing. + +- The session id is the rollout's `session_meta.session_id`, else its `id`. + This is the value that Codex sends in the `Session-Id` header. +- The rollout of a subagent is in the session of its root, with `subagent` + set to the subagent's thread id. +- Each event has the `codex` client, the model of the turn + (`turn_context.model`), and the project of the turn's working directory. +- Cortex prices a Codex turn at today's rates, from the usage of its + `token_usage_record` or `token_count` line. A tool result does not end a + turn, because some Codex versions write `token_count` after the tool + results. A turn with no usage has no `cost` record and no ledger row. When a + later import finds its usage, that import adds the row. + ## `POST /v1/ingest` — rows from cortex-gateway (praxis mode) Registered only when `praxis.enabled` and `listener.bind_loopback_only` are diff --git a/docs/superpowers/plans/2026-11-16-import-codex-transcripts-1873.md b/docs/superpowers/plans/2026-11-16-import-codex-transcripts-1873.md new file mode 100644 index 000000000..cbdc56dc7 --- /dev/null +++ b/docs/superpowers/plans/2026-11-16-import-codex-transcripts-1873.md @@ -0,0 +1,346 @@ +# Import Codex transcripts (#1873) Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** `agentop import --agent codex` imports Codex history from +`$CODEX_HOME/sessions/YYYY/MM/DD/rollout-*.jsonl` (default `~/.codex`). + +**Architecture:** A new importer source `core/session/importer/codex`, built like +`core/session/importer/claude`. It reads each rollout file line by line. It keeps the +`response_item` payloads as the Responses API `input` array of the conversation, and closes +one model turn at each `token_count` event (or at the next input item). It runs each turn +through `inference.ParseRequest` / `inference.ReadResponse` with the path `/v1/responses`, +as the live proxy parses Codex. `importer.Run` prices the turns from the rate table. + +**Tech Stack:** Go 1.26.10, `encoding/json`, `bufio`, `github.com/klauspost/compress/zstd` +(already a direct requirement of `core/go.mod`). + +**Spec:** issue #1873 (body), and the shared path of #1871 as merged +(`core/session/importer/types.go`, `importer.go`, `cost.go`). Template sources: +`core/session/importer/claude/{claude.go,turns.go}`. + +## Global Constraints + +- A source only parses. It never touches the archive, the store or the ledger. +- Implement `importer.Source` exactly as it is in `core/session/importer/types.go` on the + base (`Agent()`, `PricingHost()`, `Sessions(since, skip)`). Do not change that interface. +- Agent name: `codex` (the canonical client name, `core/model/client.go`: `"codex_exec": "codex"`). +- Honour `CODEX_HOME`: when it is set and not empty, the store is `$CODEX_HOME/sessions`. + Else `~/.codex/sessions`. +- Price through the existing pricing table (`importer.price` does it; the source sets no + cost record). A turn with no usage gets no cost record. +- Do not add a module requirement. `go mod tidy -diff` must stay clean in `core`. +- Run Go commands with `GOWORK=off`. Log with `log/slog`. +- Commits: `git commit -s`, and end the message with + `Assisted-By: Claude (Anthropic AI) `. No `Co-Authored-By`. +- Write prose and comments in ASD-STE100 Simplified Technical English. + +## Facts from the Codex source (openai/codex tag `rust-v0.169.0`, read 2026-11-16) + +Codex is not installed on the laptop that wrote this plan. These facts come from the +Rust source, not from a real rollout file. See "For a human after review". + +- **Line shape** (`codex-rs/history/src/lib.rs` `RolloutLine`, + `rollout_payload.rs` `RolloutItemWire`, `#[serde(tag = "type", rename_all = "snake_case")]`): + `{"timestamp":"","ordinal":,"type":"","payload":{...}}`. + Kinds: `session_meta`, `response_item`, `event_msg`, `turn_context`, `compacted`, + `token_usage_record`, `dynamic_tools_updated`, `inter_agent_communication`, `world_state`, + `retained_context`, `security_risk_score`, `realtime_item`, and others. +- **`session_meta` payload** (`protocol.rs` `SessionMeta`): `id` (thread id, a UUID), + `session_id` ("equal to the root thread's ID"; when absent, Codex reads it as `id`), + `timestamp`, `cwd`, `originator`, `cli_version`, `source`, `model_provider`, + `agent_role`, `agent_nickname`, `parent_thread_id`, `forked_from_id`. `source` is a + string (`"cli"`, `"vscode"`, `"exec"`, `"mcp"`) or an object + (`{"subagent": {"thread_spawn": {"parent_thread_id": ..., "depth": 1, "agent_role": ...}}}`, + `{"subagent": "review"}`, `{"internal": ...}`). +- **`turn_context` payload**: `cwd`, `model` (for example `gpt-5-codex`), `turn_id`, `effort`. +- **`response_item` payload** is one Responses API item (`models.rs` `ResponseItem`): + `message` (`role`, `content: [{type: input_text|output_text, text}]`), `reasoning` + (`summary: [{type: summary_text, text}]`, `content`, `encrypted_content`), + `function_call` (`name`, `arguments` string, `call_id`), `function_call_output` + (`call_id`, `output`), `custom_tool_call` (`name`, `input`, `call_id`), + `custom_tool_call_output`, `local_shell_call`, `web_search_call`, `tool_search_call`, + `tool_search_output`, `image_generation_call`, `additional_tools` (`role`, `tools`), + `agent_message`, `configuration_update`, `compaction`, `context_compaction`. +- **`event_msg` payload** has its own `type`. `token_count`: `{"type":"token_count", + "info": null | {"total_token_usage": U, "last_token_usage": U, "model_context_window": n}, + "rate_limits": ...}`. `U` = `{input_tokens, cached_input_tokens, + cache_write_input_tokens (default 0), output_tokens, reasoning_output_tokens, total_tokens}`. + `input_tokens` includes `cached_input_tokens` (OpenAI semantics). +- **`token_usage_record` payload**: `{thread_id, turn_id, session_id, root_turn_id, + response_id, usage: U, turn_token_usage: U, thread_token_usage: U}`. `usage` is the one response. +- **File names** (`rollout/src/rollout_file_name.rs`): `rollout-YYYY-MM-DDThh-mm-ss-.jsonl`, + or `...-_.jsonl` for a reverted thread. A rollout older than + 7 days can be compressed to `.jsonl.zst` (`rollout/src/compression.rs`). +- **The `Session-Id` header** (`codex-api/src/requests/headers.rs`, `core/src/client.rs` + `responses_session_id`): for a non-root agent it is `metadata.session_id`; for a root + agent it is `session_id_override`, else `":"` for an `internal` source + with a parent thread, else `metadata.session_id`. So for a normal root session and for + a spawned subagent, the header equals `session_meta.session_id` (the root thread id, + which is also the root file's uuid). Cortex files Codex under this header + (`CodexSessionHeader = "Session-Id"`, `core/session/idheader.go`). + +## Decisions (made here, with the reason) + +1. **Session id** = `session_meta.payload.session_id`, else `payload.id`. Reason: this is + the value Codex sends as `Session-Id` (Facts, last bullet), so the skip-live rule of + `importer.Run` matches a live session. A file whose `id` differs from its session id + is a child: its events go in the session of that id with `Subagent` = the file's + `id` and `Inference.AgentRole = model.AgentRoleSubagent`. Root events get + `model.AgentRoleMain`. `SubagentKind` and `ParentSubagent` stay empty (those are Bob's + and Claude Code's fields). +2. **Files read:** every regular file under `/sessions` (walk all depths) whose name + starts with `rollout-` and ends with `.jsonl` or `.jsonl.zst`. A `.zst` file is read + through `zstd.NewReader`. `archived_sessions/` and the opt-in SQLite thread store + (`codex migrate-rollouts`) are not read. Reason: the issue names `sessions/` only. +3. **Grouping needs the first line of every file.** The listing reads only the first line + (the `session_meta` line) of each file. A file whose first line is not a + `session_meta` line, or that cannot be opened, is left out with `slog.Warn` (it names + no session, so no session can count it). Two files with one thread `id`: the newer + mtime wins (a reverted thread, or a `.jsonl` and its `.jsonl.zst` during compression). +4. **Order, `since` and `skip`:** the session time = the newest mtime of its files. Sort + newest first, then by id. With a non-zero `since`, drop a session whose files are all + older than `since`. Call `skip(id, sessionTime)` before the parse. Reason: Codex writes + each line when it happens, so no line is newer than its file (the same rule as the + open PR #1893 uses for Claude Code). `importer.Run` calls `skip` again with the parsed + `Updated`. +5. **Unreadable:** when the file whose `id` equals the session id fails to open or read, + yield `Session{ID, Unreadable: true}` (with `slog.Warn` that names the path). A child + file that fails → `Skipped++`, go on. A session with no root file (only children + found) is yielded with the children's events. +6. **Turn rule** (per file, in line order). Keep `conv []json.RawMessage` (every + `response_item` payload so far), `out []json.RawMessage` (the output items of the open + turn), `model` and `cwd` (from the newest `turn_context`; `cwd` starts as + `session_meta.cwd`), `inAt` (timestamp of the newest input item), `prevAt` (the previous + response's `At`), and `n` (the turn number in this file). + - Output items: `type` in `reasoning`, `function_call`, `custom_tool_call`, + `local_shell_call`, `web_search_call`, `tool_search_call`, `image_generation_call`, + or `type == "message"` with `role == "assistant"`. Every other `response_item` is an + input item. + - Input item: when `out` is not empty, close the turn with no usage. Then append the + item to `conv` and set `inAt`. + - Output item: append it to `out` (not to `conv` yet). + - `event_msg` with `payload.type == "token_count"` and non-null `info`: when `out` is + not empty, close the turn with `info.last_token_usage`. When `out` is empty, ignore + it (Codex also sends `token_count` for rate-limit updates; this stops a double count). + - `token_usage_record`: the same as `token_count`, with `payload.usage`. + - `compacted`: close an open turn with no usage; then `conv` = `payload.replacement_history` + when it is a non-empty array, else an empty array. + - `turn_context`: set `model` and `cwd` from it. + - A line that is not JSON, or that has no `type` → `Skipped++`. Every other kind is ignored. + - End of file: close an open turn with no usage. + - **Close a turn:** request body `{"model": model, "input": conv}`; `req := + inference.ParseRequest("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/v1/responses", nil, body)`; nil → `Skipped++`, drop `out`. + Response body `{"model": model, "output": out, "usage": {...}}`, where `usage` (only + when the turn has a usage `U`) is `{"input_tokens": U.input_tokens, + "input_tokens_details": {"cached_tokens": U.cached_input_tokens, + "cache_write_tokens": U.cache_write_input_tokens}, "output_tokens": U.output_tokens, + "output_tokens_details": {"reasoning_tokens": U.reasoning_output_tokens}, + "total_tokens": U.total_tokens}`. `resp := *req`; + `inference.ReadResponse("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/v1/responses", false, respBody, &resp)`. Set + `AgentRole` on both. Thinking: for each `reasoning` item in `out`, + `th.Add("thinking", , len(encrypted_content), 0)`; + set `resp.ResponseThinking = th` when there is at least one. No `FinishReason`: a + rollout records none per response. Then append `out` to `conv`, clear `out`, `n++`. + - **Event fields** (both events): `Direction: model.Outbound`, `Phase` request/response, + `RequestID: ":"` (unique in the session, stable across runs), + `Client: &model.EventClient{Name: "codex", Version: session_meta.cli_version}`, + `Project: project.Label(project.Root(cwd, home), home)` (cache by cwd, as + `claude/turns.go` does), `Subagent` (Decision 1). Response `At` = timestamp of the line + that closed the turn (the `token_count` line, else the last output item). Request `At` = + `inAt`, else the first output item's timestamp; never before `prevAt`. Intern each + event with one `session.Interner` per session (`InternEvent`), as `claude/turns.go` does. +7. **Merge:** events of all files of a session are sorted stable by `At`; `Updated` = the + max event `At`; `SizeHint` = the sum of file sizes on disk. +8. **`PricingHost()`** = `"api.openai.com"`. Reason: the bundled table prices the GPT + models under host `*` (`core/cost/pricing/bundled.go`, for example `gpt-5-codex`), and a + rollout does not say whether Codex used an API key or a ChatGPT login. +9. **Title:** none from the source. The archive folds it from the user messages, as for a + live session (`importer.Session` has no `Title`). +10. **Fixtures are synthetic,** written from the Facts above, because Codex is not + installed here. The human step below compares them with a real, scrubbed rollout. + +## Review Focus + +1. A `token_count` with `info: null`, or a second `token_count` after a turn closed, must + not make a turn or a cost. Test: `TestSource_DuplicateTokenCountIsIgnored` (T1). +2. A rollout compressed to `.jsonl.zst` must import like a plain one. Test: + `TestSource_CompressedRollout` (T1; the test writes the `.zst` file with `zstd.NewWriter` + in `t.TempDir()`, so no binary file is in git). +3. A spawned subagent file must not become its own session. Test: + `TestSource_SubagentInRootSession` (T1). +4. `CODEX_HOME` set to a directory must be read in place of `~/.codex`. Test: + `TestSource_HonoursCodexHome` (T1). +5. A missing `sessions/` directory (Codex not installed) gives no session and no error. + Test: `TestSource_NoSessionsDirYieldsNothing` (T1). +6. Interface drift: open PR #1893 adds a `progress` argument to `Source.Sessions`. If it + merges first, the PR rebase adds that argument here as #1893 does for Claude Code. + +--- + +### Task T1: The Codex source, its fixture tests, and its registration + +Depends on: none + +**Files:** +- Create: `core/session/importer/codex/codex.go` (home dir, listing, grouping, `Sessions`) +- Create: `core/session/importer/codex/turns.go` (one rollout file → events) +- Create: `core/session/importer/codex/testdata/sessions/2026/11/02/rollout-2026-11-02T10-00-00-11111111-1111-4111-8111-111111111111.jsonl` (plain) +- Create: `core/session/importer/codex/testdata/sessions/2026/11/03/rollout-2026-11-03T09-00-00-22222222-2222-4222-8222-222222222222.jsonl` (tools) +- Create: `core/session/importer/codex/testdata/sessions/2026/11/03/rollout-2026-11-03T09-05-00-33333333-3333-4333-8333-333333333333.jsonl` (subagent of 2222…) +- Create: `core/session/importer/codex/codex_test.go` +- Create: `core/session/importer/codex/timeline_test.go` +- Modify: `cmd/cortex/main.go` (import `codeximport "github.com/rossoctl/cortex/core/session/importer/codex"`; + `Sources: []importer.Source{claudeimport.New(""), bobimport.New(""), codeximport.New("")}`, near line 1283) + +**Interfaces:** +- Produces: `func New(home string) importer.Source`. `home ""` resolves `$CODEX_HOME`, else + `~/.codex`, when `Sessions` runs. `Agent()` = `"codex"`, `PricingHost()` = `"api.openai.com"`. + +**Fixtures** (synthetic, see Decision 10; one JSON object per line, shapes from Facts): +- Plain `1111…`: `session_meta` (`id` 1111…, no `session_id`, `cwd` `/tmp/demo`, + `cli_version` `0.169.0`, `source` `"cli"`); `turn_context` (`model` `gpt-5-codex`, + `cwd` `/tmp/demo`); `response_item` message `developer`; `response_item` message + `user` `hello codex`; `event_msg` `user_message` (ignored); `event_msg` `token_count` + with `info: null`; `response_item` reasoning (one `summary_text` `thinking`, `encrypted_content` `abc`); + `response_item` message `assistant` `hi`; `event_msg` `token_count` with + `last_token_usage {input_tokens 1200, cached_input_tokens 1000, output_tokens 50, + reasoning_output_tokens 20, total_tokens 1250}`; then a second identical `token_count`; + then one line `not json`. +- Tools `2222…`: `session_meta` (`id` = `session_id` = 2222…, `cwd` `/tmp/tools`); + `turn_context` (`gpt-5-codex`); `response_item` `additional_tools` (role `developer`, + `tools: [{"type":"namespace","name":"functions","tools":[{"type":"function","name":"shell","description":"Run a command","parameters":{"type":"object"}}]}]`); + user message; `function_call` `shell` `call_id` `c1`, `arguments` `{"command":["ls"]}`; + `custom_tool_call` `apply_patch` `call_id` `c2` `input` `*** Begin Patch`; + `token_count` (usage 500/0/30/0/530); `function_call_output` `c1` `a.txt`; + `custom_tool_call_output` `c2` `Done`; assistant message `listed` (no `token_count` + after it: closes at EOF with no usage). +- Subagent `3333…`: `session_meta` (`id` 3333…, `session_id` 2222…, `source` + `{"subagent":{"thread_spawn":{"parent_thread_id":"2222…","depth":1,"agent_role":"explorer"}}}`, + `cwd` `/tmp/tools`); `turn_context`; user message; assistant `found`; `token_count` (100/0/10/0/110). +- Timestamps: each line 1 s after the one before; the tools session's newest line is newest. + Git does not keep mtimes, so `fixtures(t)` sets the mtime of each copied file to the + `timestamp` of its last JSON line with `os.Chtimes`. Every test that uses `fixtures(t)` + gets these mtimes. + +- [ ] **Step 1: Write the failing tests** in `codex_test.go`. A helper `fixtures(t)` copies + `testdata` into `t.TempDir()` and returns that home. A helper `readAll(t, src, since)` + collects `Sessions(since, func(string, time.Time) bool { return false })` and fails on an error. + - `TestSource_AgentAndHost`: `"codex"`, `"api.openai.com"`. + - `TestSource_NoSessionsDirYieldsNothing`: `New(t.TempDir())` yields 0 sessions, no error. + - `TestSource_HonoursCodexHome`: `t.Setenv("CODEX_HOME", fixtures(t))`; `New("")` yields + the session ids `2222…` and `1111…`. + - `TestSource_PlainSession`: session `1111…` has 2 events with one `RequestID` + (`1111…:1`); request `Inference.Model == "gpt-5-codex"`, `Messages` roles + `developer`, `user`; response `Completion == "hi"`, `InputTokens == 200`, + `CacheReadTokens == 1000`, `CompletionTokens == 50`, `ReasoningTokens == 20`, + `TotalTokens == 1250`, `ResponseThinking.Blocks == 1`; + `Client.Name == "codex"`, `Client.Version == "0.169.0"`; `Project` is the label of + `/tmp/demo`; `Inference.AgentRole == model.AgentRoleMain`; `Skipped == 1`. + - `TestSource_DuplicateTokenCountIsIgnored`: in `1111…`, exactly one response event. + - `TestSource_ToolCallsAndResults`: in `2222…`, the first response has `ToolCalls` ids + `c1` (`shell`, `Arguments` `{"command":["ls"]}`) and `c2` (`apply_patch`); the first + request's `Tools` names are `[shell]`; the second request's `ToolResults` ids are `c1`, + `c2`; the second response has `Completion == "listed"` and no token counts. + - `TestSource_SubagentInRootSession`: no session has id `3333…`; `2222…` holds events + with `Subagent == "3333…"` and `Inference.AgentRole == model.AgentRoleSubagent`, and + their `Project` is the label of `/tmp/tools`. + - `TestSource_NewestFirstSinceAndSkip`: ids in order are `2222…`, `1111…`; a `since` + 1 s after the plain file's mtime (and before the tools files' mtimes) drops `1111…`; a `skip` that gives true for `2222…` + stops it, and the time it got is not before that session's `Updated` from a full read. + - `TestSource_CompressedRollout`: replace the plain file in the copy with + `.zst` written by `zstd.NewWriter`; the session `1111…` equals the plain read + (same event count and `Completion`). + - `TestSource_UnreadableRootIsReported`: the package has an unexported variable + `var openRollout = openFile` (`func(path string) (io.ReadCloser, error)`; it handles + `.zst`), and both the listing and the parse open files through it. The test replaces it + with a wrapper that fails the second open of the tools root file (`2222…`). The session + `2222…` is yielded with `Unreadable == true`, and the source gives no error. + - `TestSource_UnlistableFileIsLeftOut`: a wrapper that fails every open of the plain file + (`1111…`) gives no session `1111…`, no error, and the session `2222…` as before. +- [ ] **Step 2:** In `timeline_test.go`, `TestTimeline_ImportedSessionShowsToolsAndSubagent` + (copy the shape of `claude/timeline_test.go`): set `Seq = uint64(i + 1)` and + `Source = model.ImportedSource("codex")` on `2222…`'s events, run `timeline.Build`; + assert tools `shell` and `apply_patch` are in `tl.Tools`, and `tl.Agents` has a row with + `ID == "3333…"`. +- [ ] **Step 3:** Run `GOWORK=off go -C core test ./session/importer/codex/` — FAIL (no package). +- [ ] **Step 4:** Implement `codex.go` and `turns.go` (Decisions 1-9). Register the source in + `cmd/cortex/main.go`. +- [ ] **Step 5:** Run `GOWORK=off go -C core test -race ./session/importer/...` and + `GOWORK=off go -C cmd/cortex build ./...` — PASS. Run `GOWORK=off go -C core mod tidy -diff` — no output. +- [ ] **Step 6:** Commit: `feat: Import Codex rollout files with agentop import`. + +### Task T2: Docs + +Depends on: none + +**Files:** +- Modify: `docs/session-api.md` (the `**Sources.**` paragraph near line 487, and the cost + bullet "Cortex prices a Claude Code turn at today's rates" near line 470) +- Modify: `cmd/agentop/README.md` (the `--agent` row near line 794, and the example block near line 787) +- Modify: `docs/laptop-service.md` ("Importing history from before Cortex", near line 599) + +Facts to write (all from this plan): +- Supported sources now: `claude-code`, `bob` and `codex`. #1874 and #1875 add the others + (`opencode`, `pi`). The proxy answers the others with an error that names the supported agents. +- The Codex source reads `~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`, or the same path + under `CODEX_HOME` when that variable is set. It also reads a rollout that Codex + compressed to `.jsonl.zst`. It does not read `archived_sessions/`. A missing + `sessions/` directory imports nothing. +- The session id is the rollout's `session_meta.session_id` (else its `id`): the value + that Codex sends in the `Session-Id` header. A subagent's rollout is in its root + session, with `subagent` set to the subagent's thread id. +- Each Codex event has the `codex` client, the model of the turn (`turn_context.model`), + and the project of the turn's working directory. +- A Codex turn is priced at today's rates from its `token_count` usage. A turn with no + `token_count` has no `cost` record. +- `cmd/agentop/README.md` example line: `agentop import --agent codex # Codex's rollouts, from ~/.codex/sessions`. +- laptop-service.md: say that `agentop import` also adds the Codex sessions in + `~/.codex/sessions` (or under `CODEX_HOME`), and that a Codex turn is priced at today's rates. + +- [ ] **Step 1:** Edit the three files. Keep the existing style; STE prose. +- [ ] **Step 2:** Commit: `docs: Describe the Codex import source`. + +## PRs + +| PR | Title | Parent | Tasks | estLines | +|---|---|---|---|---| +| P1 | `feat: Import Codex transcripts with agentop import` | (none) | T1, T2 | 950 | + +Estimates: T1 about 920 (source about 420, fixtures about 40, tests about 460), T2 about +30. The total is below 2000, so one PR. + +## Gate + +From the worktree root: + +```sh +GOWORK=off go -C core vet ./... && GOWORK=off go -C core test -race ./session/importer/... ./sessionapi/... && GOWORK=off go -C core mod tidy -diff && GOWORK=off go -C cmd/cortex vet ./... && GOWORK=off go -C cmd/cortex build ./... && test -z "$(gofmt -l core/session/importer cmd/cortex)" +``` + +## Gate check (run on the base, 2026-11-16) + +From the worktree root, on the unchanged base (edd296580), each format and vet step of the +gate was run alone, and each passed with no change to how it is called: +`GOWORK=off go -C core vet ./...`, `GOWORK=off go -C cmd/cortex vet ./...`, +`test -z "$(gofmt -l core/session/importer cmd/cortex)"`. The plan review did not run the +test, build and `mod tidy -diff` steps. + +## For a human after review + +Needs T1 merged (or the PR branch built), on a machine with Codex installed. + +1. **The id check the issue asks for.** Run one Codex session through the local Cortex + (`agentop configure codex`, then `codex exec "say hi"`). Take the session id that + agentop shows for it. Open the newest file under `~/.codex/sessions/` and read + `payload.session_id` (else `payload.id`) of its first line. They must be equal. If they + differ, stop and report it in the PR body: the skip-live rule depends on it. The plan's + claim that they are equal comes from the Codex source only (Facts, last bullet). +2. **Fixture check.** Compare one real rollout file with the fixtures in + `core/session/importer/codex/testdata/`. If a line kind or field differs, scrub a real + file (replace prompts, paths and ids) and replace the fixtures in a follow-up commit on the PR. +3. Run `agentop import --agent codex --dry-run`, then `agentop import --agent codex`, + against the real local Cortex. Check that Codex sessions list with project, model, + tokens and estimated cost, and that the Timeline opens one with its tool calls. A + Cortex built from the branch restarts the shared proxy: coordinate first. +4. Put the result of step 1, and Decision 10 (synthetic fixtures), in the PR body.