From d1fb476c37a777b03b272865a5651fffa7fbdebd Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Tue, 6 Oct 2026 22:41:25 +0800 Subject: [PATCH 1/2] fix: generalize the #2241 persona continuity resolver to the codex / claude-over-Responses instructions lanes (#2250) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An instructions drift mid-conversation (model switch, AGENTS.md edit, -c override, codex upgrade reassembly) forked the main lane off its raw key onto |sub: — zero compression state, refs re-minted (#2241 exposure shape). The drift now MIGRATES the anchor when the replayed input continues the raw key's prefix-affinity chain; a genuinely fresh task reusing the id (#150) still forks. Kernel subagentNamespace swap at the responses call site; dsh lanes unchanged (already #2247); fork id format identical. --- src/persona-anchor.ts | 22 +++++--- src/server.ts | 20 +++++--- tests/responses-instructions-drift.test.ts | 59 +++++++++++++++++++++- 3 files changed, 87 insertions(+), 14 deletions(-) diff --git a/src/persona-anchor.ts b/src/persona-anchor.ts index dff5051517..ea46e86706 100644 --- a/src/persona-anchor.ts +++ b/src/persona-anchor.ts @@ -1,4 +1,5 @@ -// #2241: continuity-aware persona anchor for id-sharing dsh traffic. +// #2241/#2250: continuity-aware persona anchor for id-sharing traffic +// (dsh persona lanes, codex root threads / older builds, claude-over-Responses). // // The original dsh persona fingerprint (db21309d, #1916/#1307/#1314) keyed // dsh traffic by id + system-text hash with kernel subagentNamespace @@ -78,18 +79,27 @@ export function resolvePersonaKey(rawId: string, systemText: string, messages: u return { key: `${rawId}|sub:${fp}`, action: "fork" }; } -/** server.ts wrapper: resolves the key and surfaces anchor migrations in - * the log (forks stay silent — they are the designed review path). */ -export function dshPersonaNamespace( +/** + * server.ts wrapper: resolves the key and surfaces anchor migrations in the + * log (forks stay silent — they are the designed review path). Protocol + * neutral since #2250: `systemText` is the lane's persona carrier — the dsh + * main system text, or the Responses top-level `instructions` — and + * `messages` is the same list prefix-affinity hashes (system carriers are + * never part of it, so a pure persona drift cannot break the chain). + * Whitespace-only carriers pass through un-anchored (kernel subagentNamespace + * semantics, kept for the codex swap). + */ +export function personaNamespace( rawId: string, systemText: string, messages: unknown, log: (level: "info" | "warn" | "error", message: string) => void, ): string { const list = Array.isArray(messages) ? messages : []; - const res = resolvePersonaKey(rawId, systemText, list); + const text = typeof systemText === "string" && systemText.trim().length > 0 ? systemText : ""; + const res = resolvePersonaKey(rawId, text, list); if (res.action === "migrate") { - log("info", `[persona] system text changed mid-conversation but the history continues ${rawId}'s chain — anchor migrated, compression state stays on the raw key (#2241)`); + log("info", `[persona] persona text changed mid-conversation but the history continues ${rawId}'s chain — anchor migrated, compression state stays on the raw key (#2241/#2250)`); } return res.key; } diff --git a/src/server.ts b/src/server.ts index 434e3fe044..de6010b714 100644 --- a/src/server.ts +++ b/src/server.ts @@ -46,7 +46,6 @@ import { injectResponsesDeveloperMessage, conversationIdentityResponses, conversationSignalResponses, - subagentNamespace, } from "acp-kernel/wire"; import { responsesToCoreWithToolImages as responsesToCore, patchResponsesInputWithToolImages as patchResponsesInput, mergeAdjacentConfigurationUpdates } from "./responses-tool-output.js"; import { reconcileFoldCoverage, noteSystemPromptFingerprint, resolveFoldReconcileMode } from "./fold-reconcile.js"; @@ -111,7 +110,7 @@ import { rewriteResponsesJsonResponse } from "./stream-responses.js"; import { observeResponsesTerminalState } from "./stream-terminal.js"; import { emitPreflightError, emitStreamError } from "./stream-error.js"; import { affinityToken, claudeSubagentAgentId, claudeSubagentSplit, clientConversationHeader, codexTurnIdentity, conversationHeaderSource, dshPersonaFingerprintApplies, instructionsFingerprintApplies, openaiSystemTextForPersona, preferPromptCacheKeyIdentity, shouldStampRelayAffinityPck, type ConversationIdentity } from "./session-id.js"; -import { dshPersonaNamespace } from "./persona-anchor.js"; +import { personaNamespace } from "./persona-anchor.js"; import { prefixAffinity, type AnonymousAffinity } from "./prefix-affinity.js"; import { maybeAdoptForkBlocks, maybeAdoptResume } from "./fork-adoption.js"; import { publicForkInputMatches } from "./plugin.js"; @@ -2281,7 +2280,7 @@ async function handle( // (model switch) MIGRATES the anchor instead of forking // the main lane off the raw key; only history-discontinuous // requests (review blobs) still fork onto `|sub:`. - ? dshPersonaNamespace( + ? personaNamespace( anthropicIdentity?.value ?? anthropicSignal, personaSystemText, (parsed as AnthropicRequestBody).messages, @@ -2290,7 +2289,7 @@ async function handle( : anthropicIdentity?.value ?? anthropicSignal) : protocol === "openai" ? (dshPersona && !sideRequestLike - ? dshPersonaNamespace( + ? personaNamespace( openaiIdentity?.value ?? openaiSignal, personaSystemText, (parsed as OpenAIRequestBody).messages, @@ -2326,9 +2325,18 @@ async function handle( // not a new persona. See instructionsFingerprintApplies // in src/session-id.ts. ? (!sideRequestLike - ? subagentNamespace( + ? // #2250: same continuity resolver as the dsh lanes + // — an instructions drift whose history continues + // the raw key's chain (model switch / AGENTS.md + // edit / -c override / upgrade reassembly) MIGRATES + // the anchor instead of forking the main lane off + // its compression state; a genuinely fresh task + // reusing the id (#150) still forks `|sub:`. + personaNamespace( responsesIdentity?.value ?? conversationSignalResponses(parsed as ResponsesRequestBody, convHeader), - (parsed as ResponsesRequestBody).instructions, + (parsed as ResponsesRequestBody).instructions ?? "", + (parsed as ResponsesRequestBody).input, + log, ) : (responsesIdentity?.value ?? conversationSignalResponses(parsed as ResponsesRequestBody, convHeader))) : (responsesIdentity?.value ?? conversationSignalResponses(parsed as ResponsesRequestBody, convHeader)); diff --git a/tests/responses-instructions-drift.test.ts b/tests/responses-instructions-drift.test.ts index bb39ae25da..ee999c4b16 100644 --- a/tests/responses-instructions-drift.test.ts +++ b/tests/responses-instructions-drift.test.ts @@ -9,6 +9,7 @@ import { SessionStore, _setStoreForTest } from "../src/persist.ts"; import { _setForTest as setRegistryForTest } from "../src/registry.ts"; import { _resetSessionsForTest } from "../src/session.ts"; import { conversationHeaderSource, instructionsFingerprintApplies } from "../src/session-id.ts"; +import { resetPersonaAnchorsForTest } from "../src/persona-anchor.ts"; // #1102: opencode's system-context reconcile rewrites `instructions` whenever // AGENTS.md is edited mid-session. Its conversation ids are persona-scoped @@ -297,11 +298,16 @@ test("e2e #150: codex root thread reusing a task id across personas still splits res.write(completed(700)); res.end(); }, async (url, statsUrl, _bodies) => { - const input = [{ type: "message", role: "user", content: "task turn" }]; + // #2250: the two tasks must differ in CONTENT, not just instructions — + // continuity now keys on the message chain; a byte-identical payload + // under new instructions is the SAME conversation evolving (migrate), + // while #150's scenario is a genuinely fresh task reusing the id. + const input = [{ type: "message", role: "user", content: "task A first turn" }]; const req1 = await fetch(url, { method: "POST", headers, body: JSON.stringify({ model: "gpt-drift-e2e", stream: true, instructions: "task A persona instructions", input }) }); assert.equal(req1.status, 200); await req1.text(); - const req2 = await fetch(url, { method: "POST", headers, body: JSON.stringify({ model: "gpt-drift-e2e", stream: true, instructions: "task B persona instructions (different task reusing the id)", input }) }); + const inputB = [{ type: "message", role: "user", content: "task B first turn (unrelated task reusing the id)" }]; + const req2 = await fetch(url, { method: "POST", headers, body: JSON.stringify({ model: "gpt-drift-e2e", stream: true, instructions: "task B persona instructions (different task reusing the id)", input: inputB }) }); assert.equal(req2.status, 200); await req2.text(); @@ -312,3 +318,52 @@ test("e2e #150: codex root thread reusing a task id across personas still splits assert.ok(ids[1].startsWith(`${TASK_ID}|sub:`), `forked namespace, got ${ids[1]}`); }); }); + +test("e2e #2250: codex instructions drift with CONTINUING history keeps ONE session (model switch / AGENTS.md edit)", async () => { + _setStoreForTest(new SessionStore({ enabled: false })); + _resetSessionsForTest(); + setRegistryForTest({}); + resetPersonaAnchorsForTest(); + + const TASK_ID = "codex-task-id-2250"; + const headers = { + "content-type": "application/json", + "user-agent": "codex_cli_rs/0.147.0", + "session-id": TASK_ID, + "x-codex-turn-metadata": JSON.stringify({ thread_source: "user", thread_id: "t-root-2250" }), + "thread-id": "t-root-2250", + }; + const INSTRUCTIONS_A = "You are Codex, the main agent (model: gpt-5.3)."; + const INSTRUCTIONS_B = "You are Codex, the main agent (model: glm-5.3). \nWorkspace guidance updated."; + + const user = (n: number) => ({ type: "message", role: "user", content: [`turn ${n}: please continue the task`] }); + const assistant = (n: number) => ({ type: "message", role: "assistant", content: [{ type: "output_text", text: `assistant answer ${n}` }] }); + const post = async (url: string, instructions: string, input: unknown[]) => { + const res = await fetch(url, { method: "POST", headers, body: JSON.stringify({ model: "gpt-drift-e2e", stream: true, instructions, input }) }); + assert.equal(res.status, 200); + await res.text(); + }; + + await withProxy((_req, res) => { + res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache" }); + res.write(textEvents("codex answer")); + res.write(completed(700)); + res.end(); + }, async (url, statsUrl) => { + // Turn 1-2 on instructions A: grow the conversation (full replay each + // turn — the codex shape). + await post(url, INSTRUCTIONS_A, [user(1)]); + await post(url, INSTRUCTIONS_A, [user(1), assistant(1), user(2)]); + + // Turn 3: instructions drift (model switch / AGENTS.md edit), history + // fully replayed and continued. Must NOT fork — the anchor migrates. + await post(url, INSTRUCTIONS_B, [user(1), assistant(1), user(2), assistant(2), user(3)]); + + // Turn 4: still instructions B — plain match on the migrated anchor. + await post(url, INSTRUCTIONS_B, [user(1), assistant(1), user(2), assistant(2), user(3), assistant(3), user(4)]); + + const stats = (await (await fetch(statsUrl)).json()) as { sessions: Array<{ id: string }> }; + assert.equal(stats.sessions.length, 1, `instructions drift with continuing history must keep ONE session (got ${JSON.stringify(stats.sessions.map((x) => x.id))})`); + assert.equal(stats.sessions[0]!.id, TASK_ID, "the session stays on the raw key — no |sub: fork"); + }); +}); From d66ccffc88ee77cda966bf0229030801a72f6aab Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Tue, 6 Oct 2026 23:04:26 +0800 Subject: [PATCH 2/2] =?UTF-8?q?test:=20#2250=20e2e=20=E2=80=94=20fold=20st?= =?UTF-8?q?ate=20carries=20across=20the=20codex=20instructions-drift=20mig?= =?UTF-8?q?rate;=20claude-over-Responses=20drift=20variant?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/responses-instructions-drift.test.ts | 115 +++++++++++++++++++++ 1 file changed, 115 insertions(+) diff --git a/tests/responses-instructions-drift.test.ts b/tests/responses-instructions-drift.test.ts index ee999c4b16..0adc00f443 100644 --- a/tests/responses-instructions-drift.test.ts +++ b/tests/responses-instructions-drift.test.ts @@ -319,6 +319,121 @@ test("e2e #150: codex root thread reusing a task id across personas still splits }); }); +test("e2e #2250: codex instructions drift CARRIES the compression state across the migrate (fold survives)", async () => { + _setStoreForTest(new SessionStore({ enabled: false })); + _resetSessionsForTest(); + setRegistryForTest({}); + resetPersonaAnchorsForTest(); + + const TASK_ID = "codex-task-id-2250-fold"; + const headers = { + "content-type": "application/json", + "user-agent": "codex_cli_rs/0.147.0", + "session-id": TASK_ID, + "x-codex-turn-metadata": JSON.stringify({ thread_source: "user", thread_id: "t-root-2250f" }), + "thread-id": "t-root-2250f", + }; + const INSTRUCTIONS_A = "You are Codex, the main agent (model: gpt-5.3)."; + const INSTRUCTIONS_B = "You are Codex, the main agent (model: glm-5.3). Workspace guidance updated."; + const SEED_USER = "Kick off the working session."; + const SEED_ASSISTANT = "Understood, starting now."; + const TURN_1 = `FOLD2250-A ${"y".repeat(6000)}`; + const TURN_2 = "FOLD2250-B acknowledged"; + // Same ref discipline as the #1102 case above: kernel refs are per-session + // render-order snapshots — m00001/m00002 = seed pair, m00003/m00004 = fold + // targets, and the six medium turns keep them outside the protected zone. + const REF_1 = "m00003"; + const REF_2 = "m00004"; + + await withProxy((_req, res, bodies) => { + res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache" }); + if (bodies.length === 1) { + const compressArgs = JSON.stringify({ + content: [{ startId: REF_1, endId: REF_2, topic: "session setup", summary: "FOLD2250-SUMMARY-SETUP-CONTEXT-FOLDED-BY-COMPRESSION-LONG-ENOUGH-FOR-KERNEL-MIN-LENGTH-CHECK" }], + }); + res.write(fcEvents(0, "call_d", "compress", compressArgs)); + res.write(completed(1600)); + } else { + res.write(textEvents("post-drift answer")); + res.write(completed(1700)); + } + res.end(); + }, async (url, statsUrl, bodies) => { + const med = (i: number) => `Message ${i} of the working session. ` + `WORK_${i}_content_`.repeat(290); + const baseInput = [ + { type: "message", role: "user", content: SEED_USER }, + { type: "message", role: "assistant", content: SEED_ASSISTANT }, + { type: "message", role: "user", content: TURN_1 }, + { type: "message", role: "assistant", content: TURN_2 }, + { type: "message", role: "user", content: med(5) }, + { type: "message", role: "assistant", content: med(6) }, + { type: "message", role: "user", content: med(7) }, + { type: "message", role: "assistant", content: med(8) }, + { type: "message", role: "user", content: med(9) }, + { type: "message", role: "assistant", content: med(10) }, + ]; + const req1 = await fetch(url, { method: "POST", headers, body: JSON.stringify({ model: "gpt-drift-e2e", stream: true, instructions: INSTRUCTIONS_A, input: baseInput }) }); + assert.equal(req1.status, 200); + await req1.text(); + assert.equal(bodies.length, 2, "original + post-compress re-request"); + + // Model switch: instructions drift, history fully replayed + one new + // turn. The anchor must MIGRATE — the folded block stays on the raw + // key instead of the conversation re-folding from zero on |sub:. + const newTurn = "model switched to glm-5.3 — continue the task (TURN-MARKER-2250)"; + const req2 = await fetch(url, { method: "POST", headers, body: JSON.stringify({ model: "gpt-drift-e2e", stream: true, instructions: INSTRUCTIONS_B, input: [...baseInput, { type: "message", role: "user", content: newTurn }] }) }); + assert.equal(req2.status, 200); + await req2.text(); + assert.equal(bodies.length, 3); + + assert.ok(!bodies[2].includes("FOLD2250-A"), "folded message stays off the wire across the instructions drift"); + assert.ok(!bodies[2].includes("FOLD2250-B"), "both folded messages are off the wire after the drift"); + assert.ok(bodies[2].includes("FOLD2250-SUMMARY"), "the folded summary renders in place of the compressed range — compression state CARRIED"); + assert.ok(bodies[2].includes(newTurn), "the new turn is forwarded"); + + const stats = (await (await fetch(statsUrl)).json()) as { sessions: Array<{ id: string }> }; + assert.equal(stats.sessions.length, 1, "the drifted turn must NOT have forked a second session"); + assert.equal(stats.sessions[0]!.id, TASK_ID, "the fold stays on the raw key"); + }); +}); + +test("e2e #2250: claude-over-Responses instructions drift with continuing history keeps ONE session (#970 lane)", async () => { + _setStoreForTest(new SessionStore({ enabled: false })); + _resetSessionsForTest(); + setRegistryForTest({}); + resetPersonaAnchorsForTest(); + + const CLAUDE_ID = "claude-code-uuid-2250"; + const headers = { "content-type": "application/json", "x-claude-code-session-id": CLAUDE_ID }; + const INSTRUCTIONS_A = "You are Claude Code, the main agent."; + const INSTRUCTIONS_B = "You are Claude Code, the main agent. (claude-code upgraded — reassembled system)"; + + const user = (n: number) => ({ type: "message", role: "user", content: [`turn ${n}: continue`] }); + const assistant = (n: number) => ({ type: "message", role: "assistant", content: [{ type: "output_text", text: `answer ${n}` }] }); + const post = async (url: string, instructions: string, input: unknown[]) => { + const res = await fetch(url, { method: "POST", headers, body: JSON.stringify({ model: "gpt-drift-e2e", stream: true, instructions, input }) }); + assert.equal(res.status, 200); + await res.text(); + }; + + await withProxy((_req, res) => { + res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache" }); + res.write(textEvents("claude answer")); + res.write(completed(700)); + res.end(); + }, async (url, statsUrl) => { + await post(url, INSTRUCTIONS_A, [user(1)]); + await post(url, INSTRUCTIONS_A, [user(1), assistant(1), user(2)]); + // upgrade reassembly: instructions drift, history continues → migrate + await post(url, INSTRUCTIONS_B, [user(1), assistant(1), user(2), assistant(2), user(3)]); + await post(url, INSTRUCTIONS_B, [user(1), assistant(1), user(2), assistant(2), user(3), assistant(3), user(4)]); + + const stats = (await (await fetch(statsUrl)).json()) as { sessions: Array<{ id: string }> }; + assert.equal(stats.sessions.length, 1, `claude-over-Responses drift with continuing history keeps ONE session (got ${JSON.stringify(stats.sessions.map((x) => x.id))})`); + assert.equal(stats.sessions[0]!.id, CLAUDE_ID, "no |sub: fork on the claude lane"); + }); +}); + test("e2e #2250: codex instructions drift with CONTINUING history keeps ONE session (model switch / AGENTS.md edit)", async () => { _setStoreForTest(new SessionStore({ enabled: false })); _resetSessionsForTest();