Skip to main content

agent_top_core/harness/
codex.rs

1//! OpenAI Codex CLI: `~/.codex/sessions/YYYY/MM/DD/rollout-<ts>-<id>.jsonl`.
2//!
3//! Format notes (verified on Codex CLI 0.149, 2026-09-03):
4//! * The first line is `session_meta` with `payload.cwd`, `payload.id`,
5//!   `payload.cli_version` and `payload.originator`.
6//! * `event_msg` / `token_count` carries `info.total_token_usage`, which is
7//!   cumulative for the session; `info` is null on rate-limit-only events.
8//!   `input_tokens` includes `cached_input_tokens`.
9//! * `task_started` / `task_complete` / `turn_aborted` bracket a turn.
10//! * `response_item` with `payload.type` `function_call` or
11//!   `custom_tool_call` is one tool call; the matching `*_output` item
12//!   carries the same `payload.call_id`, and the two lines' timestamps
13//!   bracket the call. That pairing is the trace.
14//! * `task_started` and `task_complete` bracket a turn span. An inference
15//!   span runs from a user `message` item or a `*_output` item to the next
16//!   thing the model produced: a call, a `reasoning` item, a
17//!   `web_search_call`, or an assistant `message`.
18//! * `response_item` `web_search_call` is one server-side web search.
19//!
20//! Codex model prices are not in the static table, so cost is reported as
21//! unpriced tokens.
22
23use super::{AttributeContext, HarnessAdapter, REFRESH_BUDGET_BYTES, SessionSummary, SessionTracker, SpanRetention, parse_rfc3339_utc};
24use crate::jsonl::TailReader;
25use crate::model::{Activity, Attribution, Harness, ProcNode, SpanKind, TokenUsage};
26use crate::pricing::{self, Table};
27use crate::process::RawProc;
28use serde_json::Value;
29use std::collections::{HashMap, HashSet};
30use std::path::{Path, PathBuf};
31use std::time::{Duration, SystemTime};
32
33pub fn codex_dir() -> Option<PathBuf> {
34    if let Some(d) = std::env::var_os("CODEX_HOME") {
35        return Some(PathBuf::from(d));
36    }
37    std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".codex"))
38}
39
40pub fn sessions_dir() -> Option<PathBuf> {
41    codex_dir().map(|d| d.join("sessions"))
42}
43
44/// Rollout files modified after `since`. Walks `YYYY/MM/DD` and prunes by
45/// directory mtime so the walk stays cheap on a long history.
46/// Rollouts the process has open: the app-server's live threads, or the CLI's
47/// one conversation. `None` when the platform cannot say. Filtered to the
48/// sessions directory so an unrelated file the process holds (a log, a
49/// config) is never mistaken for a thread, and mapped back under the
50/// un-canonicalised sessions directory so the paths compare equal to those
51/// from `recent_rollouts`.
52pub fn rollouts_open_by(pid: u32) -> Option<Vec<PathBuf>> {
53    let root = sessions_dir()?;
54    let canonical = std::fs::canonicalize(&root).unwrap_or_else(|_| root.clone());
55    let open = crate::openfiles::open_files(pid)?;
56    Some(
57        open.into_iter()
58            .filter(|p| p.extension().and_then(|x| x.to_str()) == Some("jsonl"))
59            .filter_map(|p| p.strip_prefix(&canonical).ok().map(|rel| root.join(rel)))
60            .collect(),
61    )
62}
63
64/// Every rollout written since `since`.
65pub fn recent_rollouts(since: SystemTime) -> Vec<PathBuf> {
66    let Some(root) = sessions_dir() else { return Vec::new() };
67    rollouts_under(&root, since)
68}
69
70/// The tree is `YYYY/MM/DD/*.jsonl` and is walked in full, three levels deep,
71/// with only the files filtered by mtime. Pruning directories by their mtime
72/// looked cheaper and was wrong: a directory's mtime moves only when an entry
73/// is created directly inside it, so the year directory is touched once a
74/// month and every rollout written after the first of the month was invisible.
75/// Pruning by name would be wrong too, since a directory's date says when a
76/// thread started, not whether it is still being written to; the app-server
77/// keeps a thread for days. A few hundred directories cost a few milliseconds.
78pub(crate) fn rollouts_under(root: &Path, since: SystemTime) -> Vec<PathBuf> {
79    let mut out = Vec::new();
80    walk(root, 0, since, &mut out);
81    out
82}
83
84fn walk(dir: &Path, depth: usize, since: SystemTime, out: &mut Vec<PathBuf>) {
85    let Ok(rd) = std::fs::read_dir(dir) else { return };
86    for e in rd.flatten() {
87        let p = e.path();
88        let Ok(md) = e.metadata() else { continue };
89        if md.is_dir() {
90            if depth < 3 {
91                walk(&p, depth + 1, since, out);
92            }
93        } else if p.extension().and_then(|x| x.to_str()) == Some("jsonl") && md.modified().map(|m| m >= since).unwrap_or(false) {
94            out.push(p);
95        }
96    }
97}
98
99/// Cheap header read: cwd and start time from the first line only.
100pub fn read_meta(path: &Path) -> Option<(PathBuf, SystemTime)> {
101    use std::io::{BufRead, BufReader};
102    let f = std::fs::File::open(path).ok()?;
103    let mut first = String::new();
104    BufReader::new(f).read_line(&mut first).ok()?;
105    let v: Value = serde_json::from_str(&first).ok()?;
106    if v.get("type").and_then(Value::as_str) != Some("session_meta") {
107        return None;
108    }
109    let cwd = v.pointer("/payload/cwd").and_then(Value::as_str).map(PathBuf::from)?;
110    let ts = v.get("timestamp").and_then(Value::as_str).and_then(parse_rfc3339_utc)?;
111    Some((cwd, ts))
112}
113
114/// The Codex adapter: a process is matched to the rollouts it holds open,
115/// and only where the platform cannot say to the cwd and activity heuristics.
116/// See DEC-006.
117#[derive(Default)]
118pub struct CodexAdapter {
119    /// Recent rollouts with the cwd and start time from their header.
120    recent: Vec<(PathBuf, PathBuf, SystemTime)>,
121    /// Which rollouts each Codex process has open, gathered before any
122    /// attribution so that no process's fallback can claim a thread another
123    /// process is demonstrably writing. `None` when the platform cannot say.
124    held: HashMap<u32, Option<Vec<PathBuf>>>,
125    all_held: HashSet<PathBuf>,
126}
127
128impl HarnessAdapter for CodexAdapter {
129    fn harness(&self) -> Harness {
130        Harness::Codex
131    }
132
133    fn rescan(&mut self, since: SystemTime) {
134        self.recent = recent_rollouts(since).into_iter().filter_map(|p| read_meta(&p).map(|(cwd, ts)| (p, cwd, ts))).collect();
135    }
136
137    fn prepare(&mut self, roots: &[&ProcNode]) {
138        self.held = roots.iter().map(|r| (r.pid, rollouts_open_by(r.pid))).collect();
139        self.all_held = self.held.values().flatten().flatten().cloned().collect();
140    }
141
142    fn attribute(&self, root: &ProcNode, _raw: Option<&RawProc>, ctx: &AttributeContext) -> (Vec<PathBuf>, Attribution) {
143        let mine: Option<Vec<PathBuf>> =
144            self.held.get(&root.pid).and_then(|h| h.as_ref()).map(|h| h.iter().filter(|p| !ctx.attached.contains(*p)).cloned().collect());
145        let taken: HashSet<PathBuf> = ctx.attached.union(&self.all_held).cloned().collect();
146        attribute(ctx.cwd, ctx.proc_start, mine.as_deref(), &self.recent, &taken, ctx.now, ctx.activity_timeout)
147    }
148
149    fn unowned(&self, attached: &HashSet<PathBuf>) -> Vec<PathBuf> {
150        self.recent.iter().map(|(p, _, _)| p).filter(|p| !attached.contains(*p)).cloned().collect()
151    }
152
153    fn open(&self, path: &Path, spans: SpanRetention) -> Box<dyn SessionTracker> {
154        Box::new(CodexTranscript::new(path).with_spans(spans))
155    }
156
157    /// Every rollout opens with a `session_meta` record.
158    fn detect(&self, path: &Path) -> bool {
159        super::head_lines(path).iter().any(|v| v.get("type").and_then(Value::as_str) == Some("session_meta"))
160    }
161
162    fn transcripts(&self) -> Vec<(String, PathBuf)> {
163        recent_rollouts(SystemTime::UNIX_EPOCH).into_iter().map(|p| (rollout_id(&p), p)).collect()
164    }
165}
166
167/// The id in `rollout-2026-05-14T21-37-50-<id>`: what follows the fixed-width
168/// timestamp. A file named some other way is matched on its whole stem.
169pub fn rollout_id(p: &Path) -> String {
170    const TS_LEN: usize = "2026-05-14T21-37-50-".len();
171    let stem = p.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
172    stem.strip_prefix("rollout-").and_then(|s| s.get(TS_LEN..)).map(str::to_string).unwrap_or(stem)
173}
174
175/// Codex conversations belonging to one process, newest activity first.
176///
177/// `held` are the rollouts the process has open, which is not a guess: Codex
178/// opens a thread's rollout when the thread starts and closes it when the
179/// thread ends. When the platform can say (`Some`), that list is the answer,
180/// an empty one included: a process holding no rollout is hosting no thread,
181/// and a rollout nobody holds is a finished conversation for the stopped
182/// list. The heuristics below are for when it cannot (`None`).
183///
184/// A `codex` CLI runs one conversation from the directory it was started in, so
185/// a cwd match finds it. The VS Code app-server is a different shape: one
186/// long-lived process, running from `/`, hosting any number of conversations
187/// over its life. Returning a single rollout for it collapses every one of
188/// those into one row and attributes whichever happened to be newest, so this
189/// returns all of them that are currently live and lets the caller give each
190/// its own row.
191///
192/// A rollout in `taken` is skipped: one already claimed by another process,
193/// or one some process has open, so that two Codex processes cannot both
194/// show the same conversation and an older app-server cannot collect the
195/// threads of a newer one.
196pub(crate) fn attribute(
197    cwd: Option<&Path>,
198    proc_start: SystemTime,
199    held: Option<&[PathBuf]>,
200    recent: &[(PathBuf, PathBuf, SystemTime)],
201    taken: &HashSet<PathBuf>,
202    now: SystemTime,
203    activity_timeout: Duration,
204) -> (Vec<PathBuf>, Attribution) {
205    if let Some(held) = held {
206        let mut mine = held.to_vec();
207        mine.sort_by_key(|p| std::cmp::Reverse(written_at(p)));
208        mine.truncate(MAX_THREADS);
209        let attribution = if mine.is_empty() { Attribution::None } else { Attribution::OpenFile };
210        return (mine, attribution);
211    }
212
213    let slack = Duration::from_secs(60);
214    let started_after = |ts: &SystemTime| *ts + slack >= proc_start;
215    let candidates = || recent.iter().filter(|(p, _, ts)| started_after(ts) && !taken.contains(p));
216
217    // The CLI case: the conversation runs where the process runs.
218    if let Some(cwd) = cwd {
219        let mut matched: Vec<&(PathBuf, PathBuf, SystemTime)> = candidates().filter(|(_, c, _)| c == cwd).collect();
220        if !matched.is_empty() {
221            matched.sort_by_key(|(p, _, _)| std::cmp::Reverse(written_at(p)));
222            return (matched.into_iter().map(|(p, _, _)| p.clone()).collect(), Attribution::CwdHeuristic);
223        }
224    }
225
226    // The app-server case: no cwd to match on, so take the conversations that
227    // are actually being written to. A rollout nobody has touched in a while is
228    // a finished conversation, not a thread of this process.
229    let mut live: Vec<&(PathBuf, PathBuf, SystemTime)> = candidates()
230        .filter(|(p, _, _)| written_at(p).map(|w| now.duration_since(w).unwrap_or_default() <= activity_timeout).unwrap_or(false))
231        .collect();
232    live.sort_by_key(|(p, _, _)| std::cmp::Reverse(written_at(p)));
233    live.truncate(MAX_THREADS);
234    let attribution = if live.is_empty() { Attribution::None } else { Attribution::CwdHeuristic };
235    (live.into_iter().map(|(p, _, _)| p.clone()).collect(), attribution)
236}
237
238/// One process is not plausibly running more conversations than this at once,
239/// and an unbounded fan-out would let a stale directory fill the table.
240const MAX_THREADS: usize = 12;
241
242fn written_at(p: &Path) -> Option<SystemTime> {
243    std::fs::metadata(p).and_then(|m| m.modified()).ok()
244}
245
246pub struct CodexTranscript {
247    reader: TailReader,
248    prices: &'static Table,
249    summary: SessionSummary,
250    /// Counters naming the turn and inference spans, and the ids of the ones
251    /// currently being extended.
252    turns: u64,
253    inferences: u64,
254    turn: Option<String>,
255    inference: Option<String>,
256}
257
258impl CodexTranscript {
259    pub fn new(path: impl Into<PathBuf>) -> Self {
260        CodexTranscript {
261            reader: TailReader::new(path),
262            prices: pricing::table(),
263            summary: SessionSummary { harness: Some(Harness::Codex), ..Default::default() },
264            turns: 0,
265            inferences: 0,
266            turn: None,
267            inference: None,
268        }
269    }
270
271    /// Something was submitted to the model. One inference at a time: a
272    /// developer message followed by a user message is one submission.
273    fn begin_inference(&mut self, ts: SystemTime) {
274        if self.summary.spans.open_of_kind(SpanKind::Inference).is_some() {
275            return;
276        }
277        // A turn that ended without the model replying (aborted) leaves the
278        // previous inference open; it produced nothing, so it goes.
279        if let Some(id) = self.inference.take() {
280            self.summary.spans.discard_open(&id);
281        }
282        self.inferences += 1;
283        let id = format!("inference:{}", self.inferences);
284        self.summary.spans.open_kind(id.clone(), "inference".into(), ts, false, SpanKind::Inference);
285        self.inference = Some(id);
286    }
287
288    /// The model produced something: the inference in progress ends here.
289    fn end_inference(&mut self, ts: SystemTime) {
290        if let Some(id) = self.inference.take() {
291            self.summary.spans.end_at(&id, ts);
292        }
293    }
294
295    /// See `ClaudeTranscript::with_prices`.
296    pub fn with_prices(mut self, prices: &'static Table) -> Self {
297        self.prices = prices;
298        self
299    }
300
301    /// Keep every span instead of the newest `MAX_SPANS`. See `SpanRetention`.
302    pub fn with_spans(mut self, retention: SpanRetention) -> Self {
303        self.summary.spans = retention.log();
304        self
305    }
306
307    fn ingest(&mut self, line: &str) {
308        let Ok(v) = serde_json::from_str::<Value>(line) else { return };
309        let ts = v.get("timestamp").and_then(Value::as_str).and_then(parse_rfc3339_utc);
310        if let Some(ts) = ts {
311            if self.summary.started_at.is_none() {
312                self.summary.started_at = Some(ts);
313            }
314            self.summary.last_activity = Some(ts);
315        }
316        let kind = v.get("type").and_then(Value::as_str).unwrap_or("");
317        let payload = v.get("payload");
318        let ptype = payload.and_then(|p| p.get("type")).and_then(Value::as_str).unwrap_or("");
319        match kind {
320            "session_meta" => {
321                if let Some(p) = payload {
322                    self.summary.session_id = p.get("id").or(p.get("session_id")).and_then(Value::as_str).map(str::to_string);
323                    self.summary.cwd = p.get("cwd").and_then(Value::as_str).map(PathBuf::from);
324                    self.summary.harness_version = p.get("cli_version").and_then(Value::as_str).map(str::to_string);
325                }
326            }
327            "turn_context" => {
328                if let Some(m) = payload.and_then(|p| p.get("model")).and_then(Value::as_str) {
329                    self.summary.model = Some(m.to_string());
330                }
331            }
332            "event_msg" => match ptype {
333                "token_count" => {
334                    if let Some(total) = payload.and_then(|p| p.pointer("/info/total_token_usage")) {
335                        let g = |k: &str| total.get(k).and_then(Value::as_u64).unwrap_or(0);
336                        self.summary.health.usage_records += 1;
337                        if g("input_tokens") + g("output_tokens") + g("cached_input_tokens") == 0 {
338                            self.summary.health.empty_usage_records += 1;
339                        }
340                        let cached = g("cached_input_tokens");
341                        let usage = TokenUsage {
342                            input: g("input_tokens").saturating_sub(cached),
343                            cache_read: cached,
344                            output: g("output_tokens"),
345                            ..Default::default()
346                        };
347                        self.summary.usage = usage;
348                        let price = self.summary.model.as_deref().and_then(|m| self.prices.lookup(m));
349                        match price {
350                            Some(p) => {
351                                self.summary.cost_breakdown = p.breakdown(&usage);
352                                self.summary.cost_usd = self.summary.cost_breakdown.total();
353                                self.summary.unpriced_tokens = 0;
354                            }
355                            None => {
356                                self.summary.cost_breakdown = Default::default();
357                                self.summary.cost_usd = 0.0;
358                                self.summary.unpriced_tokens = usage.total();
359                            }
360                        }
361                    }
362                    // The rate-limit snapshot rides on every token_count; the
363                    // latest one is the current state.
364                    if let Some(rl) = payload.and_then(|p| p.get("rate_limits")).filter(|v| v.is_object()) {
365                        self.summary.rate_limit = Some(parse_rate_limits(rl));
366                    }
367                }
368                "task_started" => {
369                    self.summary.activity = Activity::Working;
370                    if let Some(ts) = ts {
371                        self.turns += 1;
372                        let id = format!("turn:{}", self.turns);
373                        self.summary.spans.open_kind(id.clone(), "turn".into(), ts, false, SpanKind::Turn);
374                        self.turn = Some(id);
375                    }
376                }
377                "user_message" => self.summary.activity = Activity::Working,
378                // An MCP tool call. Codex records the call as a `response_item`
379                // `function_call` too, which the block below counts as a tool
380                // call and turns into a span; this line is the only one that
381                // names the server, so it feeds the per-server map and nothing
382                // else, to avoid double counting. `mcp_tool_call_begin` carries
383                // the same `invocation`; the pair brackets the call, but the
384                // `end` alone is enough for a count and is the one always
385                // present in the versions seen.
386                "mcp_tool_call_end" => {
387                    if let Some(inv) = payload.and_then(|p| p.get("invocation"))
388                        && let Some(server) = inv.get("server").and_then(Value::as_str).filter(|s| !s.is_empty())
389                    {
390                        let error = payload
391                            .and_then(|p| p.get("result"))
392                            .and_then(Value::as_object)
393                            .map(|r| !r.contains_key("Ok"))
394                            .unwrap_or(false);
395                        let u = self.summary.mcp.entry(server.to_string()).or_default();
396                        u.calls += 1;
397                        u.errors += u64::from(error);
398                        u.last_call = u.last_call.max(ts);
399                    }
400                }
401                "task_complete" | "turn_aborted" | "error" => {
402                    self.summary.activity = Activity::Waiting;
403                    if let (Some(ts), Some(id)) = (ts, self.turn.take()) {
404                        self.summary.spans.end_at(&id, ts);
405                    }
406                    if let Some(id) = self.inference.take() {
407                        self.summary.spans.discard_open(&id);
408                    }
409                }
410                _ => {}
411            },
412            "response_item" => match ptype {
413                "function_call" | "custom_tool_call" | "local_shell_call" => {
414                    self.summary.tool_calls += 1;
415                    if let (Some(ts), Some(p)) = (ts, payload) {
416                        self.end_inference(ts);
417                        let id = call_id(p);
418                        let name = p.get("name").and_then(Value::as_str).unwrap_or(ptype);
419                        self.summary.spans.open(id, name.to_string(), ts, false);
420                    }
421                }
422                "function_call_output" | "custom_tool_call_output" | "local_shell_call_output" => {
423                    if let (Some(ts), Some(p)) = (ts, payload) {
424                        // Codex reports the result as an opaque string, and
425                        // agent-top does not read tool output, so a failed call
426                        // is not distinguishable from a successful one here.
427                        self.summary.spans.close(&call_id(p), ts, false);
428                        self.begin_inference(ts);
429                    }
430                }
431                // A server-side web search: billed per search by OpenAI, but
432                // at a rate this table does not carry, so counted only.
433                "web_search_call" => {
434                    self.summary.web_searches += 1;
435                    if let Some(ts) = ts {
436                        self.end_inference(ts);
437                    }
438                }
439                "reasoning" => {
440                    if let Some(ts) = ts {
441                        self.end_inference(ts);
442                    }
443                }
444                "message" => match payload.and_then(|p| p.get("role")).and_then(Value::as_str) {
445                    Some("assistant") => {
446                        self.summary.turns += 1;
447                        self.summary.health.billable_messages += 1;
448                        if let Some(ts) = ts {
449                            self.end_inference(ts);
450                        }
451                    }
452                    Some("user") => {
453                        if let Some(ts) = ts {
454                            self.begin_inference(ts);
455                        }
456                    }
457                    _ => {}
458                },
459                _ => {}
460            },
461            _ => {}
462        }
463    }
464}
465
466/// Codex's `rate_limits`: a short window (`primary`) and a long one
467/// (`secondary`), each a used-percent, a window length and a reset time in
468/// epoch seconds, plus the plan and whether the limit is currently hit.
469fn parse_rate_limits(v: &Value) -> crate::model::RateLimit {
470    use crate::model::{RateLimit, RateWindow};
471    let window = |w: Option<&Value>| -> Option<RateWindow> {
472        let w = w?;
473        Some(RateWindow {
474            used_percent: w.get("used_percent").and_then(Value::as_f64).unwrap_or(0.0),
475            window_minutes: w.get("window_minutes").and_then(Value::as_u64).unwrap_or(0),
476            resets_at: w
477                .get("resets_at")
478                .and_then(Value::as_i64)
479                .filter(|s| *s > 0)
480                .map(|s| std::time::UNIX_EPOCH + std::time::Duration::from_secs(s as u64)),
481        })
482    };
483    RateLimit {
484        primary: window(v.get("primary")),
485        secondary: window(v.get("secondary")),
486        plan: v.get("plan_type").and_then(Value::as_str).map(str::to_string),
487        reached: v.get("rate_limit_reached_type").map(|x| !x.is_null()).unwrap_or(false),
488    }
489}
490
491/// `call_id` on function calls, `id` on the shell-call variants.
492fn call_id(payload: &Value) -> String {
493    payload.get("call_id").or_else(|| payload.get("id")).and_then(Value::as_str).unwrap_or_default().to_string()
494}
495
496impl SessionTracker for CodexTranscript {
497    fn refresh(&mut self) -> anyhow::Result<bool> {
498        let (lines, more) = self.reader.read_new_lines(REFRESH_BUDGET_BYTES)?;
499        for l in &lines {
500            self.ingest(l);
501        }
502        Ok(more)
503    }
504
505    fn summary(&self) -> &SessionSummary {
506        &self.summary
507    }
508
509    fn path(&self) -> &Path {
510        self.reader.path()
511    }
512}
513
514#[cfg(test)]
515mod tests {
516    use super::*;
517    use std::io::Write;
518    use std::time::Duration;
519
520    /// The bug this guards: the year and month directories were last touched
521    /// when a child directory was created, long before the rollout of
522    /// interest was written.
523    /// Write a rollout with an explicit modification time.
524    ///
525    /// Ordering must not be left to how finely the filesystem happens to
526    /// timestamp three writes microseconds apart: Linux gave all three the
527    /// same mtime, the stable sort preserved insertion order, and the test
528    /// failed there while passing on macOS.
529    fn rollout(dir: &Path, name: &str, written: SystemTime) -> PathBuf {
530        let p = dir.join(name);
531        std::fs::write(&p, b"x").unwrap();
532        let f = std::fs::File::options().write(true).open(&p).unwrap();
533        f.set_times(std::fs::FileTimes::new().set_accessed(written).set_modified(written)).unwrap();
534        p
535    }
536
537    const TIMEOUT: Duration = Duration::from_secs(15 * 60);
538
539    /// One app-server, several conversations. Every live one must get a row:
540    /// returning only the newest is what collapsed them into a single
541    /// mis-attributed row.
542    #[test]
543    fn every_live_codex_thread_is_returned_newest_first() {
544        let dir = std::env::temp_dir().join(format!("agent-top-threads-{}", std::process::id()));
545        let _ = std::fs::remove_dir_all(&dir);
546        std::fs::create_dir_all(&dir).unwrap();
547        let now = SystemTime::now();
548        let started = now - Duration::from_secs(600);
549
550        // Distinct write times, oldest first, so "newest first" has a single
551        // correct answer.
552        let a = rollout(&dir, "a.jsonl", now - Duration::from_secs(300));
553        let b = rollout(&dir, "b.jsonl", now - Duration::from_secs(200));
554        let c = rollout(&dir, "c.jsonl", now - Duration::from_secs(100));
555        let recent: Vec<(PathBuf, PathBuf, SystemTime)> =
556            [&a, &b, &c].iter().map(|p| ((*p).clone(), PathBuf::from("/Users/dev/code/one"), started)).collect();
557
558        // The app-server case: the process cwd matches no conversation.
559        let (paths, attribution) = attribute(Some(Path::new("/")), started, None, &recent, &HashSet::new(), now, TIMEOUT);
560        assert_eq!(paths.len(), 3, "all three conversations get a row");
561        assert_eq!(paths[0], c, "newest activity first");
562        assert_eq!(attribution, Attribution::CwdHeuristic, "still a heuristic, and still labelled one");
563
564        // A conversation already claimed by another process is not shown twice.
565        let taken: HashSet<PathBuf> = [c.clone()].into_iter().collect();
566        let (paths, _) = attribute(Some(Path::new("/")), started, None, &recent, &taken, now, TIMEOUT);
567        assert_eq!(paths.len(), 2);
568        assert!(!paths.contains(&c));
569
570        // A conversation nobody has written to for longer than the activity
571        // window has finished; it belongs in the stopped list, not on this
572        // process.
573        let stale = now + TIMEOUT + Duration::from_secs(60);
574        let (paths, attribution) = attribute(Some(Path::new("/")), started, None, &recent, &HashSet::new(), stale, TIMEOUT);
575        assert!(paths.is_empty());
576        assert_eq!(attribution, Attribution::None);
577
578        // The CLI case: one conversation, in the directory the process runs in.
579        let (paths, _) = attribute(Some(Path::new("/Users/dev/code/one")), started, None, &recent, &HashSet::new(), now, TIMEOUT);
580        assert_eq!(paths.len(), 3, "a cwd match takes every conversation in that directory");
581        assert_eq!(paths[0], c);
582
583        // A rollout that predates the process is not this process's.
584        let (paths, _) = attribute(Some(Path::new("/")), now + Duration::from_secs(3600), None, &recent, &HashSet::new(), now, TIMEOUT);
585        assert!(paths.is_empty());
586
587        let _ = std::fs::remove_dir_all(&dir);
588    }
589
590    /// Two app-servers at once, the VS Code one and a CLI-spawned one, both
591    /// running from `/`. Without the open-file signal the one asked first
592    /// took every live thread. The bug this guards was found live on
593    /// 2026-09-04: two threads of a fresh app-server were shown on the four
594    /// day old VS Code one.
595    #[test]
596    fn an_open_rollout_belongs_to_the_process_holding_it() {
597        let dir = std::env::temp_dir().join(format!("agent-top-held-{}", std::process::id()));
598        let _ = std::fs::remove_dir_all(&dir);
599        std::fs::create_dir_all(&dir).unwrap();
600        let now = SystemTime::now();
601        let started = now - Duration::from_secs(600);
602        let a = rollout(&dir, "a.jsonl", now - Duration::from_secs(200));
603        let b = rollout(&dir, "b.jsonl", now - Duration::from_secs(100));
604        let recent: Vec<(PathBuf, PathBuf, SystemTime)> =
605            [&a, &b].iter().map(|p| ((*p).clone(), PathBuf::from("/Users/dev/code/one"), started)).collect();
606
607        // The newer app-server holds both rollouts open. It started after the
608        // rollouts' recorded start, which the heuristic would reject; the open
609        // file settles it.
610        let held = vec![a.clone(), b.clone()];
611        let (paths, attribution) = attribute(Some(Path::new("/")), now, Some(&held), &recent, &HashSet::new(), now, TIMEOUT);
612        assert_eq!(paths, vec![b.clone(), a.clone()], "held rollouts, newest written first");
613        assert_eq!(attribution, Attribution::OpenFile);
614
615        // The older app-server holds nothing. Its fallback would have taken
616        // both live rollouts; with them marked taken it gets no row.
617        let taken: HashSet<PathBuf> = held.iter().cloned().collect();
618        let (paths, attribution) = attribute(Some(Path::new("/")), started, None, &recent, &taken, now, TIMEOUT);
619        assert!(paths.is_empty());
620        assert_eq!(attribution, Attribution::None);
621
622        let _ = std::fs::remove_dir_all(&dir);
623    }
624
625    #[test]
626    fn the_rollout_id_follows_the_timestamp() {
627        assert_eq!(
628            rollout_id(Path::new("/x/2026/05/14/rollout-2026-05-14T21-37-50-01000000-0000-7000-0000-000000000000.jsonl")),
629            "01000000-0000-7000-0000-000000000000"
630        );
631        assert_eq!(rollout_id(Path::new("/x/odd.jsonl")), "odd");
632    }
633
634    #[test]
635    fn finds_a_fresh_rollout_under_stale_directories() {
636        let root = std::env::temp_dir().join(format!("agent-top-rollouts-{}", std::process::id()));
637        let day = root.join("2026").join("09").join("04");
638        std::fs::create_dir_all(&day).unwrap();
639        let fresh = day.join("rollout-fresh.jsonl");
640        let stale = day.join("rollout-stale.jsonl");
641        std::fs::write(&fresh, "{}\n").unwrap();
642        std::fs::write(&stale, "{}\n").unwrap();
643        let now = SystemTime::now();
644        let long_ago = now - Duration::from_secs(40 * 86_400);
645        std::fs::File::open(&stale).unwrap().set_modified(long_ago).unwrap();
646        for dir in [&root, &root.join("2026"), &root.join("2026").join("09"), &day] {
647            std::fs::File::open(dir).unwrap().set_modified(long_ago).unwrap();
648        }
649        let found = rollouts_under(&root, now - Duration::from_secs(1800));
650        assert_eq!(found, vec![fresh], "the fresh file is found through directories nobody has touched in weeks");
651        std::fs::remove_dir_all(&root).unwrap();
652    }
653
654    #[test]
655    fn reads_the_latest_rate_limit_snapshot() {
656        let dir = std::env::temp_dir().join(format!("agent-top-codex-rl-{}", std::process::id()));
657        std::fs::create_dir_all(&dir).unwrap();
658        let path = dir.join("rollout.jsonl");
659        let mut f = std::fs::File::create(&path).unwrap();
660        writeln!(f, r#"{{"timestamp":"2026-06-16T20:45:04.000Z","type":"event_msg","payload":{{"type":"token_count","info":{{"total_token_usage":{{"input_tokens":10,"output_tokens":1,"total_tokens":11}}}},"rate_limits":{{"limit_id":"codex","primary":{{"used_percent":1.0,"window_minutes":300,"resets_at":1781660699}},"secondary":{{"used_percent":27.0,"window_minutes":10080,"resets_at":1782080576}},"plan_type":"plus","rate_limit_reached_type":null}}}}}}"#).unwrap();
661        // A later snapshot with higher usage; the latest wins.
662        writeln!(f, r#"{{"timestamp":"2026-06-16T20:50:00.000Z","type":"event_msg","payload":{{"type":"token_count","info":{{"total_token_usage":{{"input_tokens":20,"output_tokens":2,"total_tokens":22}}}},"rate_limits":{{"limit_id":"codex","primary":{{"used_percent":42.0,"window_minutes":300,"resets_at":1781660999}},"secondary":{{"used_percent":28.0,"window_minutes":10080,"resets_at":1782080576}},"plan_type":"plus","rate_limit_reached_type":"primary"}}}}}}"#).unwrap();
663        let mut t = CodexTranscript::new(&path);
664        t.refresh().unwrap();
665        let rl = t.summary().rate_limit.as_ref().expect("rate limit parsed");
666        assert_eq!(rl.plan.as_deref(), Some("plus"));
667        assert!(rl.reached, "the latest snapshot reports the primary window hit");
668        let p = rl.primary.expect("primary window");
669        assert_eq!(p.used_percent, 42.0, "the latest value, not the first");
670        assert_eq!(p.window_minutes, 300);
671        assert_eq!(rl.secondary.unwrap().used_percent, 28.0);
672        assert_eq!(rl.tightest().map(|w| w.used_percent), Some(42.0));
673        let _ = std::fs::remove_dir_all(&dir);
674    }
675
676    #[test]
677    fn counts_mcp_calls_per_server_from_the_end_event() {
678        let dir = std::env::temp_dir().join(format!("agent-top-codex-mcp-{}", std::process::id()));
679        std::fs::create_dir_all(&dir).unwrap();
680        let path = dir.join("rollout.jsonl");
681        let mut f = std::fs::File::create(&path).unwrap();
682        // Two MCP servers, one call failing. The matching response_item
683        // function_call/output pair is what makes the tool-call count and span;
684        // the mcp_tool_call_end is the only line naming the server.
685        writeln!(f, r#"{{"timestamp":"2026-05-27T09:00:01.000Z","type":"response_item","payload":{{"type":"function_call","call_id":"c1","name":"github_fetch_file"}}}}"#).unwrap();
686        writeln!(f, r#"{{"timestamp":"2026-05-27T09:00:02.000Z","type":"response_item","payload":{{"type":"function_call_output","call_id":"c1"}}}}"#).unwrap();
687        writeln!(f, r#"{{"timestamp":"2026-05-27T09:00:02.100Z","type":"event_msg","payload":{{"type":"mcp_tool_call_end","call_id":"c1","invocation":{{"server":"codex_apps","tool":"github_fetch_file"}},"duration":{{"secs":1,"nanos":0}},"result":{{"Ok":{{}}}}}}}}"#).unwrap();
688        writeln!(f, r#"{{"timestamp":"2026-05-27T09:00:05.000Z","type":"event_msg","payload":{{"type":"mcp_tool_call_end","call_id":"c2","invocation":{{"server":"codex_apps","tool":"github_search"}},"duration":{{"secs":0,"nanos":0}},"result":{{"Err":"boom"}}}}}}"#).unwrap();
689        writeln!(f, r#"{{"timestamp":"2026-05-27T09:00:07.000Z","type":"event_msg","payload":{{"type":"mcp_tool_call_end","call_id":"c3","invocation":{{"server":"node_repl","tool":"js"}},"duration":{{"secs":0,"nanos":0}},"result":{{"Ok":{{}}}}}}}}"#).unwrap();
690        let mut t = CodexTranscript::new(&path);
691        t.refresh().unwrap();
692        let s = t.summary();
693        assert_eq!(s.mcp.len(), 2);
694        let apps = &s.mcp["codex_apps"];
695        assert_eq!((apps.calls, apps.errors), (2, 1));
696        assert_eq!(apps.last_call, parse_rfc3339_utc("2026-05-27T09:00:05.000Z"));
697        assert_eq!(s.mcp["node_repl"].calls, 1);
698        // The one call with a response_item pair is one tool call and one span;
699        // the mcp_tool_call_end lines do not add to that.
700        assert_eq!(s.tool_calls, 1, "mcp_tool_call_end must not double-count tool calls");
701        let _ = std::fs::remove_dir_all(&dir);
702    }
703
704    #[test]
705    fn reads_cumulative_usage_and_state() {
706        let dir = std::env::temp_dir().join(format!("agent-top-codex-{}", std::process::id()));
707        std::fs::create_dir_all(&dir).unwrap();
708        let path = dir.join("rollout.jsonl");
709        let mut f = std::fs::File::create(&path).unwrap();
710        writeln!(f, r#"{{"timestamp":"2026-08-28T08:53:20.787Z","type":"session_meta","payload":{{"id":"01a0","cwd":"/tmp/p","cli_version":"0.149.1"}}}}"#).unwrap();
711        writeln!(f, r#"{{"timestamp":"2026-08-28T08:53:21.000Z","type":"turn_context","payload":{{"model":"gpt-5-codex"}}}}"#).unwrap();
712        writeln!(f, r#"{{"timestamp":"2026-08-28T08:53:22.000Z","type":"event_msg","payload":{{"type":"task_started"}}}}"#).unwrap();
713        writeln!(
714            f,
715            r#"{{"timestamp":"2026-08-28T08:53:23.000Z","type":"response_item","payload":{{"type":"function_call","call_id":"call_1","name":"shell"}}}}"#
716        )
717        .unwrap();
718        writeln!(f, r#"{{"timestamp":"2026-08-28T08:53:24.000Z","type":"event_msg","payload":{{"type":"token_count","info":{{"total_token_usage":{{"input_tokens":14778,"cached_input_tokens":12672,"output_tokens":241,"total_tokens":15019}}}}}}}}"#).unwrap();
719        writeln!(f, r#"{{"timestamp":"2026-08-28T08:53:25.000Z","type":"event_msg","payload":{{"type":"token_count","info":null}}}}"#)
720            .unwrap();
721        writeln!(f, r#"{{"timestamp":"2026-08-28T08:53:25.500Z","type":"response_item","payload":{{"type":"web_search_call","status":"completed"}}}}"#).unwrap();
722        let mut t = CodexTranscript::new(&path).with_prices(pricing::builtin_table());
723        t.refresh().unwrap();
724        let s = t.summary();
725        assert_eq!(s.session_id.as_deref(), Some("01a0"));
726        assert_eq!(s.model.as_deref(), Some("gpt-5-codex"));
727        assert_eq!(s.usage.input, 14778 - 12672);
728        assert_eq!(s.usage.cache_read, 12672);
729        assert_eq!(s.usage.total(), 15019);
730        // gpt-5-codex has no entry of its own; it resolves to gpt-5 by the
731        // longest-prefix rule (input 1.25, cache read 0.125, output 10).
732        assert_eq!(s.unpriced_tokens, 0, "priced now that OpenAI's rows are in the table");
733        assert!((s.cost_usd - (2106.0 * 1.25 + 12672.0 * 0.125 + 241.0 * 10.0) / 1_000_000.0).abs() < 1e-9, "{}", s.cost_usd);
734        assert_eq!(s.tool_calls, 1);
735        assert_eq!(s.activity, Activity::Working);
736        assert_eq!(read_meta(&path).unwrap().0, PathBuf::from("/tmp/p"));
737        assert_eq!(s.web_searches, 1);
738        let tools: Vec<_> = s.spans.iter().filter(|sp| sp.kind == SpanKind::Tool).collect();
739        assert_eq!(tools.len(), 1);
740        assert_eq!(tools[0].name, "shell");
741        assert!(tools[0].is_open(), "no output item yet");
742        let turns: Vec<_> = s.spans.iter().filter(|sp| sp.kind == SpanKind::Turn).collect();
743        assert_eq!(turns.len(), 1);
744        assert!(turns[0].is_open(), "task_started with no task_complete");
745        let _ = std::fs::remove_dir_all(&dir);
746    }
747
748    #[test]
749    fn pairs_calls_with_their_outputs() {
750        let dir = std::env::temp_dir().join(format!("agent-top-codex-spans-{}", std::process::id()));
751        std::fs::create_dir_all(&dir).unwrap();
752        let path = dir.join("rollout.jsonl");
753        let mut f = std::fs::File::create(&path).unwrap();
754        writeln!(f, r#"{{"timestamp":"2026-08-28T08:53:23.000Z","type":"response_item","payload":{{"type":"function_call","call_id":"call_1","name":"exec_command"}}}}"#).unwrap();
755        writeln!(f, r#"{{"timestamp":"2026-08-28T08:53:23.100Z","type":"response_item","payload":{{"type":"custom_tool_call","call_id":"call_2","name":"apply_patch"}}}}"#).unwrap();
756        writeln!(f, r#"{{"timestamp":"2026-08-28T08:53:24.000Z","type":"response_item","payload":{{"type":"function_call_output","call_id":"call_1","output":"ok"}}}}"#).unwrap();
757        writeln!(f, r#"{{"timestamp":"2026-08-28T08:53:26.100Z","type":"response_item","payload":{{"type":"custom_tool_call_output","call_id":"call_2","output":"ok"}}}}"#).unwrap();
758        // The model answers the outputs 1.5 s after the last one, then the turn completes.
759        writeln!(
760            f,
761            r#"{{"timestamp":"2026-08-28T08:53:27.600Z","type":"response_item","payload":{{"type":"message","role":"assistant"}}}}"#
762        )
763        .unwrap();
764        writeln!(f, r#"{{"timestamp":"2026-08-28T08:53:27.700Z","type":"event_msg","payload":{{"type":"task_complete"}}}}"#).unwrap();
765        let mut t = CodexTranscript::new(&path);
766        t.refresh().unwrap();
767        let all = t.summary().spans.to_vec();
768        let spans: Vec<_> = all.iter().filter(|sp| sp.kind == SpanKind::Tool).collect();
769        assert_eq!(spans.len(), 2);
770        assert_eq!(spans[0].name, "exec_command");
771        assert_eq!(spans[0].duration_ms, Some(1_000));
772        assert_eq!(spans[1].name, "apply_patch");
773        assert_eq!(spans[1].duration_ms, Some(3_000));
774        assert_eq!(t.summary().tool_calls, 2);
775        // One inference: opened by the first output at :24, not re-opened by the
776        // second at :26.1, ended by the assistant message at :27.6.
777        let inf: Vec<_> = all.iter().filter(|sp| sp.kind == SpanKind::Inference).collect();
778        assert_eq!(inf.len(), 1);
779        assert_eq!(inf[0].duration_ms, Some(3_600));
780        assert!(all.iter().all(|sp| sp.kind != SpanKind::Turn), "no task_started in this file");
781        let _ = std::fs::remove_dir_all(&dir);
782    }
783}