From 4adc70a76c44fca4d32f5af87ac64e3a38efdc83 Mon Sep 17 00:00:00 2001 From: Hai Huang Date: Mon, 16 Nov 2026 20:19:43 -0500 Subject: [PATCH 01/14] docs: Add the plan to import Codex transcripts (#1873) Assisted-By: Claude (Anthropic AI) Signed-off-by: Hai Huang --- ...026-11-16-import-codex-transcripts-1873.md | 342 ++++++++++++++++++ 1 file changed, 342 insertions(+) create mode 100644 docs/superpowers/plans/2026-11-16-import-codex-transcripts-1873.md 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..35f1d1fc6 --- /dev/null +++ b/docs/superpowers/plans/2026-11-16-import-codex-transcripts-1873.md @@ -0,0 +1,342 @@ +# 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. + Tests set file mtimes with `os.Chtimes` on a copy in `t.TempDir()` when an order matters. + +- [ ] **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` + after the plain file's mtime 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, these passed: +`GOWORK=off go -C core vet ./session/...`, `GOWORK=off go -C core mod tidy -diff`, +`GOWORK=off go -C cmd/cortex vet ./...`, `test -z "$(gofmt -l core/session/importer cmd/cortex)"`. + +## 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. From af3f30ad4ce83d339e854e4e7b2c3e78b4e55eaa Mon Sep 17 00:00:00 2001 From: Hai Huang Date: Mon, 16 Nov 2026 20:21:16 -0500 Subject: [PATCH 02/14] docs: Make the fixture mtimes in the Codex import plan exact Assisted-By: Claude (Anthropic AI) Signed-off-by: Hai Huang --- .../2026-11-16-import-codex-transcripts-1873.md | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) 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 index 35f1d1fc6..cbdc56dc7 100644 --- a/docs/superpowers/plans/2026-11-16-import-codex-transcripts-1873.md +++ b/docs/superpowers/plans/2026-11-16-import-codex-transcripts-1873.md @@ -219,7 +219,9 @@ Depends on: none `{"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. - Tests set file mtimes with `os.Chtimes` on a copy in `t.TempDir()` when an order matters. + 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)` @@ -244,7 +246,7 @@ Depends on: none 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` - after the plain file's mtime drops `1111…`; a `skip` that gives true for `2222…` + 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 @@ -318,9 +320,11 @@ GOWORK=off go -C core vet ./... && GOWORK=off go -C core test -race ./session/im ## Gate check (run on the base, 2026-11-16) -From the worktree root, on the unchanged base, these passed: -`GOWORK=off go -C core vet ./session/...`, `GOWORK=off go -C core mod tidy -diff`, -`GOWORK=off go -C cmd/cortex vet ./...`, `test -z "$(gofmt -l core/session/importer cmd/cortex)"`. +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 From 98bdee04aadccb9b720272318e63355a29952eb4 Mon Sep 17 00:00:00 2001 From: Hai Huang Date: Mon, 16 Nov 2026 20:22:30 -0500 Subject: [PATCH 03/14] docs: Describe the Codex import source Add Codex to the supported import sources in docs/session-api.md, cmd/agentop/README.md and docs/laptop-service.md. Tell where the source reads the rollouts, how it sets the session id and the subagent, and how it prices a turn. Assisted-By: Claude (Anthropic AI) Signed-off-by: Hai Huang --- cmd/agentop/README.md | 3 ++- docs/laptop-service.md | 9 +++++---- docs/session-api.md | 26 +++++++++++++++++++++----- 3 files changed, 28 insertions(+), 10 deletions(-) diff --git a/cmd/agentop/README.md b/cmd/agentop/README.md index 438b19ba2..fc374eaec 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/docs/laptop-service.md b/docs/laptop-service.md index d76d6d512..250579269 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 `imp` 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 `imp` 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 ed23fd06b..dee4c7ba6 100644 --- a/docs/session-api.md +++ b/docs/session-api.md @@ -467,8 +467,9 @@ 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`. - A turn before the ledger's retention cutoff goes to the archive only. @@ -484,9 +485,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 @@ -526,6 +527,21 @@ 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 read +`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 its `token_count` usage. + A turn with no `token_count` has no `cost` record. + ## `POST /v1/ingest` — rows from cortex-gateway (praxis mode) Registered only when `praxis.enabled` and `listener.bind_loopback_only` are From 3804955b52e4458589c85a582eed0399982a5cb8 Mon Sep 17 00:00:00 2001 From: Hai Huang Date: Mon, 16 Nov 2026 20:25:32 -0500 Subject: [PATCH 04/14] feat: Import Codex rollout files with agentop import Add the importer source "codex". It reads the rollout files under $CODEX_HOME/sessions (else ~/.codex/sessions), also when Codex compressed them to .jsonl.zst. The session id is session_meta.session_id (else id), the value that Codex sends in the Session-Id header. A subagent rollout goes into the session of its root. One model turn closes at each token_count event, and the turn goes through the live Responses API parser. Register the source in cmd/cortex. Assisted-By: Claude (Anthropic AI) Signed-off-by: Hai Huang --- cmd/cortex/main.go | 3 +- core/session/importer/codex/codex.go | 246 ++++++++++++ core/session/importer/codex/codex_test.go | 353 ++++++++++++++++++ ...11111111-1111-4111-8111-111111111111.jsonl | 11 + ...22222222-2222-4222-8222-222222222222.jsonl | 10 + ...33333333-3333-4333-8333-333333333333.jsonl | 5 + core/session/importer/codex/timeline_test.go | 36 ++ core/session/importer/codex/turns.go | 274 ++++++++++++++ 8 files changed, 937 insertions(+), 1 deletion(-) create mode 100644 core/session/importer/codex/codex.go create mode 100644 core/session/importer/codex/codex_test.go create mode 100644 core/session/importer/codex/testdata/sessions/2026/11/02/rollout-2026-11-02T10-00-00-11111111-1111-4111-8111-111111111111.jsonl create mode 100644 core/session/importer/codex/testdata/sessions/2026/11/03/rollout-2026-11-03T09-00-00-22222222-2222-4222-8222-222222222222.jsonl create mode 100644 core/session/importer/codex/testdata/sessions/2026/11/03/rollout-2026-11-03T09-05-00-33333333-3333-4333-8333-333333333333.jsonl create mode 100644 core/session/importer/codex/timeline_test.go create mode 100644 core/session/importer/codex/turns.go 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..a416a3536 --- /dev/null +++ b/core/session/importer/codex/codex.go @@ -0,0 +1,246 @@ +// 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 + 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) 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 + } + groups := group(list(filepath.Join(dir, "sessions"))) + 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)) + }) + home, _ := os.UserHomeDir() + for _, id := range sids { + // 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 + } + if !yield(readSession(id, groups[id], home), nil) { + return + } + } + } +} + +// list finds the rollout files under dir at all depths and reads the first line of each. +// A missing dir gives none. +func list(dir string) []rollout { + var out []rollout + // 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 + } + thread, session, err := readMeta(path) + if err != nil { + slog.Warn("importer: cannot list a Codex rollout", "path", path, "error", err) + return nil + } + out = append(out, rollout{path: path, thread: thread, session: session, mod: fi.ModTime(), size: fi.Size()}) + return nil + }) + return out +} + +// 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 and the session id from the first line of a rollout. +func readMeta(path string) (thread, session string, err error) { + f, err := openRollout(path) + if err != nil { + return "", "", err + } + defer f.Close() + raw, err := bufio.NewReader(f).ReadBytes('\n') + if err != nil && len(raw) == 0 { + return "", "", err + } + var l struct { + Type string `json:"type"` + Payload struct { + ID string `json:"id"` + SessionID string `json:"session_id"` + } `json:"payload"` + } + if json.Unmarshal(raw, &l) != nil || l.Type != "session_meta" || l.Payload.ID == "" { + return "", "", errNoMeta + } + // Codex sends session_id as the Session-Id header; when it is absent it reads it as id. + return l.Payload.ID, cmp.Or(l.Payload.SessionID, l.Payload.ID), nil +} + +// 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. +func readSession(id string, files []rollout, home string) importer.Session { + p := parser{home: home, projects: map[string]string{}} + 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) + 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 +} diff --git a/core/session/importer/codex/codex_test.go b/core/session/importer/codex/codex_test.go new file mode 100644 index 000000000..eac81eb34 --- /dev/null +++ b/core/session/importer/codex/codex_test.go @@ -0,0 +1,353 @@ +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 + for s, err := range src.Sessions(since, func(string, time.Time) bool { return false }) { + if err != nil { + t.Fatal(err) + } + out = append(out, s) + } + 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 + }) { + 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) + failOpens(t, func(path string, n int) bool { return strings.Contains(path, toolsID) && n == 2 }) + 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}) { + t.Fatalf("ids = %v", got) + } + if len(all[0].Events) != 6 { + t.Errorf("tools session has %d events, want 6", len(all[0].Events)) + } +} 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..4767d4b45 --- /dev/null +++ b/core/session/importer/codex/turns.go @@ -0,0 +1,274 @@ +package codex + +import ( + "bufio" + "bytes" + "cmp" + "encoding/json" + "errors" + "io" + "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, +} + +type fileResult struct { + events []model.SessionEvent + skipped int +} + +// 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 +} + +// file parses one rollout. thread is the file's thread id; subagent is "" for the root. +func (p *parser) file(path, thread, subagent string) (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 []json.RawMessage + var mdl, cwd, version string + var inAt, prevAt, firstOutAt, lastOutAt time.Time + n := 1 + + closeTurn := func(at time.Time, u *usage) { + if len(out) == 0 { + return + } + if at.IsZero() { + at = lastOutAt + } + turnOut := out + out = nil + 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, turnOut, 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 + conv = append(conv, turnOut...) + n++ + } + + 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": + 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(out) == 0 { + firstOutAt = l.Timestamp + } + out = append(out, l.Payload) + lastOutAt = 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 = append([]json.RawMessage{}, c.ReplacementHistory...) + } + } + } + if rerr != nil { + closeTurn(time.Time{}, nil) + if errors.Is(rerr, io.EOF) { + return res, nil + } + return res, rerr + } + } +} + +// 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 +} From 9f092f781cf2c6bb94f198bfadb85db307c6f0e2 Mon Sep 17 00:00:00 2001 From: Hai Huang Date: Mon, 16 Nov 2026 20:29:10 -0500 Subject: [PATCH 05/14] test: Cover the Codex turn boundaries and the rollout grouping rules Add tests for these plan decisions: - An input item, a compacted line and a token_usage_record line close a turn. - A compacted line replaces the conversation. - Of two rollouts with one thread id, the newer mtime wins. - A child rollout that cannot be read gives Skipped++. - A session with only child rollouts is yielded. Assisted-By: Claude (Anthropic AI) Signed-off-by: Hai Huang --- core/session/importer/codex/decisions_test.go | 140 ++++++++++++++++++ 1 file changed, 140 insertions(+) create mode 100644 core/session/importer/codex/decisions_test.go diff --git a/core/session/importer/codex/decisions_test.go b/core/session/importer/codex/decisions_test.go new file mode 100644 index 000000000..6b76ee7de --- /dev/null +++ b/core/session/importer/codex/decisions_test.go @@ -0,0 +1,140 @@ +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) + } +} + +// 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) + failOpens(t, func(path string, n int) bool { return strings.Contains(path, subID) && n == 2 }) + 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) + } +} From 7426f252fa1886cd984289c57cd7dbc071001ae1 Mon Sep 17 00:00:00 2001 From: Hai Huang Date: Mon, 16 Nov 2026 20:57:04 -0500 Subject: [PATCH 06/14] fix(importer): Do not make turns from a Codex fork's copy of its parent A rollout whose session_meta names a forked_from_id starts with a copy of its parent's lines. The Codex source now reads the parent rollout, and the fork's first turns that match the parent's turns, in order, become conversation context. They make no events, so the import does not price them a second time at the fork time. Fixes review: - A forked Codex thread priced its parent's copied turns again. - No test had a forked rollout. Files: - core/session/importer/codex/codex.go - core/session/importer/codex/turns.go - core/session/importer/codex/fork_test.go Assisted-By: Claude (Anthropic AI) Signed-off-by: Hai Huang --- core/session/importer/codex/codex.go | 53 +++++++++--- core/session/importer/codex/fork_test.go | 103 +++++++++++++++++++++++ core/session/importer/codex/turns.go | 25 +++++- 3 files changed, 166 insertions(+), 15 deletions(-) create mode 100644 core/session/importer/codex/fork_test.go diff --git a/core/session/importer/codex/codex.go b/core/session/importer/codex/codex.go index fbb6814a7..e433b466f 100644 --- a/core/session/importer/codex/codex.go +++ b/core/session/importer/codex/codex.go @@ -40,6 +40,7 @@ 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 } @@ -94,6 +95,12 @@ func (s source) Sessions(since time.Time, skip func(id string, updated time.Time return } groups := group(list(filepath.Join(dir, "sessions"))) + threads := map[string]rollout{} + 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 { @@ -117,7 +124,7 @@ func (s source) Sessions(since time.Time, skip func(id string, updated time.Time if skip(id, newest[id]) { continue } - if !yield(readSession(id, groups[id], home), nil) { + if !yield(readSession(id, groups[id], threads, home), nil) { return } } @@ -146,12 +153,13 @@ func list(dir string) []rollout { if err != nil { return nil } - thread, session, err := readMeta(path) + r, err := readMeta(path) if err != nil { slog.Warn("importer: cannot list a Codex rollout", "path", path, "error", err) return nil } - out = append(out, rollout{path: path, thread: thread, session: session, mod: fi.ModTime(), size: fi.Size()}) + r.path, r.mod, r.size = path, fi.ModTime(), fi.Size() + out = append(out, r) return nil }) return out @@ -160,29 +168,31 @@ func list(dir string) []rollout { // 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 and the session id from the first line of a rollout. -func readMeta(path string) (thread, session string, err error) { +// 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 "", "", err + return rollout{}, err } defer f.Close() raw, err := bufio.NewReader(f).ReadBytes('\n') if err != nil && len(raw) == 0 { - return "", "", err + return rollout{}, err } var l struct { Type string `json:"type"` Payload struct { - ID string `json:"id"` - SessionID string `json:"session_id"` + 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 "", "", errNoMeta + return rollout{}, errNoMeta } // Codex sends session_id as the Session-Id header; when it is absent it reads it as id. - return l.Payload.ID, cmp.Or(l.Payload.SessionID, l.Payload.ID), nil + return rollout{thread: l.Payload.ID, session: cmp.Or(l.Payload.SessionID, l.Payload.ID), forkedFrom: l.Payload.ForkedFromID}, nil } // group puts the rollouts by session id. Of two rollouts with one thread id the newer wins: @@ -215,8 +225,8 @@ func isChild(f rollout) int { return 1 } -// readSession parses the rollouts of one session. -func readSession(id string, files []rollout, home string) importer.Session { +// 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{}} s := importer.Session{ID: id} for _, f := range files { @@ -224,7 +234,7 @@ func readSession(id string, files []rollout, home string) importer.Session { if f.thread != id { subagent = f.thread } - r, err := p.file(f.path, f.thread, subagent) + 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) @@ -246,3 +256,18 @@ func readSession(id string, files []rollout, home string) importer.Session { } return s } + +// copied gives 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: then f's turns are +// the only copy. +func (p *parser) copied(f rollout, threads map[string]rollout) []turnSig { + parent, ok := threads[f.forkedFrom] + if f.forkedFrom == "" || !ok { + return nil + } + r, err := p.file(parent.path, parent.thread, "", nil, true) + if err != nil { + return nil + } + return r.sigs +} diff --git a/core/session/importer/codex/fork_test.go b/core/session/importer/codex/fork_test.go new file mode 100644 index 000000000..9dbefb2f4 --- /dev/null +++ b/core/session/importer/codex/fork_test.go @@ -0,0 +1,103 @@ +package codex + +import ( + "bufio" + "bytes" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/rossoctl/cortex/core/model" +) + +const forkID = "44444444-4444-4444-8444-444444444444" + +// writeFork writes a rollout that forks the plain fixture the way Codex copies a thread: the +// parent's lines after its session_meta, stamped with the fork time, then one new turn. +// session is the fork's session_id; parent "" leaves forked_from_id out. +func writeFork(t *testing.T, dir, session, parent string) { + t.Helper() + data, err := os.ReadFile(filepath.Join(dir, plainFile)) + if err != nil { + t.Fatal(err) + } + stamp := func(at time.Time, typ, payload string) string { + return `{"timestamp":"` + at.Format(time.RFC3339) + `","type":"` + typ + `","payload":` + payload + "}\n" + } + at := time.Date(2026, 11, 4, 8, 0, 0, 0, time.UTC) + meta := `{"id":"` + forkID + `","session_id":"` + session + `","cwd":"/tmp/demo","cli_version":"0.169.0"` + if parent != "" { + meta += `,"forked_from_id":"` + parent + `"` + } + var b strings.Builder + b.WriteString(stamp(at, "session_meta", meta+"}")) + sc := bufio.NewScanner(bytes.NewReader(data)) + for sc.Scan() { + var l line + if json.Unmarshal(sc.Bytes(), &l) != nil || l.Type == "session_meta" { + continue + } + b.WriteString(stamp(at, l.Type, string(l.Payload))) + } + b.WriteString(stamp(at, "event_msg", `{"type":"thread_settings_applied"}`)) + at = at.Add(time.Minute) + b.WriteString(stamp(at, "response_item", `{"type":"message","role":"user","content":[{"type":"input_text","text":"again"}]}`)) + b.WriteString(stamp(at.Add(time.Second), "response_item", `{"type":"message","role":"assistant","content":[{"type":"output_text","text":"forked"}]}`)) + b.WriteString(stamp(at.Add(2*time.Second), "event_msg", + `{"type":"token_count","info":{"last_token_usage":{"input_tokens":1500,"cached_input_tokens":1200,"output_tokens":7,"total_tokens":1507}}}`)) + path := filepath.Join(dir, "sessions/2026/11/04/rollout-2026-11-04T08-00-00-"+forkID+".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) + } + end := at.Add(2 * time.Second) + if err := os.Chtimes(path, end, end); err != nil { + t.Fatal(err) + } +} + +// A fork's copy of its parent's turns is conversation, not turns: the parent keeps them, and +// the fork has only its own turn, whose request carries the copied conversation. +func TestSource_ForkDoesNotRepeatParentTurns(t *testing.T) { + for _, tc := range []struct{ name, session, subagent string }{ + {"thread fork", forkID, ""}, + {"forked subagent", plainID, forkID}, + } { + t.Run(tc.name, func(t *testing.T) { + dir := fixtures(t) + writeFork(t, dir, tc.session, plainID) + fork := sessionByID(t, dir, tc.session) + resps := phase(fork, model.SessionResponse, tc.subagent) + if len(resps) != 1 || resps[0].Inference.Completion != "forked" || resps[0].Inference.CompletionTokens != 7 { + t.Fatalf("fork responses = %+v, want only the new turn", resps) + } + reqs := phase(fork, model.SessionRequest, tc.subagent) + var texts []string + for _, m := range reqs[0].Inference.Messages { + texts = append(texts, m.Role) + } + if got := strings.Join(texts, ","); got != "developer,user,assistant,user" { + t.Errorf("fork request roles = %s, want the copied conversation first", got) + } + if n := len(phase(sessionByID(t, dir, plainID), model.SessionResponse, "")); n != 1 { + t.Errorf("parent has %d responses, want 1", n) + } + }) + } +} + +// With no parent rollout to compare, the fork's turns are the only copy, so they stay. +func TestSource_ForkWithoutParentKeepsItsTurns(t *testing.T) { + for _, parent := range []string{"", "55555555-5555-4555-8555-555555555555"} { + dir := fixtures(t) + writeFork(t, dir, forkID, parent) + if n := len(phase(sessionByID(t, dir, forkID), model.SessionResponse, "")); n != 2 { + t.Errorf("forked_from_id %q: %d responses, want 2", parent, n) + } + } +} diff --git a/core/session/importer/codex/turns.go b/core/session/importer/codex/turns.go index 4767d4b45..c594f825d 100644 --- a/core/session/importer/codex/turns.go +++ b/core/session/importer/codex/turns.go @@ -46,6 +46,15 @@ var outputTypes = map[string]bool{ type fileResult struct { events []model.SessionEvent skipped int + sigs []turnSig // every turn of the file, in order +} + +// turnSig tells a turn from the turns next to it. Codex copies a parent's lines into a fork +// with new timestamps, so the time is not part of it. +type turnSig struct { + model string + outputs int + usage usage } // parser holds what the rollouts of one session share. @@ -56,7 +65,9 @@ type parser struct { } // file parses one rollout. thread is the file's thread id; subagent is "" for the root. -func (p *parser) file(path, thread, subagent string) (fileResult, error) { +// The file's first turns that match copied, in order, are a fork's copy of its parent's turns: +// they are conversation and make no events. sigsOnly gives only the sigs. +func (p *parser) file(path, thread, subagent string, copied []turnSig, sigsOnly bool) (fileResult, error) { f, err := openRollout(path) if err != nil { return fileResult{}, err @@ -73,6 +84,7 @@ func (p *parser) file(path, thread, subagent string) (fileResult, error) { var mdl, cwd, version string var inAt, prevAt, firstOutAt, lastOutAt time.Time n := 1 + matching := true // no turn so far differs from copied closeTurn := func(at time.Time, u *usage) { if len(out) == 0 { @@ -83,6 +95,17 @@ func (p *parser) file(path, thread, subagent string) (fileResult, error) { } turnOut := out out = nil + sig := turnSig{model: mdl, outputs: len(turnOut)} + if u != nil { + sig.usage = *u + } + res.sigs = append(res.sigs, sig) + if k := len(res.sigs) - 1; sigsOnly || (matching && k < len(copied) && copied[k] == sig) { + conv = append(conv, turnOut...) + n++ + return + } + matching = false reqBody, _ := json.Marshal(struct { Model string `json:"model"` Input []json.RawMessage `json:"input"` From 481118ca6a6e5592276ac7cca88a3244465f275e Mon Sep 17 00:00:00 2001 From: Hai Huang Date: Mon, 16 Nov 2026 21:06:22 -0500 Subject: [PATCH 07/14] fix(importer): Match a Codex fork's copied turns by their usage A fork's copied turns are now found by the usage of each turn, in the order of the parent's turns, so a copy without the parent's tool calls is found too. While the copy matches, a turn with no usage is the copy of a turn that was open at the fork, and makes no event. The source also finds a parent rollout under archived_sessions, and reads each parent once. Fixes review: - A fork without its parent's tool calls priced the copied turns again. - A fork in the middle of a turn made a zero-usage row. - A fork of an archived parent priced the copied turns again. - Each fork read its parent rollout again. Files: - core/session/importer/codex/codex.go - core/session/importer/codex/turns.go - core/session/importer/codex/fork_test.go Assisted-By: Claude (Anthropic AI) Signed-off-by: Hai Huang --- core/session/importer/codex/codex.go | 22 +++- core/session/importer/codex/fork_test.go | 156 ++++++++++++++--------- core/session/importer/codex/turns.go | 41 +++--- 3 files changed, 134 insertions(+), 85 deletions(-) diff --git a/core/session/importer/codex/codex.go b/core/session/importer/codex/codex.go index e433b466f..03a4ff362 100644 --- a/core/session/importer/codex/codex.go +++ b/core/session/importer/codex/codex.go @@ -95,7 +95,12 @@ func (s source) Sessions(since time.Time, skip func(id string, updated time.Time return } groups := group(list(filepath.Join(dir, "sessions"))) + // 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{} + for _, f := range list(filepath.Join(dir, "archived_sessions")) { + threads[f.thread] = f + } for _, files := range groups { for _, f := range files { threads[f.thread] = f @@ -227,7 +232,7 @@ func isChild(f rollout) int { // 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{}} + p := parser{home: home, projects: map[string]string{}, parents: map[string][]usage{}} s := importer.Session{ID: id} for _, f := range files { subagent := "" @@ -257,17 +262,20 @@ func readSession(id string, files []rollout, threads map[string]rollout, home st return s } -// copied gives 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: then f's turns are -// the only copy. -func (p *parser) copied(f rollout, threads map[string]rollout) []turnSig { +// 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 { - return nil + r.usages = nil } - return r.sigs + p.parents[parent.path] = r.usages + return r.usages } diff --git a/core/session/importer/codex/fork_test.go b/core/session/importer/codex/fork_test.go index 9dbefb2f4..99c335e2d 100644 --- a/core/session/importer/codex/fork_test.go +++ b/core/session/importer/codex/fork_test.go @@ -1,8 +1,6 @@ package codex import ( - "bufio" - "bytes" "encoding/json" "os" "path/filepath" @@ -13,79 +11,123 @@ import ( "github.com/rossoctl/cortex/core/model" ) -const forkID = "44444444-4444-4444-8444-444444444444" +const ( + parentID = "44444444-4444-4444-8444-444444444444" + forkID = "55555555-5555-4555-8555-555555555555" +) -// writeFork writes a rollout that forks the plain fixture the way Codex copies a thread: the -// parent's lines after its session_meta, stamped with the fork time, then one new turn. -// session is the fork's session_id; parent "" leaves forked_from_id out. -func writeFork(t *testing.T, dir, session, parent string) { - t.Helper() - data, err := os.ReadFile(filepath.Join(dir, plainFile)) - if err != nil { - t.Fatal(err) - } - stamp := func(at time.Time, typ, payload string) string { - return `{"timestamp":"` + at.Format(time.RFC3339) + `","type":"` + typ + `","payload":` + payload + "}\n" +// 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"` } - at := time.Date(2026, 11, 4, 8, 0, 0, 0, time.UTC) - meta := `{"id":"` + forkID + `","session_id":"` + session + `","cwd":"/tmp/demo","cli_version":"0.169.0"` - if parent != "" { - meta += `,"forked_from_id":"` + parent + `"` + _ = 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 - b.WriteString(stamp(at, "session_meta", meta+"}")) - sc := bufio.NewScanner(bytes.NewReader(data)) - for sc.Scan() { - var l line - if json.Unmarshal(sc.Bytes(), &l) != nil || l.Type == "session_meta" { - continue - } - b.WriteString(stamp(at, l.Type, string(l.Payload))) + for _, l := range lines { + at = at.Add(time.Second) + b.WriteString(`{"timestamp":"` + at.Format(time.RFC3339) + `",` + l[1:] + "\n") } - b.WriteString(stamp(at, "event_msg", `{"type":"thread_settings_applied"}`)) - at = at.Add(time.Minute) - b.WriteString(stamp(at, "response_item", `{"type":"message","role":"user","content":[{"type":"input_text","text":"again"}]}`)) - b.WriteString(stamp(at.Add(time.Second), "response_item", `{"type":"message","role":"assistant","content":[{"type":"output_text","text":"forked"}]}`)) - b.WriteString(stamp(at.Add(2*time.Second), "event_msg", - `{"type":"token_count","info":{"last_token_usage":{"input_tokens":1500,"cached_input_tokens":1200,"output_tokens":7,"total_tokens":1507}}}`)) - path := filepath.Join(dir, "sessions/2026/11/04/rollout-2026-11-04T08-00-00-"+forkID+".jsonl") + 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) } - end := at.Add(2 * time.Second) - if err := os.Chtimes(path, end, end); err != nil { + if err := os.Chtimes(path, at, at); err != nil { t.Fatal(err) } } -// A fork's copy of its parent's turns is conversation, not turns: the parent keeps them, and -// the fork has only its own turn, whose request carries the copied conversation. +// 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) { - for _, tc := range []struct{ name, session, subagent string }{ - {"thread fork", forkID, ""}, - {"forked subagent", plainID, forkID}, + 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 := fixtures(t) - writeFork(t, dir, tc.session, plainID) + 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) fork := sessionByID(t, dir, tc.session) resps := phase(fork, model.SessionResponse, tc.subagent) - if len(resps) != 1 || resps[0].Inference.Completion != "forked" || resps[0].Inference.CompletionTokens != 7 { - t.Fatalf("fork responses = %+v, want only the new turn", resps) + 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) - var texts []string - for _, m := range reqs[0].Inference.Messages { - texts = append(texts, m.Role) + 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 got := strings.Join(texts, ","); got != "developer,user,assistant,user" { - t.Errorf("fork request roles = %s, want the copied conversation first", got) - } - if n := len(phase(sessionByID(t, dir, plainID), model.SessionResponse, "")); n != 1 { - t.Errorf("parent has %d responses, want 1", n) + 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) + } } }) } @@ -93,11 +135,9 @@ func TestSource_ForkDoesNotRepeatParentTurns(t *testing.T) { // With no parent rollout to compare, the fork's turns are the only copy, so they stay. func TestSource_ForkWithoutParentKeepsItsTurns(t *testing.T) { - for _, parent := range []string{"", "55555555-5555-4555-8555-555555555555"} { - dir := fixtures(t) - writeFork(t, dir, forkID, parent) - if n := len(phase(sessionByID(t, dir, forkID), model.SessionResponse, "")); n != 2 { - t.Errorf("forked_from_id %q: %d responses, want 2", parent, n) - } + 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/turns.go b/core/session/importer/codex/turns.go index c594f825d..05034bc9a 100644 --- a/core/session/importer/codex/turns.go +++ b/core/session/importer/codex/turns.go @@ -7,6 +7,7 @@ import ( "encoding/json" "errors" "io" + "slices" "strconv" "time" @@ -46,28 +47,24 @@ var outputTypes = map[string]bool{ type fileResult struct { events []model.SessionEvent skipped int - sigs []turnSig // every turn of the file, in order -} - -// turnSig tells a turn from the turns next to it. Codex copies a parent's lines into a fork -// with new timestamps, so the time is not part of it. -type turnSig struct { - model string - outputs int - usage usage + 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 + 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. -// The file's first turns that match copied, in order, are a fork's copy of its parent's turns: -// they are conversation and make no events. sigsOnly gives only the sigs. -func (p *parser) file(path, thread, subagent string, copied []turnSig, sigsOnly bool) (fileResult, error) { +// 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 @@ -84,7 +81,7 @@ func (p *parser) file(path, thread, subagent string, copied []turnSig, sigsOnly var mdl, cwd, version string var inAt, prevAt, firstOutAt, lastOutAt time.Time n := 1 - matching := true // no turn so far differs from copied + matching := len(copied) > 0 // no turn so far is the fork's own closeTurn := func(at time.Time, u *usage) { if len(out) == 0 { @@ -95,17 +92,21 @@ func (p *parser) file(path, thread, subagent string, copied []turnSig, sigsOnly } turnOut := out out = nil - sig := turnSig{model: mdl, outputs: len(turnOut)} if u != nil { - sig.usage = *u + 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 + } } - res.sigs = append(res.sigs, sig) - if k := len(res.sigs) - 1; sigsOnly || (matching && k < len(copied) && copied[k] == sig) { + if usagesOnly || matching { conv = append(conv, turnOut...) n++ return } - matching = false reqBody, _ := json.Marshal(struct { Model string `json:"model"` Input []json.RawMessage `json:"input"` From bfd5406d9a8f53b66095923f97627bd11128995e Mon Sep 17 00:00:00 2001 From: Hai Huang Date: Mon, 16 Nov 2026 21:11:25 -0500 Subject: [PATCH 08/14] docs: Say that the Codex source does not import an archived rollout Fixes review: - "It does not read archived_sessions/" became false: the source reads an archived rollout to find a fork's parent. Files: - docs/session-api.md Assisted-By: Claude (Anthropic AI) Signed-off-by: Hai Huang --- docs/session-api.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/session-api.md b/docs/session-api.md index c96d6778a..a63a59b81 100644 --- a/docs/session-api.md +++ b/docs/session-api.md @@ -546,7 +546,7 @@ agents continue. When `bob.db` does not exist, the source imports nothing. 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 +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. From 9aea4feec2b18aef2bf6d91e113849d2ef856119 Mon Sep 17 00:00:00 2001 From: Hai Huang Date: Mon, 16 Nov 2026 21:31:31 -0500 Subject: [PATCH 09/14] fix: Keep the usage of a Codex turn that calls a tool Codex 0.142.3 writes the token_count line of a turn after the results of its tool calls, and writes no token_usage_record line. The import closed the turn at the first tool result, with no usage. Then it ignored the token_count line, because no turn was open. So each model call that ended in a tool call had no cost record. Now a tool result does not close an open turn. The import holds the tool results, and adds them to the conversation after the turn closes. The request of the next turn starts at the last tool result. TestSource_TokenCountAfterToolResults fails without the fix. Assisted-By: Claude (Anthropic AI) Signed-off-by: Hai Huang --- core/session/importer/codex/decisions_test.go | 36 +++++++++++++++++++ core/session/importer/codex/turns.go | 34 +++++++++++++----- docs/session-api.md | 6 ++-- 3 files changed, 66 insertions(+), 10 deletions(-) diff --git a/core/session/importer/codex/decisions_test.go b/core/session/importer/codex/decisions_test.go index 6b76ee7de..f71449be5 100644 --- a/core/session/importer/codex/decisions_test.go +++ b/core/session/importer/codex/decisions_test.go @@ -97,6 +97,42 @@ func TestSource_TurnBoundaries(t *testing.T) { } } +// 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) + } +} + // Of two rollouts with one thread id, the newer mtime wins, whatever the path order. func TestSource_NewerRolloutOfAThreadWins(t *testing.T) { home := t.TempDir() diff --git a/core/session/importer/codex/turns.go b/core/session/importer/codex/turns.go index 05034bc9a..c9ba46739 100644 --- a/core/session/importer/codex/turns.go +++ b/core/session/importer/codex/turns.go @@ -44,6 +44,13 @@ var outputTypes = map[string]bool{ "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 @@ -77,9 +84,9 @@ func (p *parser) file(path, thread, subagent string, copied []usage, usagesOnly } conv := []json.RawMessage{} - var out []json.RawMessage + var out, held []json.RawMessage // held: the tool results that came after out; see toolOutputTypes var mdl, cwd, version string - var inAt, prevAt, firstOutAt, lastOutAt time.Time + var inAt, heldAt, prevAt, firstOutAt, lastOutAt time.Time n := 1 matching := len(copied) > 0 // no turn so far is the fork's own @@ -90,8 +97,16 @@ func (p *parser) file(path, thread, subagent string, copied []usage, usagesOnly if at.IsZero() { at = lastOutAt } - turnOut := out - out = nil + 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) } @@ -103,8 +118,7 @@ func (p *parser) file(path, thread, subagent string, copied []usage, usagesOnly } } if usagesOnly || matching { - conv = append(conv, turnOut...) - n++ + keep() return } reqBody, _ := json.Marshal(struct { @@ -147,8 +161,7 @@ func (p *parser) file(path, thread, subagent string, copied []usage, usagesOnly p.in.InternEvent(&res.events[i]) } prevAt = at - conv = append(conv, turnOut...) - n++ + keep() } r := bufio.NewReader(f) @@ -188,6 +201,11 @@ func (p *parser) file(path, thread, subagent string, copied []usage, usagesOnly 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 diff --git a/docs/session-api.md b/docs/session-api.md index a63a59b81..27ccda2c1 100644 --- a/docs/session-api.md +++ b/docs/session-api.md @@ -556,8 +556,10 @@ source imports nothing. 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 its `token_count` usage. - A turn with no `token_count` has no `cost` record. +- 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. ## `POST /v1/ingest` — rows from cortex-gateway (praxis mode) From 6b207e32df405016e015ceae59878e673489074a Mon Sep 17 00:00:00 2001 From: Hai Huang Date: Mon, 16 Nov 2026 21:42:10 -0500 Subject: [PATCH 10/14] fix(importer): Skip a Codex item that the Responses parser refuses Fixes review: - One off-spec response_item made ParseRequest refuse each later turn of the rollout. The import now skips that item and counts it in Skipped. A compacted replacement_history item gets the same check. - A rollout that cannot be opened was in no session and not in the report. The import now counts it as unreadable. Files: - core/session/importer/codex/codex.go - core/session/importer/codex/codex_test.go - core/session/importer/codex/decisions_test.go - core/session/importer/codex/turns.go Assisted-By: Claude (Anthropic AI) Signed-off-by: Hai Huang --- core/session/importer/codex/codex.go | 28 +++++++--- core/session/importer/codex/codex_test.go | 8 +-- core/session/importer/codex/decisions_test.go | 54 +++++++++++++++++++ core/session/importer/codex/turns.go | 19 ++++++- 4 files changed, 96 insertions(+), 13 deletions(-) diff --git a/core/session/importer/codex/codex.go b/core/session/importer/codex/codex.go index 03a4ff362..5c579cdb7 100644 --- a/core/session/importer/codex/codex.go +++ b/core/session/importer/codex/codex.go @@ -94,11 +94,13 @@ func (s source) Sessions(since time.Time, skip func(id string, updated time.Time yield(importer.Session{}, err) return } - groups := group(list(filepath.Join(dir, "sessions"))) + 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{} - for _, f := range list(filepath.Join(dir, "archived_sessions")) { + archived, _ := list(filepath.Join(dir, "archived_sessions")) + for _, f := range archived { threads[f.thread] = f } for _, files := range groups { @@ -119,9 +121,17 @@ func (s source) Sessions(since time.Time, skip func(id string, updated time.Time 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(i, len(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 @@ -133,14 +143,13 @@ func (s source) Sessions(since time.Time, skip func(id string, updated time.Time return } } - progress(len(sids), len(sids)) + progress(total, total) } } // list finds the rollout files under dir at all depths and reads the first line of each. -// A missing dir gives none. -func list(dir string) []rollout { - var out []rollout +// 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 { @@ -161,13 +170,16 @@ func list(dir string) []rollout { 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 + return out, unopened } // errNoMeta is the error of a rollout whose first line is not a session_meta line. diff --git a/core/session/importer/codex/codex_test.go b/core/session/importer/codex/codex_test.go index 97881dfe1..8603c39b8 100644 --- a/core/session/importer/codex/codex_test.go +++ b/core/session/importer/codex/codex_test.go @@ -349,10 +349,10 @@ 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}) { - t.Fatalf("ids = %v", got) + 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[0].Events) != 6 { - t.Errorf("tools session has %d events, want 6", len(all[0].Events)) + 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 index f71449be5..d3a58543a 100644 --- a/core/session/importer/codex/decisions_test.go +++ b/core/session/importer/codex/decisions_test.go @@ -174,3 +174,57 @@ func TestSource_ChildOnlySessionIsYielded(t *testing.T) { 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/turns.go b/core/session/importer/codex/turns.go index c9ba46739..4ef8935d4 100644 --- a/core/session/importer/codex/turns.go +++ b/core/session/importer/codex/turns.go @@ -188,6 +188,10 @@ func (p *parser) file(path, thread, subagent string, copied []usage, usagesOnly _ = 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"` @@ -234,7 +238,14 @@ func (p *parser) file(path, thread, subagent string, copied []usage, usagesOnly ReplacementHistory []json.RawMessage `json:"replacement_history"` } _ = json.Unmarshal(l.Payload, &c) - conv = append([]json.RawMessage{}, c.ReplacementHistory...) + conv = []json.RawMessage{} + for _, item := range c.ReplacementHistory { + if !validItem(item) { + res.skipped++ + continue + } + conv = append(conv, item) + } } } } @@ -248,6 +259,12 @@ func (p *parser) file(path, thread, subagent string, copied []usage, usagesOnly } } +// 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 +} + // responsesUsage is the usage block of a Responses API response. type responsesUsage struct { InputTokens int `json:"input_tokens"` From 231d529edc06072f63b70c368a327488d54213ab Mon Sep 17 00:00:00 2001 From: Hai Huang Date: Mon, 16 Nov 2026 21:58:05 -0500 Subject: [PATCH 11/14] fix: Record a Codex turn whose usage comes after an import Two review findings on the Codex source. 1. An import that runs while Codex waits for a tool result reads the open turn with no usage. The archive keeps that response. The next import then skipped the turn, because its request id was in the archived copy. So the cost of the turn never got to the ledger. readPrior now keeps only the ids of priced responses, and toLedger records only priced responses. A turn with no usage has no ledger row, and a later import adds the row when the usage is on disk. 2. A provider that sends no usage writes token_count with info null. Then the output of the next model call joined the open turn, after its held tool results. Now an output that comes after held tool results closes the open turn first. TestRun_LedgerGetsTurnWhoseUsageCameLater and TestSource_OutputAfterToolResultsIsANewCall fail without these fixes. Assisted-By: Claude (Anthropic AI) Signed-off-by: Hai Huang --- core/session/importer/codex/decisions_test.go | 35 +++++++++++++++++++ core/session/importer/codex/turns.go | 3 ++ core/session/importer/importer.go | 12 ++++--- core/session/importer/importer_test.go | 22 ++++++++++++ docs/session-api.md | 3 +- 5 files changed, 70 insertions(+), 5 deletions(-) diff --git a/core/session/importer/codex/decisions_test.go b/core/session/importer/codex/decisions_test.go index d3a58543a..1d458656b 100644 --- a/core/session/importer/codex/decisions_test.go +++ b/core/session/importer/codex/decisions_test.go @@ -133,6 +133,41 @@ func TestSource_TokenCountAfterToolResults(t *testing.T) { } } +// 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() diff --git a/core/session/importer/codex/turns.go b/core/session/importer/codex/turns.go index 4ef8935d4..5a81b4014 100644 --- a/core/session/importer/codex/turns.go +++ b/core/session/importer/codex/turns.go @@ -198,6 +198,9 @@ func (p *parser) file(path, thread, subagent string, copied []usage, usagesOnly } _ = 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 } 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/session-api.md b/docs/session-api.md index 27ccda2c1..79abba628 100644 --- a/docs/session-api.md +++ b/docs/session-api.md @@ -559,7 +559,8 @@ source imports nothing. - 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. + 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) From f41d5927e15ea29ab36d72757843da5deb62314d Mon Sep 17 00:00:00 2001 From: Hai Huang Date: Mon, 16 Nov 2026 22:10:40 -0500 Subject: [PATCH 12/14] fix(importer): Skip an unchanged Codex session before the parse Before the parse, the Codex source gave Rule 2 the mtime of the rollout. Codex writes each line after it takes the line's timestamp, so the mtime is always after the newest event. Rule 2 never skipped a session there, and each import parsed all of the Codex history again. The parse of one 1.7 MB rollout with 400 model calls takes 5 s. newestAt now reads each rollout of a session fast. It gives the newest token record that closes an open turn, or the newest model output. That is the Updated of the parse. Rule 2 then skips an unchanged session before the parse. The scan of the same rollout takes 18 ms. The claude source does the same with its newestAt. - TestSource_UnchangedSessionIsNotParsedAgain gives each fixture a real mtime, after its last line. It fails without the scan. - TestSource_NewestAtFollowsTheParse and the fork tests check that the scan gives the Updated of the parse for each turn boundary. - Two tests make the open of the parse fail. That open is now the third: the listing, the scan, the parse. Assisted-By: Claude (Anthropic AI) Signed-off-by: Hai Huang --- core/session/importer/codex/codex.go | 68 ++++++++++++ core/session/importer/codex/codex_test.go | 3 +- core/session/importer/codex/decisions_test.go | 3 +- core/session/importer/codex/fork_test.go | 1 + core/session/importer/codex/newest_test.go | 100 ++++++++++++++++++ 5 files changed, 173 insertions(+), 2 deletions(-) create mode 100644 core/session/importer/codex/newest_test.go diff --git a/core/session/importer/codex/codex.go b/core/session/importer/codex/codex.go index 5c579cdb7..01dc460d4 100644 --- a/core/session/importer/codex/codex.go +++ b/core/session/importer/codex/codex.go @@ -139,6 +139,11 @@ func (s source) Sessions(since time.Time, skip func(id string, updated time.Time 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 } @@ -212,6 +217,69 @@ func readMeta(path string) (rollout, error) { 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 { diff --git a/core/session/importer/codex/codex_test.go b/core/session/importer/codex/codex_test.go index 8603c39b8..fd7766401 100644 --- a/core/session/importer/codex/codex_test.go +++ b/core/session/importer/codex/codex_test.go @@ -338,7 +338,8 @@ func TestSource_CompressedRollout(t *testing.T) { func TestSource_UnreadableRootIsReported(t *testing.T) { dir := fixtures(t) - failOpens(t, func(path string, n int) bool { return strings.Contains(path, toolsID) && n == 2 }) + // 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) diff --git a/core/session/importer/codex/decisions_test.go b/core/session/importer/codex/decisions_test.go index 1d458656b..be06c7781 100644 --- a/core/session/importer/codex/decisions_test.go +++ b/core/session/importer/codex/decisions_test.go @@ -188,7 +188,8 @@ func TestSource_NewerRolloutOfAThreadWins(t *testing.T) { func TestSource_UnreadableChildIsSkipped(t *testing.T) { dir := fixtures(t) base := sessionByID(t, dir, toolsID) - failOpens(t, func(path string, n int) bool { return strings.Contains(path, subID) && n == 2 }) + // 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) diff --git a/core/session/importer/codex/fork_test.go b/core/session/importer/codex/fork_test.go index 99c335e2d..825dae981 100644 --- a/core/session/importer/codex/fork_test.go +++ b/core/session/importer/codex/fork_test.go @@ -111,6 +111,7 @@ func TestSource_ForkDoesNotRepeatParentTurns(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" { 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) + }) + } +} From bc9963bd08b434a3caa37ed09705afb01a7fc870 Mon Sep 17 00:00:00 2001 From: Hai Huang Date: Mon, 16 Nov 2026 22:17:45 -0500 Subject: [PATCH 13/14] docs(session-api): Say that a turn with no cost record has no ledger row The importer change of this PR applies to every source, not only to Codex. A Bob or Claude Code turn with no usage now makes no ledger row. The live proxy records such a turn as one request at $0. The doc now says this, so a difference between import counts and live counts has an explanation. Assisted-By: Claude (Anthropic AI) Signed-off-by: Hai Huang --- docs/session-api.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/session-api.md b/docs/session-api.md index 79abba628..2315f8482 100644 --- a/docs/session-api.md +++ b/docs/session-api.md @@ -487,6 +487,10 @@ only another session of the same project made a row in that minute. 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 From 09a4e662d3be0e574c0af9edf95be96ad0f976e9 Mon Sep 17 00:00:00 2001 From: Hai Huang Date: Mon, 16 Nov 2026 22:47:33 -0500 Subject: [PATCH 14/14] fix(importer): Leave a refused Codex output item out of the turn's response Fixes review: a tool_search_call with object arguments made the live response decoder refuse the whole body, so the turn lost its usage, tool calls and completion. Files: - core/session/importer/codex/turns.go - core/session/importer/codex/decisions_test.go Assisted-By: Claude (Anthropic AI) Signed-off-by: Hai Huang --- core/session/importer/codex/decisions_test.go | 39 +++++++++++++++++++ core/session/importer/codex/turns.go | 10 ++++- 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/core/session/importer/codex/decisions_test.go b/core/session/importer/codex/decisions_test.go index be06c7781..fa2c52d6b 100644 --- a/core/session/importer/codex/decisions_test.go +++ b/core/session/importer/codex/decisions_test.go @@ -133,6 +133,45 @@ func TestSource_TokenCountAfterToolResults(t *testing.T) { } } +// 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) { diff --git a/core/session/importer/codex/turns.go b/core/session/importer/codex/turns.go index 5a81b4014..5de04e192 100644 --- a/core/session/importer/codex/turns.go +++ b/core/session/importer/codex/turns.go @@ -135,7 +135,7 @@ func (p *parser) file(path, thread, subagent string, copied []usage, usagesOnly Model string `json:"model"` Output []json.RawMessage `json:"output"` Usage *responsesUsage `json:"usage,omitempty"` - }{mdl, turnOut, toResponsesUsage(u)}) + }{mdl, slices.DeleteFunc(slices.Clone(turnOut), invalidOutput), toResponsesUsage(u)}) resp := *req inference.ReadResponse(responsesPath, false, respBody, &resp) if th := thinking(turnOut); th.Blocks > 0 { @@ -268,6 +268,14 @@ 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"`