Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

sessions: a Codex rollout magpie rewrites keeps every line where it was

yetone67b12956acc0
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md
index 08ea3194d..6fd072b81 100644
--- a/docs/subsystems/gateway-routing.md
+++ b/docs/subsystems/gateway-routing.md
@@ -233,7 +233,7 @@ recorded as a prediction failure (`noPrediction`).
- A translated Responses reply gives Codex the reasoning items a Responses upstream sent, as it sent them; any other upstream's reasoning becomes items magpie made: an `rs_` id and a summary, nothing sealed. Codex hands them back on every turn. A request relayed as is to OpenAI's API or Azure OpenAI goes without them (`withoutBareReasoning`) unless `store` is true, because both look the id up among stored items and answer 400 "Item with id 'rs_…' not found" (#1008). Any other Responses upstream gets them, because a DeepSeek model wants its reasoning back (#388). When one answers 400 naming the input (`refusesInput`: `param` is `input`, or the error names an item by id), as a relay in front of OpenAI does with a message of its own, `passthrough` asks once more without them and, once that works, leaves them out for that provider and model from then on (`bareReasoningRefused`, #1044). Codex's compaction offers no tools, so it is relayed even when its turns were translated. The summary request magpie makes offers none either: `codexInputAs` sends `tools: []` and leaves out the `additional_tools` input item, where Codex's Responses Lite (the entry of a ChatGPT account's gpt-6 model, copied from Codex's own) puts every tool; left in, the model may call one in place of the summary (the likely cause of WuSix's codex/gpt-6-astra "the model wrote no summary" on Discord, not confirmed on a real reply), and a reply with no summary says what it held instead (`answeredWith`). When a provider answers its summary request 404, 405 or 501 (`lacksEndpoint`), or 400 for an item it didn't find (`itemNotFound`, a relay in front of either), `codexCompact` asks once more with the conversation as text (`plainCompact`), then compacts locally (#866, #1008). Any other failure goes back with its status, said as the compaction's with who answered it (`compactFailed`: "compaction: <provider> (<model>, <base URL>) answered the summary request 502 Bad Gateway: …"), the vendor's code, param and Retry-After kept. A compaction relayed to OpenAI (`/responses/compact` on Codex's own model, as a `/responses` turn) that OpenAI answers with an error status and an empty body, which Codex shows as "unexpected status 502 Bad Gateway: Unknown error", or with a web page, is said in words naming the model, the status, and the account it went to (`codexSaidNothing`, outrageous_piglet on Discord); an error OpenAI says in JSON goes as it came. `TestCodexOwnCompactFailureIsSaid`, `TestCodexCompactFailureSaysCompaction`, `TestCodexCompactNoEndpointCompactsLocally`. So does the ChatGPT backend's 502 "response protection is unavailable" (`protectionRefused`): a long history refused so was answered as text. Codex also compacts remotely, a `compaction_trigger` on `/responses` that wants exactly one compaction item back, on any provider table named "OpenAI", as CC Switch names its relay tables. magpie points those at `/v1` while a magpie model is on, so `handle` makes the summary there too (`codexInput`, `codexCompact`), and magpie's summaries go back to the model as text (#1301). A summary is wanted only whole (`askWhole`, `holdWriter.wantWhole`): its stream is held to its end, not let through at its first words, so a reply cut short (`errEndedShort`), failed halfway (a 429 "Individual quota reached" after some of it) or ended `incomplete` (`endedIncomplete`, `incompleteReply`) fails over to the next candidate like a failure before any of it, and rests the account as that failure would; one that reached its output limit rests nobody. With nobody left, `codexCompact` answers 502 and never hands Codex the words before the cut as the summary (#2274, huangzuomin: Antigravity cutting each summary short). Codex with context_management's experimental mode compacts in the background at every step while the conversation is over its threshold and drops a failed compaction without a word, so a conversation whose summaries keep failing is asked again every few seconds, each paying for the whole history (1169 compactions in 6 hours there). After `compactFailsMost` (3) failed summaries in a row of one conversation (`prompt_cache_key`) on one model, each within `compactHeldFor` (5 minutes) of the last, the next is answered at once with a 400 naming the last failure, which Codex doesn't ask again, and no model is asked until 5 minutes have passed (`compactFails` in [`codex_compact_guard.go`](../../internal/gateway/codex_compact_guard.go)); a summary that comes clears the count, and a sign-in's 401 or 403 isn't counted. `TestCodexCompactCutSummaryFailsOver`, `TestCodexCompactCutSummaryIsNoSummary`, `TestCodexCompactKeepsFailingIsHeld`.
- A reasoning item with its text in it (`content` parts: DeepSeek's Responses API writes `reasoning_text`, relayed to Codex as it came) is another vendor's. OpenAI's API and the ChatGPT backend take a reasoning item's `content` only empty, and refuse the whole request over one with 400 "Invalid 'input[n].content': array too long. Expected an array with maximum length 0" (`array_above_max_length`). Codex hands the item back on every later turn, so it never goes to them: for one of Codex's own models, `codexInput(body, false)` leaves it out (and a reasoning item with nothing sealed in it) on `/backend-api/codex`'s `/responses` and on `/responses/compact`, before Codex's own sign-in, its API key or a magpie Codex account (`compactOn`) is asked. Codex compacts a thread before its first turn back on its own model, and a refused compaction shows as that turn's error (jue on Discord). `passthrough` leaves it out for OpenAI, Azure OpenAI and a Codex account (`withoutReasoningText`), and for any other upstream once it has refused one (`refusesReasoningText`, `reasoningTextRefused`, #1411). OpenAI's own sealed reasoning (`encrypted_content`, no text) stays, and a DeepSeek model (`replaysReasoning`) still gets the text. `TestForeignReasoningNeverReachesOpenAI`, `TestReasoningTextLeftOutWhereRefused`, `TestReasoningTextNotSentToCodexAccount`.
- Native compaction (#1099, off by default): a provider with `nativeCompaction` on (`provider.Provider.CompactsOn`; the editor's Compaction row, `magpie provider set <id> compaction=native`) is asked Codex's `compaction_trigger` as Codex sent it, and the compaction item it seals goes back to Codex unchanged, not as a `magpie1:` summary. Only a wire that carries it can be set so (`CarriesCompaction`): a Responses API, a ChatGPT account, GitHub Copilot (its models asked on Responses; its Claude models keep magpie's summary). The decision is made where `handle` and `codexBackend` read the input (`nativeCompactionFor`, `codexInputAs`): a group compacts natively only when every member does. Such a request, and a later one carrying a sealed compaction to a provider set so or to the provider recorded as its writer, is relayed, never translated, which would drop the item (`keepsCompaction` in `attempt`); a provider that can't be asked it on Responses answers a 400 saying so. The key or account that answered is recorded, whoever it is: a fallback or another member that answered the trigger sealed it whatever its own setting, and only it can read the seal (#2271, JasonBuildAI: a fallback's seal went unrecorded, and the next turn was answered 200 without the compacted history; `TestNativeCompactionFallbackSealStaysWithItsWriter`). It is recorded by the hash of what it sealed (`wroteCheckpoint`, `compactions.json` beside `affinity.json`, 0600, at most 1024 for 30 days). A later request carrying it goes only to that writer (`checkpointReaders`); a writer whose own list has since dropped the model is tried still, as the last resort an account whose list lacks the model is — it sealed the model's compaction, and no other can read it (`planned.unlisted`, `TestNativeCompactionWriterWhoseListLacksTheModel`, #2642: it was refused as "switched off, removed, or no longer serves" though it was on, and switching it on changed nothing). With the writer gone from the candidates, magpie answers 400 `checkpointError` with the reason its settings give (`checkpointGone`: the provider removed, the account signed out, its sign-in lapsed, paused while others are on, switched off, kept from the model in Names & levels, the key off or gone, the model disabled, or the model or group asked for not going to it), what lets the conversation go on, and whether native compaction is on for the writer's provider now, and never sends it to another key, drops it, or summarises it in its place (`TestNativeCompactionWriterGoneSaysWhy`). One of Codex's own models asked on the backend path is decided as a magpie model is when magpie's Codex accounts serve it (`codexAccounts`): the trigger is kept only with the codex provider's native compaction on, else `codexCompact` gives magpie's summary, which any account reads, and no writer is recorded (#2582, ump45nose; before, every such compaction was sealed natively whatever the setting, and the conversation was held to its account; `TestCodexOwnModelCompactionHonoursTheToggle`). Codex's own sign-in alone, relayed as it came, still compacts natively, unrecorded, as does `/responses/compact`; but a request carrying a compaction magpie recorded the writer of goes through routing even then (`codexSealedFor`), so with the writer switched off the one account left isn't sent it. A legacy `/responses/compact` carrying one is judged at its passthrough (`sealedCompact`): the writer on in magpie answers it signed as the writer — its own seal while the sign-in can be asked, a key's seal, a request signing with its own `chatgpt-account-id`, or an unreadable sign-in state relays as it came — and a writer gone is refused with `checkpointError`'s reason, the same words as on `/responses` (`TestNativeCompactionCompactJudgesItsWriter`, #2727). The writer matched is the account user the record holds, so two Team seats of one email read as one and such a compact relays as it came. A gateway key held to some accounts (#905) is asked of the account the compact goes to (`compactSigninHeld`): the writer when it answers it, so a writer the key may not use is refused 403 (`sealedCompactHeldError`) with nothing asked, and one it may use answers though the sign-in isn't the key's (`TestNativeCompactionCompactKeepsTheKeysAccounts`). With the writer held at its usage cap or for credits it may not spend, the answer is 429 `checkpointCappedError` (record `checkpointCappedRecord`, "native compaction's account at its usage cap"), naming that account, that the others serving the model weren't tried for the compaction, and that neither the routing mode nor how conversations stay changes that: wait for the window, raise or lift its cap, or start a new conversation (#2517, lm0711; before, it read "every account at its usage cap" though another had room; `TestNativeCompactionWriterAtItsCap`). `withoutCompaction` (the drop after a refused reasoning item) isn't used for such a request. A route carrying a compaction names its sealer (`Route.Compaction`), and Routing says that is why no other account was asked, not that it is "the only account on" for the model (#2639; `TestNativeCompactionRouteNamesItsWriter`, `routing-compaction.test.cjs`). A refusal of the trigger reaches Codex as the upstream sent it. Not tried against a real upstream; Copilot may refuse a history that holds Codex's `web_search` items. [`native_compaction.go`](../../internal/gateway/native_compaction.go), `TestNativeCompaction*`.
-- A compaction magpie answers itself (`codexCompact`: a magpie model, Codex's own models through magpie's Codex accounts, a CC Switch table) goes to Codex as a `compaction` item whose `encrypted_content` is `magpie1:` and the summary in base64 (`codexsummary.Encrypted`), and `codexInputAs` sends Codex's own summary message in its place (`codexsummary.Message`: Codex's summary prefix, a newline and the summary, as a user message). Codex keeps the item in its rollout and replays it, and OpenAI refuses it once Codex talks to OpenAI itself (`invalid_encrypted_content`, LukeMa on X). So `sessions.PortCodexRollouts` writes that same message into the rollouts in its place ([`codex_portable.go`](../../internal/sessions/codex_portable.go)). A reasoning item carrying Claude's block (`magpie-claude1:`, above) is written as its summary, as the gateway sends it to OpenAI (`TestPortLineDropsClaudeBlocks`). It changes only magpie's items, keeps every other line's bytes and the file's line count, mode and time, and drops an unreadable item together with its `replacement_history_metadata` entry. It publishes as Codex publishes a compressed rollout: under `thread-writer-locks/.coordination.lock`, only with the thread's lock free, through a temp file and a rename. A thread a Codex has open is left for a later pass, and a Codex home without writer locks is left alone. It runs 2 minutes after the GUI or `magpie serve` starts and every 10 minutes after, on Codex Disconnect (3s), and as the GUI quits (3s). Each pass reads what changed since the last whole pass, plus what was held (`codex-portable.json`). A ported thread was resumed by Codex 0.162.1 against an upstream that refuses `magpie1:` as OpenAI does. Not tried: a Codex in a WSL distro, whose locks this machine can't take, so it is skipped. `TestPortCodexRollouts*`, `TestPortedCompactionReadsTheSame`.
+- A compaction magpie answers itself (`codexCompact`: a magpie model, Codex's own models through magpie's Codex accounts, a CC Switch table) goes to Codex as a `compaction` item whose `encrypted_content` is `magpie1:` and the summary in base64 (`codexsummary.Encrypted`), and `codexInputAs` sends Codex's own summary message in its place (`codexsummary.Message`: Codex's summary prefix, a newline and the summary, as a user message). Codex keeps the item in its rollout and replays it, and OpenAI refuses it once Codex talks to OpenAI itself (`invalid_encrypted_content`, LukeMa on X). So `sessions.PortCodexRollouts` writes that same message into the rollouts in its place ([`codex_portable.go`](../../internal/sessions/codex_portable.go)). A reasoning item carrying Claude's block (`magpie-claude1:`, above) is written as its summary, as the gateway sends it to OpenAI (`TestPortLineDropsClaudeBlocks`). It changes only magpie's items, keeps every other line's bytes and the file's line count, mode and time, and drops an unreadable item together with its `replacement_history_metadata` entry. Every rewritten line keeps its length (`fitLine`: a shorter one padded with spaces after its JSON, a longer one in a paginated rollout not written), as Codex keeps places in a rollout by byte: a fork's `history_base.end_byte_offset` and the state database's turn and projection offsets. A shorter parent left a fork's place past its end, and Codex refused to open the fork ("cutoff byte offset is past the source rollout", xybio on Discord); once per Codex home a pass sets each such fork's place again from the ordinal it names (`repairLineages`). `MoveCodexProvider` keeps the session_meta line's length the same way and refuses a longer provider id for a paginated rollout. It publishes as Codex publishes a compressed rollout: under `thread-writer-locks/.coordination.lock`, only with the thread's lock free, through a temp file and a rename. A thread a Codex has open is left for a later pass, and a Codex home without writer locks is left alone. It runs 2 minutes after the GUI or `magpie serve` starts and every 10 minutes after, on Codex Disconnect (3s), and as the GUI quits (3s). Each pass reads what changed since the last whole pass, plus what was held (`codex-portable.json`). A ported thread was resumed by Codex 0.162.1 against an upstream that refuses `magpie1:` as OpenAI does. Not tried: a Codex in a WSL distro, whose locks this machine can't take, so it is skipped. `TestPortCodexRollouts*`, `TestPortedCompactionReadsTheSame`.
- A Responses request Codex sends a Responses provider is fitted for a backend that isn't OpenAI's before it goes (`passthrough`): Responses Lite's shape taken off (`fromLite`): its `additional_tools` item lifted into `tools` (`liftAdditionalTools`, #350), its `reasoning.context` left out, and its `X-OpenAI-Internal-Codex-Responses-Lite` header not sent on (`liteKept`). A subagent a Lite lead (gpt-6.1-sol) spawns on another model comes in that shape, its model name alone changed, and OpenCode Go's DeepSeek answered it 503 "Endpoint is unavailable" (TangForX on X, `TestLiteSubagentLeavesLite`). Also the tool search as a function, OpenAI-only fields left out. A relay that checks a request is Codex's own turns that shape away (#1758: 400 "Codex 客户端请求特征无效", 10014). A provider set `codexAsSent` (`magpie provider set <id> codex=as-sent`) gets a request from Codex (`fromCodex`) as Codex sent it, its model name alone swapped, with Codex's own headers (`codexClientHeader`). That holds when Codex offers `web_search` too: the request is relayed with it, not translated for magpie's search (`searchedForIt`), which merged the developer messages into `instructions`, sent `apply_patch` as a function, left `web_search` out and added `max_output_tokens` (`codexAsSent` in `route`; maralica on Discord). `spawn_agent`'s description is still widened with the catalog's models (`spawnAgentModels`). Off is the default, and a subscription account is never sent so. `TestCodexAsSent`, `TestCodexAsSentWebSearch`.
- A tool a Chat request's message carries joins the request's `tools` (`liftMessageTools` in [`message_tools.go`](../../internal/gateway/message_tools.go), #2322). Pi with `supportsMidConvoToolAdditions` gives a tool it adds mid-conversation as `{"role":"system","tools":[…]}` with no content, and keeps top-level `tools` as they were at the start; no Chat API reads tools there, and `parseChat` read only the top-level ones, so the tool could be called on no route. `handle` lifts them for every Chat body before `serveAgent`, so the Chat relay, the schema fixers, redaction (the tool is a tool definition, not message text), the prompt shown and routing all see them; `parseChat` lifts too, for a body that never came through `handle` (the Claude subscription bridge's direct callers). Each tool joins once by name and the first definition wins: a top-level tool keeps its own, then the earliest message's, as `liftAdditionalTools` and a `tool_addition` (`withoutDeferredTools`) do. A system or developer message that carried only tools is left out, so it is neither relayed as an empty system message nor joined into the system text as an empty part; one with content keeps its place without `tools`. Messages stay where they are: the in-place system message the issue also asks for is not this change. `TestPiAddedToolReachesEveryRoute` sends deephbz's Pi 1.2.0 bytes through the Chat relay, Messages, Responses, Gemini and Codex, and `TestPiAddedToolOfferedToClaudeCode` through the Claude subscription bridge.
- A Chat request's tool in another API's shape is put in the Chat shape, `{"type":"function","function":{name, description, parameters, strict}}` (`shapeChatTools` in [`chat_tool_shape.go`](../../internal/gateway/chat_tool_shape.go), #2622, jinyue806): MCP's `{"name","description","inputSchema"}` (ZCode), Anthropic's `input_schema`, a bare `{"name","parameters"}` and Responses' flat `{"type":"function","name",…}`. No Chat API takes those (SenseNova: "field Tools[0].Type invalid, should be set" and "function cannot be empty"), and `parseChat` read no name from them, so a translated request offered a tool named "". It runs right after `liftMessageTools`, in `handle` for every Chat body and in `parseChat`, so it holds for every Chat upstream, not SenseNova's alone. A tool with its `function`, a hosted tool (any other `type`) and one with no name are left as they came, and a request with none to shape is relayed byte for byte. `TestChatToolInAnotherShapeIsShaped` sends the report's request with each of its four tools through the Chat relay, Messages and Responses; `TestShapeChatToolsLeavesChatShape`.
diff --git a/internal/sessions/codex_portable.go b/internal/sessions/codex_portable.go
index a543ded2d..25377fab5 100644
--- a/internal/sessions/codex_portable.go
+++ b/internal/sessions/codex_portable.go
@@ -12,10 +12,12 @@ import (
"os"
"path/filepath"
"regexp"
+ "strconv"
"strings"
"time"
"github.com/klauspost/compress/zstd"
+ "github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/claudeseal"
"github.com/yetone/magpie/internal/codexsummary"
@@ -59,6 +61,9 @@ type codexPortState struct {
type codexPortHome struct {
Since time.Time `json:"since"`
Pending []string `json:"pending,omitempty"`
+ // Lineage: every fork's place in its parent was looked at once
+ // (repairLineages), after magpie before it moved them
+ Lineage bool `json:"lineage,omitempty"`
}
// codexPortFirst is the first day magpie wrote a compaction item of its
@@ -75,6 +80,7 @@ func codexPortPath() string { return filepath.Join(settings.Dir(), "codex-portab
type CodexPort struct {
Rewritten []string // rollouts written portable
Held []string // rollouts with magpie's item a Codex holds, left for a later pass
+ Repaired []string // forks whose place in their parent was set again (repairLineages)
Done bool // every rollout due was looked at
}
@@ -165,7 +171,12 @@ func PortCodexRollouts(ctx context.Context, home string) (CodexPort, error) {
break
}
}
- now := codexPortHome{Since: was.Since, Pending: pending}
+ now := codexPortHome{Since: was.Since, Pending: pending, Lineage: was.Lineage}
+ if res.Done && !was.Lineage {
+ fixed, whole := repairLineages(ctx, home)
+ res.Repaired = fixed
+ now.Lineage = whole
+ }
if res.Done {
now.Since = start
} else {
@@ -217,6 +228,19 @@ var claudeMark = []byte(claudeseal.Mark)
// portRollout writes the rollout at path portable, if it has magpie's
// compaction item, and says whether it did.
func portRollout(ctx context.Context, home, path string) (bool, error) {
+ return editRollout(ctx, home, path, func(line []byte, paged bool) ([]byte, bool) {
+ out, ok := portLine(line)
+ if ok {
+ out, ok = fitLine(line, out, paged)
+ }
+ return out, ok
+ })
+}
+
+// editRollout writes the rollout at path with each line as edit gives it,
+// if edit changed one, and says whether it did; paged is whether the
+// rollout's history is paginated.
+func editRollout(ctx context.Context, home, path string, edit func(line []byte, paged bool) ([]byte, bool)) (bool, error) {
thread := codexThreadOf(filepath.Base(path))
if thread == "" {
return false, nil
@@ -252,13 +276,17 @@ func portRollout(ctx context.Context, home, path string) (bool, error) {
bw := bufio.NewWriterSize(w, 64<<10)
br := bufio.NewReaderSize(in, 64<<10)
changed := false
+ paged, metaSeen := false, false
for n := 0; ; n++ {
if n%4096 == 0 && ctx.Err() != nil {
return false, ctx.Err()
}
line, err := br.ReadBytes('\n')
if len(line) > 0 {
- out, ok := portLine(line)
+ if !metaSeen && isMetaLine(line) {
+ paged, metaSeen = paginated(line), true
+ }
+ out, ok := edit(line, paged)
changed = changed || ok
if _, werr := bw.Write(out); werr != nil {
return false, werr
@@ -324,6 +352,174 @@ func portRollout(ctx context.Context, home, path string) (bool, error) {
return true, nil
}
+// Codex keeps places in a rollout by byte: a fork's or a revert's
+// rollout names where its parent's history ends (session_meta's
+// history_base.end_byte_offset), and Codex's state database where each
+// turn starts and ends and how far it has read (thread_turns,
+// thread_history_projection_state). A rewritten line that is shorter or
+// longer moves every place after it, and a rollout that shrinks leaves
+// them past its end: Codex then won't open the thread ("invalid paginated
+// history lineage …: cutoff byte offset is past the source rollout",
+// xybio on Discord). So a line magpie rewrites keeps its length: a
+// shorter one is padded with spaces after its JSON, which Codex's reader
+// (serde_json) skips, and a longer one, in a rollout whose history is
+// paginated, is not written at all.
+
+// isMetaLine says whether a rollout line is a session_meta.
+func isMetaLine(line []byte) bool {
+ return bytes.Contains(line[:min(len(line), 1024)], cxMeta) && gjson.GetBytes(line, "type").String() == "session_meta"
+}
+
+// paginated says whether a session_meta line's rollout keeps its history
+// paginated, the one whose places Codex keeps by byte.
+func paginated(meta []byte) bool {
+ return gjson.GetBytes(meta, "payload.history_mode").String() == "paginated"
+}
+
+// fitLine is out, a rewrite of line, as long as line: padded with spaces
+// after its JSON when it is shorter (spaces line had there are taken
+// first). One that is longer is out as it is, unless paged: then it is
+// line, and false.
+func fitLine(line, out []byte, paged bool) ([]byte, bool) {
+ body := bytes.TrimRight(line, "\r\n")
+ end := line[len(body):]
+ nb := bytes.TrimRight(bytes.TrimRight(out, "\r\n"), " ")
+ if len(nb) > len(body) {
+ if paged {
+ return line, false
+ }
+ return out, true
+ }
+ fit := make([]byte, 0, len(line))
+ fit = append(fit, nb...)
+ fit = append(fit, bytes.Repeat([]byte{' '}, len(body)-len(nb))...)
+ return append(fit, end...), true
+}
+
+// A fork made before magpie kept a parent's lines whole names a byte in
+// it that a shorter parent no longer ends a line at, or no longer has:
+// Codex refuses to open it. Every line kept its place by count, though,
+// and Codex names each line's ordinal, so repairLineages sets each such
+// place again to where the parent's line before history_base's
+// end_ordinal_exclusive ends now, in the fork's session_meta, which keeps
+// its own length (fitLine). It says which forks it wrote, and whether it
+// looked at every one (none held by a Codex, ctx not done).
+func repairLineages(ctx context.Context, home string) (fixed []string, whole bool) {
+ rollouts := map[string]string{} // rollout id → its file
+ var all []string
+ for _, folder := range []string{"sessions", "archived_sessions"} {
+ filepath.WalkDir(filepath.Join(home, folder), func(p string, d fs.DirEntry, err error) error {
+ if err != nil || d.IsDir() || !d.Type().IsRegular() {
+ return nil
+ }
+ if id := codexRolloutID(d.Name()); id != "" {
+ rollouts[id] = p
+ all = append(all, p)
+ }
+ return nil
+ })
+ }
+ whole = true
+ known := map[string]map[int64]int64{} // a parent's ordinalEnds
+ for _, p := range all {
+ if ctx.Err() != nil {
+ return fixed, false
+ }
+ meta := firstLine(p)
+ base := gjson.GetBytes(meta, "payload.history_base")
+ if !isMetaLine(meta) || !paginated(meta) || !base.IsObject() {
+ continue
+ }
+ parent, ok := rollouts[strings.ToLower(base.Get("thread_id").String())]
+ n := base.Get("end_ordinal_exclusive").Int()
+ if !ok || n <= 0 {
+ continue
+ }
+ ends, seen := known[parent]
+ if !seen {
+ ends = ordinalEnds(parent)
+ known[parent] = ends
+ }
+ at, ok := ends[n-1]
+ if !ok || at == base.Get("end_byte_offset").Int() {
+ continue
+ }
+ changed, err := editRollout(ctx, home, p, func(line []byte, paged bool) ([]byte, bool) {
+ r := gjson.GetBytes(line, "payload.history_base.end_byte_offset")
+ if !isMetaLine(line) || r.Index <= 0 || r.Type != gjson.Number {
+ return line, false
+ }
+ out := append([]byte{}, line[:r.Index]...)
+ out = strconv.AppendInt(out, at, 10)
+ out = append(out, line[r.Index+len(r.Raw):]...)
+ return fitLine(line, out, true)
+ })
+ switch {
+ case err != nil:
+ whole = false
+ if !errors.Is(err, errRolloutHeld) {
+ log.Printf("codex rollout %s: %v", p, err)
+ }
+ case changed:
+ fixed = append(fixed, p)
+ }
+ }
+ return fixed, whole
+}
+
+// codexRolloutID is the id a rollout's file name gives it: a later
+// rollout of a thread's own, else its thread's.
+func codexRolloutID(name string) string {
+ m := codexRolloutName.FindStringSubmatch(name)
+ if m == nil {
+ return ""
+ }
+ if i := strings.IndexByte(name, '_'); i > 0 {
+ return strings.ToLower(strings.TrimSuffix(strings.TrimSuffix(name[i+1:], zstSuffix), ".jsonl"))
+ }
+ return strings.ToLower(m[1])
+}
+
+// firstLine is a rollout's first line, "" when it can't be read.
+func firstLine(path string) []byte {
+ r, err := openLines(path)
+ if err != nil {
+ return nil
+ }
+ defer r.Close()
+ line, _ := bufio.NewReaderSize(r, 64<<10).ReadBytes('\n')
+ return line
+}
+
+// ordinalEnds is where, in a rollout's lines, each line Codex numbered
+// ends, its newline included, up to the first line without an ordinal
+// (after which there is no telling).
+func ordinalEnds(path string) map[int64]int64 {
+ ends := map[int64]int64{}
+ r, err := openLines(path)
+ if err != nil {
+ return ends
+ }
+ defer r.Close()
+ br := bufio.NewReaderSize(r, 64<<10)
+ var at int64
+ for {
+ line, err := br.ReadBytes('\n')
+ if len(line) == 0 || line[len(line)-1] != '\n' {
+ return ends
+ }
+ at += int64(len(line))
+ o := gjson.GetBytes(line, "ordinal")
+ if o.Type != gjson.Number {
+ return ends
+ }
+ ends[o.Int()] = at
+ if err != nil {
+ return ends
+ }
+ }
+}
+
// portLine is a rollout line with each of magpie's compaction items in it
// written as the message it stands for; any other line as it is, byte for
// byte. One of magpie's items whose summary can't be read is left out of
diff --git a/internal/sessions/codex_portable_test.go b/internal/sessions/codex_portable_test.go
index 5f1c8ec0a..2091253f4 100644
--- a/internal/sessions/codex_portable_test.go
+++ b/internal/sessions/codex_portable_test.go
@@ -7,6 +7,7 @@ import (
"os"
"path/filepath"
"reflect"
+ "strconv"
"strings"
"testing"
"time"
@@ -263,3 +264,154 @@ func TestPortLineDropsClaudeBlocks(t *testing.T) {
}
}
}
+
+// lineEnds is where each line of a rollout ends, newline included: the
+// places Codex keeps by byte (history_base.end_byte_offset, the state
+// database's turn and projection offsets).
+func lineEnds(t *testing.T, path string) []int {
+ t.Helper()
+ in, err := openLines(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer in.Close()
+ var buf bytes.Buffer
+ buf.ReadFrom(in)
+ var ends []int
+ for i, c := range buf.Bytes() {
+ if c == '\n' {
+ ends = append(ends, i+1)
+ }
+ }
+ return ends
+}
+
+// xybio (Discord): the Codex app wouldn't reopen threads ("invalid
+// paginated history lineage for …: cutoff byte offset is past the source
+// rollout"). A fork or a revert names the byte its parent's history ends
+// at (session_meta.history_base), and Codex's state database keeps turns
+// and how far it has read by byte too; a ported line, a summary message
+// shorter than magpie's base64 item, made the parent shorter, so every
+// such place moved or went past its end. A rollout written portable keeps
+// every line where it was, and a fork's place in it stays a line's end.
+func TestPortCodexRolloutsKeepsBytePlaces(t *testing.T) {
+ for _, zst := range []bool{false, true} {
+ t.Run(map[bool]string{false: "plain", true: "zst"}[zst], func(t *testing.T) {
+ summary := strings.Repeat("Progress: build fixed in internal/x; next the suite. ", 80)
+ lines := portRolloutLines(summary)
+ lines[0] = strings.Replace(lines[0], `"model_provider":"openai"`, `"model_provider":"openai","history_mode":"paginated"`, 1)
+ sealed := claudeseal.Seal([]byte(`{"type":"thinking","thinking":"hm","signature":"` + strings.Repeat("s", 600) + `"}`))
+ lines = append(lines, `{"timestamp":"2026-10-20T09:00:06.000Z","type":"response_item","payload":{"type":"reasoning","summary":[{"type":"summary_text","text":"hm"}],"encrypted_content":"`+sealed+`"}}`)
+ home, path := portHome(t, lines, zst)
+ before := lineEnds(t, path)
+
+ // a fork of the thread made at its end, as the Codex app makes
+ // one from where it has read to
+ child := "01a1430d-e3a9-7a72-a466-071d2e3dd46b"
+ cpath := filepath.Join(filepath.Dir(path), "rollout-2026-10-20T18-00-00-"+child+".jsonl")
+ meta := `{"timestamp":"2026-10-20T10:00:00.000Z","type":"session_meta","payload":{"id":"` + child + `","history_mode":"paginated","history_base":{"thread_id":"` + portThread + `","end_ordinal_exclusive":` + strconv.Itoa(len(lines)) + `,"end_byte_offset":` + strconv.Itoa(before[len(before)-1]) + `}}}` + "\n"
+ if err := os.WriteFile(cpath, []byte(meta), 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ res, err := PortCodexRollouts(context.Background(), home)
+ if err != nil || len(res.Rewritten) != 1 || res.Rewritten[0] != path {
+ t.Fatalf("pass: %+v, %v", res, err)
+ }
+ if after := lineEnds(t, path); !reflect.DeepEqual(after, before) {
+ t.Fatalf("lines end at %v, were at %v", after, before)
+ }
+ got := readRollout(t, path)
+ want, _ := json.Marshal(codexsummary.UserMessage(codexsummary.Prefix + "\n" + summary))
+ var wantAny any
+ json.Unmarshal(want, &wantAny)
+ if p := decode(t, got[2])["payload"]; !reflect.DeepEqual(p, wantAny) {
+ t.Errorf("not written portable: %s", got[2])
+ }
+ for i, l := range got {
+ decode(t, l) // padded lines still read as JSON
+ if i != 1 && (strings.Contains(l, codexsummary.Mark) || strings.Contains(l, claudeseal.Mark)) {
+ t.Errorf("line %d still has magpie's item: %.200s", i, l)
+ }
+ }
+ if b, _ := os.ReadFile(cpath); string(b) != meta {
+ t.Error("the fork's rollout changed")
+ }
+ })
+ }
+}
+
+// A line whose portable form is longer (a short summary, under Codex's
+// prefix) can't keep its length: in a paginated rollout it is left as it
+// was, never moving what follows; in a legacy one, where Codex keeps no
+// place by byte, it is written as before.
+func TestPortCodexRolloutsLongerLine(t *testing.T) {
+ lines := portRolloutLines("short")
+ lines[0] = strings.Replace(lines[0], `"model_provider":"openai"`, `"model_provider":"openai","history_mode":"paginated"`, 1)
+ home, path := portHome(t, lines, false)
+ before := lineEnds(t, path)
+ if _, err := PortCodexRollouts(context.Background(), home); err != nil {
+ t.Fatal(err)
+ }
+ if after := lineEnds(t, path); !reflect.DeepEqual(after, before) {
+ t.Fatalf("lines end at %v, were at %v", after, before)
+ }
+ got := readRollout(t, path)
+ if got[2] != lines[2] {
+ t.Errorf("a longer line was written: %s", got[2])
+ }
+ if strings.Contains(got[4], "magpie1:%%%") {
+ t.Errorf("the shorter one wasn't: %s", got[4])
+ }
+}
+
+// A fork made before magpie kept its parent's lines whole names a byte
+// the shorter parent doesn't end a line at, or doesn't have (xybio's
+// thread). The pass after sets it again, once, from the ordinal the fork
+// names, keeping the fork's first line as long as it was; a fork whose
+// place is right keeps its bytes.
+func TestPortCodexRolloutsRepairsForks(t *testing.T) {
+ parent := []string{
+ `{"timestamp":"2026-10-20T07:05:20.118Z","ordinal":0,"type":"session_meta","payload":{"id":"` + portThread + `","history_mode":"paginated","model_provider":"openai"}}`,
+ `{"timestamp":"2026-10-20T07:05:31.002Z","ordinal":1,"type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"fix it"}]}}`,
+ `{"timestamp":"2026-10-20T07:05:40.002Z","ordinal":2,"type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"done"}]}}`,
+ }
+ home, path := portHome(t, parent, false)
+ ends := lineEnds(t, path)
+ dir := filepath.Dir(path)
+ fork := func(id string, ord, at int) string {
+ p := filepath.Join(dir, "rollout-2026-10-20T18-00-00-"+id+".jsonl")
+ b := `{"timestamp":"2026-10-20T10:00:00.000Z","ordinal":` + strconv.Itoa(ord) + `,"type":"session_meta","payload":{"id":"` + id + `","history_mode":"paginated","history_base":{"thread_id":"` + portThread + `","end_ordinal_exclusive":` + strconv.Itoa(ord) + `,"end_byte_offset":` + strconv.Itoa(at) + `}}}` + "\n" +
+ `{"timestamp":"2026-10-20T10:00:01.000Z","ordinal":` + strconv.Itoa(ord+1) + `,"type":"event_msg","payload":{"type":"task_started"}}` + "\n"
+ if err := os.WriteFile(p, []byte(b), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ return p
+ }
+ // made when the parent was longer, at its end then
+ broken := fork("01a1430d-e3a9-7a72-a466-071d2e3dd46b", 3, 14362)
+ right := fork("01a1430d-ffff-7a72-a466-071d2e3dd46b", 2, ends[1])
+ was, _ := os.ReadFile(broken)
+ rightWas, _ := os.ReadFile(right)
+
+ res, err := PortCodexRollouts(context.Background(), home)
+ if err != nil || len(res.Repaired) != 1 || res.Repaired[0] != broken {
+ t.Fatalf("pass: %+v, %v", res, err)
+ }
+ now, _ := os.ReadFile(broken)
+ if len(now) != len(was) {
+ t.Fatalf("%d bytes, was %d", len(now), len(was))
+ }
+ first := decode(t, readRollout(t, broken)[0])
+ if at := first["payload"].(map[string]any)["history_base"].(map[string]any)["end_byte_offset"]; at != float64(ends[2]) {
+ t.Errorf("end_byte_offset %v, want %d", at, ends[2])
+ }
+ if b, _ := os.ReadFile(right); !bytes.Equal(b, rightWas) {
+ t.Error("a fork whose place was right changed")
+ }
+ // looked at once
+ os.WriteFile(broken, was, 0o600)
+ if res, err := PortCodexRollouts(context.Background(), home); err != nil || len(res.Repaired) != 0 {
+ t.Fatalf("second pass: %+v, %v", res, err)
+ }
+}
diff --git a/internal/sessions/codex_provider.go b/internal/sessions/codex_provider.go
index c8d2b4f73..982faa834 100644
--- a/internal/sessions/codex_provider.go
+++ b/internal/sessions/codex_provider.go
@@ -525,6 +525,13 @@ func rewriteCodexProvider(path, to string) (bool, error) {
line, err := br.ReadBytes('\n')
if len(line) > 0 {
out, ok := setMetaProvider(line, to)
+ if ok {
+ // a session_meta names its own history_mode: Codex keeps
+ // places in a paginated rollout by byte (fitLine)
+ if out, ok = fitLine(line, out, paginated(line)); !ok {
+ return false, fmt.Errorf("%s keeps its history by byte, and %q is longer than the provider it names: Codex couldn't open it moved", filepath.Base(path), to)
+ }
+ }
changed = changed || ok
if _, werr := bw.Write(out); werr != nil {
return false, werr
diff --git a/internal/sessions/codex_provider_test.go b/internal/sessions/codex_provider_test.go
index 4848de429..56b42672b 100644
--- a/internal/sessions/codex_provider_test.go
+++ b/internal/sessions/codex_provider_test.go
@@ -179,3 +179,42 @@ func TestCodexProviderIn(t *testing.T) {
t.Fatalf("profile: %q", p)
}
}
+
+// Codex keeps places in a paginated rollout by byte (xybio on Discord, see
+// TestPortCodexRolloutsKeepsBytePlaces): a move keeps the session_meta
+// line's length, padded after its JSON for a shorter id, and a longer id
+// is refused with the files as they were; moving back gives the bytes it
+// had.
+func TestMoveCodexProviderKeepsBytePlaces(t *testing.T) {
+ _, codex := manageSetup(t)
+ main := filepath.Join(codex, "sessions", "2026", "09", "20", "rollout-2026-09-20T15-48-28-"+mgCX+".jsonl")
+ b, _ := os.ReadFile(main)
+ orig := bytes.Replace(b, []byte(`"model_provider":"openai"`), []byte(`"model_provider":"custom","history_mode":"paginated"`), 1)
+ old := time.Now().Add(-24 * time.Hour).Truncate(time.Second)
+ os.WriteFile(main, orig, 0o644)
+ os.Chtimes(main, old, old)
+
+ if _, err := MoveCodexProvider(mgCX, "cc"); err != nil {
+ t.Fatal(err)
+ }
+ now, _ := os.ReadFile(main)
+ if len(now) != len(orig) {
+ t.Fatalf("%d bytes, was %d", len(now), len(orig))
+ }
+ first := now[:bytes.IndexByte(now, '\n')]
+ if !bytes.HasSuffix(first, []byte("} ")) || !bytes.Contains(first, []byte(`"model_provider":"cc"`)) || !bytes.Equal(now[len(first):], orig[len(first):]) {
+ t.Fatalf("the file became\n%s", now)
+ }
+ if _, err := MoveCodexProvider(mgCX, "a-longer-provider"); err == nil {
+ t.Fatal("a longer id was written")
+ }
+ if b, _ := os.ReadFile(main); !bytes.Equal(b, now) {
+ t.Fatal("a refused move changed the file")
+ }
+ if _, err := MoveCodexProvider(mgCX, "custom"); err != nil {
+ t.Fatal(err)
+ }
+ if b, _ := os.ReadFile(main); !bytes.Equal(b, orig) {
+ t.Fatalf("moving back gave\n%s", b)
+ }
+}