fix(orchestration-v2): resolve cross-provider forks

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-08-14 11:22:51 +02:00
1 parent 404393a840
commit caf564ad94
3 files changed
+285 -44

No files matched your search

+134 -37
View File
@@ -1706,18 +1706,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
(candidate) => candidate.id === sourceRun.activeAttemptId,
)?.providerTurnId ??
undefined);
const canResolveForkNatively =
pendingForkTransfer !== undefined &&
pendingForkTransfer.sourceProvider === modelSelection.instanceId &&
sourceProviderThread?.nativeThreadRef?.strength === "strong";
const requiresPortableFork = pendingForkTransfer !== undefined && !canResolveForkNatively;
if (pendingForkTransfer !== undefined) {
if (
pendingForkTransfer.sourceProvider === null ||
pendingForkTransfer.sourceProvider !== modelSelection.provider
) {
return yield* new OrchestratorDispatchError({
commandId: command.commandId,
commandType: command.type,
cause: `Pending fork transfer ${pendingForkTransfer.id} requires portable context for provider ${modelSelection.provider}, which is not implemented yet.`,
});
}
if (sourceRun === null || sourceProviderThread === undefined) {
return yield* new OrchestratorDispatchError({
commandId: command.commandId,
@@ -1725,11 +1720,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
cause: `Pending fork transfer ${pendingForkTransfer.id} has no resolvable source provider thread.`,
});
}
if (sourceProviderThread.nativeThreadRef?.strength !== "strong") {
if (pendingForkTransfer.sourceProvider === null) {
return yield* new OrchestratorDispatchError({
commandId: command.commandId,
commandType: command.type,
cause: `Pending fork transfer ${pendingForkTransfer.id} cannot resolve natively without a strong source native thread ref.`,
cause: `Pending fork transfer ${pendingForkTransfer.id} has no source provider.`,
});
}
}
@@ -1791,7 +1786,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
}),
),
);
if (pendingForkTransfer !== undefined) {
if (canResolveForkNatively) {
yield* enforceCommandPolicy(command)(
commandPolicy.ensureNativeFork({
commandId: command.commandId,
@@ -1804,7 +1799,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
}
const ensuredProviderThread =
pendingForkTransfer !== undefined && sourceProviderThread !== undefined
canResolveForkNatively && sourceProviderThread !== undefined
? yield* session
.forkThread({
sourceProviderThread,
@@ -1860,6 +1855,60 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
}),
),
);
const portableForkItems =
!requiresPortableFork || sourceProjection === null || sourceRun === null
? []
: sourceProjection.turnItems.filter((item) => {
if (item.runId === null) {
return false;
}
const itemRun = sourceProjection.runs.find(
(candidate) => candidate.id === item.runId,
);
return itemRun !== undefined && itemRun.ordinal <= sourceRun.ordinal;
});
if (requiresPortableFork) {
yield* enforceCommandPolicy(command)(
commandPolicy.ensureContextHandoff({
commandId: command.commandId,
threadId: command.threadId,
provider: modelSelection.instanceId,
capabilities: session.providerSession.capabilities,
strategy: "full_thread_summary",
}),
);
}
const portableForkHandoff =
!requiresPortableFork ||
pendingForkTransfer === undefined ||
sourceProjection === null ||
sourceRun === null
? null
: yield* contextHandoffService
.prepareProviderHandoff({
threadId: command.threadId,
targetRunId: runId,
transferId: pendingForkTransfer.id,
fromProviderThreadIds:
sourceProviderThread === undefined ? [] : [sourceProviderThread.id],
toProviderThreadId: ensuredProviderThread.id,
fromProvider: sourceRun.provider,
toProvider: modelSelection.instanceId,
coveredRunOrdinals: visibleDeltaRunOrdinals(sourceProjection, portableForkItems),
strategy: "full_thread_summary",
items: portableForkItems,
createdAt: now,
})
.pipe(
Effect.mapError(
(cause) =>
new OrchestratorDispatchError({
commandId: command.commandId,
commandType: command.type,
cause,
}),
),
);
const providerSwitchCoveredRuns =
!isProviderSwitch || latestCompletedRun === undefined
? []
@@ -1942,10 +1991,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
status: "active",
firstRunOrdinal: ensuredProviderThread.firstRunOrdinal ?? ordinal,
lastRunOrdinal: ordinal,
handoffIds:
providerSwitchHandoff === null
? ensuredProviderThread.handoffIds
: [...ensuredProviderThread.handoffIds, providerSwitchHandoff.id],
handoffIds: [
...ensuredProviderThread.handoffIds,
...[portableForkHandoff, providerSwitchHandoff].flatMap((handoff) =>
handoff === null ? [] : [handoff.id],
),
],
updatedAt: now,
};
@@ -2082,7 +2133,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
startedAt: now,
completedAt: null,
checkpointId: null,
contextHandoffId: providerSwitchHandoff?.id ?? mergeBackHandoff?.id ?? null,
contextHandoffId:
portableForkHandoff?.id ?? providerSwitchHandoff?.id ?? mergeBackHandoff?.id ?? null,
};
const attempt: OrchestrationV2RunAttempt = {
id: attemptId,
@@ -2147,13 +2199,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
text: command.text,
attachments: command.attachments,
};
const activeHandoff = portableForkHandoff ?? providerSwitchHandoff ?? mergeBackHandoff;
const handoffTurnItem: OrchestrationV2TurnItem | null =
providerSwitchHandoff === null && mergeBackHandoff === null
activeHandoff === null
? null
: {
id: idAllocator.derive.runSignalTurnItem({
runId,
signal: `context-handoff:${(providerSwitchHandoff ?? mergeBackHandoff)!.id}`,
signal: `context-handoff:${activeHandoff.id}`,
}),
threadId: command.threadId,
runId,
@@ -2164,32 +2217,47 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
parentItemId: null,
ordinal: ordinal * 100 - 1,
status: "completed",
title: providerSwitchHandoff === null ? "Merge-back context" : "Provider handoff",
title:
portableForkHandoff !== null
? "Fork context"
: providerSwitchHandoff !== null
? "Provider handoff"
: "Merge-back context",
startedAt: now,
completedAt: now,
updatedAt: now,
type: "handoff",
contextHandoffId: (providerSwitchHandoff ?? mergeBackHandoff)!.id,
fromProviderThreadIds: (providerSwitchHandoff ?? mergeBackHandoff)!
.fromProviderThreadIds,
toProviderThreadId: (providerSwitchHandoff ?? mergeBackHandoff)!.toProviderThreadId,
contextHandoffId: activeHandoff.id,
fromProviderThreadIds: activeHandoff.fromProviderThreadIds,
toProviderThreadId: activeHandoff.toProviderThreadId,
fromProviders:
providerSwitchHandoff === null
? mergeBackSourceRun === null
portableForkHandoff !== null
? sourceRun === null
? []
: [mergeBackSourceRun.provider]
: Array.from(new Set(providerSwitchCoveredRuns.map((run) => run.provider))),
: [sourceRun.provider]
: providerSwitchHandoff === null
? mergeBackSourceRun === null
? []
: [mergeBackSourceRun.provider]
: Array.from(new Set(providerSwitchCoveredRuns.map((run) => run.provider))),
toProvider: modelSelection.instanceId,
strategy: (providerSwitchHandoff ?? mergeBackHandoff)!.strategy,
summary: (providerSwitchHandoff ?? mergeBackHandoff)!.summaryText,
strategy: activeHandoff.strategy,
summary: activeHandoff.summaryText,
};
const nativeForkResolution: OrchestrationV2ContextTransferResolution | null =
pendingForkTransfer === undefined || providerThread.nativeThreadRef === null
!canResolveForkNatively || providerThread.nativeThreadRef === null
? null
: {
strategy: "native_fork",
providerThreadRef: providerThread.nativeThreadRef,
};
const portableForkResolution: OrchestrationV2ContextTransferResolution | null =
pendingForkTransfer === undefined || portableForkHandoff === null
? null
: {
strategy: "portable_context",
contextHandoffId: portableForkHandoff.id,
};
const mergeBackResolution: OrchestrationV2ContextTransferResolution | null =
pendingMergeBackTransfer === undefined || mergeBackHandoff === null
? null
@@ -2216,6 +2284,24 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
},
});
}
if (pendingForkTransfer !== undefined && portableForkResolution !== null) {
yield* emitEvent({
type: "context-transfer.updated",
threadId: command.threadId,
runId,
provider: modelSelection.instanceId,
occurredAt: now,
payload: {
...pendingForkTransfer,
targetProvider: modelSelection.instanceId,
targetRunId: runId,
status: "resolved_portable",
resolution: portableForkResolution,
error: null,
updatedAt: now,
},
});
}
yield* emitEvent({
type: "provider-session.updated",
threadId: command.threadId,
@@ -2230,6 +2316,16 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
occurredAt: now,
payload: providerThread,
});
if (portableForkHandoff !== null) {
yield* emitEvent({
type: "context-handoff.updated",
threadId: command.threadId,
runId,
provider: modelSelection.instanceId,
occurredAt: now,
payload: portableForkHandoff,
});
}
if (
providerSwitchTransferId !== null &&
providerSwitchHandoff !== null &&
@@ -2408,7 +2504,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
occurredAt: now,
payload: turnItem,
});
if (pendingForkTransfer !== undefined && nativeForkResolution !== null) {
const forkResolution = nativeForkResolution ?? portableForkResolution;
if (pendingForkTransfer !== undefined && forkResolution !== null) {
yield* emitEvent({
type: "context-transfer.updated",
threadId: command.threadId,
@@ -2420,7 +2517,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
targetProvider: modelSelection.provider,
targetRunId: runId,
status: "consumed",
resolution: nativeForkResolution,
resolution: forkResolution,
error: null,
updatedAt: now,
consumedAt: now,
@@ -2429,10 +2526,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
}
const providerMessageText =
providerSwitchHandoff === null && mergeBackHandoff === null
activeHandoff === null
? command.text
: providerMessageWithContextHandoff({
handoff: (providerSwitchHandoff ?? mergeBackHandoff)!,
handoff: activeHandoff,
userText: command.text,
});
yield* runExecution
@@ -44,6 +44,7 @@ const returnPrompt = "Respond with exactly: codex after return";
interface CapturedTurn {
readonly provider: ProviderKind;
readonly threadId: ThreadId;
readonly providerThreadId: ProviderThreadId;
readonly text: string;
}
@@ -120,6 +121,7 @@ function makeTestAdapter(input: {
...turns,
{
provider: input.provider,
threadId: turnInput.threadId,
providerThreadId: turnInput.providerThread.id,
text: turnInput.message.text,
},
@@ -204,10 +206,12 @@ function makeTestAdapter(input: {
};
}
const waitForIdle = Effect.fn("ProviderSwitchTest.waitForIdle")(function* () {
const waitForIdle = Effect.fn("ProviderSwitchTest.waitForIdle")(function* (
targetThreadId: ThreadId,
) {
const orchestrator = yield* OrchestratorV2;
for (let attempt = 0; attempt < 1_000; attempt += 1) {
const projection = yield* orchestrator.getThreadProjection(threadId);
const projection = yield* orchestrator.getThreadProjection(targetThreadId);
if (
projection.runs.every(
(run) => !["queued", "starting", "running", "waiting"].includes(run.status),
@@ -296,11 +300,11 @@ describe("orchestration v2 provider switching", () => {
const orchestrator = yield* OrchestratorV2;
yield* orchestrator.dispatch(commands[0]!);
yield* orchestrator.dispatch(commands[1]!);
yield* waitForIdle();
yield* waitForIdle(threadId);
yield* orchestrator.dispatch(commands[2]!);
yield* waitForIdle();
yield* waitForIdle(threadId);
yield* orchestrator.dispatch(commands[3]!);
return yield* waitForIdle();
return yield* waitForIdle(threadId);
}).pipe(
Effect.provide(
makeOrchestratorV2ReplayLayerWithRegistry(
@@ -384,4 +388,142 @@ describe("orchestration v2 provider switching", () => {
);
}
});
it("resolves a Claude fork into portable Codex context on first dispatch", async () => {
const sourceThreadId = ThreadId.make("thread:cross-provider-fork:source");
const targetThreadId = ThreadId.make("thread:cross-provider-fork:target");
const sourcePrompt = "Remember that the release color is violet.";
const targetPrompt = "What release color did we choose?";
const cwd = await makeCheckpointWorkspace("cross-provider-fork");
const capturedTurns = await Effect.runPromise(Ref.make<ReadonlyArray<CapturedTurn>>([]));
const registryLayer = makeProviderAdapterRegistryLayer([
makeTestAdapter({
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
capabilities: CodexProviderCapabilitiesV2,
modelSelection: CODEX_MODEL_SELECTION,
responseByRunOrdinal: { 1: "The release color is violet." },
capturedTurns,
}),
makeTestAdapter({
instanceId: ProviderInstanceId.make("claudeAgent"),
provider: "claudeAgent",
capabilities: ClaudeProviderCapabilitiesV2,
modelSelection: CLAUDE_MODEL_SELECTION,
responseByRunOrdinal: { 1: "I will remember violet." },
capturedTurns,
}),
]);
const commands = [
{
type: "thread.create",
commandId: CommandId.make("command:cross-provider-fork:create"),
threadId: sourceThreadId,
projectId,
title: "Cross-provider fork source",
modelSelection: CLAUDE_MODEL_SELECTION,
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
},
{
type: "message.dispatch",
commandId: CommandId.make("command:cross-provider-fork:source"),
threadId: sourceThreadId,
messageId: MessageId.make("message:cross-provider-fork:source"),
text: sourcePrompt,
attachments: [],
modelSelection: CLAUDE_MODEL_SELECTION,
dispatchMode: { type: "start_immediately" },
},
{
type: "thread.fork",
commandId: CommandId.make("command:cross-provider-fork:fork"),
sourceThreadId,
targetThreadId,
sourcePoint: { type: "latest_stable" },
title: "Cross-provider fork target",
},
{
type: "message.dispatch",
commandId: CommandId.make("command:cross-provider-fork:target"),
threadId: targetThreadId,
messageId: MessageId.make("message:cross-provider-fork:target"),
text: targetPrompt,
attachments: [],
modelSelection: CODEX_MODEL_SELECTION,
dispatchMode: { type: "start_immediately" },
},
] satisfies ReadonlyArray<OrchestrationV2Command>;
try {
const targetProjection = await Effect.runPromise(
Effect.gen(function* () {
const orchestrator = yield* OrchestratorV2;
yield* orchestrator.dispatch(commands[0]!);
yield* orchestrator.dispatch(commands[1]!);
yield* waitForIdle(sourceThreadId);
yield* orchestrator.dispatch(commands[2]!);
yield* orchestrator.dispatch(commands[3]!);
return yield* waitForIdle(targetThreadId);
}).pipe(
Effect.provide(
makeOrchestratorV2ReplayLayerWithRegistry(
{
name: "cross-provider-fork",
runtimePolicyOverride: {
cwd,
approvalPolicy: "never",
sandboxPolicy: {
type: "readOnly",
access: { type: "fullAccess" },
networkAccess: false,
},
},
},
registryLayer,
),
),
),
);
const turns = await Effect.runPromise(Ref.get(capturedTurns));
const targetTurn = turns.find((turn) => turn.threadId === targetThreadId);
assert.deepEqual(
targetProjection.runs.map((run) => [run.provider, run.status]),
[["codex", "completed"]],
);
assert.lengthOf(targetProjection.providerThreads, 1);
assert.equal(targetProjection.providerThreads[0]?.provider, "codex");
assert.isNull(targetProjection.providerThreads[0]?.forkedFrom);
assert.deepEqual(
targetProjection.contextTransfers.map((transfer) => [
transfer.type,
transfer.status,
transfer.resolution?.strategy,
]),
[["fork", "consumed", "portable_context"]],
);
assert.deepEqual(
targetProjection.contextHandoffs.map((handoff) => handoff.strategy),
["full_thread_summary"],
);
assert.equal(
targetProjection.runs[0]?.contextHandoffId,
targetProjection.contextHandoffs[0]?.id,
);
assert.include(targetTurn?.text ?? "", "Context handoff (full_thread_summary):");
assert.include(targetTurn?.text ?? "", sourcePrompt);
assert.include(targetTurn?.text ?? "", "I will remember violet.");
assert.include(targetTurn?.text ?? "", targetPrompt);
} finally {
await Effect.runPromise(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
yield* fs.remove(cwd, { recursive: true, force: true });
}).pipe(Effect.provide(NodeServices.layer)),
);
}
});
});
@@ -270,10 +270,12 @@ The first backend slice implements lazy same-provider fork resolution:
- `thread.fork` creates a target app thread with fork lineage and a pending `ContextTransfer`.
- `thread.fork` does not create a provider session, provider thread, provider turn, or portable context artifact.
- The first dispatch on the fork resolves the pending transfer. For Codex-to-Codex forks with strong native refs and `thread/fork` support, the orchestrator uses the provider-native fork path and records `resolved_native` then `consumed`.
- Cross-provider or otherwise portable transfers fail explicitly before provider side effects. Portable `ContextHandoff` materialization is still future work.
- Cross-provider or otherwise non-native fork transfers materialize a portable `ContextHandoff`
lazily on the target thread's first dispatch.
- Active source runs are rejected for explicit run/checkpoint forks; `latest_stable` resolves to the latest completed checkpointed run.
This keeps the current runtime aligned with the architecture without shipping compatibility shims or placeholder prompt concatenation for context handoff.
This keeps the runtime aligned with the architecture while making portable context explicit and
auditable through `ContextTransfer` and `ContextHandoff` records.
## Relationship To Provider Switching