Skip to content

feat(agents): Codex and Gemini serve atif/1, from the CLI's rollout and its session transcript - #924

Open
earakely-scale wants to merge 8 commits into
mainfrom
edgararakelyan/fd-6082-y8-codex-gemini-atif
Open

earakely-scale wants to merge 8 commits into
mainfrom
edgararakelyan/fd-6082-y8-codex-gemini-atif

Conversation

@earakely-scale

@earakely-scale earakely-scale commented Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator

Codex and Gemini now serve atif/1 when a run prescribes it, as Claude Code has since #854. Their native trajectories stay the default. Before this, a prescribed run fell back to native for these two agents, so their judges and live followers read the CLI's stdout events, which carry no times, no per-call usage, no thoughts and (for Gemini) no tool results.

What changes

Codex (agents/codex/codex_atif.py, codex_bridge.py)

  • Where the copy comes from. The bridge tails the CLI's rollout ($CODEX_HOME/sessions/.../rollout-*.jsonl) while the CLI runs, and each sub-agent's rollout as it appears, at any depth. It feeds the records the adapter reads as the rollout aux file (RolloutTail, rollout_aux). The exec JSON events on stdout stay the native log.
  • A step per model response. A step holds the response's reasoning, message and calls, timed by its first item. It takes the response's own usage from its token_usage_record. A response that wrote nothing gets a step for its usage alone, so the steps add up to the turn's usage.
  • Calls and results.
    • Calls keep the rollout's call ids.
    • An MCP tool keeps its namespace, as the model sees it (mcp__browser__browser_navigate).
    • A patch keeps its text.
    • An image a tool returns is a media file.
    • A web search the provider ran has no output item, so the adapter answers it with the status the rollout gives. Otherwise its step would wait on a result until the turn ended, and live followers would stall there.
  • Reasoning. A summary is summary, else the ciphertext is kept as redacted, else omitted.
  • Sub-agents. Each sub-agent is an embedded trajectory under the spawn_agent call that started it. The bridge marks each sub-agent's records with the thread that spawned it. The spawn's result and the sub-agent's records are held until both have arrived, in either order.
  • Forks. A sub-agent forked with its parent's history (fork_turns: "all") begins its rollout with a copy of the parent's meta and turns, the parent's own replies among them, under their ids. The tail leaves out the records of every turn the parent's rollout holds, so the sub-agent's trajectory holds only what it did. A turn the parent's rollout didn't hold when the fork was found has the parent's rollout read again before it's taken for the sub-agent's own.
  • Attempts and failures. A resumed attempt starts with another task_started, and its steps carry the attempt's number. A failed or refused model call ends its attempt's task_complete with an error, which becomes a step with no model call holding that error.

Gemini (agents/gemini/gemini_atif.py, gemini_bridge.py, a2a_server.py)

  • Where the copy comes from. The bridge tails the session transcript (~/.gemini/tmp/<project>/chats/session-*.json), which the CLI rewrites whole. It feeds each model message once a later message follows it, since the CLI adds a message's calls and results after writing it, and the last message at the turn's end (SessionTail, session_aux). A resumed session's earlier messages aren't fed again.
  • A step per model response.
    • Its thoughts are summary reasoning.
    • It holds its text, its calls and their results; an image returned beside a result is a media file, an error response is an error result, and a cancelled call without a result is canceled.
    • Its usage is that of the proxy's agentenv.model_call whose input it names (the prompt plus any tool-use prompt, as the proxy counts it).
  • Calls with no message.
    • A call the proxy forwarded that wrote no message (the CLI's routing and next-speaker checks) is a step with its usage alone.
    • A refused call is a step with no model call holding the error, which the CLI's own report replaces when the turn ended there.
  • A response the proxy didn't count takes the transcript's count. It is joined only to an uncounted call that no answered call comes ahead of, so no call is counted twice.
  • The proxy's records now say when each call ended (timestamp).

The cards. Both offer atif/1 beside their native format, which stays the default. Their images and install lists carry the adapters.

Choices to review

  • Codex's copy comes from the rollout alone, not stdout. The exec JSON events have no times and only the turn's total usage. The rollout has each item's time and each response's usage. The cost is one more file the bridge follows.
  • Gemini's live copy runs one response behind. A message is fed once the next one exists, because the CLI keeps changing the last one (its calls, then their results). Feeding every version would mean merging versions in the adapter.
  • Gemini sub-agents aren't embedded. The CLI writes them to transcripts of their own. Their calls still reach the copy, as steps with their usage alone, so the totals hold.
  • A Codex sub-agent the CLI continues in a later turn isn't placed in that turn's copy. ATIF embeds a sub-agent under the call that spawned it, in that call's task. Its records stay in the native log and are counted as unmatched.
  • Protocol floors stay as they are (Codex 0.1.640, Gemini 0.1.643). Both adapters import only what those versions have. The recorded fixtures replay through each floor's own protocol with no finding.

Testing

  • Unit, the adapters
    • Each mapping above has a case, run through the protocol's adapter kit (the live rule after every record, the document valid).
    • Seeded conversations, 150 per agent, about 3 s each:
      • Codex: random responses, sub-agents, attempts.
      • Gemini: random proxy records and messages fed late.
    • Each copy's usage is checked against what was fed, with every call answered and every sub-agent embedded.
  • Unit, the tails
    • Codex's rollout tail: a resumed thread read from where it ended; a line still being written; sub-agents at any depth, one seen before its parent; a replaced file; a fork's copies left out.
    • Gemini's session tail: messages fed once settled; a resumed session; a transcript caught half-written.
    • run_codex and run_gemini both feed while the CLI runs and once more after it exits.
  • Recorded runs (tst/data/codex_atif, tst/data/gemini_atif), through each agent's image built from this branch, with tst/manual/codex_gemini_atif/record.py:
    • Codex: coding over two turns, a browser screenshot, high reasoning effort, a refused call, a resumed attempt, a sub-agent, and a second turn's forked sub-agent, whose rollout copied the first turn and the parent's reply (none of it reaches the copy).
    • Gemini: coding over two turns, a browser screenshot, a refused call, failed calls the CLI retried.
    • Each replays to its document under the live rule.
    • Its steps sum to each turn's reported usage, every response has its time and model, and every call has its result.
  • Chaos (kept outside the repo)
    • Adapters: harsher random conversations. For Codex, interleaved sub-agents, depth two, forks, continued sub-agents, broken images and non-JSON arguments. For Gemini, lag of 0 to 3 messages, side calls, refused and uncounted calls, equal inputs. Invariants: no kit finding, the copy's prompt tokens equal to what was fed, every call once with its result, every sub-agent that showed embedded once. Clean over 68,227 seeds per adapter locally and 67,289 in 30 minutes on a test host. It catches seven planted bugs: Codex usage dropped, sub-agent records not held, held results lost, attempts ignored; Gemini joined by order, tool-use tokens ignored, side calls lost at the end. It found both ways Gemini's copy could count a call twice, fixed above.
    • Tails: a writer thread tearing lines, replacing files, starting forks and rewriting the transcript non-atomically, against a polling reader, fresh and resumed. Invariant: each record fed exactly once, in its file's order, a fork's copies never, and each Gemini message as its final version. Clean over 6,717 seeds per agent locally and 15,281 in 30 minutes on a test host. It catches three planted bugs: fork copies kept, torn lines fed, and the last message fed before it settled. It led to the fork check reading the parent's rollout again for a turn it hadn't seen yet.
  • e2e on a test host, about $2 in all, recordings included
    • Bundle runs with agent-env run, atif/1 prescribed, each turn followed live, each turn graded by a direct judge reading its copy:
      • Codex, two turns, the second spawning a sub-agent forked with the conversation: both judges pass. The judge's reasons name the fork, the sub-agent's own command and its result.
      • Gemini, two turns: both judges pass.
      • Snapshot and restore. Each agent's turn was snapshotted and restored into a fresh agent under a new context (snapshot_agent_state, then deploy_agent with the snapshot).
        • The restored turn resumes from the restored rollout or transcript, and its judge passes for both agents: the reply recalls the first turn's output.
        • Its copy holds its own turn alone.
        • One Gemini judge failed the first turn because the model replied "Output: one-42" when asked for the output alone. The copy matches the agent's reply.
      • Every copy and live follow. Every turn's copy is recorded valid, and every live follow's pages match the final copy, the Codex sub-agent's included.
    • Straight against each image:
      • A restart between turns gives the second turn a valid copy of its own turn alone.
      • Two contexts at once each hold only their own calls, and each Codex context only its own sub-agent.
    • Recordings. All 14 recorded turns' served copies pass the validator with no finding. Each replay through the adapter equals the served copy, except for the task data the SDK adds at the end.

🤖 Generated with Claude Code

RetriggerView in GreptileConfidence Score: 3/5

Fix the dropped tail batches and repeated Codex sub-agent name lookup before merging.

Fix All in CursorFindings

  1. P1 Final records can disappear ▶
  2. P1 Reused names break later turns ▶
Fix with agent prompt
### Issue 1
src/agent_env/agents/agents/codex/codex_bridge.py:300-302
When the CLI exits while `follow_rollout` awaits `asyncio.to_thread(tail.read)`, canceling the follower drops that batch even though the reader advances its offsets. The final read then skips those records. Gemini has the same race because `SessionTail.read` adds message IDs to `_fed` before returning them. Responses, tool results, and usage can silently disappear from the served copy.

Let the pending read finish and feed its batch before stopping, or commit reader progress only after delivery.

### Issue 2
src/agent_env/agents/agents/codex/codex_atif.py:184
When a later task spawns a new sub-agent with a previously used `task_name`, this lookup can select the old thread. `_subs` survives across tasks, while `end` resets every old entry's `declared` flag to false. The old entry therefore matches first, even if the new thread's metadata has arrived. `_declare` then declares the old thread again, which the builder rejects, stopping the ATIF copy.

Limit this lookup to threads first seen in the current task, or separately track retired threads.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

Adds prescribed atif/1 copies for Codex and Gemini while keeping native formats as the default.

  • Codex turns its rollout records into a live atif/1 trajectory.
  • Gemini builds atif/1 steps from settled messages and matching proxy calls.

Intentional exclusions acknowledged by earakely-scale: Gemini sub-agents remain usage-only steps; Codex sub-agents continued in later tasks remain unmatched because their embedded trajectory belongs to the spawning task.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  C[Codex rollout] --> CT[RolloutTail]
  CT --> CA[CodexAtif]
  G[Gemini transcript] --> GT[SessionTail]
  GT --> GA[GeminiAtif]
  P[Gemini proxy call records] --> GA
  CA --> B[ATIF builder]
  GA --> B
  B --> L[Live pages]
  B --> F[Final document]
Loading

Reviews (1) · Last reviewed commit: "test(agents): a fork's copied turns hold..." · Reviewed by Greptile

earakely-scale and others added 8 commits November 25, 2026 08:46
The bridge tails the thread's rollout, and each sub-agent's, and feeds its
records as the rollout aux file; the adapter writes a step per model
response with its items' times and the response's own usage, embeds each
sub-agent under its spawn_agent call, marks a resumed attempt, and turns
a failed call into an error step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ts proxy's calls

The bridge tails the session transcript and feeds each model message once
it is settled; the adapter writes a step per response with its thoughts,
calls, results and images, takes each step's usage from the proxy call
whose input it names, and writes the calls that wrote no message, and the
refused ones, as steps of their own. Each proxy record now has a time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… images

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…and answers hosted web searches

A sub-agent forked with its parent's history begins its rollout with a copy
of the parent's meta and turns, whose call ids the copy already holds: the
tail leaves out the records of every turn the parent's rollout holds. A web
search the provider runs has no output item, so its step waited on a result
until the turn ended: the adapter answers it with its status. Adds the
recorded fixtures and tests for both agents, and seeded conversations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…cks a fork's parent for a new turn

A Gemini response the proxy didn't count is joined only to an uncounted call
no answered call comes ahead of, and leaves the calls not yet written alone,
since they may be later messages'. A forked Codex sub-agent's record of a
turn its parent's rollout didn't hold when the fork was found reads the
parent's rollout again before taking the turn for the sub-agent's own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…th a forked sub-agent

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…h the tail leaves out

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@earakely-scale
earakely-scale marked this pull request as ready for review November 25, 2026 18:25
@earakely-scale
earakely-scale requested a review from a team as a code owner November 25, 2026 18:25
Comment on lines +300 to +302
following.cancel()
try:
await following

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Final records can disappear

When the CLI exits while follow_rollout awaits asyncio.to_thread(tail.read), canceling the follower drops that batch even though the reader advances its offsets. The final read then skips those records. Gemini has the same race because SessionTail.read adds message IDs to _fed before returning them. Responses, tool results, and usage can silently disappear from the served copy.

Let the pending read finish and feed its batch before stopping, or commit reader progress only after delivery.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agent_env/agents/agents/codex/codex_bridge.py
Line: 300-302

Comment:
**Final records can disappear**

When the CLI exits while `follow_rollout` awaits `asyncio.to_thread(tail.read)`, canceling the follower drops that batch even though the reader advances its offsets. The final read then skips those records. Gemini has the same race because `SessionTail.read` adds message IDs to `_fed` before returning them. Responses, tool results, and usage can silently disappear from the served copy.

Let the pending read finish and feed its batch before stopping, or commit reader progress only after delivery.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Cursor Fix in Claude Code Fix in Codex

if path is None:
self._result(record, turn)
return
thread = next((t for t, sub in self._subs.items() if sub.path == path and not sub.declared), None)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Reused names break later turns

When a later task spawns a new sub-agent with a previously used task_name, this lookup can select the old thread. _subs survives across tasks, while end resets every old entry's declared flag to false. The old entry therefore matches first, even if the new thread's metadata has arrived. _declare then declares the old thread again, which the builder rejects, stopping the ATIF copy.

Limit this lookup to threads first seen in the current task, or separately track retired threads.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agent_env/agents/agents/codex/codex_atif.py
Line: 184

Comment:
**Reused names break later turns**

When a later task spawns a new sub-agent with a previously used `task_name`, this lookup can select the old thread. `_subs` survives across tasks, while `end` resets every old entry's `declared` flag to false. The old entry therefore matches first, even if the new thread's metadata has arrived. `_declare` then declares the old thread again, which the builder rejects, stopping the ATIF copy.

Limit this lookup to threads first seen in the current task, or separately track retired threads.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Cursor Fix in Claude Code Fix in Codex

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant