Skip to content

thread/resume and thread/fork ignore developerInstructions override on first resumed turn #19045

Open

Description

@CyberShadow

What issue are you seeing?

When thread/resume or thread/fork is given new plain thread-level developerInstructions, Codex accepts and stores the override in runtime session state, but the first resumed/forked model turn may not actually receive it.

The issue appears on cold resume/fork paths that reconstruct prior rollout state. In that case, the first subsequent turn can be built from replay baseline plus steady-state context diffs. That diff path does not emit updates for plain thread-level developer_instructions, so the model can still see stale instructions from the original thread instead of the override supplied to thread/resume or thread/fork.

This was reproduced with targeted app-server tests that assert on the actual first /responses request after resume/fork. In both cases, the request still contained the old developer instructions A, while the new override B was missing from the latest developer-visible update.

What steps can reproduce the bug?

  1. Start a thread with plain thread-level developerInstructions = "A".
  2. Run at least one turn so the thread has persisted rollout/history state.
  3. Stop the session.
  4. Call thread/resume or thread/fork with developerInstructions = "B".
  5. Start the first turn on the resumed/forked thread.
  6. Inspect the first /responses request sent to the model.

Observed result:

  • historical developer context still includes A
  • the latest developer-visible update does not include B
  • the first resumed/forked turn therefore behaves according to stale instructions instead of the override

Minimal repro shape:

thread/start(developerInstructions="A")
turn/start("seed history")
shutdown session

thread/resume(developerInstructions="B")
turn/start("first resumed turn")

or

thread/start(developerInstructions="A")
turn/start("seed history")
shutdown session

thread/fork(developerInstructions="B")
turn/start("first forked turn")

What is the expected behavior?

If a caller supplies new developerInstructions to thread/resume or thread/fork, the next model turn should see those instructions as the active developer instructions.

In other words, thread/start.developerInstructions, thread/resume.developerInstructions, and thread/fork.developerInstructions should all define the effective developer/system prompt for subsequent turns.

Additional information

Root cause from investigation:

  • resume/fork reconstructs a prior reference_context_item from persisted rollout state
  • that causes the next turn to go through build_settings_update_items(...) instead of full initial-context injection
  • full initial-context injection includes plain thread-level developer instructions
  • the steady-state diff path does not currently emit diffs for plain thread-level developer_instructions

So the new value is stored in session state but never becomes model-visible on the first resumed/forked turn.

This is separate from the already-running-thread behavior where app-server explicitly ignores resume overrides for loaded threads.

Smallest likely fix:

  • add explicit diff handling for plain thread-level developer_instructions in codex-rs/core/src/context_manager/updates.rs

Patch draft: main...CyberShadow:codex:fix-resume-and-fork

Downstream project impact:

  • The CyDo SwitchMode tool allows agents to switch modes (e.g. personalities) mid-conversation, varying parameters including the system prompt. This issue's impact is that the agent is unable to see the new prompt, and thus is not able to see its operating instructions.

Activity

  1. added
    bug
    on Apr 22, 2026
  2. added
    app-server
    on Apr 22, 2026
  3. github-actions commented on Apr 22, 2026

    @github-actions
    Contributor

    Potential duplicates detected. Please review them and close your issue if it is a duplicate.

    Powered by Codex Action

  4. cyhhao commented on Sep 8, 2026

    @cyhhao

    Confirmed the cold-resume behavior on codex-cli 0.153.2, macOS/arm64. I also tested the developer-message injection workaround: it delivers an update immediately, but does not make that update the native baseline used after compaction.

    The reproduction below is independent of Avibe, uses Node.js 22 built-ins only, creates an isolated temporary Codex home, and sends requests to a loopback fake Responses endpoint. It requires no API key or real model and does not touch existing sessions or configuration.

    Observed model input, not just successful RPCs

    A and B are distinct non-ASCII instruction strings. Each row counts their complete text in the actual outbound request's developer messages. Every scenario starts with a fresh thread.

    Scenario A copies B copies
    Initial native developerInstructions=A 1 0
    Cold thread/resume(developerInstructions=B), first subsequent turn 1 0
    Same cold-resumed thread, after explicit compaction and another turn 0 1
    Warm thread/resume(developerInstructions=B) while loaded but idle 1 0
    Append developer B with thread/inject_items, then start a turn 1 1
    Automatic compaction with ordinary retained history 1 1
    Automatic compaction after a newer user item exhausts the retention budget 1 0

    The last two cases enable features.retain_client_developer_messages=true. To trigger the real client-side automatic compaction path deterministically, the mock returns usage above model_auto_compact_token_limit=100000; the following turn/start must send a compaction_trigger. The pressure case supplies "Recent history data. ".repeat(18000) after injected B. The ordinary-history case is a control using the same usage trigger.

    This characterizes verbatim request composition. The mock returns a fixed opaque compaction item; it does not establish what the real summarizer might encode, whether a real model follows the text, or production cache-hit behavior. It does show that the retention flag does not pin B and that the native configuration can still reconstruct A.

    Source cross-check

    Runtime results above are from released 0.153.2, not a build of main. Separately inspected main at 94e4b3d0bd5c:

    Why this matters / requested contract

    Embedding hosts need to refresh an agent definition or capability catalog without abandoning a healthy thread and its native resources. In Avibe, our interim implementation combines a native baseline with injected updates; it does not solve latest-version persistence.

    For this bug, the essential contract is that an accepted cold resume/fork override reaches the next model request, not only a later context reconstruction.

    The related loaded-thread need is a supported turn-boundary update of the host-owned native instruction value:

    1. The next turn receives B; B also becomes the baseline used by subsequent compaction and cold resume.
    2. Reapplying unchanged B is idempotent, and repeated updates do not require accumulating a new full prompt indefinitely.
    3. Updating instructions alone does not require restarting/unloading the thread, stopping its native background resources, or changing model, reasoning, or permission settings.
    4. Preserve user/project instructions and unrelated conversation history. This is not a request for arbitrary rollout/history rewriting; the implementation should use Codex's context lifecycle. Define clearly when an update during an active turn takes effect.

    I am adding the reproduction here rather than opening another report of the cold-resume bug. If the loaded-thread API contract belongs in a separate feature request, I can split that out.

    Standalone reproduction — save as repro.mjs, then run node repro.mjs /absolute/path/to/codex
    // Node.js 22+, no npm dependencies or model credentials.
    // Usage: node repro.mjs /absolute/path/to/codex
    import assert from "node:assert/strict";
    import { spawn } from "node:child_process";
    import { once, EventEmitter } from "node:events";
    import { mkdtemp, mkdir, writeFile, rm } from "node:fs/promises";
    import http from "node:http";
    import { tmpdir } from "node:os";
    import { join, resolve } from "node:path";
    import { createInterface } from "node:readline";
    
    const binary = process.argv[2] ? resolve(process.argv[2]) : "codex";
    const A = "HOST_BASELINE_A:旧版本。";
    const B = "HOST_BASELINE_B:新版本。";
    const OVERLAY = `Latest host instructions, superseding prior host instructions:\n${B}`;
    const MODEL = "instruction-lifecycle-repro";
    
    async function bounded(promise, label) {
      let timer;
      try {
        return await Promise.race([
          promise,
          new Promise((_, reject) => {
            timer = setTimeout(() => reject(new Error(`Timed out: ${label}`)), 15000);
          }),
        ]);
      } finally {
        clearTimeout(timer);
      }
    }
    
    function client(root) {
      const child = spawn(binary, ["app-server"], {
        cwd: root,
        env: {
          PATH: process.env.PATH || "",
          HOME: root,
          CODEX_HOME: join(root, "codex"),
          XDG_CONFIG_HOME: join(root, "config"),
        },
        stdio: ["pipe", "pipe", "pipe"],
      });
      const pending = new Map();
      const events = new EventEmitter();
      let sequence = 0;
      let diagnostic = "";
      let spawnFailed = false;
      child.stderr.on("data", chunk => { diagnostic = (diagnostic + chunk).slice(-4000); });
      child.on("error", error => {
        spawnFailed = true;
        for (const waiter of pending.values()) waiter.reject(error);
      });
      child.on("exit", code => {
        for (const waiter of pending.values()) {
          waiter.reject(new Error(`app-server exited ${code}: ${diagnostic}`));
        }
      });
      const lines = createInterface({ input: child.stdout });
      lines.on("line", line => {
        const message = JSON.parse(line);
        if (message.id !== undefined && pending.has(message.id)) {
          const waiter = pending.get(message.id);
          pending.delete(message.id);
          if (message.error) waiter.reject(new Error(JSON.stringify(message.error)));
          else waiter.resolve(message.result);
        } else if (message.method) {
          events.emit(message.method, message.params);
        }
      });
      const send = message => child.stdin.write(`${JSON.stringify(message)}\n`);
      async function rpc(method, params = {}) {
        const id = ++sequence;
        try {
          return await bounded(new Promise((resolve, reject) => {
            pending.set(id, { resolve, reject });
            send({ id, method, params });
          }), method);
        } finally {
          pending.delete(id);
        }
      }
      return {
        rpc,
        async start() {
          await rpc("initialize", {
            clientInfo: { name: "instruction_lifecycle_repro", version: "1" },
            capabilities: { experimentalApi: true },
          });
          send({ method: "initialized", params: {} });
        },
        async turn(threadId, text = "Continue") {
          const completion = bounded(once(events, "turn/completed"), "turn completion");
          const [[event]] = await Promise.all([
            completion,
            rpc("turn/start", { threadId, input: [{ type: "text", text, text_elements: [] }] }),
          ]);
          assert.equal(event.turn.status, "completed", JSON.stringify(event));
        },
        async compact(threadId) {
          const completion = bounded(once(events, "turn/completed"), "compaction");
          const [[event]] = await Promise.all([
            completion, rpc("thread/compact/start", { threadId }),
          ]);
          assert.equal(event.turn.status, "completed", JSON.stringify(event));
        },
        async stop() {
          if (spawnFailed || child.exitCode !== null || child.signalCode !== null) return;
          const exited = once(child, "exit");
          child.stdin.end();
          const timer = setTimeout(() => child.kill("SIGKILL"), 3000);
          try { await exited; } finally { clearTimeout(timer); lines.close(); }
        },
      };
    }
    
    async function scenario(mode) {
      const root = await mkdtemp(join(tmpdir(), "codex-instruction-repro-"));
      const requests = [];
      let inputTokens = 10;
      const server = http.createServer(async (request, response) => {
        try {
          assert.equal(request.url, "/responses");
          const chunks = [];
          for await (const chunk of request) chunks.push(chunk);
          const body = JSON.parse(Buffer.concat(chunks));
          requests.push(body);
          const compacting = body.input.some(item => item.type === "compaction_trigger");
          const item = compacting
            ? { type: "compaction", encrypted_content: "REPRO_SUMMARY" }
            : {
              type: "message", id: `msg-${requests.length}`, role: "assistant",
              content: [{ type: "output_text", text: "OK", annotations: [] }],
            };
          const id = `resp-${requests.length}`;
          const events = [
            { type: "response.created", response: { id } },
            { type: "response.output_item.done", output_index: 0, item },
            {
              type: "response.completed",
              response: {
                id, usage: { input_tokens: inputTokens, output_tokens: 1, total_tokens: inputTokens + 1 },
              },
            },
          ];
          inputTokens = 10;
          response.writeHead(200, { "Content-Type": "text/event-stream" });
          response.end(events.map(event => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(""));
        } catch (error) {
          response.writeHead(500);
          response.end(String(error));
        }
      });
      let native;
      try {
        server.listen(0, "127.0.0.1");
        await once(server, "listening");
        await mkdir(join(root, "codex"));
        const catalog = join(root, "models.json");
        await writeFile(catalog, JSON.stringify({ models: [{
          slug: MODEL, display_name: MODEL, supported_reasoning_levels: [],
          shell_type: "unified_exec", visibility: "list", supported_in_api: true,
          priority: 1, support_verbosity: false, experimental_supported_tools: [],
          truncation_policy: { mode: "tokens", limit: 10000 },
          base_instructions: "You are a test assistant.",
        }] }));
        await writeFile(join(root, "codex", "config.toml"), [
          `model = "${MODEL}"`, 'model_provider = "repro"',
          `model_catalog_json = ${JSON.stringify(catalog)}`,
          "model_auto_compact_token_limit = 100000",
          'approval_policy = "never"', 'sandbox_mode = "read-only"',
          "[features]", "retain_client_developer_messages = true", "hooks = false",
          "[model_providers.repro]", 'name = "OpenAI"', 'wire_api = "responses"',
          `base_url = "http://127.0.0.1:${server.address().port}"`, "requires_openai_auth = false",
        ].join("\n"));
        native = client(root);
        await native.start();
        const started = await native.rpc("thread/start", { cwd: root, developerInstructions: A });
        const threadId = started.thread.id;
        function check(stage, a, b, overlay) {
          const texts = requests.at(-1).input
            .filter(item => item.role === "developer")
            .flatMap(item => item.content.filter(part => part.type === "input_text").map(part => part.text))
            .join("\n");
          const counts = {
            A: texts.split(A).length - 1,
            B: texts.split(B).length - 1,
            overlay: texts.split(OVERLAY).length - 1,
          };
          console.log(JSON.stringify({ mode, stage, ...counts }));
          assert.deepEqual(counts, { A: a, B: b, overlay });
        }
        await native.turn(threadId);
        check("initial", 1, 0, 0);
        if (mode === "cold-resume") {
          await native.stop();
          native = client(root);
          await native.start();
          await native.rpc("thread/resume", { threadId, developerInstructions: B });
          await native.turn(threadId);
          check("first resumed turn", 1, 0, 0);
          await native.compact(threadId);
          await native.turn(threadId);
          check("after reconstruction", 0, 1, 0);
        } else {
          await native.rpc("thread/resume", { threadId, developerInstructions: B });
          await native.turn(threadId);
          check("warm resume ignored", 1, 0, 0);
          await native.rpc("thread/inject_items", {
            threadId,
            items: [{ type: "message", role: "developer", content: [{ type: "input_text", text: OVERLAY }] }],
          });
          inputTokens = 200000; // Force automatic pre-turn compaction on the following turn.
          await native.turn(threadId, mode === "pressure" ? "Recent history data. ".repeat(18000) : "Continue");
          check("injected update", 1, 1, 1);
          const previousCount = requests.length;
          await native.turn(threadId);
          assert(requests.slice(previousCount).some(body =>
            body.input.some(item => item.type === "compaction_trigger")));
          check("after auto compaction", 1, mode === "pressure" ? 0 : 1, mode === "pressure" ? 0 : 1);
        }
      } finally {
        if (native) await native.stop();
        server.closeAllConnections();
        await new Promise(resolve => server.close(resolve));
        await rm(root, { recursive: true, force: true }); // Only this test's fresh mkdtemp directory.
      }
    }
    
    for (const mode of ["cold-resume", "ordinary", "pressure"]) await scenario(mode);
  5. rhettg commented on Sep 22, 2026

    @rhettg

    Confirmed independently on codex-cli 0.154.0, Linux x86_64, using codex app-server over stdio with experimentalApi: true and model gpt-6-astra.

    We reproduced this independently using a small Node.js client and a disposable thread:

    1. thread/start with developerInstructions: “This is an isolated instruction propagation test. Do not use any tools or change any files. Reply with exactly AMBER when asked for the probe word.”
    2. turn/start: “Return the probe word specified by your current developer instruction. Do not use tools.” → AMBER.
    3. Stop the app-server process and launch a new one using the same Codex home.
    4. thread/resume with the same thread ID and the same developer instruction except VIOLET replaces AMBER. The RPC succeeds.
    5. Send the same turn input → AMBER.
    6. Control: start a separate fresh thread with the VIOLET instruction and send the same turn input → VIOLET.

    We captured the client’s outbound JSON-RPC request: the cold resume request contains the replacement developerInstructions with VIOLET. Inspection of the saved rollout shows the original AMBER developer message but no replacement VIOLET developer message in the resumed thread. This test used real model responses; we did not capture the outbound Responses API request or test compaction, so the request-level and compaction findings in the September 8 comment remain separate evidence.

    Downstream impact: An integration sends execution-policy developer instructions on thread start and resume. After deploying a policy update that permits scoped disposable test storage, an existing agent conversation continues to receive the old checkout-only restriction and stops otherwise authorized testing. Updated skill context does arrive, making the stale developer policy particularly confusing. We verified the running integration contains the new policy and reproduced the resume failure independently as above.

    This supports fixing cold-resume instruction propagation while preserving the existing conversation, rather than requiring thread resets. We have not changed the affected production thread or applied a workaround.

  6. RevealUIStudio commented on Nov 2, 2026

    @RevealUIStudio

    Independently reproduced on codex-cli 0.166.0, Linux x86_64, pinned upstream commit 6ff1e1ca3b30fc8b914720681fcf5fe62e95f856. This adds interactive TUI coverage and a context-budget requirement to the existing cold-resume report.

    The test uses a disposable Codex home and a loopback synthetic Responses endpoint in an isolated network namespace. It uses no real credentials, real model, existing conversation, or external network. Assertions inspect developer-role content in the actual outbound model request; success of thread/resume alone is insufficient.

    1. Start an interactive CLI conversation with configured developer marker A and save a user/assistant turn.
    2. Close that client normally.
    3. Resume the exact saved UUID in a fresh client with configured developer marker B, using --no-daemon.
    4. Send a continuation that contains neither policy marker.
    5. Assert that the outbound primary request retains the saved user/assistant content and includes B as current developer authority.

    The unchanged official client preserves the UUID and saved user/assistant content, but sends the original developer marker A without B. Direct stdio app-server cold resume with an explicit developerInstructions field also reproduces the omission. Rejoining an already-loaded thread intentionally ignores overrides and is a separate constraint.

    Two owning paths matter. In tui/src/app_server_session.rs, thread_resume_params_from_config supplies None to the developer-instruction helper when constructing ordinary resume parameters; the fork builder forwards configured instructions. Fixing that alone is insufficient: core restores a reference context and saved generic developer text, while its subsequent context-diff path does not emit the newly configured generic instructions. This matches the core cause reported above.

    A complete fix also needs to account for policy changes at the actual pre-turn context gate. A long replacement policy can increase request size even when the restored last usage count remains small. Prompt generation, compaction and token estimates should share the same typed projection. Accounting needs a stable measured contribution across later resumes, compaction, duplicate tail reinjection, explicit clear, full-context markers and spending-only events. Lifetime spending must survive synthetic full-context resets.

    The local regression design replaces or clears only the exact typed generic configured-developer slot, preserves additional requirements, tool guidance, Guardian policy and unknown legacy content, and leaves raw rollout/history bytes intact. Saved-history tests cover both Legacy and Paginated storage, the same UUID, two subsequent requests and preservation of the original rollout prefix. Both Legacy and Paginated integration cases have now executed and passed. Both modes check two resumed model requests and reach all history, UUID and current-policy assertions. Legacy additionally requires a real saved rollout and preserved original byte prefix. There is no early-return sandbox skip.

    Writer isolation is separately verified against the unchanged official client: a second TUI shows the conversation-open-elsewhere notice; ordinary input causes no model request or new conversation, and the original writer plus an unrelated conversation retain their histories and continue normally. A policy-renewal fix should preserve that behavior.

    Local validation: 369 unchanged protocol tests, 14 targeted core/TUI regressions, 111 history tests, three resume-parameter tests and both saved-session integrations passed. Counts overlap. Four generated-schema checks also passed after canonical regeneration of the internal rollout metadata schema; public exports and the normal frozen SDK output are unchanged. Fresh related token-filter checks also passed (47 Core and 47 TUI tests), followed by all four Guardian checkpoint cases. Both stages had no failed or ignored tests and no early-skip output. Counts overlap with earlier selections; these local results do not establish official artifact or native acceptance.

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

    app-serverbug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions