sessions: a compaction that doesn't fit its line goes as text, never as magpie's seal (hey_boyce on X)

hey_boyce on X: Codex, talking to OpenAI itself, got 400
invalid_encrypted_content "The encrypted content for item
cmp_magpie_1794916786407450000 could not be verified".

Cause: PortCodexRollouts writes magpie's compaction item (magpie1:
base64 summary) as Codex's own summary message, keeping each line's
length, since a paginated rollout keeps places by byte. A message
longer than the line (a short summary under Codex's ~400-char prefix)
was left as it was, so the magpie1: seal stayed in the rollout, Codex
replayed it to OpenAI every turn, and the thread was stuck. The
incremental pass never looked at such a rollout again.

Change:
- fitShorter: when the full message doesn't fit, the summary goes
  under a short heading, then cut to fit (rune-safe, "…"), then
  with no heading. If nothing fits, a standalone item is retired as
  {"type":"magpie_compaction"}, which Codex reads as unknown and
  never sends.
- In replacement_history an unknown item IS sent (as "other"), and
  OpenAI refuses it ("Invalid value: 'other'"; seen with real
  codex-cli 0.165.0 and 0.169.1). So a compaction or reasoning item
  retired there is left out with its metadata entry, and
  magpie_reasoning items main's PortCodexRolloutsLeft already wrote
  there are taken out (retiredInList). That was a sibling bug: those
  threads failed the same way.
- codex-portable.json gains refit: a state from before makes one
  whole pass again, so rollouts already left with the seal are fixed.
- The gateway's last line: a 400 naming an item of magpie's own
  compaction asks again with its summary message in its place
  (withoutItem), not with the summary dropped.
- codexsummary.Summary decodes the seal; Message uses it.
- docs/subsystems/gateway-routing.md says all of this.

Run (on mica, at this head rebased on a265632da):
- red on the old code, green now: TestPortCodexRolloutsLongerLine
  (short, cut), TestPortCodexRolloutsDropsRetiredFromHistory,
  TestPortCodexRolloutsRefitsOnce,
  TestPortCodexRolloutsLeftRetiresUnsealedReasoning,
  TestRefusedMagpieCompactionGoesAsText (old withoutItem: 2 items,
  the summary gone).
- broken by hand: without `&& was.Refit` RefitsOnce is red.
- real Codex, sandbox HOME with a copy of the owner's ChatGPT auth,
  codex-cli 0.169.1, gpt-6-sol, against OpenAI:
  - the reporter's item (id cmp_magpie_1794916786407450000, summary
    "ok") gave the same 400 word for word. Ported by this code, resume
    answered.
  - an id-less item plus a magpie_reasoning in replacement_history
    (as main left it) failed "Invalid value: 'other'" before. Ported,
    resume answered.
- go test -count=1 -timeout 45m ./internal/codexsummary
  ./internal/sessions ./internal/gateway ./internal/agent: all ok
  (gateway 1026s, agent 221s), log kept in enc-scratch/pkgs.log;
  TestLoopGuard* again after the doc edit: ok.
- rebased on 53db3e389 (stream keepalive; only the doc page is
  shared): the refusal, seal, compaction, LoopGuard and Quiet tests
  in internal/gateway again at this head: ok.
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., go build ./... ok.

Not tried: a summary cut to fit with real Codex (the unit test checks
it is a plain user message, the same shape as the case that was run);
a Codex in WSL; the full ./... suite: mote was over its cores and both mote and
mica were running another session's GUI suite, so only the changed
packages and internal/agent, which ports rollouts, ran (above).
This commit is contained in:
yetone
2026-11-18 11:16:54 +08:00
parent 53db3e3891
commit 7707ba9adb
6 changed files with 365 additions and 51 deletions
File diff suppressed because one or more lines are too long
+18 -7
View File
@@ -32,20 +32,31 @@ func Encrypted(summary string) string {
return Mark + base64.StdEncoding.EncodeToString([]byte(summary))
}
// Summary is the summary in a compaction item's encrypted_content: ours
// is false for one magpie didn't make, and ok false for one of magpie's
// whose summary can't be read.
func Summary(encrypted string) (summary string, ours, ok bool) {
b64, isOurs := strings.CutPrefix(encrypted, Mark)
if !isOurs {
return "", false, false
}
b, err := base64.StdEncoding.DecodeString(b64)
if err != nil {
return "", true, false
}
return string(b), true, true
}
// Message is what a compaction item's encrypted_content is read as: ours
// is false for one magpie didn't make (OpenAI's own, left as it is), and
// msg nil for one of magpie's whose summary can't be read, which is left
// out.
func Message(encrypted string) (msg map[string]any, ours bool) {
b64, ok := strings.CutPrefix(encrypted, Mark)
summary, ours, ok := Summary(encrypted)
if !ok {
return nil, false
return nil, ours
}
b, err := base64.StdEncoding.DecodeString(b64)
if err != nil {
return nil, true
}
return UserMessage(Prefix + "\n" + string(b)), true
return UserMessage(Prefix + "\n" + summary), true
}
// UserMessage is a Responses input message of the user's.
+16 -3
View File
@@ -1957,6 +1957,9 @@ func withoutUnreadable(body, msg []byte) ([]byte, bool) {
}
// withoutItem is a Responses request without the input item of this id.
// A compaction of magpie's own (cmp_magpie_…, hey_boyce on X: one that
// reached OpenAI as it was written) goes as the summary it holds, so
// the turn keeps what came before.
func withoutItem(body []byte, id string) ([]byte, bool) {
var q map[string]json.RawMessage
if json.Unmarshal(body, &q) != nil {
@@ -1966,17 +1969,27 @@ func withoutItem(body []byte, id string) ([]byte, bool) {
if json.Unmarshal(q["input"], &items) != nil {
return nil, false
}
kept := items[:0:0]
kept, found := items[:0:0], false
for _, it := range items {
var t struct {
ID string `json:"id"`
ID string `json:"id"`
Type string `json:"type"`
Encrypted string `json:"encrypted_content"`
}
if json.Unmarshal(it, &t) == nil && t.ID == id {
found = true
if t.Type == "compaction" {
if msg, ours := codexsummary.Message(t.Encrypted); ours && msg != nil {
if b, err := json.Marshal(msg); err == nil {
kept = append(kept, b)
}
}
}
continue
}
kept = append(kept, it)
}
if len(kept) == len(items) {
if !found {
return nil, false
}
q["input"], _ = json.Marshal(kept)
@@ -0,0 +1,59 @@
package gateway
import (
"encoding/json"
"strings"
"testing"
"github.com/yetone/magpie/internal/codexsummary"
)
// hey_boyce on X: OpenAI turned a turn away for magpie's own compaction
// ("The encrypted content for item cmp_magpie_1794916786407450000 could
// not be verified"). Asked again, the item goes as the summary it holds,
// not dropped with it, and every other item stays; an item of OpenAI's
// own that it refuses is still left out.
func TestRefusedMagpieCompactionGoesAsText(t *testing.T) {
msg := []byte(`{"error":{"code":"invalid_encrypted_content","message":"The encrypted content for item cmp_magpie_1794916786407450000 could not be verified. Reason: Encrypted content could not be decrypted or parsed.","param":null,"type":"invalid_request_error"}}`)
body, _ := json.Marshal(map[string]any{"model": "gpt-5.4", "input": []any{
map[string]any{"type": "message", "role": "user", "content": []any{map[string]any{"type": "input_text", "text": "first"}}},
map[string]any{"type": "compaction", "id": "cmp_magpie_1794916786407450000", "encrypted_content": codexsummary.Encrypted("we fixed the parser")},
map[string]any{"type": "message", "role": "user", "content": []any{map[string]any{"type": "input_text", "text": "next"}}},
}})
got, ok := withoutUnreadable(body, msg)
if !ok {
t.Fatal("not asked again")
}
var q struct {
Input []struct {
Type string `json:"type"`
ID string `json:"id"`
Content []struct {
Text string `json:"text"`
} `json:"content"`
} `json:"input"`
}
if err := json.Unmarshal(got, &q); err != nil {
t.Fatal(err)
}
if len(q.Input) != 3 {
t.Fatalf("%d items asked again, want 3: %s", len(q.Input), got)
}
mid := q.Input[1]
if mid.Type != "message" || len(mid.Content) != 1 || !strings.HasSuffix(mid.Content[0].Text, "\nwe fixed the parser") || !strings.HasPrefix(mid.Content[0].Text, codexsummary.Prefix) {
t.Fatalf("the compaction went as %+v", mid)
}
if strings.Contains(string(got), "magpie1:") {
t.Fatalf("the sealed form still goes: %s", got)
}
// OpenAI's own compaction it can't read is left out
body, _ = json.Marshal(map[string]any{"model": "gpt-5.4", "input": []any{
map[string]any{"type": "compaction", "id": "cmp_0abc", "encrypted_content": "gAAAAB"},
map[string]any{"type": "message", "role": "user", "content": []any{map[string]any{"type": "input_text", "text": "next"}}},
}})
msg = []byte(`{"error":{"code":"invalid_encrypted_content","message":"The encrypted content for item cmp_0abc could not be verified."}}`)
if got, ok = withoutUnreadable(body, msg); !ok || strings.Contains(string(got), "cmp_0abc") || !strings.Contains(string(got), "next") {
t.Fatalf("OpenAI's own: %v %s", ok, got)
}
}
+137 -22
View File
@@ -15,6 +15,7 @@ import (
"strings"
"sync/atomic"
"time"
"unicode/utf8"
"github.com/klauspost/compress/zstd"
"github.com/tidwall/gjson"
@@ -56,9 +57,11 @@ import (
//
// Every reasoning item OpenAI didn't seal (its encrypted_content is a
// Fernet token, "gAAAA…"), one with Claude's block too, is written as
// magpie_reasoning, a type Codex reads as one it doesn't know and never
// sends (ResponseItem::Other), its summary and content kept for magpie's
// own reading. That is done only as magpie lets Codex go
// magpie_reasoning, a type Codex reads as one it doesn't know
// (ResponseItem::Other), its summary and content kept for magpie's own
// reading. Codex never sends one that is a response_item; one in a
// compacted line's replacement_history it sends as "other", which OpenAI
// refuses (codex-cli 0.165.0), so there it is left out. That is done only as magpie lets Codex go
// (PortCodexRolloutsLeft), as through magpie the gateway sends each as
// the model it goes to takes it (a DeepSeek or Kimi one gets its
// reasoning back from them), and only in a thread begun on OpenAI's or
@@ -89,6 +92,11 @@ type codexPortHome struct {
// Lineage: every fork's place in its parent was looked at once
// (repairLineages), after magpie before it moved them
Lineage bool `json:"lineage,omitempty"`
// Refit: a whole pass was made since a line too long for a paginated
// rollout is written shorter (fitShorter) and a retired item is left
// out of replacement_history, which earlier passes left as they were
// and never looked at again
Refit bool `json:"refit,omitempty"`
}
// codexPortFirst is the first day magpie wrote a compaction item of its
@@ -162,7 +170,7 @@ func portCodexRollouts(ctx context.Context, home string, left bool) (CodexPort,
}
was := st.Homes[key]
since := first
if !was.Since.IsZero() {
if !was.Since.IsZero() && was.Refit {
since = was.Since.Add(-codexPortSlack)
}
start := time.Now()
@@ -219,14 +227,14 @@ func portCodexRollouts(ctx context.Context, home string, left bool) (CodexPort,
break
}
}
now := codexPortHome{Since: was.Since, Pending: pending, Lineage: was.Lineage}
now := codexPortHome{Since: was.Since, Pending: pending, Lineage: was.Lineage, Refit: was.Refit}
if res.Done && !was.Lineage {
fixed, whole := repairLineages(ctx, home)
res.Repaired = fixed
now.Lineage = whole
}
if res.Done {
now.Since = start
now.Since, now.Refit = start, true
} else {
now.Pending = append(now.Pending, was.Pending...)
now.Pending = uniq(now.Pending)
@@ -301,10 +309,20 @@ func portRollout(ctx context.Context, home, path string, left bool) (bool, error
}
}
out, ok := portLineAs(line, left && ours)
if ok {
out, ok = fitLine(line, out, paged)
if !ok {
return out, false
}
return out, ok
if fit, ok := fitLine(line, out, paged); ok {
return fit, true
}
// a paginated rollout's line can't grow, and the message
// with Codex's long summary prefix often is longer than the
// item it stands for (a short summary): left as it was, the
// item went to OpenAI and the chat stopped on
// invalid_encrypted_content (hey_boyce on X). It goes as the
// summary under a short heading, cut to fit when even that is
// longer, as no form of it is worse than the item itself.
return fitShorter(line, left && ours)
}
})
}
@@ -639,14 +657,94 @@ func ordinalEnds(path string) map[int64]int64 {
// portLineAs is portLine, with magpie's reasoning items written as
// magpie_reasoning first when left.
func portLineAs(line []byte, left bool) ([]byte, bool) {
return portLineWith(line, left, fullSummary)
}
// portLineWith is portLineAs with each of magpie's summaries written as
// text makes it, or retired (retiredItem) when text is nil.
func portLineWith(line []byte, left bool, text func(summary string) string) ([]byte, bool) {
retired := false
if left && unsealedReasoning(line) {
line, retired = retireReasoning(line)
}
out, ok := portLine(line)
out, ok := portLineText(line, text)
return out, ok || retired
}
// fullSummary is the text of the message a summary stands for, as Codex's
// own local compaction writes it.
func fullSummary(summary string) string { return codexsummary.Prefix + "\n" + summary }
// shortHeading heads a summary written where Codex's own prefix doesn't
// fit (fitShorter).
const shortHeading = "Summary of the conversation so far:"
// fitShorter is line, a paginated rollout's, with magpie's compaction
// items in it written as a message no longer than line: the summary under
// shortHeading, or as much of its start as fits under it, or, where not
// even the heading fits (a summary of a few words), as much of the
// summary alone. When not even that fits, each item is retired as one
// Codex reads as of a type it doesn't know and never sends (retiredItem):
// the chat goes on without the few words rather than stopping on them.
// It is line and false only when none of these fits.
func fitShorter(line []byte, left bool) ([]byte, bool) {
try := func(text func(string) string) ([]byte, bool) {
out, ok := portLineWith(line, left, text)
if !ok {
return line, false
}
return fitLine(line, out, true)
}
cut := func(head string, n int) func(string) string {
return func(s string) string {
if n >= len(s) {
return head + s
}
for n > 0 && !utf8.RuneStart(s[n]) {
n--
}
return head + s[:n] + "…"
}
}
for _, head := range []string{shortHeading + "\n", ""} {
if out, ok := try(cut(head, len(line))); ok {
return out, true
}
if _, ok := try(cut(head, 0)); !ok {
continue
}
lo, hi := 0, len(line) // the most kept that fits is in [lo, hi)
for hi-lo > 1 {
mid := (lo + hi) / 2
if _, ok := try(cut(head, mid)); ok {
lo = mid
} else {
hi = mid
}
}
return try(cut(head, lo))
}
return try(nil)
}
// retiredReasoning is the type a reasoning item OpenAI didn't seal is
// retired as (retireReasoning).
const retiredReasoning = "magpie_reasoning"
// retiredInList says a line may hold an item retired as a type Codex
// doesn't know in a compacted line's replacement_history, where Codex
// sends it (portValue leaves it out).
func retiredInList(line []byte) bool {
return bytes.Contains(line[:min(len(line), 256)], []byte(`"type":"compacted"`)) &&
(bytes.Contains(line, []byte(`"`+retiredReasoning+`"`)) || bytes.Contains(line, []byte(`"`+retiredItem+`"`)))
}
// retiredItem is the type magpie's compaction item is retired as where
// no message for it fits (fitShorter), with nothing else kept: like
// magpie_reasoning, a type Codex reads as one it doesn't know
// (ResponseItem::Other) and never sends.
const retiredItem = "magpie_compaction"
// retireReasoning is a rollout line with each reasoning item in it that
// OpenAI didn't seal (a response_item's, those in a compacted line's
// replacement_history) written as magpie_reasoning: a type Codex reads
@@ -701,7 +799,7 @@ func retireReasoning(line []byte) ([]byte, bool) {
obj = append(obj, k.Raw...)
obj = append(obj, ':')
if k.String() == "type" {
obj = append(obj, `"magpie_reasoning"`...)
obj = append(obj, `"`+retiredReasoning+`"`...)
} else {
obj = append(obj, v.Raw...)
}
@@ -727,7 +825,12 @@ func retireReasoning(line []byte) ([]byte, bool) {
// gateway leaves it out; a line that is one alone stays as it is, as
// leaving a line out would move every line after it.
func portLine(line []byte) ([]byte, bool) {
if !bytes.Contains(line, magpieMark) && !bytes.Contains(line, claudeMark) {
return portLineText(line, fullSummary)
}
// portLineText is portLine with each summary written as text makes it.
func portLineText(line []byte, text func(summary string) string) ([]byte, bool) {
if !bytes.Contains(line, magpieMark) && !bytes.Contains(line, claudeMark) && !retiredInList(line) {
return line, false
}
body := bytes.TrimRight(line, "\r\n")
@@ -738,7 +841,7 @@ func portLine(line []byte) ([]byte, bool) {
if d.Decode(&v) != nil || d.More() {
return line, false
}
v, changed, _ := portValue(v)
v, changed, _ := portValue(v, text)
if !changed {
return line, false
}
@@ -753,16 +856,28 @@ func portLine(line []byte) ([]byte, bool) {
// portValue is v with magpie's compaction items in it written as their
// messages; drop says v is one of magpie's that can't be read.
func portValue(v any) (_ any, changed, drop bool) {
func portValue(v any, text func(summary string) string) (_ any, changed, drop bool) {
switch x := v.(type) {
case map[string]any:
if t, _ := x["type"].(string); t == retiredReasoning || t == retiredItem {
// Codex never sends one in a response_item, but one in a
// compacted line's replacement_history it sends as
// "other", which OpenAI refuses ("Invalid value: 'other'",
// codex-cli 0.165.0): in a list it is left out
return x, false, true
}
if t, _ := x["type"].(string); t == "compaction" || t == "compaction_summary" {
enc, _ := x["encrypted_content"].(string)
if msg, ours := codexsummary.Message(enc); ours {
if msg == nil {
if sum, ours, ok := codexsummary.Summary(enc); ours {
if !ok {
return x, false, true
}
return msg, true, false
if text == nil {
// left out of a list (replacement_history), where
// Codex sends an item it doesn't know as "other"
return map[string]any{"type": retiredItem}, true, true
}
return codexsummary.UserMessage(text(sum)), true, false
}
return x, false, false
}
@@ -779,7 +894,7 @@ func portValue(v any) (_ any, changed, drop bool) {
for k, c := range x {
list, isList := c.([]any)
if !isList {
if nv, ch, dr := portValue(c); ch && !dr {
if nv, ch, _ := portValue(c, text); ch {
x[k], changed = nv, true
}
continue
@@ -791,7 +906,7 @@ func portValue(v any) (_ any, changed, drop bool) {
meta, hasMeta := x[k+"_metadata"]
metaList, _ := meta.([]any)
drop := !hasMeta || meta == nil || len(metaList) == len(list)
kept, gone, ch := portList(list, drop)
kept, gone, ch := portList(list, drop, text)
if !ch {
continue
}
@@ -808,16 +923,16 @@ func portValue(v any) (_ any, changed, drop bool) {
}
return x, changed, false
case []any:
kept, _, ch := portList(x, true)
kept, _, ch := portList(x, true, text)
return kept, ch, false
}
return v, false, false
}
func portList(list []any, drop bool) (_ []any, gone map[int]bool, changed bool) {
func portList(list []any, drop bool, text func(summary string) string) (_ []any, gone map[int]bool, changed bool) {
out := make([]any, 0, len(list))
for i, e := range list {
nv, ch, dr := portValue(e)
nv, ch, dr := portValue(e, text)
if dr && drop {
if gone == nil {
gone = map[int]bool{}
+134 -18
View File
@@ -13,6 +13,7 @@ import (
"time"
"github.com/klauspost/compress/zstd"
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/claudeseal"
"github.com/yetone/magpie/internal/codexsummary"
@@ -380,26 +381,139 @@ func TestPortCodexRolloutsKeepsBytePlaces(t *testing.T) {
}
// 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.
// prefix) can't grow in a paginated rollout, where Codex keeps each
// line's place by byte. It was left as it was, so the item went to OpenAI
// and the chat stopped on invalid_encrypted_content (hey_boyce on X): it
// goes as the summary under a short heading, as long as the line was,
// cut to fit when even that is longer (a summary of quotes, which JSON
// writes in two bytes and base64 in fewer).
func TestPortCodexRolloutsLongerLine(t *testing.T) {
lines := portRolloutLines("short")
lines[0] = strings.Replace(lines[0], `"model_provider":"openai"`, `"model_provider":"openai","history_mode":"paginated"`, 1)
for _, c := range []struct{ name, summary, want string }{
{"short", "short", "short"},
{"cut", "keep this" + strings.Repeat(`"`, 3000) + "the end", shortHeading + "\nkeep this"},
} {
t.Run(c.name, func(t *testing.T) {
lines := portRolloutLines(c.summary)
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)
for i, l := range got {
if strings.Contains(l, `"encrypted_content":"magpie1:`) {
t.Errorf("line %d still has magpie's item: %.300s", i, l)
}
if !json.Valid([]byte(l)) {
t.Errorf("line %d isn't JSON: %.300s", i, l)
}
}
for _, at := range []string{"payload.content.0.text", "payload.replacement_history.2.content.0.text"} {
i := 2
if strings.HasPrefix(at, "payload.replacement") {
i = 3
}
text := gjson.Get(got[i], at).String()
if !strings.HasPrefix(text, c.want) {
t.Errorf("line %d's %s is %.200q, want it to begin %q", i, at, text, c.want)
}
if c.name == "cut" && (!strings.HasSuffix(text, "…") || strings.Contains(text, "the end")) {
t.Errorf("line %d's summary isn't cut: %.200q…%.50q", i, text, text[max(0, len(text)-50):])
}
}
})
}
}
// An item with no id and a summary of a word has no message as short as
// it: it is retired as a type Codex never sends, never left to be sent.
func TestFitShorterRetires(t *testing.T) {
line := []byte(`{"timestamp":"2026-10-20T07:40:02.551Z","type":"response_item","payload":{"type":"compaction","encrypted_content":"` + codexsummary.Encrypted("ok") + `"}}` + "\n")
out, ok := fitShorter(line, false)
if !ok || len(out) != len(line) {
t.Fatalf("got %q, %v", out, ok)
}
if got := gjson.GetBytes(out, "payload.type").String(); got != retiredItem {
t.Errorf("type %q, want %q: %s", got, retiredItem, out)
}
if gjson.GetBytes(out, "timestamp").String() != "2026-10-20T07:40:02.551Z" {
t.Errorf("the line's head changed: %s", out)
}
}
// A compacted line an earlier pass wrote with magpie_reasoning in its
// replacement_history (or a compaction item retired) had Codex send the
// item as "other", and OpenAI refused every turn after ("Invalid
// response.create payload: Invalid value: 'other'", real codex-cli
// 0.169.1). The next pass leaves it out, and its metadata entry with it,
// the line as long as it was; a magpie_reasoning response_item, which
// Codex never sends, stays.
func TestPortCodexRolloutsDropsRetiredFromHistory(t *testing.T) {
lines := []string{
`{"timestamp":"2026-10-30T07:05:20.118Z","type":"session_meta","payload":{"id":"` + portThread + `","model_provider":"openai","history_mode":"paginated"}}`,
`{"timestamp":"2026-10-30T07:05:40.551Z","type":"response_item","payload":{"type":"magpie_reasoning","summary":[{"type":"summary_text","text":"先看 go.mod"}]}}`,
`{"timestamp":"2026-10-30T07:40:02.553Z","type":"compacted","payload":{"message":"","replacement_history":[{"type":"message","role":"user","content":[{"type":"input_text","text":"修一下构建"}]},{"type":"magpie_reasoning","summary":[]},{"type":"magpie_compaction"},{"type":"message","role":"user","content":[{"type":"input_text","text":"go on"}]}],"replacement_history_metadata":[{"client_authored":true},{},{"compaction_model_hash":"h1"},{"client_authored":true}]}}`,
}
home, path := portHome(t, lines, false)
before := lineEnds(t, path)
ends := 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 !reflect.DeepEqual(lineEnds(t, path), ends) {
t.Fatalf("lines moved: %v, were %v", lineEnds(t, path), ends)
}
if strings.Contains(got[4], "magpie1:%%%") {
t.Errorf("the shorter one wasn't: %s", got[4])
if got[1] != lines[1] {
t.Errorf("the response_item changed: %s", got[1])
}
p := decode(t, got[2])["payload"].(map[string]any)
var types []string
for _, it := range p["replacement_history"].([]any) {
types = append(types, it.(map[string]any)["type"].(string))
}
if !reflect.DeepEqual(types, []string{"message", "message"}) {
t.Errorf("replacement_history is %v: %s", types, got[2])
}
if m := p["replacement_history_metadata"].([]any); !reflect.DeepEqual(m, []any{map[string]any{"client_authored": true}, map[string]any{"client_authored": true}}) {
t.Errorf("metadata %v", m)
}
}
// A pass before this one looked at a paginated rollout, left its too-long
// line as it was, and never looked at it again, as no later pass reads a
// rollout last written before the one before it. One whole pass is made
// again, once.
func TestPortCodexRolloutsRefitsOnce(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)
st := codexPortState{Homes: map[string]codexPortHome{filepath.Clean(home): {Since: time.Now(), Lineage: true}}}
b, _ := json.Marshal(st)
if err := os.MkdirAll(filepath.Dir(codexPortPath()), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(codexPortPath(), b, 0o600); err != nil {
t.Fatal(err)
}
res, err := PortCodexRollouts(context.Background(), home)
if err != nil || len(res.Rewritten) != 1 {
t.Fatalf("pass: %+v, %v", res, err)
}
if got := readRollout(t, path); strings.Contains(got[2], `"encrypted_content":"magpie1:`) {
t.Errorf("not written: %s", got[2])
}
// the next pass reads only what changed since
lines[2] = strings.Replace(lines[2], "cmp_magpie_1761000002", "cmp_magpie_1761000003", 1)
b2 := []byte(strings.Join(lines, "\n") + "\n")
os.WriteFile(path, b2, 0o640)
old := time.Now().Add(-time.Hour)
os.Chtimes(path, old, old)
if res, err := PortCodexRollouts(context.Background(), home); err != nil || len(res.Rewritten) != 0 {
t.Errorf("second pass: %+v, %v", res, err)
}
}
@@ -470,8 +584,10 @@ func TestPortCodexRolloutsRepairsForks(t *testing.T) {
// ("Invalid 'input[5].content': array too long"). A pass made as magpie
// lets Codex go writes each reasoning item OpenAI didn't seal as
// magpie_reasoning, a type Codex reads as Other and never sends, in a
// response_item and in replacement_history (its metadata kept beside
// it), each line its length; OpenAI's own sealed reasoning and every
// response_item; in replacement_history, where Codex sends an Other as
// "other" and OpenAI refuses the turn ("Invalid value: 'other'", real
// codex-cli 0.165.0 and 0.169.1), it is left out with its metadata entry.
// Each line keeps its length; OpenAI's own sealed reasoning and every
// other line keep their bytes. A pass while Codex goes through magpie
// leaves them: there a DeepSeek or Kimi model gets its reasoning back
// from them. A thread begun on a provider of the user's own is left be.
@@ -522,11 +638,11 @@ func TestPortCodexRolloutsLeftRetiresUnsealedReasoning(t *testing.T) {
}
p4 := decode(t, got[4])["payload"].(map[string]any)
hist := p4["replacement_history"].([]any)
if len(hist) != 3 || hist[1].(map[string]any)["type"] != "magpie_reasoning" ||
hist[2].(map[string]any)["type"] != "reasoning" || hist[2].(map[string]any)["encrypted_content"] != "gAAAAABo_OpenAIsOwn==" {
if len(hist) != 2 || hist[0].(map[string]any)["type"] != "message" ||
hist[1].(map[string]any)["type"] != "reasoning" || hist[1].(map[string]any)["encrypted_content"] != "gAAAAABo_OpenAIsOwn==" {
t.Errorf("replacement_history %v", hist)
}
if m := p4["replacement_history_metadata"].([]any); len(m) != 3 {
if m := p4["replacement_history_metadata"].([]any); len(m) != 2 || !reflect.DeepEqual(m[0], map[string]any{"client_authored": true}) {
t.Errorf("metadata %v", m)
}
if p7 := decode(t, got[7])["payload"].(map[string]any); p7["type"] != "magpie_reasoning" || strings.Contains(got[7], claudeseal.Mark) {