Skip to content

Automatic compaction loses active task: continuation receives environment-only user context despite preserved rollout #57608

Closed as not planned

Description

@nurazem

What issue are you seeing?

A long-running Codex session lost its active task immediately after automatic compaction. The assistant stopped and asked the user to resend the task, despite the original conversation and a task checkpoint still existing locally. When the user pasted the recent transcript and asked to locate the chat, the assistant located the very same session but presented it as a separate chat to resume.

This is an observed continuity failure; the precise client/server root cause is not established.

Environment

  • Session metadata: Codex 0.164.0; source vscode, originator codex-tui.
  • macOS 15.7.7, arm64.
  • Model recorded at the affected boundary: gpt-6-astra, medium reasoning.
  • Occurred 2026-10-27 at 22:16:27 UTC during ongoing work.

Evidence from the saved rollout

At the affected compacted record:

  • message was an empty string.
  • replacement_history contained seven entries: one additional-tools entry, five developer-message entries, and one user-message entry.
  • The sole user message was environment context, not the user's task.
  • No assistant summary or substantive user task message was present in that replacement history.
  • retained_context separately recorded eight user messages and eight assistant messages, with both corresponding incomplete flags true. This establishes that retained metadata existed; it does not establish that its contents reached the continuation model.
  • The original earlier transcript remained readable in the same local session file. This was not deletion of the on-disk transcript.

At 22:16:49 UTC, the assistant responded:

I have the workspace context, but the active request isn’t available. Please resend the task you’d like me to continue.

Later, reading the original session file and an existing filesystem checkpoint recovered the authorized task and progress.

What steps can reproduce the bug?

Observed sequence (not yet a deterministic minimal reproduction):

  1. Run a long, multi-stage coding/validation task in one session across several automatic compactions.
  2. Let another automatic compaction occur while the task is unfinished.
  3. Inspect whether the continuation retains the active task, prior decisions, and pending work.
  4. In this occurrence, it instead stopped and requested the task again; inspecting the compacted rollout showed the replacement-history shape above.

Earlier compactions also had empty message strings, so an empty string alone is not claimed to be sufficient to reproduce this failure.

What is the expected behavior?

Compaction should preserve enough usable task state for continued work, or explicitly surface a failed handoff and recover the prior state before continuing. It should not silently resume with only environment context and then abandon an active authorized task. The continuation should also recognize its own current session when locating the transcript.

Additional information

Related: #54584 and #55508 concern invalid or stale local-compaction summaries with other providers. This report does not establish that the same code path is responsible: this occurrence used the model listed above and includes separate retained-context metadata.

Please investigate validation of the replacement context and delivery of retained task state at this boundary. A regression test should verify that a continuing long-running task can recover its objective and pending operation after compaction.

Project names, repository details, credentials, source code, private task content, and full session logs are intentionally omitted.

Activity

  1. added
    bug
    extension
    context
    session
    on Oct 28, 2026
  2. r266-tech commented on Oct 28, 2026

    @r266-tech

    A source check against the published rust-v0.164.0 tag (6aaac694) narrows the handoff to inspect:

    Is the seven-entry list exhaustive, including non-message items? A sanitized list of only each entry's type and, for messages, role would help distinguish an absent checkpoint from a present opaque checkpoint that failed to preserve the task. No message text or encrypted_content is needed.

    I inspected the release source only; I have not reproduced the incident or established which compaction path the affected client used. AI-assisted analysis.

  3. wyshmily commented on Oct 28, 2026

    @wyshmily

    Adding an independent Windows occurrence from October 28, 2026, with evidence inspected in the local rollout. Immediately after automatic compaction, Codex abandoned the active implementation task and ended the turn with an acknowledgement of AGENTS.md rules.

    Environment: Codex desktop on Windows; the turn context at the affected boundary records gpt-6-astra, medium reasoning. The exact desktop/runtime build responsible for this boundary has not been independently established.

    The sequence below is from one continuous session. Times are UTC:

    Timestamp on 2026-10-28 Observed record
    03:18:44.412 The assistant reported that relevant checks had passed and said it was moving on to the final build/release and documentation wrap-up. This describes the assistant's progress report, not an independent audit of those checks.
    03:21:09.184 A compacted record was written.
    03:21:26.893 The assistant issued the rules-only final response quoted below.
    03:21:26.943 A task_complete event ended the turn.

    The final response, translated from Chinese with the workspace path redacted:

    Acknowledged. Going forward in [workspace], I will follow these rules, communicate in Chinese, complete the necessary build validation, and commit locally.

    There was no new user message between the compaction and turn completion. The response did not deliver the pending work or report its actual remaining status. It behaved as though acknowledging the injected AGENTS.md instructions was the task.

    For comparison with the type/role question in the preceding comment, the following is the complete replacement_history type/role list from this occurrence, including non-message entries:

    [
      {"type":"additional_tools","role":"developer"},
      {"type":"message","role":"developer"},
      {"type":"message","role":"developer"},
      {"type":"message","role":"developer"},
      {"type":"message","role":"developer"},
      {"type":"message","role":"developer"},
      {"type":"message","role":"user"}
    ]

    The sole user-role message contained AGENTS.md instructions plus environment context. It did not contain the substantive active task. There was no assistant summary or compaction-typed item in this serialized array.

    Other fields at that boundary:

    message: ""
    retained_context.user_messages: 8 entries
    retained_context.assistant_messages: 8 entries
    retained_context.incomplete: false
    retained_context.user_messages_incomplete: true
    retained_context.assistant_messages_incomplete: true
    

    The original task messages and pre-compaction progress remained readable in the same local rollout. This was not deletion of the on-disk conversation.

    Evidence limits: an earlier compaction in this session had the same seven-entry type/role shape, so that shape alone is not a failure detector. An empty message alone is also insufficient. The separate retained-context fields establish that additional state was recorded, but do not establish what was delivered to, or effectively used by, the continuation model. This does not prove the internal checkpoint was absent or identify a client/server root cause.

    Please include “AGENTS.md acknowledgement followed by immediate turn completion while substantive work remains pending” as a continuation-failure case when investigating this issue. The expected behavior is to recover the active objective and remaining work, treating AGENTS.md as execution constraints rather than the deliverable.

    Privacy: project names, local paths, business details, account/session/message identifiers, source code, screenshots, credentials, opaque payloads, and raw logs are omitted. This is an AI-assisted, user-authorized report based on inspected local records.

  4. nurazem commented on Oct 28, 2026

    @nurazem
    Author

    Follow-up from the original reporter: this is still occurring, including in a session whose metadata records 0.165.0. I inspected the 10 most recently active main sessions (excluding this investigation and background agents), cloned the public repository, and ran a synthetic local probe before posting.

    New finding: the failures include unsuccessful recovery operations after a fresh-window transition. The seven-entry replacement array is not, by itself, evidence that remote V2 compaction lost its opaque checkpoint.

    Anonymized observed failures

    20 compaction boundaries were inspected across 10 sessions. Six clear lost-task continuations occurred in three sessions. All six had substantive work pending, no intervening user message, and a final lost-task response followed by task_complete. Session labels below are arbitrary and contain no original identifiers. Times are UTC.

    Session Session metadata version Compaction timestamp Final response timestamp Failed recovery operations before final
    A 0.165.0 2026-10-28 01:32:11.508 01:32:33.023 3
    A 0.165.0 2026-10-28 02:43:19.123 02:43:40.887 4
    A 0.165.0 2026-10-28 05:17:12.497 05:17:42.215 5
    B 0.164.0 2026-10-27 19:58:03.225 19:58:16.303 3
    B 0.164.0 2026-10-27 22:16:27.476 22:16:49.717 4
    C 0.164.0 2026-10-28 00:58:05.512 00:58:17.173 3

    The second B occurrence is the original issue's incident, not an additional incident. The recorded model at all six boundaries is gpt-6-astra, medium reasoning. Version labels above are session metadata, not a claim that every resumed turn used that exact executable build.

    The repeated recovery error was:

    Unable to perform operation: The backend request failed.
    

    Two other boundaries also had these errors but continued substantive work, so backend errors alone are not a sufficient failure detector either. The other 14 inspected boundaries did not show this immediate lost-task final response; that is not a claim that their entire sessions were error-free.

    Common fields at all six failure boundaries:

    {
      "message": "",
      "compaction_response_id": null,
      "replacement_history_type_role_list": [
        {"type":"additional_tools","role":"developer"},
        {"type":"message","role":"developer"},
        {"type":"message","role":"developer"},
        {"type":"message","role":"developer"},
        {"type":"message","role":"developer"},
        {"type":"message","role":"developer"},
        {"type":"message","role":"user"}
      ]
    }

    This list is exhaustive, including non-message entries. The sole user entry is environment context. Retained-context counts (user, assistant) are A: (2,8), (5,8), (8,8); B: (4,8), (8,8); C: (8,8). These counts establish separately recorded state, not successful delivery or recovery.

    Local source investigation and runnable boundary reproduction

    Source checkout: rust-v0.165.0, commit 360319d8dee62d87e2d59fc0c21805d79519cfed. Executed binary: locally installed codex-cli 0.165.0. I inspected the pinned source but did not build it or run its Rust test suite.

    Relevant source:

    I ran the Python probe below against the installed binary. It uses a loopback SSE server, synthetic content, no API credentials, an ephemeral session, and a temporary workspace. A synthetic tool call and reported token usage force a mid-turn threshold crossing. The mock final response is fixed; it does not simulate or establish an actual model's reasoning or recovery behavior.

    Observed results:

    Probe Requests Compaction requests Continuation requests Task marker in continuation Opaque checkpoint in continuation
    V2, checkpoint supplied 3 1 1 yes yes
    V2, checkpoint omitted 2 1 0 n/a n/a
    Token-budget fresh window 2 0 1 no no

    The fresh-window continuation also included a previous-window reference. The omitted-checkpoint V2 case exited with an error; it did not silently continue.

    Reproduction boundary: this deterministically reproduces the task-free fresh-window request, not the production backend failure or the model's subsequent abandonment. That fresh-window behavior is intentional in the source. Combined with the observed recovery errors, it points investigation toward recovery availability and fail-safe continuation at that boundary. It does not prove which client/server component failed in the real sessions.

    A useful regression would force this window transition during an unfinished task, make recovery unavailable, and verify that the session preserves/reacquires a minimal active-task checkpoint or explicitly reports a recoverable handoff failure rather than successfully completing a turn by asking for a new task.

    Runnable Python probe (Python 3, codex-cli 0.165.0 on PATH)

    Save as mock_compaction.py and run python3 mock_compaction.py. No dependencies beyond Python's standard library and the installed Codex binary are required. Localhost socket access is required. Three passing assertions confirm the boundary behavior described above, not an end-to-end reproduction of the production incident.

    #!/usr/bin/env python3
    """Credential-free client-boundary probe. Does not reproduce a model failure."""
    import json, os, subprocess, tempfile, threading
    from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
    
    MARKER = 'SYNTHETIC_TASK_57608: finish step two after step one'
    CHECKPOINT = 'SYNTHETIC_OPAQUE_CHECKPOINT_57608'
    
    def run_case(mode):
        requests = []
        class Handler(BaseHTTPRequestHandler):
            def log_message(self, *args): pass
            def do_GET(self):
                self.send_response(404); self.end_headers()
            def do_POST(self):
                body = json.loads(self.rfile.read(int(self.headers['Content-Length'])))
                compact = any(x.get('type') == 'compaction_trigger' for x in body.get('input', []))
                requests.append({'path': self.path, 'compact': compact, 'body': body})
                n = len(requests)
                if compact:
                    items = [] if mode == 'missing' else [{'type':'compaction','encrypted_content':CHECKPOINT}]
                    tokens = 50
                elif n == 1:
                    items = [{'type':'function_call','call_id':'synthetic-call','name':'synthetic_noop','arguments':'{}'}]
                    tokens = 250000
                else:
                    items = [{'type':'message','role':'assistant','id':'synthetic-final','content':[{'type':'output_text','text':'SYNTHETIC_DONE'}]}]
                    tokens = 50
                events = [{'type':'response.output_item.done','item':x} for x in items]
                events.append({'type':'response.completed','response':{'id':f'synthetic-response-{n}','usage':{'input_tokens':tokens,'output_tokens':0,'total_tokens':tokens}}})
                data = ''.join('data: '+json.dumps(e)+'\n\n' for e in events).encode()
                self.send_response(200); self.send_header('Content-Type','text/event-stream'); self.send_header('Content-Length',str(len(data))); self.end_headers(); self.wfile.write(data)
        server = ThreadingHTTPServer(('127.0.0.1',0),Handler)
        threading.Thread(target=server.serve_forever,daemon=True).start()
        with tempfile.TemporaryDirectory(prefix='codex-57608-') as temp:
            settings = {
                'model_provider':'synthetic','model_providers.synthetic.name':'synthetic',
                'model_providers.synthetic.base_url':f'http://127.0.0.1:{server.server_port}/v1',
                'model_providers.synthetic.wire_api':'responses',
                'model_providers.synthetic.capabilities.remote_compaction':'v2',
                'model_providers.synthetic.requires_openai_auth':False,
                'model_providers.synthetic.supports_websockets':False,
                'model_providers.synthetic.stream_max_retries':0,
                'model_providers.synthetic.request_max_retries':0,
                'model_auto_compact_token_limit':200000,
                'sqlite_home':temp, 'log_dir':temp,
                'features.shell_snapshot':False,
                'features.token_budget':mode=='fresh_window',
            }
            cmd=['codex','exec','--ignore-user-config','--ignore-rules','--ephemeral','--skip-git-repo-check','-C',temp,'-s','read-only','-m','gpt-6-astra','--json']
            for k,v in settings.items():cmd += ['-c',k+'='+json.dumps(v)]
            cmd.append(MARKER)
            env={k:v for k,v in os.environ.items() if not any(s in k.upper() for s in ('TOKEN','API_KEY','SECRET','PASSWORD'))}
            p=subprocess.run(cmd,env=env,text=True,capture_output=True,stdin=subprocess.DEVNULL,timeout=90)
        server.shutdown()
        continuation=[r for r in requests[1:] if not r['compact']]
        result={'mode':mode,'exit_code':p.returncode,'request_count':len(requests),'compaction_requests':sum(r['compact'] for r in requests),'continuation_requests':len(continuation),'checkpoint_in_continuation':any(any(x.get('type')=='compaction' and x.get('encrypted_content')==CHECKPOINT for x in r['body'].get('input',[])) for r in continuation)}
        result['task_marker_in_continuation'] = any(MARKER in json.dumps(r['body'].get('input',[])) for r in continuation)
        result['previous_window_in_continuation'] = any('Previous context window id:' in json.dumps(r['body'].get('input',[])) for r in continuation)
        print(json.dumps(result,indent=2))
        if not requests or (mode != 'fresh_window' and not result['compaction_requests']):
            print('Probe did not reach the intended compaction path; inspect locally if needed.')
        if mode=='fresh_window':
            assert len(continuation)==1 and result['previous_window_in_continuation'], 'fresh window not installed'
            assert not result['task_marker_in_continuation'] and not result['checkpoint_in_continuation'], 'task or checkpoint unexpectedly retained'
        elif mode=='valid':
            assert result['compaction_requests']==1 and result['checkpoint_in_continuation'], 'valid checkpoint not carried forward'
        else:
            assert result['compaction_requests']>=1 and not continuation, 'missing checkpoint did not fail closed'
        return result
    
    if __name__=='__main__':
        for mode in ('valid','missing','fresh_window'):run_case(mode)

    Privacy: no original session/message/window identifiers, private workspace paths, project names, task text, private source code, credentials, opaque production payloads, or raw logs are included. This is an AI-assisted, user-authorized report based on inspected local records and a synthetic client-boundary probe.

  5. 1939869736luosi commented on Oct 28, 2026

    @1939869736luosi

    Independent confirmation from macOS desktop on October 28, 2026: five lost-task continuations across four main chats (anonymous sessions A: two incidents; B, C, D: one each). The affected boundaries record gpt-6-astra, and experimental context management is enabled locally.

    For each incident, inspected local records show:

    • Authorized work was still pending.
    • No new user message intervened between the recorded boundary and the final answer.
    • Three recovery operations failed with Unable to perform operation: The backend request failed.
    • The assistant ended with an acknowledgement of workspace rules, including using Chinese by default, instead of continuing the task.
    • The original task and progress remained readable in the local transcript.

    All five boundaries had an empty message, null compaction_response_id, and seven replacement entries: one additional-tools/developer item, five developer messages, and one user message containing workspace/environment instructions. There was no assistant summary or compaction-typed item. Separate retained-context metadata recorded eight user and eight assistant messages.

    The structure alone is not a failure detector; the failure is unsuccessful recovery followed by an unrelated final answer while work remains pending. One occurrence spans a desktop relaunch and another is an app-update resume; the first three occurred before that relaunch.

    The underlying HTTP status and server-side cause are unverified. No isolated reproduction or workaround validation was performed.

    Please test recovery-unavailable transitions explicitly: preserve/reacquire the active task or report a recoverable handoff failure, rather than treating rule acknowledgement as task completion.

    This user-authorized, AI-assisted summary excludes original chat content/titles, project details, paths, account/session identifiers, credentials, screenshots, and raw logs.

  6. John-Rood commented on Oct 28, 2026

    @John-Rood

    You traced the fresh-window selection and left one question open in the follow-up: whether the seven-entry list is evidence that remote V2 lost its checkpoint. It is not, and the reason sits in the retention filter. Nothing on that path can put a user message into the replacement history.

    Where the shape comes from

    run_auto_compact branches on a feature before it looks at remote_compaction at all:

    // codex-rs/core/src/session/turn.rs#L1556-L1568
    if turn_context.config.features.enabled(Feature::TokenBudget) {
        crate::compact_token_budget::run_inline_auto_compact_task(
            Arc::clone(sess),
            replacement_step_context,
            world_state,
        )
        .await?;
        return Ok(true);
    }

    That path never asks a model to summarise. compact_token_budget.rs#L42-L58 goes straight to start_new_context_window, and the same feature disables summarization for the turn at turn.rs#L187 (auto_summarization_enabled = auto_compaction_enabled && !features.enabled(Feature::TokenBudget)). So message: "" and compaction_response_id: null are what this installer writes, not signs that a summary was produced and dropped.

    start_new_context_window (codex-rs/core/src/session/mod.rs#L4968) builds the new history from the initial context items, then retained_client_items, then installs them through replace_compacted_history. The filter is the whole story:

    // mod.rs#L4976-L4992
    .filter(|item| {
        (self.enabled(Feature::RetainClientToolOutputs)
            && crate::compact_retained_tool_outputs::is_retained_tool_output(item))
            || (self.enabled(Feature::RetainClientDeveloperMessages)
                && crate::compact_remote_v2::is_client_authored_developer_message(item))
    })

    and is_client_authored_developer_message (compact_remote_v2.rs#L507-L512) matches role == "developer" behind a client_authored flag. A user turn has no branch into that list. So one additional_tools entry, five developer entries and one user entry, with the user entry carrying environment context, is the deterministic output of this path when nothing is retained. You and three independent reporters produced the same list because it is fixed, not because you hit the same server failure.

    retained_context is not a second channel. It is written as a field on the CompactedItem rollout record at mod.rs#L4485, sitting next to mcp_resource_origins and resume_metadata. The model receives replacement_history. Counts of 8 and 8 with incomplete flags describe what the history tracked for resume bookkeeping, and they cannot describe what the continuation saw, because that channel does not reach a request. That was the one thing the thread could not close from the outside, and it closes from the source.

    The lever

    token_budget is Stage::UnderDevelopment with default_enabled: false (codex-rs/features/src/lib.rs#L2002-L2005). Turn it off and the V2 branch runs instead, which your probe already shows carries the checkpoint into the continuation. In config:

    [features]
    token_budget = false

    or -c features.token_budget=false. It is worth asking each reporter whether experimental context management was on, since every boundary in this thread has the shape that only this path produces. 1939869736luosi already said it was enabled locally.

    Measured contrast

    Ten compaction boundaries in my own rollouts that carry a compaction-typed item retained between one and fourteen substantive user messages each. The reported shape retains zero. Same rollout format, different installer.

    Detecting it and getting the task back

    compact-audit.mjs walks a rollout, classifies every compacted record as checkpointed, task-free, or a local summary, and prints the pending user task from before any boundary that came out task-free. Point it at ~/.codex/sessions.

    compact-audit.mjs (node, no dependencies, read-only, no network)
    #!/usr/bin/env node
    // Audit Codex rollout files for compaction boundaries that carry no task state.
    // Usage: node compact-audit.mjs <rollout.jsonl|dir> [more...]
    
    import { readFileSync, readdirSync, statSync } from "node:fs";
    import { join, basename } from "node:path";
    
    const CONTEXT_TAGS = [
      "environment_context",
      "user_instructions",
      "skills_instructions",
      "permissions instructions",
      "system_context",
    ];
    
    // Remove blocks codex injects itself. What survives is authored by the human, i.e. the task.
    function stripContext(text) {
      let t = String(text ?? "");
      for (const tag of CONTEXT_TAGS) {
        t = t.replace(new RegExp(`<${tag}>[\\s\\S]*?<\\/${tag}>`, "gi"), " ");
      }
      t = t.replace(/^#+\s*AGENTS\.md instructions[\s\S]*$/im, " ");
      t = t.replace(/<user_instructions>[\s\S]*$/i, " ");
      return t.replace(/\n{2,}/g, "\n").trim();
    }
    
    function textOf(item) {
      const content = item?.content;
      if (typeof content === "string") return content;
      if (!Array.isArray(content)) return "";
      return content.map((c) => (typeof c === "string" ? c : c?.text ?? "")).filter(Boolean).join("\n");
    }
    
    function readRollout(path) {
      const out = [];
      for (const line of readFileSync(path, "utf8").split("\n")) {
        if (!line.trim()) continue;
        try { out.push(JSON.parse(line)); } catch { /* truncated tail line */ }
      }
      return out;
    }
    
    function classify(payload) {
      const rh = payload?.replacement_history ?? [];
      const hasCompactionItem = rh.some((i) => i?.type === "compaction");
      const taskBearing = rh
        .filter((i) => i?.type === "message" && i?.role === "user")
        .filter((i) => stripContext(textOf(i)).length >= 40);
      const emptyMessage = !payload?.message;
      const noResponseId = payload?.compaction_response_id == null;
    
      let kind;
      if (hasCompactionItem) kind = "checkpointed_or_v2";
      else if (emptyMessage && noResponseId && taskBearing.length === 0) kind = "fresh_window_no_task";
      else if (emptyMessage && noResponseId) kind = "unclassified_empty_message";
      else kind = "local_summary";
    
      return { kind, rh, taskBearing };
    }
    
    function recoverTask(records, uptoIndex, want = 2) {
      const found = [];
      for (let i = uptoIndex - 1; i >= 0 && found.length < want; i--) {
        const r = records[i];
        let role = null;
        let text = "";
        if (r?.type === "response_item" && r.payload?.type === "message") {
          role = r.payload.role;
          text = textOf(r.payload);
        } else if (r?.type === "event_msg" && r.payload?.type === "user_message") {
          role = "user";
          text = r.payload.message ?? "";
        }
        if (role !== "user") continue;
        const clean = stripContext(text);
        if (clean.length >= 40) found.push({ at: r.timestamp, text: clean });
      }
      return found.reverse();
    }
    
    function expand(target) {
      if (!statSync(target).isDirectory()) return [target];
      return readdirSync(target, { withFileTypes: true }).flatMap((e) => {
        const p = join(target, e.name);
        return e.isDirectory() ? expand(p) : e.name.endsWith(".jsonl") ? [p] : [];
      });
    }
    
    const files = process.argv.slice(2).flatMap(expand);
    if (!files.length) { console.error("usage: node compact-audit.mjs <rollout.jsonl|dir> ..."); process.exit(2); }
    
    const tally = {};
    const lost = [];
    
    for (const file of files) {
      const records = readRollout(file);
      records.forEach((r, idx) => {
        if (r?.type !== "compacted") return;
        const { kind, rh, taskBearing } = classify(r.payload);
        tally[kind] = (tally[kind] ?? 0) + 1;
        const shape = rh.map((i) => `${i?.type}/${i?.role ?? "-"}`).join(",");
        console.log(`${basename(file)} #${r.ordinal} ${r.timestamp} ${kind} entries=${rh.length} task_user_msgs=${taskBearing.length} [${shape}]`);
        if (kind === "fresh_window_no_task") {
          lost.push({ file, ordinal: r.ordinal, timestamp: r.timestamp, recovered: recoverTask(records, idx) });
        }
      });
    }
    
    console.log("\nsummary:", JSON.stringify(tally));
    
    for (const l of lost) {
      console.log(`\n--- recoverable task at ${basename(l.file)} #${l.ordinal} ${l.timestamp} ---`);
      if (!l.recovered.length) { console.log("(no substantive user message found before the boundary)"); continue; }
      for (const m of l.recovered) console.log(`[${m.at}]\n${m.text.slice(0, 1200)}\n`);
    }

    I built a fixture that reproduces your exact seven-entry list and the script flagged it as task-free and printed the task from before the boundary. Run across my local sessions it classified ten checkpointed boundaries and reported zero task-free, so it is not firing on the normal shape.

    The fix

    A retention budget already exists for developer messages: RETAINED_MESSAGE_TOKEN_BUDGET = 64_000 (compact_remote_v2.rs#L87). The narrow change is to apply the same idea to user-authored messages under its own smaller budget, so a fresh window always carries the objective it is supposed to continue. The regression you asked for can then assert it directly: at a token-budget boundary with a turn in flight, replacement_history must contain at least one user-role item that is not environment context.

    If the requirement is memory that survives the boundary regardless of which installer runs, that is what I built MemoryRouter for: the agent's memory on the account rather than inside the window. https://docs.memoryrouter.ai/codex?utm_source=github&utm_medium=issue&utm_campaign=openai-codex

  7. tk-neuron commented on Oct 29, 2026

    @tk-neuron

    I’m seeing a similar issue in Codex Desktop on macOS: after “Optimized the conversation,” Codex sometimes loses the active task and asks me to explain what I want to work on again.

    In one session on October 29, I found the following sequence in the local logs (times in JST):

    • 09:33:28 — notes/v2/write_file returned HTTP 404, followed by Unable to perform operation: The backend request failed.
    • 09:33:32 — new_context ran. During run_auto_compact, notes/v2/thread_hint returned HTTP 404.
    • 09:33:35 — notes/v2/list_files_by_prefix returned HTTP 404, again followed by The backend request failed. The same endpoint returned another 404 at 09:33:44.

    The failures around the context transition may be related to the recovery failures reported above, although I can’t establish from these logs whether they caused the task to be lost. The 404s came from notes-related endpoints, not the compaction endpoint.

    The retained logs also show thread_hint returning HTTP 200 on October 27 and HTTP 404 on October 28–29. I don’t know when or why that changed.

    Environment:

    • Codex Desktop 26.1007.71326, build 20398, production channel

    • macOS 26.6 on Apple Silicon

    • Japanese UI

    • Experimental context management is currently enabled:

      [features.context_management]
      experimental_mode = true

    I haven’t confirmed whether this setting was enabled at every affected boundary or tested whether disabling it changes the behavior.

  8. John-Rood commented on Oct 29, 2026

    @John-Rood

    Your config answers the question the thread left open for the reporters, and it answers it harder than you probably intended.

    [features.context_management] experimental_mode = true does not sit next to token_budget. It turns token_budget on. On rust-v0.165.0, apply_experimental_context gates on ContextManagement and then switches the flag itself:

    // codex-rs/core/src/session/token_budget.rs#L27-L41
    if !config.features.enabled(Feature::ContextManagement)
        || !starting_model.supports_experimental_context
        ...
        || config.features.enable(Feature::TokenBudget).is_err()
        || !config.features.enabled(Feature::TokenBudget)
    {
        return Ok(());
    }

    and it runs at session start (core/src/session/mod.rs#L824-L834), before the turn. So token_budget = false will not hold while context management is on: the gate re-inserts TokenBudget on the next session. That is my correction to the lever I gave earlier in this thread. To leave the fresh-window path you have to turn off context_management, not token_budget.

    The same function sets use_history_notes_extension = true unconditionally (token_budget.rs#L56). That is why a desktop session on experimental context management is calling notes routes at all. It is not a separate feature you opted into.

    Which makes your 404s the interesting part of this comment, not a side note. thread_hint is a context contributor, not a convenience call:

    // codex-rs/ext/history-notes/src/extension.rs#L127-L136
    let Ok(result) = config.backend
        .call("alpha/notes/v2/thread_hint", ..., TruncationPolicy::Bytes(MAX_THREAD_HINT_BYTES))
        .await
    else {
        track_status(ThreadHintStatus::Failed);
        return Vec::new();
    };

    On any error, 404 included, it emits an analytics status and returns an empty fragment list. No prompt fragment, no error surfaced, nothing in the transcript saying the hint did not arrive. And that fragment is contributed to PromptSlot::ContextWindow, meaning it is the channel that carries what the thread was working on into the next window. On the fresh-window installer, replacement_history has no user-authored task by construction, so the hint is the one thing that can put the objective back. A 404 there removes it silently.

    Your other two endpoints are the same extension's tools: write_file and list_files_by_prefix at ext/history-notes/src/tools.rs#L80-L98. The wrap-up prompt that asks for a note is fired when the window is spent (core/src/session/turn.rs#L682-L687 into token_budget.rs#L201-L212). Read against that, your 09:33 sequence is the whole extension failing in order: the note write fails, new_context runs with nothing task-bearing to retain, the hint read fails, the notes read fails. Every step of the recovery path 404s and every step is silent. That does not prove the model abandoned the task, but it does mean there was nothing left in the request that could have kept it, which is a better explanation than the model freely choosing to re-acknowledge rules.

    thread_hint returning 200 on October 27 and 404 on October 28-29 also rules something out. The client build did not change and the call site did not change, so a backend route retired or moved under a live client. Any client on experimental context management between those dates is calling a route that no longer answers, and failing soft.

    Worth checking before anyone hand-correlates logs: ThreadHintStatusEvent already records thread id, status and timestamp. The Failed events are in telemetry now. Joining those to the task-free boundaries gives the correlation directly instead of rebuilding it from local logs.

    The fix you asked for is right, and the code makes the cheap half of it obvious. A contributor that cannot deliver its fragment should contribute a line saying so rather than an empty vector, and nothing should complete a turn as successful while the window that replaced the task carried no task.

  9. Shimada666 commented on Oct 30, 2026

    @Shimada666

    Independent Linux occurrence on October 30, 2026, with a read-only HTTP recheck and local mitigation.

    Environment:

    • Linux; installed CLI reports codex-cli 0.165.0 at investigation time. This is not proof that every earlier turn used that executable.
    • The affected turn's client log records gpt-6-astra, medium reasoning.
    • Local configuration had [features] context_management = true.

    Observed sequence in the same ongoing session (UTC):

    • 02:24:05: user requested an operational investigation.
    • 02:24:12: assistant acknowledged the concrete investigation and described its next actions.
    • 02:24:13: assistant read the relevant skill instructions.
    • 02:25:22: a compacted record installed replacement history.
    • 02:25:38: assistant ended the turn by acknowledging workspace rules, without continuing the requested investigation. No new user request intervened.

    The serialized replacement history had exactly seven entries: one additional_tools developer entry, five developer messages, and one user message containing AGENTS.md/environment context. It contained neither the active user task nor an assistant summary or compaction item. message was empty. The preceding task and progress were still readable in the local rollout; the on-disk transcript was not deleted.

    Client HTTP logs independently show four related backend requests returning HTTP 404 around the handoff, at 02:25:18, 02:25:22, 02:25:26 and 02:25:30 UTC. A read-only retry at 02:36:10 UTC also returned HTTP 404; x-oai-request-id: 5d622df4-6f65-45c9-88b4-85afa653ba05.

    Evidence limits:

    • Available local HTTP logs cover October 29–30 only. We found no earlier successful response for this recovery path in that retained interval, so we cannot claim a local 200-to-404 transition or identify when it broke.
    • This confirms an observed failed continuation and HTTP failures, not the private server-side cause or a feature-retirement decision.
    • The seven-entry shape alone is not an end-to-end failure detector.

    Mitigation applied after investigation: removed the local context_management opt-in. A fresh codex features list reports both context_management and token_budget as false. This validates configuration only; we have not yet verified a subsequent long-task compaction or claimed that the already-running session changed behavior.

    Please include the case where unfinished work is followed by a rules-only final response, and ensure a failed task-state handoff cannot silently be treated as successful task completion.

    User-authorized, AI-assisted report. Private task details, workspace paths, account/session/window identifiers, credentials, and full logs are omitted.

  10. charles39 commented on Oct 30, 2026

    @charles39

    Another observed task-continuity failure on 2026-10-30, reported at the user's explicit request.

    Environment: macOS 27.0.1 (26A434), desktop app 26.1023.51421 (build 22530), bundled codex-cli 0.165.0-alpha.1.2. These are locally verified versions; the independently installed CLI is different and is not used as the app version.

    Observed sequence in one long-running chat:

    1. The user authorized a concrete next operation in an existing project.
    2. The assistant correctly restated the requested operation, began inspecting the relevant files, and then a context-compaction event occurred during that same turn.
    3. Its final response only acknowledged generic AGENTS.md preferences (language, desktop UI scope, and search preferences). It neither performed the active operation nor explained that it had lost the task.
    4. The user had to point out the lost context and explicitly ask it to continue.
    5. Reading recent turns of the same chat recovered the exact preceding request and progress, allowing work to resume without requiring the user to repeat the specification.

    Expected: a compaction boundary should preserve the current user request, unfinished operation, scope, and authorization. A continuation containing only repository/environment instructions must not be treated as a completed task. If usable task state is missing, recovery should happen before emitting a final acknowledgement.

    This is an additional observed failure, not a deterministic reproduction or a confirmed model/client/server root cause. No private project content, wallet information, credentials, local paths, or full session transcript is attached.

  11. LitghtCoder commented on Oct 30, 2026

    @LitghtCoder

    Adding two independent Windows occurrences on October 30, 2026, at the user's explicit request. Both happened in the same long-running session and match the reported symptom: immediately after a context transition, Codex ended the turn by acknowledging project rules instead of continuing authorized work.

    Environment:

    • Windows 10, build 19045; PowerShell.
    • Affected session metadata records cli_version: 0.160.0, source: vscode, originator: codex-tui. These are recorded session values, not a claim that the currently installed desktop or extension executable has that exact version; multiple Codex installations exist on this machine.
    • Affected turn contexts record gpt-6-astra, high reasoning.
    • Local configuration at investigation time includes:
    model_context_window = 300000
    model_auto_compact_token_limit = 270000
    model_provider = "custom"
    
    [features]
    context_management.experimental_mode = true
    
    [model_providers.custom]
    name = "OpenAI"
    requires_openai_auth = true
    supports_websockets = true
    wire_api = "responses"

    No explicit base URL is present in that provider section. This provider configuration is a possible confounder; a built-in-provider control has not been performed.

    Observed sequence from the saved local session (all times UTC, 2026-10-30):

    Occurrence Context-transition record Final response Turn marked complete
    A 03:03:04.594 03:03:28.916 03:03:28.944
    B 04:33:13.194 04:33:31.380 04:33:31.598

    In each case:

    • Substantive authorized work was in progress.
    • No new user message intervened between the transition and final answer.
    • Backend failures were recorded after the transition: three in A and four in B, with the error text Unable to perform operation: The backend request failed.
    • The final answer only acknowledged generic project design rules. It did not deliver the pending work or explain why work had stopped.
    • The user subsequently had to ask Codex to continue. After the first occurrence, work resumed and a later completion report was produced.

    This establishes a repeatable observed task-continuity failure within this session (two occurrences), not a deterministic minimal reproduction or proof of a particular release regression. We have not captured an underlying HTTP status for these failures, and are not assuming they were 404s. We have not tested disabling the experimental setting, changing provider, or rolling back versions.

    Expected: an unfinished authorized task should continue across the transition. If continuation cannot be recovered, the client should surface a clear recoverable failure rather than silently ending with a rules-only acknowledgement.

    Please include these Windows occurrences in the existing investigation. A regression test for "unfinished task -> context transition -> backend failure -> rules-only final answer/task_complete" would cover the observed failure.

    AI-assisted report based on inspected local records. Project content, source code, local paths, account/session identifiers, credentials, and raw transcripts are omitted.

  12. John-Rood commented on Oct 30, 2026

    @John-Rood

    Five reports now, three of them inside two hours, and the shape is identical at every boundary: empty compaction message, a replacement history that is all tool and developer entries plus one environment user message, and a final answer that only acknowledges rules.

    Shimada666's data settles the part this thread left open. A read-only retry at 02:36 returned 404 with a request id, ten minutes after four 404s around the handoff, so this is not a transient. tk-neuron's route returned 200 on 10-27 and 404 on 10-28 and 10-29, and today's reports are 404s again. The notes route has been retired under live clients and the client does not know it.

    That carries more weight than it looks, because thread_hint is the only channel that can put the objective back into a fresh window. It is a context contributor that builds its fragment list from one backend call, and every error path including a 404 records a failed status and returns an empty list. No exception, and nothing reaches the user. The fresh window is built from developer instructions and environment context, which is exactly the seven-entry shape in all three of today's reports. The task is readable on disk and unreachable by prompt, and nothing in the client says so.

    The lever is the feature flag, not the endpoint. apply_experimental_context gates on context_management and, once past that gate, calls features.enable(Feature::TokenBudget) and sets use_history_notes_extension. An explicit token_budget = false gets re-inserted at the next session, so leaving context_management on and trying to disable the token budget from underneath it does nothing. Shimada666's mitigation is the right one and codex features list reporting both flags false is the state to hold until the route is back.

    On LitghtCoder's confounder: model_provider = "custom" with name = "OpenAI" is not insulating you. The provider test in that gate is self.name == "OpenAI", the display name, not the provider id, so your custom section clears every condition on its own terms, name OpenAI, no base URL supplied, requires_openai_auth = true, env_key and auth unset. The notes path ran because your provider was read as first party. The 300000 window and 270000 trigger just make you cross boundaries far more often than the defaults, which is why you took two hits in ninety minutes. Renaming that section would hide the symptom without changing the behavior.

    On the detector ask, the seven-entry shape alone is not enough, correct. Detect on the exit. A turn that ends with a response calling no tools whose content is only a restatement of project or environment rules, immediately after a context transition and with no intervening user message, is the failure. That is the shape of all five reports in this thread, and it is checkable against the rollout locally with no server-side signal.

  13. MarMarLabs commented on Oct 31, 2026

    @MarMarLabs

    Another occurrence on macOS. Versions and flags I read on this Mac on October 30:

    • Desktop app 26.1027.30824, build 22943, with bundled codex-cli 0.166.0-alpha.5.1
    • Standalone CLI codex-cli 0.166.0
    • codex features list on both binaries shows context_management true and token_budget false

    These are the installed versions, not necessarily the ones running during the cases below. I have not turned context_management off yet.

    Case 1. I asked for a read-only briefing. The agent read the full job, the inventory and the work orders and gave a detailed update. Then the conversation compacted. Its next response only acknowledged my AGENTS.md instructions and ended the turn without the briefing. When I challenged it, it said it had not accessed the full job and asked for screenshots of data it had already read. Feedback ID 019f98e4-2f4d-7841-b238-c47806897aaf.

    Case 2. On October 30 I sent three long local code-review tasks to one desktop thread. Each task set read limits, including directories the agent must not search and its own memory files. In each run, after what the agent itself called a continuation, it searched its memory registry before rereading those limits. In two runs it also listed workspace folders recursively. It then reread the brief, finished the task correctly and disclosed the searches in its report. Nothing was written and none of the results were used.

    I did not record the model in either case. For case 2 I also did not capture a compaction record or HTTP logs and did not inspect the local rollout, so I can't tell whether it involved a compaction or is the same bug. I have not verified the empty compaction message, the seven-entry replacement history or the notes-route 404s from this thread for either case.

  14. r266-tech commented on Oct 31, 2026

    @r266-tech

    The latest thread evidence closes the remaining causal gap in my earlier comment: the issue is the experimental context-management path, not the replacement-history shape alone.

    John-Rood's source explanation shows that context_management enables token_budget at session start and that the fresh-window installer intentionally excludes user task messages. The same thread now has repeated HTTP 404s from the history-notes recovery path, while a read-only retry returned 404 with a request ID. That matches the observed rules-only continuation: the task remains on disk, but the only task-bearing context contributor fails soft and contributes no prompt fragment.

    I am updating my conclusion accordingly: the useful diagnostic is the combination of (1) an unfinished turn followed by a rules-only completion, (2) no intervening user message, and (3) failed notes/context requests at the same boundary. The seven-entry replacement list alone is not sufficient. The immediate user mitigation is to disable context_management until the notes route and failed-handoff behavior are corrected; token_budget=false alone is not sufficient because the experimental gate re-enables it.

    This is AI-assisted source analysis and issue follow-up; it does not identify the private server-side reason for the 404s.

  15. John-Rood commented on Oct 31, 2026

    @John-Rood

    Case 2 is the part worth keeping. Your read limits were in the task message, which is a user turn. The replacement history this path installs keeps the boundary messages, developer instructions plus the AGENTS.md and environment user turn. Task-bearing user turns do not come back. At the boundary the session rules still apply and the per-task prohibitions are gone, so nothing left in the window told it to stay out of its memory registry or out of the workspace walk, and it did both before rereading the brief. Case 1 is the same mechanism caught one step earlier.

    A prohibition you need to survive a continuation has to live in AGENTS.md or another developer-level surface for that thread. Stated in the turn you would naturally type it into, it lasts until the next boundary.

    On the flags you listed: on 0.166.0 both context_management and token_budget are UnderDevelopment with default_enabled false, so context_management reading true means your config turned it on. token_budget reading false is not insulation. apply_experimental_context in core/src/session/token_budget.rs enables TokenBudget at session start whenever context_management is on, provided the model, provider and account plan all qualify, and then forces the history-notes extension on. What the list shows outside a session is not the state the session runs with. Disabling context_management is the lever that holds across sessions, and the sub-flag is not.

    Case 1's shape matches the rest of the reports here: unfinished turn, a completion that only restates project or environment rules, no user message in between. The feedback ID makes it traceable.

  16. nurazem commented on Oct 31, 2026

    @nurazem
    Author

    The issue was the experimental compaction flag. Closing this issue

  17. Beautiful12138 commented on Nov 3, 2026

    @Beautiful12138

    This happened again on Windows Codex Desktop on November 3, 2026. After a context transition, three recovery operations failed. Codex then ended the unfinished task with a reply acknowledging AGENTS.md rules.

    The session metadata records cli_version: 0.165.0-alpha.1.2. At the affected turn, the model was gpt-6-astra with high reasoning. The configuration checked during this investigation contained features.context_management = { experimental_mode = true }.

    All times below are UTC:

    • 03:37:32: The user supplied more diagnostic material, and Codex continued a read-only investigation.
    • 03:40:53.385: A compacted record was saved.
    • Three recovery operations then returned the same error: Unable to perform operation: The backend request failed.
    • 03:41:27.688: A task_complete event was recorded. The final reply only acknowledged repository rules, authorization boundaries, and Chinese output requirements. The investigation was still unfinished.

    After the user pointed out the lost context, Codex reread the original conversation and recovered the task, findings, and next steps. The conversation was still on disk.

    The saved records show this difference between the three earlier compactions and the affected one:

    Field Three earlier records Affected record
    compaction item in replacement_history One in each None
    compaction_response_id Populated Not populated
    User messages in replacement_history Multiple One, containing AGENTS.md rules and environment context

    The affected record had an empty message and seven replacement_history entries: one additional-tools entry, five developer messages, and one user message. The active task was absent from that array.

    The separate retained_context still contained eight user messages and eight assistant messages. Both message-category incomplete flags were true; the overall incomplete flag was false.

  18. alexg2009 commented on Nov 16, 2026

    @alexg2009

    I'm Alex, co-founder of Synesis OS. We're building a personal AI Chief of Staff focused on persistent memory, contextual intelligence, and keeping track of goals, decisions, and commitments.
    We've already built a working prototype, and we've recently opened our Private Beta waitlist.
    We're trying to better understand how people experience these challenges in their daily workflows, and your perspective caught my attention.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugcontextextensionsession

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions