From d17635201ccbaf73522f7b2f743fa36a2f6b97f5 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 3 Jul 2026 10:44:06 -0700 Subject: [PATCH] Route shared codex app-server logs to the owning app thread MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit One codex app-server process multiplexes many app threads (the opener plus every native subagent child), but the protocol logger froze the opener's threadId at open time, so all traffic landed in the opener's log file — and rotation of that busy file destroyed other threads' native ground truth (audit plan #9, threads c878541b/de5f191a/68f7595b/ af66fc2c had no log file at all). The logger now resolves the target per frame: it extracts the native thread id from each frame and looks it up in a per-session route map seeded when a root turn or subagent thread registers, falling back to the opener for unrouted frames. App-verified with a real codex subagent spawn: the two subagent native threads each got their own dedicated log file containing only their own traffic (94 and 54 frames), where previously everything multiplexed into the parent's file. Unit tests cover native-thread-id extraction across decoded/raw frame shapes and the two-thread routing decision. Co-Authored-By: Claude Fable 5 --- .../Adapters/CodexAdapterV2.test.ts | 69 ++++++++++++++++++ .../Adapters/CodexAdapterV2.ts | 72 ++++++++++++++++++- 2 files changed, 138 insertions(+), 3 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index a99701cb5d..1366946c65 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -48,6 +48,7 @@ import { CODEX_DEFAULT_INSTANCE_ID, CODEX_DRIVER_KIND, codexBackgroundCommandDetail, + codexNativeThreadIdFromProtocolEvent, codexThreadRuntimeParams, type CodexAgentMessageDeltaUpdate, type CodexAppServerClientFactoryShape, @@ -458,6 +459,74 @@ describe("CodexAdapterV2 native protocol logging", () => { assert.equal(protocolLogger, undefined); }); + + it("extracts the native thread id from decoded and raw frames", () => { + assert.equal( + codexNativeThreadIdFromProtocolEvent({ + payload: { method: "thread/event", params: { threadId: "019f-abc" } }, + }), + "019f-abc", + ); + assert.equal( + codexNativeThreadIdFromProtocolEvent({ + payload: { result: { thread: { id: "019f-def" } } }, + }), + "019f-def", + ); + assert.equal( + codexNativeThreadIdFromProtocolEvent({ payload: '{"id":1,"params":{"threadId":"019f-raw"}}' }), + "019f-raw", + ); + assert.equal( + codexNativeThreadIdFromProtocolEvent({ payload: { method: "initialize" } }), + undefined, + ); + }); + + it.effect("routes shared-session frames to the owning app thread's log", () => + Effect.gen(function* () { + const writes: Array<{ readonly threadId: ThreadId | null }> = []; + const logger: EventNdjsonLogger = { + filePath: "/tmp/events.log", + write: (_event, threadId) => + Effect.sync(() => { + writes.push({ threadId }); + }), + close: () => Effect.void, + }; + const openerThreadId = ThreadId.make("thread-opener"); + // Two app threads multiplexed on one app-server process: the opener and + // a second thread whose native id maps elsewhere (audit plan #9). + const routes = new Map([["019f-owned", ThreadId.make("thread-owned")]]); + const protocolLogger = makeCodexAppServerProtocolLogger({ + nativeEventLogger: logger, + threadId: openerThreadId, + providerSessionId: ProviderSessionId.make("provider-session-shared"), + resolveThreadId: (nativeThreadId) => + (nativeThreadId === undefined ? undefined : routes.get(nativeThreadId)) ?? openerThreadId, + }); + if (protocolLogger === undefined) { + assert.fail("expected a protocol logger"); + return; + } + + yield* protocolLogger({ + direction: "incoming", + stage: "decoded", + payload: { method: "thread/event", params: { threadId: "019f-owned" } }, + }); + yield* protocolLogger({ + direction: "incoming", + stage: "decoded", + payload: { method: "thread/event", params: { threadId: "019f-unknown" } }, + }); + + assert.deepEqual( + writes.map((write) => write.threadId), + [ThreadId.make("thread-owned"), openerThreadId], + ); + }), + ); }); describe("CodexAdapterV2 rollback mapping", () => { diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 8a13cab767..59a895223d 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -966,6 +966,13 @@ export interface CodexAppServerClientFactoryShape { readonly runtimePolicy: ProviderAdapterV2RuntimePolicy; readonly settings: CodexSettings; readonly environment: NodeJS.ProcessEnv; + /** + * Routes protocol log frames to the app thread that owns the native + * codex thread. One shared app-server process multiplexes many app + * threads; without per-frame routing every thread's traffic lands in + * the opener's log file (audit plan #9). + */ + readonly resolveLogThreadId?: (nativeThreadId: string | undefined) => ThreadId; }) => Effect.Effect< CodexClient.CodexAppServerClient["Service"], ProviderAdapterOpenSessionError, @@ -1072,18 +1079,57 @@ export const makeCodexAppServerClientFactoryCommandLayer = ( }), ); +const CODEX_RAW_THREAD_ID_PATTERN = /"threadId"\s*:\s*"([^"]+)"/; + +/** Best-effort native thread id extraction from a protocol log frame. */ +export function codexNativeThreadIdFromProtocolEvent(event: unknown): string | undefined { + if (typeof event !== "object" || event === null) { + return undefined; + } + const payload = (event as { readonly payload?: unknown }).payload; + if (typeof payload === "string") { + return CODEX_RAW_THREAD_ID_PATTERN.exec(payload)?.[1]; + } + if (typeof payload !== "object" || payload === null) { + return undefined; + } + const record = payload as Record; + for (const container of [record["params"], record["result"], record]) { + if (typeof container !== "object" || container === null) { + continue; + } + const threadId = (container as Record)["threadId"]; + if (typeof threadId === "string") { + return threadId; + } + const thread = (container as Record)["thread"]; + if (typeof thread === "object" && thread !== null) { + const id = (thread as Record)["id"]; + if (typeof id === "string") { + return id; + } + } + } + return undefined; +} + export function makeCodexAppServerProtocolLogger(input: { readonly nativeEventLogger: EventNdjsonLogger | undefined; readonly threadId: ThreadId; readonly providerSessionId: OrchestrationV2ProviderSession["id"]; + readonly resolveThreadId?: (nativeThreadId: string | undefined) => ThreadId; }): CodexClient.CodexAppServerClientOptions["logger"] | undefined { const { nativeEventLogger } = input; if (nativeEventLogger === undefined) { return undefined; } - return (event) => - nativeEventLogger + return (event) => { + const threadId = + input.resolveThreadId === undefined + ? input.threadId + : input.resolveThreadId(codexNativeThreadIdFromProtocolEvent(event)); + return nativeEventLogger .write( { provider: CODEX_PROVIDER, @@ -1092,9 +1138,10 @@ export function makeCodexAppServerProtocolLogger(input: { providerSessionId: input.providerSessionId, event: redactCodexProtocolValue(event), }, - input.threadId, + threadId, ) .pipe(Effect.ignore); + }; } export function redactCodexProtocolValue(value: unknown): unknown { @@ -1164,6 +1211,9 @@ export const codexAppServerClientFactoryFromSettingsLayer: Layer.Layer< nativeEventLogger, threadId: input.threadId, providerSessionId: input.providerSessionId, + ...(input.resolveLogThreadId === undefined + ? {} + : { resolveThreadId: input.resolveLogThreadId }), }); const clientOptions: CodexClient.CodexAppServerClientOptions = protocolLogger === undefined @@ -1290,6 +1340,14 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi planSelectionTransition: () => Effect.succeed(turnScopedSelectionTransition()), openSession: (input) => Effect.gen(function* () { + // native codex thread id → owning app thread. Mutable on purpose: + // the resolver closes over it before any turn registers a route. + // Unknown ids fall back to the opener (its own handshake frames carry + // no route yet); a subagent's earliest frames may land here before its + // route registers, but the bulk of its traffic gets a dedicated file — + // enough that the opener log's rotation no longer destroys other + // threads' ground truth (audit plan #9). + const logThreadRoutes = new Map(); const client = yield* clientFactory.open({ instanceId: adapterOptions.instanceId, threadId: input.threadId, @@ -1297,6 +1355,9 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi runtimePolicy: input.runtimePolicy, settings: adapterOptions.settings, environment: adapterOptions.environment, + resolveLogThreadId: (nativeThreadId) => + (nativeThreadId === undefined ? undefined : logThreadRoutes.get(nativeThreadId)) ?? + input.threadId, }); const initialized = yield* Ref.make(false); const ensureInitialized = Effect.gen(function* () { @@ -1354,6 +1415,10 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi readonly startedAt: DateTime.Utc; }) => Effect.gen(function* () { + const nativeThreadId = input.turnInput.providerThread.nativeThreadRef?.nativeId; + if (nativeThreadId !== undefined && nativeThreadId !== null) { + logThreadRoutes.set(nativeThreadId, input.turnInput.threadId); + } const existing = (yield* Ref.get(activeTurns)).get(input.nativeTurnId); if (existing !== undefined) { return existing; @@ -1716,6 +1781,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi driver: CODEX_PROVIDER, nativeThreadId: input.nativeThreadId, }); + logThreadRoutes.set(input.nativeThreadId, childThreadId); const turnItemOrdinal = yield* resolveItemOrdinal(input.context, input.nativeItemId); const providerThread = { id: idAllocator.derive.providerThread({