Add merge-back context handoff support
- Map fork and merge-back turns into stored handoffs and transfer resolutions - Add shell snapshot projection support plus coverage tests - Update replay fixtures and web contracts for the new turn flow
This commit is contained in:
1 parent
74f73e39ea
commit
7cfdb4e79e
36 files changed
+2921
-301
No files matched your search
@@ -1,11 +1,14 @@
|
||||
import {
|
||||
OrchestrationV2ContextHandoff,
|
||||
type OrchestrationV2TurnItem,
|
||||
type ProviderKind,
|
||||
ProviderThreadId,
|
||||
RunId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Context, Schema } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import { Context, DateTime, Effect, Layer, Schema } from "effect";
|
||||
|
||||
import { IdAllocatorV2 } from "./IdAllocator.ts";
|
||||
|
||||
export class ContextHandoffPrepareError extends Schema.TaggedErrorClass<ContextHandoffPrepareError>()(
|
||||
"ContextHandoffPrepareError",
|
||||
@@ -32,9 +35,193 @@ export interface ContextHandoffServiceV2Shape {
|
||||
readonly fromProviderThreadIds: ReadonlyArray<ProviderThreadId>;
|
||||
readonly toProviderThreadId: ProviderThreadId;
|
||||
}) => Effect.Effect<OrchestrationV2ContextHandoff, ContextHandoffServiceV2Error>;
|
||||
readonly prepareForkDelta: (input: {
|
||||
readonly sourceThreadId: ThreadId;
|
||||
readonly targetThreadId: ThreadId;
|
||||
readonly targetRunId: RunId;
|
||||
readonly transferId: OrchestrationV2ContextHandoff["transferId"];
|
||||
readonly fromProviderThreadIds: ReadonlyArray<ProviderThreadId>;
|
||||
readonly toProviderThreadId: ProviderThreadId;
|
||||
readonly fromProvider: ProviderKind;
|
||||
readonly toProvider: ProviderKind;
|
||||
readonly coveredRunOrdinals: OrchestrationV2ContextHandoff["coveredRunOrdinals"];
|
||||
readonly deltaItems: ReadonlyArray<OrchestrationV2TurnItem>;
|
||||
readonly createdAt: DateTime.Utc;
|
||||
}) => Effect.Effect<OrchestrationV2ContextHandoff, ContextHandoffServiceV2Error>;
|
||||
}
|
||||
|
||||
export class ContextHandoffServiceV2 extends Context.Service<
|
||||
ContextHandoffServiceV2,
|
||||
ContextHandoffServiceV2Shape
|
||||
>()("t3/orchestration-v2/ContextHandoffService") {}
|
||||
|
||||
function compactText(text: string, maxLength = 240): string {
|
||||
const compacted = text.replace(/\s+/g, " ").trim();
|
||||
if (compacted.length <= maxLength) {
|
||||
return compacted;
|
||||
}
|
||||
return `${compacted.slice(0, maxLength - 3)}...`;
|
||||
}
|
||||
|
||||
function summarizeDeltaItem(item: OrchestrationV2TurnItem): string | null {
|
||||
switch (item.type) {
|
||||
case "user_message":
|
||||
return `- User: ${compactText(item.text)}`;
|
||||
case "assistant_message":
|
||||
return `- Assistant: ${compactText(item.text)}`;
|
||||
case "command_execution":
|
||||
return `- Command: ${compactText(item.input)}`;
|
||||
case "file_change":
|
||||
return `- File change: ${item.fileName}`;
|
||||
case "checkpoint":
|
||||
return `- Checkpoint: ${item.files.length} files`;
|
||||
case "handoff":
|
||||
return `- Handoff: ${compactText(item.summary ?? item.strategy)}`;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function makeForkDeltaSummary(input: {
|
||||
readonly sourceThreadId: ThreadId;
|
||||
readonly targetThreadId: ThreadId;
|
||||
readonly coveredRunOrdinals: OrchestrationV2ContextHandoff["coveredRunOrdinals"];
|
||||
readonly deltaItems: ReadonlyArray<OrchestrationV2TurnItem>;
|
||||
}): string {
|
||||
const itemLines = input.deltaItems.flatMap((item) => {
|
||||
const line = summarizeDeltaItem(item);
|
||||
return line === null ? [] : [line];
|
||||
});
|
||||
return [
|
||||
"Merge-back context from forked conversation.",
|
||||
`Source thread: ${input.sourceThreadId}`,
|
||||
`Target thread: ${input.targetThreadId}`,
|
||||
`Covered fork runs: ${input.coveredRunOrdinals.from}-${input.coveredRunOrdinals.to}`,
|
||||
"",
|
||||
"Fork delta:",
|
||||
...(itemLines.length === 0 ? ["- No user-visible delta items."] : itemLines),
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
export function providerMessageWithContextHandoff(input: {
|
||||
readonly handoff: OrchestrationV2ContextHandoff;
|
||||
readonly userText: string;
|
||||
}): string {
|
||||
return [
|
||||
"Context handoff (merge_back / fork_delta_summary):",
|
||||
input.handoff.summaryText,
|
||||
"",
|
||||
"User message:",
|
||||
input.userText,
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
const makeContextHandoffService = Effect.fn("orchestrationV2.ContextHandoffService.layer")(
|
||||
function* () {
|
||||
const idAllocator = yield* IdAllocatorV2;
|
||||
|
||||
const prepare = Effect.fn("orchestrationV2.contextHandoff.prepare")(function* (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly targetRunId: RunId;
|
||||
readonly fromProviderThreadIds: ReadonlyArray<ProviderThreadId>;
|
||||
readonly toProviderThreadId: ProviderThreadId;
|
||||
}) {
|
||||
const now = yield* DateTime.now;
|
||||
const handoffId = yield* idAllocator.allocate
|
||||
.contextHandoff({
|
||||
threadId: input.threadId,
|
||||
fromProvider: "codex",
|
||||
toProvider: "codex",
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ContextHandoffPrepareError({
|
||||
threadId: input.threadId,
|
||||
targetRunId: input.targetRunId,
|
||||
fromProviderThreadIds: Array.from(input.fromProviderThreadIds),
|
||||
toProviderThreadId: input.toProviderThreadId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return {
|
||||
id: handoffId,
|
||||
transferId: null,
|
||||
threadId: input.threadId,
|
||||
targetRunId: input.targetRunId,
|
||||
fromProviderThreadIds: Array.from(input.fromProviderThreadIds),
|
||||
toProviderThreadId: input.toProviderThreadId,
|
||||
coveredRunOrdinals: { from: 1, to: 1 },
|
||||
strategy: "manual_context",
|
||||
status: "ready",
|
||||
summaryMessageId: null,
|
||||
summaryText: "Manual context handoff.",
|
||||
createdByProvider: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
} satisfies OrchestrationV2ContextHandoff;
|
||||
});
|
||||
|
||||
const prepareForkDelta = Effect.fn("orchestrationV2.contextHandoff.prepareForkDelta")(
|
||||
function* (input: {
|
||||
readonly sourceThreadId: ThreadId;
|
||||
readonly targetThreadId: ThreadId;
|
||||
readonly targetRunId: RunId;
|
||||
readonly transferId: OrchestrationV2ContextHandoff["transferId"];
|
||||
readonly fromProviderThreadIds: ReadonlyArray<ProviderThreadId>;
|
||||
readonly toProviderThreadId: ProviderThreadId;
|
||||
readonly fromProvider: ProviderKind;
|
||||
readonly toProvider: ProviderKind;
|
||||
readonly coveredRunOrdinals: OrchestrationV2ContextHandoff["coveredRunOrdinals"];
|
||||
readonly deltaItems: ReadonlyArray<OrchestrationV2TurnItem>;
|
||||
readonly createdAt: DateTime.Utc;
|
||||
}) {
|
||||
const handoffId = yield* idAllocator.allocate
|
||||
.contextHandoff({
|
||||
threadId: input.targetThreadId,
|
||||
fromProvider: input.fromProvider,
|
||||
toProvider: input.toProvider,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ContextHandoffPrepareError({
|
||||
threadId: input.targetThreadId,
|
||||
targetRunId: input.targetRunId,
|
||||
fromProviderThreadIds: Array.from(input.fromProviderThreadIds),
|
||||
toProviderThreadId: input.toProviderThreadId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return {
|
||||
id: handoffId,
|
||||
transferId: input.transferId,
|
||||
threadId: input.targetThreadId,
|
||||
targetRunId: input.targetRunId,
|
||||
fromProviderThreadIds: Array.from(input.fromProviderThreadIds),
|
||||
toProviderThreadId: input.toProviderThreadId,
|
||||
coveredRunOrdinals: input.coveredRunOrdinals,
|
||||
strategy: "fork_delta_summary",
|
||||
status: "ready",
|
||||
summaryMessageId: null,
|
||||
summaryText: makeForkDeltaSummary(input),
|
||||
createdByProvider: null,
|
||||
createdAt: input.createdAt,
|
||||
updatedAt: input.createdAt,
|
||||
} satisfies OrchestrationV2ContextHandoff;
|
||||
},
|
||||
);
|
||||
|
||||
return ContextHandoffServiceV2.of({
|
||||
prepare,
|
||||
prepareForkDelta,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
export const layer: Layer.Layer<ContextHandoffServiceV2, never, IdAllocatorV2> = Layer.effect(
|
||||
ContextHandoffServiceV2,
|
||||
makeContextHandoffService(),
|
||||
);
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
OrchestrationV2Command,
|
||||
type OrchestrationV2AppThread,
|
||||
type OrchestrationV2Checkpoint,
|
||||
type OrchestrationV2ContextHandoff,
|
||||
type OrchestrationV2ContextSourcePoint,
|
||||
type OrchestrationV2ContextTransfer,
|
||||
type OrchestrationV2ContextTransferResolution,
|
||||
@@ -14,6 +15,7 @@ import {
|
||||
type OrchestrationV2ProviderThread,
|
||||
type OrchestrationV2Run,
|
||||
type OrchestrationV2RunAttempt,
|
||||
type OrchestrationV2ShellSnapshot,
|
||||
type OrchestrationV2StoredEvent,
|
||||
type OrchestrationV2ThreadProjection,
|
||||
type OrchestrationV2TurnItem,
|
||||
@@ -24,6 +26,10 @@ import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import { CheckpointServiceV2 } from "./CheckpointService.ts";
|
||||
import { CommandReceiptStoreV2 } from "./CommandReceiptStore.ts";
|
||||
import {
|
||||
ContextHandoffServiceV2,
|
||||
providerMessageWithContextHandoff,
|
||||
} from "./ContextHandoffService.ts";
|
||||
import { EventSinkV2 } from "./EventSink.ts";
|
||||
import { IdAllocatorV2 } from "./IdAllocator.ts";
|
||||
import { ProjectionStoreV2 } from "./ProjectionStore.ts";
|
||||
@@ -114,6 +120,7 @@ export interface OrchestratorV2Shape {
|
||||
readonly getThreadProjection: (
|
||||
threadId: ThreadId,
|
||||
) => Effect.Effect<OrchestrationV2ThreadProjection, OrchestratorV2Error>;
|
||||
readonly getShellSnapshot: () => Effect.Effect<OrchestrationV2ShellSnapshot, OrchestratorV2Error>;
|
||||
readonly getThreadEventSequence: (
|
||||
threadId: ThreadId,
|
||||
) => Effect.Effect<number, OrchestratorV2Error>;
|
||||
@@ -141,6 +148,7 @@ function commandThreadId(command: OrchestrationV2Command): ThreadId {
|
||||
case "provider.switch":
|
||||
return command.threadId;
|
||||
case "thread.fork":
|
||||
case "thread.merge_back":
|
||||
return command.targetThreadId;
|
||||
}
|
||||
}
|
||||
@@ -177,6 +185,29 @@ function latestStableRun(projection: OrchestrationV2ThreadProjection): Orchestra
|
||||
);
|
||||
}
|
||||
|
||||
function runForSourcePoint(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
sourcePoint: Extract<
|
||||
OrchestrationV2Command,
|
||||
{ readonly type: "thread.fork" | "thread.merge_back" }
|
||||
>["sourcePoint"],
|
||||
): OrchestrationV2Run | null {
|
||||
switch (sourcePoint.type) {
|
||||
case "latest_stable":
|
||||
return latestStableRun(projection);
|
||||
case "run":
|
||||
return projection.runs.find((run) => run.id === sourcePoint.runId) ?? null;
|
||||
case "checkpoint": {
|
||||
const checkpoint = projection.checkpoints.find(
|
||||
(candidate) => candidate.id === sourcePoint.checkpointId,
|
||||
);
|
||||
return checkpoint?.runId === null || checkpoint === undefined
|
||||
? null
|
||||
: (projection.runs.find((run) => run.id === checkpoint.runId) ?? null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function providerThreadForRun(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
run: OrchestrationV2Run,
|
||||
@@ -225,8 +256,53 @@ function pendingForkTransferForThread(
|
||||
);
|
||||
}
|
||||
|
||||
function pendingMergeBackTransfersForThread(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
): ReadonlyArray<OrchestrationV2ContextTransfer> {
|
||||
return projection.contextTransfers.filter(
|
||||
(transfer) =>
|
||||
transfer.type === "merge_back" &&
|
||||
transfer.targetThreadId === projection.thread.id &&
|
||||
transfer.status === "pending",
|
||||
);
|
||||
}
|
||||
|
||||
function latestContextTransfer(
|
||||
transfers: ReadonlyArray<OrchestrationV2ContextTransfer>,
|
||||
): OrchestrationV2ContextTransfer | undefined {
|
||||
return transfers.reduce<OrchestrationV2ContextTransfer | undefined>((latest, transfer) => {
|
||||
if (latest === undefined) {
|
||||
return transfer;
|
||||
}
|
||||
return DateTime.toEpochMillis(transfer.updatedAt) >= DateTime.toEpochMillis(latest.updatedAt)
|
||||
? transfer
|
||||
: latest;
|
||||
}, undefined);
|
||||
}
|
||||
|
||||
function visibleDeltaRunOrdinals(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
items: ReadonlyArray<OrchestrationV2TurnItem>,
|
||||
): OrchestrationV2ContextHandoff["coveredRunOrdinals"] {
|
||||
const ordinals = items.flatMap((item) => {
|
||||
if (item.runId === null) {
|
||||
return [];
|
||||
}
|
||||
const run = projection.runs.find((candidate) => candidate.id === item.runId);
|
||||
return run === undefined ? [] : [run.ordinal];
|
||||
});
|
||||
if (ordinals.length === 0) {
|
||||
return { from: 1, to: 1 };
|
||||
}
|
||||
return {
|
||||
from: Math.min(...ordinals),
|
||||
to: Math.max(...ordinals),
|
||||
};
|
||||
}
|
||||
|
||||
const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(function* () {
|
||||
const checkpointService = yield* CheckpointServiceV2;
|
||||
const contextHandoffService = yield* ContextHandoffServiceV2;
|
||||
const eventSink = yield* EventSinkV2;
|
||||
const commandReceipts = yield* CommandReceiptStoreV2;
|
||||
const idAllocator = yield* IdAllocatorV2;
|
||||
@@ -593,23 +669,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
),
|
||||
);
|
||||
|
||||
const sourcePoint = command.sourcePoint;
|
||||
const sourceRun = (() => {
|
||||
switch (sourcePoint.type) {
|
||||
case "latest_stable":
|
||||
return latestStableRun(sourceProjection);
|
||||
case "run":
|
||||
return sourceProjection.runs.find((run) => run.id === sourcePoint.runId) ?? null;
|
||||
case "checkpoint": {
|
||||
const checkpoint = sourceProjection.checkpoints.find(
|
||||
(candidate) => candidate.id === sourcePoint.checkpointId,
|
||||
);
|
||||
return checkpoint?.runId === null || checkpoint === undefined
|
||||
? null
|
||||
: (sourceProjection.runs.find((run) => run.id === checkpoint.runId) ?? null);
|
||||
}
|
||||
}
|
||||
})();
|
||||
const sourceRun = runForSourcePoint(sourceProjection, command.sourcePoint);
|
||||
|
||||
if (sourceRun === null) {
|
||||
return yield* new OrchestratorDispatchError({
|
||||
@@ -693,6 +753,142 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
});
|
||||
});
|
||||
|
||||
const dispatchThreadMergeBack = Effect.fn("orchestrationV2.dispatch.threadMergeBack")(function* (
|
||||
command: Extract<OrchestrationV2Command, { readonly type: "thread.merge_back" }>,
|
||||
events: Ref.Ref<Array<OrchestrationV2StoredEvent>>,
|
||||
) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"orchestration_v2.command_id": command.commandId,
|
||||
"orchestration_v2.command_type": command.type,
|
||||
"orchestration_v2.source_thread_id": command.sourceThreadId,
|
||||
"orchestration_v2.target_thread_id": command.targetThreadId,
|
||||
"orchestration_v2.source_point_type": command.sourcePoint.type,
|
||||
});
|
||||
|
||||
const sourceProjection = yield* projectionStore
|
||||
.getThreadProjection(command.sourceThreadId)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestratorProjectionError({
|
||||
threadId: command.sourceThreadId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const targetProjection = yield* projectionStore
|
||||
.getThreadProjection(command.targetThreadId)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestratorProjectionError({
|
||||
threadId: command.targetThreadId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
if (
|
||||
sourceProjection.thread.lineage.relationshipToParent !== "fork" ||
|
||||
sourceProjection.thread.lineage.parentThreadId !== command.targetThreadId
|
||||
) {
|
||||
return yield* new OrchestratorDispatchError({
|
||||
commandId: command.commandId,
|
||||
commandType: command.type,
|
||||
cause: `Thread ${command.sourceThreadId} is not a fork of ${command.targetThreadId}.`,
|
||||
});
|
||||
}
|
||||
|
||||
const sourceRun = runForSourcePoint(sourceProjection, command.sourcePoint);
|
||||
if (sourceRun === null) {
|
||||
return yield* new OrchestratorDispatchError({
|
||||
commandId: command.commandId,
|
||||
commandType: command.type,
|
||||
cause: `No stable source run was found for merge-back source ${command.sourcePoint.type}.`,
|
||||
});
|
||||
}
|
||||
if (sourceRun.status !== "completed") {
|
||||
return yield* new OrchestratorDispatchError({
|
||||
commandId: command.commandId,
|
||||
commandType: command.type,
|
||||
cause: `Merge-back source run ${sourceRun.id} is ${sourceRun.status}; only completed runs are supported.`,
|
||||
});
|
||||
}
|
||||
|
||||
const forkTransfer = sourceProjection.contextTransfers.findLast(
|
||||
(transfer) =>
|
||||
transfer.type === "fork" &&
|
||||
transfer.sourceThreadId === command.targetThreadId &&
|
||||
transfer.targetThreadId === command.sourceThreadId,
|
||||
);
|
||||
if (forkTransfer === undefined) {
|
||||
return yield* new OrchestratorDispatchError({
|
||||
commandId: command.commandId,
|
||||
commandType: command.type,
|
||||
cause: `No fork transfer exists between ${command.targetThreadId} and ${command.sourceThreadId}.`,
|
||||
});
|
||||
}
|
||||
|
||||
const sourceProviderThread = providerThreadForRun(sourceProjection, sourceRun);
|
||||
const now = command.createdAt ?? (yield* DateTime.now);
|
||||
const emitEvent = emit(events, command);
|
||||
const transferId = yield* mapDispatchError(command)(
|
||||
idAllocator.allocate.contextTransfer({
|
||||
sourceThreadId: command.sourceThreadId,
|
||||
targetThreadId: command.targetThreadId,
|
||||
type: "merge_back",
|
||||
}),
|
||||
);
|
||||
const pendingMergeBackTransfersForPair = targetProjection.contextTransfers.filter(
|
||||
(transfer) =>
|
||||
transfer.type === "merge_back" &&
|
||||
transfer.status === "pending" &&
|
||||
transfer.sourceThreadId === command.sourceThreadId &&
|
||||
transfer.targetThreadId === command.targetThreadId,
|
||||
);
|
||||
const transfer: OrchestrationV2ContextTransfer = {
|
||||
id: transferId,
|
||||
type: "merge_back",
|
||||
sourceThreadId: command.sourceThreadId,
|
||||
targetThreadId: command.targetThreadId,
|
||||
sourcePoint: contextSourcePointForRun(sourceProjection, sourceRun),
|
||||
basePoint: forkTransfer.sourcePoint,
|
||||
sourceProvider: sourceRun.provider,
|
||||
targetProvider: targetProjection.thread.modelSelection.provider,
|
||||
targetRunId: null,
|
||||
status: "pending",
|
||||
resolution: null,
|
||||
createdBy: "user",
|
||||
error:
|
||||
sourceProviderThread === undefined ? "Source merge-back run has no provider thread." : null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
consumedAt: null,
|
||||
};
|
||||
|
||||
for (const pendingTransfer of pendingMergeBackTransfersForPair) {
|
||||
yield* emitEvent({
|
||||
type: "context-transfer.updated",
|
||||
threadId: command.targetThreadId,
|
||||
provider: sourceRun.provider,
|
||||
occurredAt: now,
|
||||
payload: {
|
||||
...pendingTransfer,
|
||||
status: "superseded",
|
||||
error: `Superseded by merge-back transfer ${transferId}.`,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
}
|
||||
yield* emitEvent({
|
||||
type: "context-transfer.created",
|
||||
threadId: command.targetThreadId,
|
||||
provider: sourceRun.provider,
|
||||
occurredAt: now,
|
||||
payload: transfer,
|
||||
});
|
||||
});
|
||||
|
||||
const dispatchSteerIntoRun = (input: {
|
||||
readonly command: Extract<
|
||||
OrchestrationV2Command,
|
||||
@@ -809,6 +1005,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
updatedAt: now,
|
||||
type: "user_message",
|
||||
messageId: input.messageId,
|
||||
inputIntent:
|
||||
input.command.type === "queued-message.promote-to-steer"
|
||||
? "promoted_queued_to_steer"
|
||||
: "steer",
|
||||
text: input.text,
|
||||
attachments: input.attachments,
|
||||
};
|
||||
@@ -1122,10 +1322,18 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
(candidate) => candidate.id === projection.thread.activeProviderThreadId,
|
||||
);
|
||||
const activeRun = projection.runs.find(isBlockingRun);
|
||||
const pendingMergeBackTransfers = pendingMergeBackTransfersForThread(projection);
|
||||
const shouldQueue =
|
||||
activeRun !== undefined &&
|
||||
(dispatchMode.type === "start_immediately" || dispatchMode.type === "queue_after_active");
|
||||
if (shouldQueue) {
|
||||
if (pendingMergeBackTransfers.length > 0) {
|
||||
return yield* new OrchestratorDispatchError({
|
||||
commandId: command.commandId,
|
||||
commandType: command.type,
|
||||
cause: `Thread ${command.threadId} has a pending merge-back transfer; queued merge-back consumption is not implemented yet.`,
|
||||
});
|
||||
}
|
||||
const queueProviderThread =
|
||||
activeProviderThread ??
|
||||
projection.providerThreads.find(
|
||||
@@ -1274,6 +1482,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
updatedAt: now,
|
||||
type: "user_message",
|
||||
messageId: command.messageId,
|
||||
inputIntent: "queued_turn",
|
||||
text: command.text,
|
||||
attachments: command.attachments,
|
||||
};
|
||||
@@ -1344,6 +1553,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
return;
|
||||
}
|
||||
const pendingForkTransfer = pendingForkTransferForThread(projection);
|
||||
const pendingMergeBackSourceThreadIds = new Set(
|
||||
pendingMergeBackTransfers.map((transfer) => transfer.sourceThreadId),
|
||||
);
|
||||
if (pendingMergeBackSourceThreadIds.size > 1) {
|
||||
return yield* new OrchestratorDispatchError({
|
||||
commandId: command.commandId,
|
||||
commandType: command.type,
|
||||
cause: `Thread ${command.threadId} has pending merge-back transfers from multiple forks.`,
|
||||
});
|
||||
}
|
||||
const pendingMergeBackTransfer = latestContextTransfer(pendingMergeBackTransfers);
|
||||
const supersededMergeBackTransfers = pendingMergeBackTransfers.filter(
|
||||
(transfer) => transfer.id !== pendingMergeBackTransfer?.id,
|
||||
);
|
||||
const now = yield* DateTime.now;
|
||||
const ordinal = nextRunOrdinal(projection);
|
||||
const runId = idAllocator.derive.run({ threadId: command.threadId, ordinal });
|
||||
@@ -1540,6 +1763,90 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
const attemptId = idAllocator.derive.runAttempt({ runId, attemptOrdinal: 1 });
|
||||
const rootNodeId = idAllocator.derive.rootNode({ runId });
|
||||
const emitEvent = emit(events, command);
|
||||
const mergeBackSourceProjection =
|
||||
pendingMergeBackTransfer === undefined
|
||||
? null
|
||||
: yield* projectionStore
|
||||
.getThreadProjection(pendingMergeBackTransfer.sourceThreadId)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestratorProjectionError({
|
||||
threadId: pendingMergeBackTransfer.sourceThreadId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const mergeBackSourceRun =
|
||||
pendingMergeBackTransfer?.sourcePoint.runId === undefined ||
|
||||
mergeBackSourceProjection === null
|
||||
? null
|
||||
: (mergeBackSourceProjection.runs.find(
|
||||
(candidate) => candidate.id === pendingMergeBackTransfer.sourcePoint.runId,
|
||||
) ?? null);
|
||||
if (pendingMergeBackTransfer !== undefined && mergeBackSourceRun === null) {
|
||||
return yield* new OrchestratorDispatchError({
|
||||
commandId: command.commandId,
|
||||
commandType: command.type,
|
||||
cause: `Pending merge-back transfer ${pendingMergeBackTransfer.id} has no resolvable source run.`,
|
||||
});
|
||||
}
|
||||
const mergeBackSourceProviderThread =
|
||||
mergeBackSourceProjection === null || mergeBackSourceRun === null
|
||||
? undefined
|
||||
: providerThreadForRun(mergeBackSourceProjection, mergeBackSourceRun);
|
||||
if (pendingMergeBackTransfer !== undefined && mergeBackSourceProviderThread === undefined) {
|
||||
return yield* new OrchestratorDispatchError({
|
||||
commandId: command.commandId,
|
||||
commandType: command.type,
|
||||
cause: `Pending merge-back transfer ${pendingMergeBackTransfer.id} has no resolvable source provider thread.`,
|
||||
});
|
||||
}
|
||||
const mergeBackDeltaItems =
|
||||
mergeBackSourceProjection === null || mergeBackSourceRun === null
|
||||
? []
|
||||
: mergeBackSourceProjection.turnItems.filter((item) => {
|
||||
if (item.runId === null) {
|
||||
return false;
|
||||
}
|
||||
const itemRun = mergeBackSourceProjection.runs.find(
|
||||
(candidate) => candidate.id === item.runId,
|
||||
);
|
||||
return itemRun !== undefined && itemRun.ordinal <= mergeBackSourceRun.ordinal;
|
||||
});
|
||||
const mergeBackHandoff =
|
||||
pendingMergeBackTransfer === undefined ||
|
||||
mergeBackSourceProjection === null ||
|
||||
mergeBackSourceRun === null ||
|
||||
mergeBackSourceProviderThread === undefined
|
||||
? null
|
||||
: yield* contextHandoffService
|
||||
.prepareForkDelta({
|
||||
sourceThreadId: pendingMergeBackTransfer.sourceThreadId,
|
||||
targetThreadId: command.threadId,
|
||||
targetRunId: runId,
|
||||
transferId: pendingMergeBackTransfer.id,
|
||||
fromProviderThreadIds: [mergeBackSourceProviderThread.id],
|
||||
toProviderThreadId: providerThread.id,
|
||||
fromProvider: mergeBackSourceRun.provider,
|
||||
toProvider: modelSelection.provider,
|
||||
coveredRunOrdinals: visibleDeltaRunOrdinals(
|
||||
mergeBackSourceProjection,
|
||||
mergeBackDeltaItems,
|
||||
),
|
||||
deltaItems: mergeBackDeltaItems,
|
||||
createdAt: now,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestratorDispatchError({
|
||||
commandId: command.commandId,
|
||||
commandType: command.type,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const checkpointScope = yield* checkpointService
|
||||
.prepareRootRunScope({
|
||||
threadId: command.threadId,
|
||||
@@ -1574,7 +1881,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
startedAt: now,
|
||||
completedAt: null,
|
||||
checkpointId: null,
|
||||
contextHandoffId: null,
|
||||
contextHandoffId: mergeBackHandoff?.id ?? null,
|
||||
};
|
||||
const attempt: OrchestrationV2RunAttempt = {
|
||||
id: attemptId,
|
||||
@@ -1635,9 +1942,40 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
updatedAt: now,
|
||||
type: "user_message",
|
||||
messageId: command.messageId,
|
||||
inputIntent: "turn_start",
|
||||
text: command.text,
|
||||
attachments: command.attachments,
|
||||
};
|
||||
const handoffTurnItem: OrchestrationV2TurnItem | null =
|
||||
mergeBackHandoff === null
|
||||
? null
|
||||
: {
|
||||
id: idAllocator.derive.runSignalTurnItem({
|
||||
runId,
|
||||
signal: `context-handoff:${mergeBackHandoff.id}`,
|
||||
}),
|
||||
threadId: command.threadId,
|
||||
runId,
|
||||
nodeId: rootNodeId,
|
||||
providerThreadId: providerThread.id,
|
||||
providerTurnId: null,
|
||||
nativeItemRef: null,
|
||||
parentItemId: null,
|
||||
ordinal: ordinal * 100 - 1,
|
||||
status: "completed",
|
||||
title: "Merge-back context",
|
||||
startedAt: now,
|
||||
completedAt: now,
|
||||
updatedAt: now,
|
||||
type: "handoff",
|
||||
contextHandoffId: mergeBackHandoff.id,
|
||||
fromProviderThreadIds: mergeBackHandoff.fromProviderThreadIds,
|
||||
toProviderThreadId: mergeBackHandoff.toProviderThreadId,
|
||||
fromProviders: mergeBackSourceRun === null ? [] : [mergeBackSourceRun.provider],
|
||||
toProvider: modelSelection.provider,
|
||||
strategy: "fork_delta_summary",
|
||||
summary: mergeBackHandoff.summaryText,
|
||||
};
|
||||
const nativeForkResolution: OrchestrationV2ContextTransferResolution | null =
|
||||
pendingForkTransfer === undefined || providerThread.nativeThreadRef === null
|
||||
? null
|
||||
@@ -1645,6 +1983,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
strategy: "native_fork",
|
||||
providerThreadRef: providerThread.nativeThreadRef,
|
||||
};
|
||||
const mergeBackResolution: OrchestrationV2ContextTransferResolution | null =
|
||||
pendingMergeBackTransfer === undefined || mergeBackHandoff === null
|
||||
? null
|
||||
: {
|
||||
strategy: "fork_delta_context",
|
||||
contextHandoffId: mergeBackHandoff.id,
|
||||
};
|
||||
|
||||
if (pendingForkTransfer !== undefined && nativeForkResolution !== null) {
|
||||
yield* emitEvent({
|
||||
@@ -1678,6 +2023,53 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
occurredAt: now,
|
||||
payload: providerThread,
|
||||
});
|
||||
if (mergeBackHandoff !== null) {
|
||||
yield* emitEvent({
|
||||
type: "context-handoff.updated",
|
||||
threadId: command.threadId,
|
||||
runId,
|
||||
provider: modelSelection.provider,
|
||||
occurredAt: now,
|
||||
payload: mergeBackHandoff,
|
||||
});
|
||||
}
|
||||
for (const supersededTransfer of supersededMergeBackTransfers) {
|
||||
yield* emitEvent({
|
||||
type: "context-transfer.updated",
|
||||
threadId: command.threadId,
|
||||
runId,
|
||||
provider: modelSelection.provider,
|
||||
occurredAt: now,
|
||||
payload: {
|
||||
...supersededTransfer,
|
||||
status: "superseded",
|
||||
error:
|
||||
pendingMergeBackTransfer === undefined
|
||||
? "Superseded while consuming merge-back transfer."
|
||||
: `Superseded by merge-back transfer ${pendingMergeBackTransfer.id}.`,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
}
|
||||
if (pendingMergeBackTransfer !== undefined && mergeBackResolution !== null) {
|
||||
yield* emitEvent({
|
||||
type: "context-transfer.updated",
|
||||
threadId: command.threadId,
|
||||
runId,
|
||||
provider: modelSelection.provider,
|
||||
occurredAt: now,
|
||||
payload: {
|
||||
...pendingMergeBackTransfer,
|
||||
targetProvider: modelSelection.provider,
|
||||
targetRunId: runId,
|
||||
status: "consumed",
|
||||
resolution: mergeBackResolution,
|
||||
error: null,
|
||||
updatedAt: now,
|
||||
consumedAt: now,
|
||||
},
|
||||
});
|
||||
}
|
||||
yield* emitEvent({
|
||||
type: "run.created",
|
||||
threadId: command.threadId,
|
||||
@@ -1723,6 +2115,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
),
|
||||
),
|
||||
});
|
||||
if (handoffTurnItem !== null) {
|
||||
yield* emitEvent({
|
||||
type: "turn-item.updated",
|
||||
threadId: command.threadId,
|
||||
runId,
|
||||
nodeId: rootNodeId,
|
||||
provider: modelSelection.provider,
|
||||
occurredAt: now,
|
||||
payload: handoffTurnItem,
|
||||
});
|
||||
}
|
||||
yield* emitEvent({
|
||||
type: "message.updated",
|
||||
threadId: command.threadId,
|
||||
@@ -1761,6 +2164,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
});
|
||||
}
|
||||
|
||||
const providerMessageText =
|
||||
mergeBackHandoff === null
|
||||
? command.text
|
||||
: providerMessageWithContextHandoff({
|
||||
handoff: mergeBackHandoff,
|
||||
userText: command.text,
|
||||
});
|
||||
yield* runExecution
|
||||
.startRootRun({
|
||||
commandId: command.commandId,
|
||||
@@ -1782,7 +2192,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
),
|
||||
message: {
|
||||
messageId: command.messageId,
|
||||
text: command.text,
|
||||
text: providerMessageText,
|
||||
attachments: command.attachments,
|
||||
},
|
||||
modelSelection,
|
||||
@@ -2515,6 +2925,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
case "thread.fork":
|
||||
yield* dispatchThreadFork(command, events);
|
||||
break;
|
||||
case "thread.merge_back":
|
||||
yield* dispatchThreadMergeBack(command, events);
|
||||
break;
|
||||
default:
|
||||
return yield* dispatchUnsupported(command);
|
||||
}
|
||||
@@ -2633,6 +3046,16 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
projectionStore
|
||||
.getThreadProjection(threadId)
|
||||
.pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))),
|
||||
getShellSnapshot: () =>
|
||||
projectionStore.getShellSnapshot().pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestratorProjectionError({
|
||||
threadId: ThreadId.make("thread:shell"),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
getThreadEventSequence: (threadId) =>
|
||||
eventSink
|
||||
.latestSequence({ threadId })
|
||||
@@ -2662,6 +3085,7 @@ export const layer: Layer.Layer<
|
||||
never,
|
||||
| CheckpointServiceV2
|
||||
| CommandReceiptStoreV2
|
||||
| ContextHandoffServiceV2
|
||||
| EventSinkV2
|
||||
| IdAllocatorV2
|
||||
| ProviderSessionManagerV2
|
||||
@@ -2688,6 +3112,13 @@ export const layerUnavailable: Layer.Layer<OrchestratorV2> = Layer.succeed(
|
||||
cause: "Orchestration V2 live runtime is not configured.",
|
||||
}),
|
||||
),
|
||||
getShellSnapshot: () =>
|
||||
Effect.fail(
|
||||
new OrchestratorProjectionError({
|
||||
threadId: ThreadId.make("thread:shell"),
|
||||
cause: "Orchestration V2 live runtime is not configured.",
|
||||
}),
|
||||
),
|
||||
getThreadEventSequence: (threadId) =>
|
||||
Effect.fail(
|
||||
new OrchestratorProjectionError({
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { EventId, ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { DateTime, Effect, Layer } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
|
||||
import { ProjectionStoreV2, layer as projectionStoreLayer } from "./ProjectionStore.ts";
|
||||
|
||||
const TestLayer = Layer.mergeAll(
|
||||
projectionStoreLayer.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
|
||||
SqlitePersistenceMemory,
|
||||
);
|
||||
|
||||
it.layer(TestLayer)("ProjectionStoreV2", (it) => {
|
||||
it.effect("builds shell snapshots without decoding full turn item payloads", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionStore = yield* ProjectionStoreV2;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const now = yield* DateTime.now;
|
||||
const nowIso = DateTime.formatIso(now);
|
||||
const threadId = ThreadId.make("thread:projection-shell-stale-item");
|
||||
const projectId = ProjectId.make("project:projection-shell");
|
||||
|
||||
yield* projectionStore.apply({
|
||||
id: EventId.make("event:projection-shell-thread-created"),
|
||||
type: "thread.created",
|
||||
threadId,
|
||||
occurredAt: now,
|
||||
payload: {
|
||||
id: threadId,
|
||||
projectId,
|
||||
title: "Projection shell",
|
||||
defaultProvider: "codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
activeProviderThreadId: null,
|
||||
lineage: {
|
||||
parentThreadId: null,
|
||||
relationshipToParent: null,
|
||||
rootThreadId: threadId,
|
||||
},
|
||||
forkedFrom: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
},
|
||||
});
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO orchestration_v2_projection_turn_items (
|
||||
turn_item_id,
|
||||
thread_id,
|
||||
run_id,
|
||||
node_id,
|
||||
provider_thread_id,
|
||||
provider_turn_id,
|
||||
parent_item_id,
|
||||
ordinal,
|
||||
type,
|
||||
status,
|
||||
updated_at,
|
||||
payload_json
|
||||
)
|
||||
VALUES (
|
||||
${"turn-item:stale-user-message"},
|
||||
${threadId},
|
||||
${null},
|
||||
${null},
|
||||
${null},
|
||||
${null},
|
||||
${null},
|
||||
${0},
|
||||
${"user_message"},
|
||||
${"completed"},
|
||||
${nowIso},
|
||||
${JSON.stringify({
|
||||
id: "turn-item:stale-user-message",
|
||||
threadId,
|
||||
runId: null,
|
||||
nodeId: null,
|
||||
providerThreadId: null,
|
||||
providerTurnId: null,
|
||||
nativeItemRef: null,
|
||||
parentItemId: null,
|
||||
ordinal: 0,
|
||||
status: "completed",
|
||||
title: null,
|
||||
startedAt: nowIso,
|
||||
completedAt: nowIso,
|
||||
updatedAt: nowIso,
|
||||
type: "user_message",
|
||||
messageId: "message:stale-user-message",
|
||||
text: "stale user message",
|
||||
attachments: [],
|
||||
})}
|
||||
)
|
||||
`;
|
||||
|
||||
const shell = yield* projectionStore.getShellSnapshot();
|
||||
const fullProjectionExit = yield* Effect.exit(projectionStore.getThreadProjection(threadId));
|
||||
|
||||
assert.deepEqual(
|
||||
shell.threads.map((thread) => ({
|
||||
id: thread.id,
|
||||
itemCount: thread.itemCount,
|
||||
visibleItemCount: thread.visibleItemCount,
|
||||
status: thread.status,
|
||||
})),
|
||||
[
|
||||
{
|
||||
id: threadId,
|
||||
itemCount: 1,
|
||||
visibleItemCount: 1,
|
||||
status: "idle",
|
||||
},
|
||||
],
|
||||
);
|
||||
assert.equal(fullProjectionExit._tag, "Failure");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,6 +1,10 @@
|
||||
import type {
|
||||
OrchestrationV2ConversationMessage,
|
||||
OrchestrationV2DomainEvent,
|
||||
OrchestrationV2ProjectedTurnItem,
|
||||
OrchestrationV2ShellSnapshot,
|
||||
OrchestrationV2ShellThreadStatus,
|
||||
OrchestrationV2ThreadShell,
|
||||
OrchestrationV2ThreadProjection,
|
||||
OrchestrationV2TurnItem,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -20,7 +24,9 @@ import {
|
||||
OrchestrationV2RunJson as OrchestrationV2RunJsonSchema,
|
||||
OrchestrationV2RuntimeRequestJson as OrchestrationV2RuntimeRequestJsonSchema,
|
||||
OrchestrationV2TurnItemJson as OrchestrationV2TurnItemJsonSchema,
|
||||
RunId,
|
||||
ThreadId,
|
||||
TurnItemId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Context, DateTime, Effect, Layer, Ref, Schema } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
@@ -83,6 +89,10 @@ export interface ProjectionStoreV2Shape {
|
||||
readonly apply: (
|
||||
event: OrchestrationV2DomainEvent,
|
||||
) => Effect.Effect<void, ProjectionStoreV2Error>;
|
||||
readonly getShellSnapshot: () => Effect.Effect<
|
||||
OrchestrationV2ShellSnapshot,
|
||||
ProjectionStoreV2Error
|
||||
>;
|
||||
readonly getThreadProjection: (
|
||||
threadId: ThreadId,
|
||||
) => Effect.Effect<OrchestrationV2ThreadProjection, ProjectionStoreV2Error>;
|
||||
@@ -122,6 +132,7 @@ export function emptyProjection(
|
||||
checkpoints: [],
|
||||
contextHandoffs: [],
|
||||
contextTransfers: [],
|
||||
visibleTurnItems: [],
|
||||
updatedAt: event.occurredAt,
|
||||
};
|
||||
}
|
||||
@@ -184,10 +195,10 @@ export function applyToProjection(
|
||||
messages: upsertById(base.messages, event.payload),
|
||||
};
|
||||
case "turn-item.updated":
|
||||
return {
|
||||
return withLocalVisibleTurnItems({
|
||||
...base,
|
||||
turnItems: upsertById(base.turnItems, event.payload),
|
||||
};
|
||||
});
|
||||
case "plan.updated":
|
||||
return {
|
||||
...base,
|
||||
@@ -221,6 +232,26 @@ type PayloadRow = {
|
||||
readonly payload_json: string;
|
||||
};
|
||||
|
||||
type ShellThreadRow = {
|
||||
readonly thread_id: string;
|
||||
readonly payload_json: string;
|
||||
readonly latest_run_id: string | null;
|
||||
readonly latest_run_status: string | null;
|
||||
readonly item_count: number;
|
||||
};
|
||||
|
||||
type ShellRunRow = {
|
||||
readonly thread_id: string;
|
||||
readonly run_id: string;
|
||||
readonly ordinal: number;
|
||||
};
|
||||
|
||||
type ShellRunItemCountRow = {
|
||||
readonly thread_id: string;
|
||||
readonly run_id: string;
|
||||
readonly item_count: number;
|
||||
};
|
||||
|
||||
const encodeThreadPayload = Schema.encodeEffect(
|
||||
Schema.fromJsonString(OrchestrationV2AppThreadJsonSchema),
|
||||
);
|
||||
@@ -375,6 +406,268 @@ function sortMessagesByTurnItemOrder(
|
||||
});
|
||||
}
|
||||
|
||||
function localVisibleTurnItems(
|
||||
turnItems: ReadonlyArray<OrchestrationV2TurnItem>,
|
||||
): Array<OrchestrationV2ProjectedTurnItem> {
|
||||
return turnItems.map((item, position) => ({
|
||||
position,
|
||||
visibility: "local",
|
||||
sourceThreadId: item.threadId,
|
||||
sourceItemId: item.id,
|
||||
item,
|
||||
}));
|
||||
}
|
||||
|
||||
function withLocalVisibleTurnItems(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
): OrchestrationV2ThreadProjection {
|
||||
return {
|
||||
...projection,
|
||||
visibleTurnItems: localVisibleTurnItems(projection.turnItems),
|
||||
};
|
||||
}
|
||||
|
||||
function renumberVisibleTurnItems(
|
||||
rows: ReadonlyArray<Omit<OrchestrationV2ProjectedTurnItem, "position">>,
|
||||
): Array<OrchestrationV2ProjectedTurnItem> {
|
||||
return rows.map((row, position) => ({ ...row, position }));
|
||||
}
|
||||
|
||||
function makeForkMarkerTurnItem(input: {
|
||||
readonly targetProjection: OrchestrationV2ThreadProjection;
|
||||
readonly sourceThreadId: ThreadId;
|
||||
readonly sourceRunId: NonNullable<OrchestrationV2TurnItem["runId"]>;
|
||||
}): OrchestrationV2TurnItem {
|
||||
const createdAt = input.targetProjection.thread.createdAt;
|
||||
return {
|
||||
id: TurnItemId.make(`turn-item:fork:${input.targetProjection.thread.id}`),
|
||||
threadId: input.targetProjection.thread.id,
|
||||
runId: null,
|
||||
nodeId: null,
|
||||
providerTurnId: null,
|
||||
nativeItemRef: null,
|
||||
parentItemId: null,
|
||||
ordinal: 0,
|
||||
status: "completed",
|
||||
title: "Forked from conversation",
|
||||
startedAt: null,
|
||||
completedAt: createdAt,
|
||||
updatedAt: createdAt,
|
||||
type: "fork",
|
||||
source: { type: "run", threadId: input.sourceThreadId, runId: input.sourceRunId },
|
||||
targetThreadId: input.targetProjection.thread.id,
|
||||
};
|
||||
}
|
||||
|
||||
function visibleTurnItemsThroughRun(input: {
|
||||
readonly sourceProjection: OrchestrationV2ThreadProjection;
|
||||
readonly sourceRunId: NonNullable<OrchestrationV2TurnItem["runId"]>;
|
||||
}): Array<Omit<OrchestrationV2ProjectedTurnItem, "position">> {
|
||||
const sourceRun = input.sourceProjection.runs.find((run) => run.id === input.sourceRunId);
|
||||
if (sourceRun === undefined) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const runOrdinalById = new Map(input.sourceProjection.runs.map((run) => [run.id, run.ordinal]));
|
||||
return input.sourceProjection.visibleTurnItems
|
||||
.filter((row) => {
|
||||
const item = row.item;
|
||||
if (item.threadId !== input.sourceProjection.thread.id) {
|
||||
return true;
|
||||
}
|
||||
if (item.type === "fork") {
|
||||
return true;
|
||||
}
|
||||
if (item.runId === null) {
|
||||
return false;
|
||||
}
|
||||
const ordinal = runOrdinalById.get(item.runId);
|
||||
return ordinal !== undefined && ordinal <= sourceRun.ordinal;
|
||||
})
|
||||
.map((row) => ({
|
||||
visibility: "inherited",
|
||||
sourceThreadId: row.sourceThreadId,
|
||||
sourceItemId: row.sourceItemId,
|
||||
item: row.item,
|
||||
}));
|
||||
}
|
||||
|
||||
function buildVisibleTurnItems(input: {
|
||||
readonly projection: OrchestrationV2ThreadProjection;
|
||||
readonly sourceProjection: OrchestrationV2ThreadProjection | null;
|
||||
}): Array<OrchestrationV2ProjectedTurnItem> {
|
||||
const forkedFrom = input.projection.thread.forkedFrom;
|
||||
if (forkedFrom?.type !== "run" || input.sourceProjection === null) {
|
||||
return localVisibleTurnItems(input.projection.turnItems);
|
||||
}
|
||||
|
||||
const inherited = visibleTurnItemsThroughRun({
|
||||
sourceProjection: input.sourceProjection,
|
||||
sourceRunId: forkedFrom.runId,
|
||||
});
|
||||
const markerItem = makeForkMarkerTurnItem({
|
||||
targetProjection: input.projection,
|
||||
sourceThreadId: forkedFrom.threadId,
|
||||
sourceRunId: forkedFrom.runId,
|
||||
});
|
||||
const local = input.projection.turnItems.map((item) => ({
|
||||
visibility: "local" as const,
|
||||
sourceThreadId: item.threadId,
|
||||
sourceItemId: item.id,
|
||||
item,
|
||||
}));
|
||||
|
||||
return renumberVisibleTurnItems([
|
||||
...inherited,
|
||||
{
|
||||
visibility: "synthetic",
|
||||
sourceThreadId: forkedFrom.threadId,
|
||||
sourceItemId: markerItem.id,
|
||||
item: markerItem,
|
||||
},
|
||||
...local,
|
||||
]);
|
||||
}
|
||||
|
||||
export function threadShellFromProjection(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
): OrchestrationV2ThreadShell {
|
||||
const latestRun = projection.runs.at(-1) ?? null;
|
||||
return {
|
||||
id: projection.thread.id,
|
||||
projectId: projection.thread.projectId,
|
||||
title: projection.thread.title,
|
||||
defaultProvider: projection.thread.defaultProvider,
|
||||
modelSelection: projection.thread.modelSelection,
|
||||
runtimeMode: projection.thread.runtimeMode,
|
||||
interactionMode: projection.thread.interactionMode,
|
||||
lineage: projection.thread.lineage,
|
||||
forkedFrom: projection.thread.forkedFrom,
|
||||
activeProviderThreadId: projection.thread.activeProviderThreadId,
|
||||
latestRunId: latestRun?.id ?? null,
|
||||
status: latestRun?.status ?? "idle",
|
||||
itemCount: projection.turnItems.length,
|
||||
visibleItemCount: projection.visibleTurnItems.length,
|
||||
createdAt: projection.thread.createdAt,
|
||||
updatedAt: projection.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
type ShellThreadState = {
|
||||
readonly thread: OrchestrationV2ThreadProjection["thread"];
|
||||
readonly latestRunId: RunId | null;
|
||||
readonly latestRunStatus: OrchestrationV2ShellThreadStatus;
|
||||
readonly itemCount: number;
|
||||
readonly updatedAt: OrchestrationV2ThreadProjection["updatedAt"];
|
||||
readonly runOrdinalById: ReadonlyMap<RunId, number>;
|
||||
readonly itemCountByRunId: ReadonlyMap<RunId, number>;
|
||||
};
|
||||
|
||||
function shellStatusFromStoredRunStatus(status: string | null): OrchestrationV2ShellThreadStatus {
|
||||
switch (status) {
|
||||
case null:
|
||||
return "idle";
|
||||
case "queued":
|
||||
case "starting":
|
||||
case "running":
|
||||
case "waiting":
|
||||
case "completed":
|
||||
case "interrupted":
|
||||
case "failed":
|
||||
case "cancelled":
|
||||
case "rolled_back":
|
||||
return status;
|
||||
default:
|
||||
return "failed";
|
||||
}
|
||||
}
|
||||
|
||||
function itemCountThroughRun(input: {
|
||||
readonly state: ShellThreadState;
|
||||
readonly runId: RunId;
|
||||
}): number {
|
||||
const runOrdinal = input.state.runOrdinalById.get(input.runId);
|
||||
if (runOrdinal === undefined) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let count = 0;
|
||||
for (const [runId, itemCount] of input.state.itemCountByRunId) {
|
||||
const itemRunOrdinal = input.state.runOrdinalById.get(runId);
|
||||
if (itemRunOrdinal !== undefined && itemRunOrdinal <= runOrdinal) {
|
||||
count += itemCount;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
function visibleItemCountForShell(input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly statesByThreadId: ReadonlyMap<ThreadId, ShellThreadState>;
|
||||
readonly seenThreadIds?: ReadonlySet<ThreadId>;
|
||||
}): number {
|
||||
const state = input.statesByThreadId.get(input.threadId);
|
||||
if (state === undefined) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const forkedFrom = state.thread.forkedFrom;
|
||||
if (forkedFrom?.type !== "run") {
|
||||
return state.itemCount;
|
||||
}
|
||||
|
||||
const seenThreadIds = input.seenThreadIds ?? new Set<ThreadId>();
|
||||
if (seenThreadIds.has(state.thread.id)) {
|
||||
return state.itemCount;
|
||||
}
|
||||
|
||||
const sourceState = input.statesByThreadId.get(forkedFrom.threadId);
|
||||
if (sourceState === undefined) {
|
||||
return state.itemCount;
|
||||
}
|
||||
|
||||
const sourceForkedFrom = sourceState.thread.forkedFrom;
|
||||
const inheritedPrefixCount =
|
||||
sourceForkedFrom?.type === "run"
|
||||
? visibleItemCountForShell({
|
||||
threadId: sourceState.thread.id,
|
||||
statesByThreadId: input.statesByThreadId,
|
||||
seenThreadIds: new Set([...seenThreadIds, state.thread.id]),
|
||||
}) - sourceState.itemCount
|
||||
: 0;
|
||||
|
||||
return (
|
||||
inheritedPrefixCount +
|
||||
itemCountThroughRun({ state: sourceState, runId: forkedFrom.runId }) +
|
||||
1 +
|
||||
state.itemCount
|
||||
);
|
||||
}
|
||||
|
||||
function shellFromState(input: {
|
||||
readonly state: ShellThreadState;
|
||||
readonly visibleItemCount: number;
|
||||
}): OrchestrationV2ThreadShell {
|
||||
return {
|
||||
id: input.state.thread.id,
|
||||
projectId: input.state.thread.projectId,
|
||||
title: input.state.thread.title,
|
||||
defaultProvider: input.state.thread.defaultProvider,
|
||||
modelSelection: input.state.thread.modelSelection,
|
||||
runtimeMode: input.state.thread.runtimeMode,
|
||||
interactionMode: input.state.thread.interactionMode,
|
||||
lineage: input.state.thread.lineage,
|
||||
forkedFrom: input.state.thread.forkedFrom,
|
||||
activeProviderThreadId: input.state.thread.activeProviderThreadId,
|
||||
latestRunId: input.state.latestRunId,
|
||||
status: input.state.latestRunStatus,
|
||||
itemCount: input.state.itemCount,
|
||||
visibleItemCount: input.visibleItemCount,
|
||||
createdAt: input.state.thread.createdAt,
|
||||
updatedAt: input.state.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> = Layer.effect(
|
||||
ProjectionStoreV2,
|
||||
Effect.gen(function* () {
|
||||
@@ -1048,7 +1341,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
|
||||
),
|
||||
);
|
||||
|
||||
const getThreadProjection: ProjectionStoreV2Shape["getThreadProjection"] = (threadId) =>
|
||||
const readCanonicalProjection: ProjectionStoreV2Shape["getThreadProjection"] = (threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const threadRows = yield* sql<PayloadRow>`
|
||||
SELECT payload_json
|
||||
@@ -1214,6 +1507,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
|
||||
checkpoints,
|
||||
contextHandoffs,
|
||||
contextTransfers,
|
||||
visibleTurnItems: localVisibleTurnItems(turnItems),
|
||||
updatedAt: thread.updatedAt,
|
||||
} satisfies OrchestrationV2ThreadProjection;
|
||||
}).pipe(
|
||||
@@ -1227,8 +1521,136 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
|
||||
),
|
||||
);
|
||||
|
||||
const readProjection = (
|
||||
threadId: ThreadId,
|
||||
seenThreadIds: ReadonlySet<ThreadId>,
|
||||
): Effect.Effect<OrchestrationV2ThreadProjection, ProjectionStoreV2Error> =>
|
||||
Effect.gen(function* () {
|
||||
const projection = yield* readCanonicalProjection(threadId);
|
||||
const forkedFrom = projection.thread.forkedFrom;
|
||||
if (forkedFrom?.type !== "run" || seenThreadIds.has(forkedFrom.threadId)) {
|
||||
return withLocalVisibleTurnItems(projection);
|
||||
}
|
||||
|
||||
const sourceProjection = yield* readProjection(
|
||||
forkedFrom.threadId,
|
||||
new Set([...seenThreadIds, threadId]),
|
||||
);
|
||||
return {
|
||||
...projection,
|
||||
visibleTurnItems: buildVisibleTurnItems({
|
||||
projection,
|
||||
sourceProjection,
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
const getThreadProjection: ProjectionStoreV2Shape["getThreadProjection"] = (threadId) =>
|
||||
readProjection(threadId, new Set());
|
||||
|
||||
const getShellSnapshot: ProjectionStoreV2Shape["getShellSnapshot"] = () =>
|
||||
Effect.gen(function* () {
|
||||
const [threadRows, runRows, itemCountRows] = yield* Effect.all([
|
||||
sql<ShellThreadRow>`
|
||||
SELECT
|
||||
t.thread_id,
|
||||
t.payload_json,
|
||||
(
|
||||
SELECT r.run_id
|
||||
FROM orchestration_v2_projection_runs r
|
||||
WHERE r.thread_id = t.thread_id
|
||||
ORDER BY r.ordinal DESC, r.run_id DESC
|
||||
LIMIT 1
|
||||
) AS latest_run_id,
|
||||
(
|
||||
SELECT r.status
|
||||
FROM orchestration_v2_projection_runs r
|
||||
WHERE r.thread_id = t.thread_id
|
||||
ORDER BY r.ordinal DESC, r.run_id DESC
|
||||
LIMIT 1
|
||||
) AS latest_run_status,
|
||||
(
|
||||
SELECT COUNT(*)
|
||||
FROM orchestration_v2_projection_turn_items i
|
||||
WHERE i.thread_id = t.thread_id
|
||||
) AS item_count
|
||||
FROM orchestration_v2_projection_threads t
|
||||
WHERE t.deleted_at IS NULL
|
||||
ORDER BY t.updated_at ASC, t.thread_id ASC
|
||||
`,
|
||||
sql<ShellRunRow>`
|
||||
SELECT thread_id, run_id, ordinal
|
||||
FROM orchestration_v2_projection_runs
|
||||
`,
|
||||
sql<ShellRunItemCountRow>`
|
||||
SELECT thread_id, run_id, COUNT(*) AS item_count
|
||||
FROM orchestration_v2_projection_turn_items
|
||||
WHERE run_id IS NOT NULL
|
||||
GROUP BY thread_id, run_id
|
||||
`,
|
||||
]);
|
||||
|
||||
const runOrdinalsByThreadId = new Map<ThreadId, Map<RunId, number>>();
|
||||
for (const row of runRows) {
|
||||
const threadId = ThreadId.make(row.thread_id);
|
||||
const runId = RunId.make(row.run_id);
|
||||
const existing = runOrdinalsByThreadId.get(threadId) ?? new Map<RunId, number>();
|
||||
existing.set(runId, row.ordinal);
|
||||
runOrdinalsByThreadId.set(threadId, existing);
|
||||
}
|
||||
|
||||
const itemCountsByThreadId = new Map<ThreadId, Map<RunId, number>>();
|
||||
for (const row of itemCountRows) {
|
||||
const threadId = ThreadId.make(row.thread_id);
|
||||
const runId = RunId.make(row.run_id);
|
||||
const existing = itemCountsByThreadId.get(threadId) ?? new Map<RunId, number>();
|
||||
existing.set(runId, row.item_count);
|
||||
itemCountsByThreadId.set(threadId, existing);
|
||||
}
|
||||
|
||||
const states = yield* Effect.forEach(threadRows, (row) =>
|
||||
decodeThreadPayload(row.payload_json).pipe(
|
||||
Effect.map(
|
||||
(thread): ShellThreadState => ({
|
||||
thread,
|
||||
latestRunId: row.latest_run_id === null ? null : RunId.make(row.latest_run_id),
|
||||
latestRunStatus: shellStatusFromStoredRunStatus(row.latest_run_status),
|
||||
itemCount: row.item_count,
|
||||
updatedAt: thread.updatedAt,
|
||||
runOrdinalById:
|
||||
runOrdinalsByThreadId.get(ThreadId.make(row.thread_id)) ?? new Map(),
|
||||
itemCountByRunId:
|
||||
itemCountsByThreadId.get(ThreadId.make(row.thread_id)) ?? new Map(),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const statesByThreadId = new Map(states.map((state) => [state.thread.id, state]));
|
||||
|
||||
return {
|
||||
threads: states.map((state) =>
|
||||
shellFromState({
|
||||
state,
|
||||
visibleItemCount: visibleItemCountForShell({
|
||||
threadId: state.thread.id,
|
||||
statesByThreadId,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
};
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProjectionStoreReadError({
|
||||
threadId: ThreadId.make("thread:shell"),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
apply,
|
||||
getShellSnapshot,
|
||||
getThreadProjection,
|
||||
} satisfies ProjectionStoreV2Shape;
|
||||
}),
|
||||
@@ -1266,10 +1688,46 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
|
||||
return yield* result;
|
||||
}
|
||||
}),
|
||||
getShellSnapshot: () =>
|
||||
Effect.gen(function* () {
|
||||
const existing = yield* Ref.get(projections);
|
||||
const shells = yield* Effect.forEach(
|
||||
[...existing.keys()].toSorted((left, right) =>
|
||||
String(left).localeCompare(String(right)),
|
||||
),
|
||||
(threadId) =>
|
||||
service.getThreadProjection(threadId).pipe(Effect.map(threadShellFromProjection)),
|
||||
);
|
||||
return { threads: shells };
|
||||
}),
|
||||
getThreadProjection: (threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const existing = yield* Ref.get(projections);
|
||||
const projection = existing.get(threadId);
|
||||
const readProjection = (
|
||||
targetThreadId: ThreadId,
|
||||
seenThreadIds: ReadonlySet<ThreadId>,
|
||||
): OrchestrationV2ThreadProjection | null => {
|
||||
const projection = existing.get(targetThreadId);
|
||||
if (!projection) {
|
||||
return null;
|
||||
}
|
||||
const forkedFrom = projection.thread.forkedFrom;
|
||||
if (forkedFrom?.type !== "run" || seenThreadIds.has(forkedFrom.threadId)) {
|
||||
return withLocalVisibleTurnItems(projection);
|
||||
}
|
||||
const sourceProjection = readProjection(
|
||||
forkedFrom.threadId,
|
||||
new Set([...seenThreadIds, targetThreadId]),
|
||||
);
|
||||
return {
|
||||
...projection,
|
||||
visibleTurnItems: buildVisibleTurnItems({
|
||||
projection,
|
||||
sourceProjection,
|
||||
}),
|
||||
};
|
||||
};
|
||||
const projection = readProjection(threadId, new Set());
|
||||
if (!projection) {
|
||||
return yield* new ProjectionStoreThreadNotFoundError({ threadId });
|
||||
}
|
||||
|
||||
@@ -6,8 +6,7 @@ import {
|
||||
RunId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Context, Schema } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import { Context, Schema, Effect } from "effect";
|
||||
|
||||
export const ProviderSwitchStrategyV2 = Schema.Literals([
|
||||
"resume_with_delta_handoff",
|
||||
|
||||
@@ -16,6 +16,8 @@ implementation checklist for `apps/server/src/orchestration-v2`.
|
||||
by fork-local `thread/rollback`.
|
||||
- Native Codex fork-from-earlier-run has a real replay-backed test fixture:
|
||||
`testkit/fixtures/thread_fork_native_prior_turn`.
|
||||
- Merge-back from a fork into its source thread records a `merge_back` context transfer, materializes
|
||||
a `fork_delta_summary` context handoff, and injects that handoff into the next source-thread run.
|
||||
|
||||
## Projection Hardening
|
||||
|
||||
@@ -27,20 +29,23 @@ Target docs:
|
||||
|
||||
TODO:
|
||||
|
||||
- [ ] Add end-to-end projection assertions for forked threads, not only provider-context behavior.
|
||||
The fork projection should show inherited user-visible items through the source point plus an
|
||||
explicit fork marker.
|
||||
- [ ] Decide and implement the projection representation for inherited fork history:
|
||||
referenced lineage overlay vs physically duplicated projection items. Prefer referenced overlay
|
||||
unless product requirements need independent editable history.
|
||||
- [x] Add end-to-end projection assertions for forked threads, not only provider-context behavior.
|
||||
The fork projection should show inherited user-visible items through the source point plus an
|
||||
explicit fork marker.
|
||||
- [x] Decide and implement the projection representation for inherited fork history:
|
||||
referenced lineage overlay vs physically duplicated projection items. Prefer referenced overlay
|
||||
unless product requirements need independent editable history.
|
||||
- [x] Add local visible projection assertions to non-fork replay fixtures:
|
||||
`visibleTurnItems` mirrors canonical local `turnItems` for simple, multi-turn, queue,
|
||||
steering, interrupt, rollback, planning, tool, and web-search fixtures.
|
||||
- [ ] Ensure projections render rollback state consistently:
|
||||
rolled-back runs/nodes/items, stale checkpoints, and active provider thread cursor.
|
||||
rolled-back runs/nodes/items, stale checkpoints, and active provider thread cursor.
|
||||
- [ ] Add projection tests for interrupt edge cases:
|
||||
provider emits chunks after interrupt requested, provider ignores/delays interrupt, interrupt is
|
||||
immediately followed by queue/steer/start.
|
||||
provider emits chunks after interrupt requested, provider ignores/delays interrupt, interrupt is
|
||||
immediately followed by queue/steer/start.
|
||||
- [ ] Add projection tests for queue/steer flows:
|
||||
queued message visibility, queue reorder, promote queued message to steer, and post-interrupt
|
||||
dispatch visibility.
|
||||
queued message visibility, queue reorder, promote queued message to steer, and post-interrupt
|
||||
dispatch visibility.
|
||||
|
||||
## Context Transfer And Merge-Back
|
||||
|
||||
@@ -51,18 +56,18 @@ Target docs:
|
||||
|
||||
TODO:
|
||||
|
||||
- [ ] Implement merge-back from a fork into its source thread:
|
||||
source fork point as `basePoint`, fork latest stable point as `sourcePoint`, and source-thread
|
||||
next user message as the consuming run.
|
||||
- [ ] Materialize delta context artifacts for merge-back and persist them as auditable
|
||||
`ContextHandoff` records.
|
||||
- [ ] Add replay-backed integration coverage for merge-back:
|
||||
fork, explore in fork, merge back, then assert source provider receives only the fork delta plus
|
||||
the new user message.
|
||||
- [x] Implement merge-back from a fork into its source thread:
|
||||
source fork point as `basePoint`, fork latest stable point as `sourcePoint`, and source-thread
|
||||
next user message as the consuming run.
|
||||
- [x] Materialize delta context artifacts for merge-back and persist them as auditable
|
||||
`ContextHandoff` records.
|
||||
- [x] Add replay-backed integration coverage for merge-back:
|
||||
fork, explore in fork, merge back, then assert source provider receives only the fork delta plus
|
||||
the new user message.
|
||||
- [ ] Implement portable context handoff for cross-provider forks and same-thread provider switches.
|
||||
- [ ] Define explicit failure states for unresolved context transfers:
|
||||
missing source point, unsupported provider capability, context too large, source projection not
|
||||
stable, and adapter resolution failure.
|
||||
missing source point, unsupported provider capability, context too large, source projection not
|
||||
stable, and adapter resolution failure.
|
||||
|
||||
## Capability And Policy Model
|
||||
|
||||
@@ -73,18 +78,17 @@ Target docs:
|
||||
|
||||
TODO:
|
||||
|
||||
- [ ] Expand `OrchestrationV2ProviderCapabilities` toward the documented nested shape:
|
||||
sessions, threads, turns, streaming, tools, approvals, planning, subagents, context,
|
||||
checkpointing, and identity.
|
||||
- [ ] Audit capability use against the documented nested `OrchestrationV2ProviderCapabilities`
|
||||
shape and fill any behavior gaps.
|
||||
- [ ] Keep orchestration decisions capability/policy driven. Shared runtime code should not branch on
|
||||
provider name except at adapter registration/resolution boundaries.
|
||||
provider name except at adapter registration/resolution boundaries.
|
||||
- [ ] Make optional adapter methods impossible to call without going through a policy wrapper or a
|
||||
capability-checked branch.
|
||||
capability-checked branch.
|
||||
- [ ] Add typed capability/policy errors for:
|
||||
native fork unavailable, rollback unavailable, steering unavailable, interrupt unavailable,
|
||||
context handoff unavailable, and weak terminal status.
|
||||
native fork unavailable, rollback unavailable, steering unavailable, interrupt unavailable,
|
||||
context handoff unavailable, and weak terminal status.
|
||||
- [ ] Add capability-aware tests using real adapter/test layers at provider boundaries only. Do not mock
|
||||
core orchestration policy.
|
||||
core orchestration policy.
|
||||
|
||||
## Checkpoint And Rollback
|
||||
|
||||
@@ -96,14 +100,14 @@ Target docs:
|
||||
TODO:
|
||||
|
||||
- [ ] Document current `checkpoint.rollback` command semantics in contracts/docs as full revert:
|
||||
filesystem restore plus provider conversation rollback.
|
||||
filesystem restore plus provider conversation rollback.
|
||||
- [ ] Decide whether we need separate commands for conversation-only rollback and filesystem-only
|
||||
restore. Do not add them until a real product flow needs them.
|
||||
restore. Do not add them until a real product flow needs them.
|
||||
- [ ] Add tests for rollback after fork and rollback inside fork:
|
||||
source rollback should not corrupt child lineage, and fork rollback should not mutate source
|
||||
provider state.
|
||||
source rollback should not corrupt child lineage, and fork rollback should not mutate source
|
||||
provider state.
|
||||
- [ ] Validate rollback behavior when no active provider thread exists. Current behavior fails; decide
|
||||
whether a filesystem-only rollback fallback is useful or too surprising.
|
||||
whether a filesystem-only rollback fallback is useful or too surprising.
|
||||
|
||||
## Provider Switching And Second Adapter
|
||||
|
||||
@@ -115,12 +119,12 @@ Target docs:
|
||||
TODO:
|
||||
|
||||
- [ ] Finish single-adapter primitives first: projections, fork source points, merge-back, rollback, and
|
||||
context transfer resolution.
|
||||
context transfer resolution.
|
||||
- [ ] Add the second adapter after the single-adapter core is stable enough to validate cross-provider
|
||||
behavior.
|
||||
behavior.
|
||||
- [ ] Use the second adapter to test:
|
||||
cross-provider fork, same-thread provider switch, returning to a previous provider thread with
|
||||
delta handoff, and unsupported capability fallback paths.
|
||||
cross-provider fork, same-thread provider switch, returning to a previous provider thread with
|
||||
delta handoff, and unsupported capability fallback paths.
|
||||
|
||||
## Subagents
|
||||
|
||||
@@ -133,11 +137,11 @@ TODO:
|
||||
|
||||
- [ ] Defer subagents until lineage, context transfer, and provider capability policy are stable.
|
||||
- [ ] Model native subagents and app-owned cross-provider subagents as related thread/subthread graph
|
||||
entries with different creator/lifecycle policy.
|
||||
entries with different creator/lifecycle policy.
|
||||
- [ ] Preserve native provider subagent refs where available, but do not make the app graph depend on
|
||||
provider-native ids as primary ids.
|
||||
provider-native ids as primary ids.
|
||||
- [ ] Add projection support for subagent lifecycle, wait, close, result transfer, and pending approvals
|
||||
originating from subagents.
|
||||
originating from subagents.
|
||||
|
||||
FOOD FOR THOUGHT:
|
||||
|
||||
@@ -147,8 +151,10 @@ FOOD FOR THOUGHT:
|
||||
|
||||
- Keep debugger UI useful but temporary. Backend semantics and projections should be the source of
|
||||
truth.
|
||||
- [x] Wire the debugger thread tree to persisted V2 shell state through websocket RPC instead of
|
||||
debugger-local thread discovery state.
|
||||
- Continue exposing lightweight controls for new backend surfaces:
|
||||
fork from response, new thread, full revert from user message checkpoint, merge-back, and provider
|
||||
switch.
|
||||
- Avoid adding mock backend behavior for debugger convenience. In-memory debugger state is fine for
|
||||
layout/tree affordances, but backend behavior must route through V2 commands/projections.
|
||||
layout affordances, but backend behavior must route through V2 commands/projections.
|
||||
@@ -4,6 +4,7 @@ import { layer as codexAdapterLayer } from "./Adapters/CodexAdapterV2.ts";
|
||||
import { codexAppServerClientFactoryFromSettingsLayer } from "./Adapters/CodexAdapterV2.ts";
|
||||
import { layer as checkpointServiceLayer } from "./CheckpointService.ts";
|
||||
import { layer as commandReceiptStoreLayer } from "./CommandReceiptStore.ts";
|
||||
import { layer as contextHandoffServiceLayer } from "./ContextHandoffService.ts";
|
||||
import { layer as eventSinkLayer } from "./EventSink.ts";
|
||||
import { layer as eventStoreLayer } from "./EventStore.ts";
|
||||
import { layer as idAllocatorLayer } from "./IdAllocator.ts";
|
||||
@@ -26,6 +27,9 @@ const providerEventIngestorProvided = providerEventIngestorLayer.pipe(
|
||||
);
|
||||
|
||||
const checkpointServiceProvided = checkpointServiceLayer.pipe(Layer.provide(idAllocatorLayer));
|
||||
const contextHandoffServiceProvided = contextHandoffServiceLayer.pipe(
|
||||
Layer.provide(idAllocatorLayer),
|
||||
);
|
||||
|
||||
const codexAdapterProvided = codexAdapterLayer.pipe(
|
||||
Layer.provide(codexAppServerClientFactoryFromSettingsLayer),
|
||||
@@ -65,6 +69,7 @@ export const OrchestrationV2LayerLive = orchestratorLayer.pipe(
|
||||
storesLayer,
|
||||
eventSinkProvided,
|
||||
commandReceiptStoreProvided,
|
||||
contextHandoffServiceProvided,
|
||||
idAllocatorLayer,
|
||||
providerEventIngestorProvided,
|
||||
runtimePolicyLayer,
|
||||
|
||||
@@ -81,6 +81,32 @@ const scenarioExpectations = {
|
||||
turnCompletedCount: 2,
|
||||
approvalRequestCount: 0,
|
||||
},
|
||||
plan_questions: {
|
||||
outgoing: [
|
||||
"initialize",
|
||||
"initialized",
|
||||
"thread/start",
|
||||
"turn/start",
|
||||
"item/tool/requestUserInput",
|
||||
],
|
||||
incoming: [
|
||||
"turn/started",
|
||||
"turn/completed",
|
||||
"item/tool/requestUserInput",
|
||||
"serverRequest/resolved",
|
||||
"item/agentMessage/delta",
|
||||
],
|
||||
turnStartCount: 1,
|
||||
turnCompletedCount: 1,
|
||||
approvalRequestCount: 0,
|
||||
},
|
||||
proposed_plan: {
|
||||
outgoing: ["initialize", "initialized", "thread/start", "turn/start"],
|
||||
incoming: ["turn/started", "turn/completed", "item/agentMessage/delta"],
|
||||
turnStartCount: 1,
|
||||
turnCompletedCount: 1,
|
||||
approvalRequestCount: 0,
|
||||
},
|
||||
provider_thread_resume: {
|
||||
outgoing: ["initialize", "initialized", "thread/start", "thread/resume", "turn/start"],
|
||||
incoming: ["thread/started", "turn/started", "turn/completed", "item/agentMessage/delta"],
|
||||
@@ -88,6 +114,13 @@ const scenarioExpectations = {
|
||||
turnCompletedCount: 2,
|
||||
approvalRequestCount: 0,
|
||||
},
|
||||
queued_turn: {
|
||||
outgoing: ["initialize", "initialized", "thread/start", "turn/start"],
|
||||
incoming: ["turn/started", "turn/completed", "item/agentMessage/delta"],
|
||||
turnStartCount: 2,
|
||||
turnCompletedCount: 2,
|
||||
approvalRequestCount: 0,
|
||||
},
|
||||
message_steering: {
|
||||
outgoing: ["initialize", "initialized", "thread/start", "turn/start", "turn/steer"],
|
||||
incoming: [
|
||||
@@ -115,6 +148,20 @@ const scenarioExpectations = {
|
||||
turnCompletedCount: 3,
|
||||
approvalRequestCount: 0,
|
||||
},
|
||||
todo_list: {
|
||||
outgoing: ["initialize", "initialized", "thread/start", "turn/start"],
|
||||
incoming: ["turn/started", "turn/completed", "turn/plan/updated", "item/agentMessage/delta"],
|
||||
turnStartCount: 1,
|
||||
turnCompletedCount: 1,
|
||||
approvalRequestCount: 0,
|
||||
},
|
||||
web_search: {
|
||||
outgoing: ["initialize", "initialized", "thread/start", "turn/start"],
|
||||
incoming: ["turn/started", "turn/completed", "item/agentMessage/delta"],
|
||||
turnStartCount: 1,
|
||||
turnCompletedCount: 1,
|
||||
approvalRequestCount: 0,
|
||||
},
|
||||
} as const;
|
||||
|
||||
async function readTranscript(file: URL): Promise<ProviderReplayTranscript> {
|
||||
|
||||
@@ -2,6 +2,7 @@ import type {
|
||||
OrchestrationV2Command,
|
||||
OrchestrationV2DomainEvent,
|
||||
OrchestrationV2RuntimeRequest,
|
||||
OrchestrationV2ShellSnapshot,
|
||||
OrchestrationV2StoredEvent,
|
||||
OrchestrationV2ThreadProjection,
|
||||
ProviderApprovalDecision,
|
||||
@@ -55,6 +56,7 @@ export interface OrchestratorV2ScenarioResult {
|
||||
readonly storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>;
|
||||
readonly domainEvents: ReadonlyArray<OrchestrationV2DomainEvent>;
|
||||
readonly projections: ReadonlyMap<ThreadId, OrchestrationV2ThreadProjection>;
|
||||
readonly shellSnapshot: OrchestrationV2ShellSnapshot;
|
||||
}
|
||||
|
||||
export class OrchestratorV2ScenarioStepError extends Schema.TaggedErrorClass<OrchestratorV2ScenarioStepError>()(
|
||||
@@ -81,6 +83,7 @@ function commandThreadIds(command: OrchestrationV2Command): ReadonlyArray<Thread
|
||||
case "provider.switch":
|
||||
return [command.threadId];
|
||||
case "thread.fork":
|
||||
case "thread.merge_back":
|
||||
return [command.sourceThreadId, command.targetThreadId];
|
||||
}
|
||||
}
|
||||
@@ -263,6 +266,7 @@ export function runOrchestratorV2Scenario(
|
||||
for (const threadId of collectProjectionThreadIds(scenario)) {
|
||||
projections.set(threadId, yield* orchestrator.getThreadProjection(threadId));
|
||||
}
|
||||
const shellSnapshot = yield* orchestrator.getShellSnapshot();
|
||||
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
@@ -274,6 +278,7 @@ export function runOrchestratorV2Scenario(
|
||||
storedEvents,
|
||||
domainEvents: storedEvents.map((stored) => stored.event),
|
||||
projections,
|
||||
shellSnapshot,
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -14,6 +14,7 @@ import { GitCoreLive } from "../../git/Layers/GitCore.ts";
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
import { layer as checkpointServiceLayer } from "../CheckpointService.ts";
|
||||
import { layer as commandReceiptStoreLayer } from "../CommandReceiptStore.ts";
|
||||
import { layer as contextHandoffServiceLayer } from "../ContextHandoffService.ts";
|
||||
import { layer as eventSinkLayer } from "../EventSink.ts";
|
||||
import { layer as eventStoreLayer } from "../EventStore.ts";
|
||||
import { layer as idAllocatorLayer } from "../IdAllocator.ts";
|
||||
@@ -192,6 +193,9 @@ export function makeOrchestratorV2ProviderReplayLayer<
|
||||
const checkpointServiceProvided = checkpointServiceLayer.pipe(
|
||||
Layer.provide(Layer.mergeAll(checkpointStoreLayer, idAllocatorLayer)),
|
||||
);
|
||||
const contextHandoffServiceProvided = contextHandoffServiceLayer.pipe(
|
||||
Layer.provide(idAllocatorLayer),
|
||||
);
|
||||
const persistenceLayer = Layer.mergeAll(
|
||||
storesLayer,
|
||||
eventSinkProvided,
|
||||
@@ -216,6 +220,7 @@ export function makeOrchestratorV2ProviderReplayLayer<
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
checkpointServiceProvided,
|
||||
contextHandoffServiceProvided,
|
||||
persistenceLayer,
|
||||
runtimeLayer,
|
||||
providerSessionManagerProvided,
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { CommandId, MessageId, type OrchestrationV2Command, ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
CommandId,
|
||||
MessageId,
|
||||
type OrchestrationV2Command,
|
||||
type ProviderReplayEntry,
|
||||
type ProviderReplayTranscript,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, FileSystem, Path } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
@@ -53,6 +60,264 @@ function readTranscript(transcriptPath: string = TRANSCRIPT_PATH) {
|
||||
});
|
||||
}
|
||||
|
||||
function compactExpectedText(text: string, maxLength = 240): string {
|
||||
const compacted = text.replace(/\s+/g, " ").trim();
|
||||
if (compacted.length <= maxLength) {
|
||||
return compacted;
|
||||
}
|
||||
return `${compacted.slice(0, maxLength - 3)}...`;
|
||||
}
|
||||
|
||||
function findCompletedAgentMessageText(input: {
|
||||
readonly transcript: ProviderReplayTranscript;
|
||||
readonly threadId: string;
|
||||
readonly turnId: string;
|
||||
}): string {
|
||||
for (const entry of input.transcript.entries) {
|
||||
if (entry.type !== "emit_inbound") {
|
||||
continue;
|
||||
}
|
||||
const frame = entry.frame as {
|
||||
readonly method?: unknown;
|
||||
readonly params?: {
|
||||
readonly threadId?: unknown;
|
||||
readonly turnId?: unknown;
|
||||
readonly item?: {
|
||||
readonly type?: unknown;
|
||||
readonly text?: unknown;
|
||||
};
|
||||
};
|
||||
};
|
||||
if (
|
||||
frame.method === "item/completed" &&
|
||||
frame.params?.threadId === input.threadId &&
|
||||
frame.params.turnId === input.turnId &&
|
||||
frame.params.item?.type === "agentMessage" &&
|
||||
typeof frame.params.item.text === "string"
|
||||
) {
|
||||
return frame.params.item.text;
|
||||
}
|
||||
}
|
||||
throw new Error(`No completed agent message found for ${input.threadId}/${input.turnId}`);
|
||||
}
|
||||
|
||||
function makeExpectedForkDeltaSummary(input: {
|
||||
readonly sourceThreadId: string;
|
||||
readonly targetThreadId: string;
|
||||
readonly forkUserText: string;
|
||||
readonly forkAssistantText: string;
|
||||
}): string {
|
||||
return [
|
||||
"Merge-back context from forked conversation.",
|
||||
`Source thread: ${input.sourceThreadId}`,
|
||||
`Target thread: ${input.targetThreadId}`,
|
||||
"Covered fork runs: 1-1",
|
||||
"",
|
||||
"Fork delta:",
|
||||
`- User: ${compactExpectedText(input.forkUserText)}`,
|
||||
`- Assistant: ${compactExpectedText(input.forkAssistantText)}`,
|
||||
"- Checkpoint: 0 files",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
function transcriptWithMergeBackContinuation(input: {
|
||||
readonly transcript: ProviderReplayTranscript;
|
||||
readonly providerMessageText: string;
|
||||
readonly projectedUserText: string;
|
||||
readonly assistantText: string;
|
||||
}): ProviderReplayTranscript {
|
||||
const sourceNativeThreadId = "019dd6ba-2681-7bf0-b051-141b0cbcbb27";
|
||||
const mergeBackNativeTurnId = "019dd6ba-5000-7000-8000-000000000001";
|
||||
const mergeBackUserItemId = "merge-back-user-message";
|
||||
const mergeBackAgentItemId = "merge-back-agent-message";
|
||||
const entriesWithoutExit = input.transcript.entries.filter(
|
||||
(entry) => entry.type !== "runtime_exit",
|
||||
);
|
||||
const continuation = [
|
||||
{
|
||||
type: "expect_outbound",
|
||||
label: "turn/start/merge-back-source",
|
||||
frame: {
|
||||
id: 9,
|
||||
method: "turn/start",
|
||||
params: {
|
||||
threadId: sourceNativeThreadId,
|
||||
input: [{ type: "text", text: input.providerMessageText }],
|
||||
approvalPolicy: "never",
|
||||
sandboxPolicy: {
|
||||
type: "readOnly",
|
||||
access: { type: "fullAccess" },
|
||||
networkAccess: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "emit_inbound",
|
||||
label: "turn/start/merge-back-source",
|
||||
frame: {
|
||||
id: 9,
|
||||
result: {
|
||||
turn: {
|
||||
id: mergeBackNativeTurnId,
|
||||
items: [],
|
||||
status: "inProgress",
|
||||
error: null,
|
||||
startedAt: 1777424041,
|
||||
completedAt: null,
|
||||
durationMs: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "emit_inbound",
|
||||
label: "thread/status/changed/merge-back-source",
|
||||
frame: {
|
||||
method: "thread/status/changed",
|
||||
params: {
|
||||
threadId: sourceNativeThreadId,
|
||||
status: { type: "active", activeFlags: [] },
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "emit_inbound",
|
||||
label: "turn/started/merge-back-source",
|
||||
frame: {
|
||||
method: "turn/started",
|
||||
params: {
|
||||
threadId: sourceNativeThreadId,
|
||||
turn: {
|
||||
id: mergeBackNativeTurnId,
|
||||
items: [],
|
||||
status: "inProgress",
|
||||
error: null,
|
||||
startedAt: 1777424041,
|
||||
completedAt: null,
|
||||
durationMs: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "emit_inbound",
|
||||
label: "item/userMessage/started/merge-back-source",
|
||||
frame: {
|
||||
method: "item/started",
|
||||
params: {
|
||||
item: {
|
||||
type: "userMessage",
|
||||
id: mergeBackUserItemId,
|
||||
content: [{ type: "text", text: input.projectedUserText, text_elements: [] }],
|
||||
},
|
||||
threadId: sourceNativeThreadId,
|
||||
turnId: mergeBackNativeTurnId,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "emit_inbound",
|
||||
label: "item/userMessage/completed/merge-back-source",
|
||||
frame: {
|
||||
method: "item/completed",
|
||||
params: {
|
||||
item: {
|
||||
type: "userMessage",
|
||||
id: mergeBackUserItemId,
|
||||
content: [{ type: "text", text: input.projectedUserText, text_elements: [] }],
|
||||
},
|
||||
threadId: sourceNativeThreadId,
|
||||
turnId: mergeBackNativeTurnId,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "emit_inbound",
|
||||
label: "item/agentMessage/started/merge-back-source",
|
||||
frame: {
|
||||
method: "item/started",
|
||||
params: {
|
||||
item: {
|
||||
type: "agentMessage",
|
||||
id: mergeBackAgentItemId,
|
||||
text: "",
|
||||
phase: "final_answer",
|
||||
memoryCitation: null,
|
||||
},
|
||||
threadId: sourceNativeThreadId,
|
||||
turnId: mergeBackNativeTurnId,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "emit_inbound",
|
||||
label: "item/agentMessage/delta/merge-back-source",
|
||||
frame: {
|
||||
method: "item/agentMessage/delta",
|
||||
params: {
|
||||
threadId: sourceNativeThreadId,
|
||||
turnId: mergeBackNativeTurnId,
|
||||
itemId: mergeBackAgentItemId,
|
||||
delta: input.assistantText,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "emit_inbound",
|
||||
label: "item/agentMessage/completed/merge-back-source",
|
||||
frame: {
|
||||
method: "item/completed",
|
||||
params: {
|
||||
item: {
|
||||
type: "agentMessage",
|
||||
id: mergeBackAgentItemId,
|
||||
text: input.assistantText,
|
||||
phase: "final_answer",
|
||||
memoryCitation: null,
|
||||
},
|
||||
threadId: sourceNativeThreadId,
|
||||
turnId: mergeBackNativeTurnId,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "emit_inbound",
|
||||
label: "thread/status/changed/merge-back-source",
|
||||
frame: {
|
||||
method: "thread/status/changed",
|
||||
params: { threadId: sourceNativeThreadId, status: { type: "idle" } },
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "emit_inbound",
|
||||
label: "turn/completed/merge-back-source",
|
||||
frame: {
|
||||
method: "turn/completed",
|
||||
params: {
|
||||
threadId: sourceNativeThreadId,
|
||||
turn: {
|
||||
id: mergeBackNativeTurnId,
|
||||
items: [],
|
||||
status: "completed",
|
||||
error: null,
|
||||
startedAt: 1777424041,
|
||||
completedAt: 1777424042,
|
||||
durationMs: 1000,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{ type: "runtime_exit", status: "success" },
|
||||
] satisfies ReadonlyArray<ProviderReplayEntry>;
|
||||
|
||||
return {
|
||||
...input.transcript,
|
||||
scenario: `${input.transcript.scenario}_merge_back`,
|
||||
entries: [...entriesWithoutExit, ...continuation],
|
||||
};
|
||||
}
|
||||
|
||||
describe("orchestration V2 thread fork", () => {
|
||||
it.effect(
|
||||
"creates an idle app fork and resolves it with Codex native thread/fork on first dispatch",
|
||||
@@ -355,6 +620,341 @@ describe("orchestration V2 thread fork", () => {
|
||||
"forking from the first source run must not preserve later source turns in native Codex context",
|
||||
);
|
||||
assert.equal(targetProjection.contextTransfers[0]?.resolution?.strategy, "native_fork");
|
||||
|
||||
const visibleItems = targetProjection.visibleTurnItems.map((row) => row.item);
|
||||
assert.deepEqual(
|
||||
visibleItems.slice(0, 2).map((item) => item.type),
|
||||
["user_message", "assistant_message"],
|
||||
"fork target projection should expose inherited source history through the fork point",
|
||||
);
|
||||
assert.equal(
|
||||
visibleItems[0]?.type === "user_message" ? visibleItems[0].inputIntent : undefined,
|
||||
"turn_start",
|
||||
"inherited fork history should preserve source message intent",
|
||||
);
|
||||
assert.equal(targetProjection.visibleTurnItems[0]?.visibility, "inherited");
|
||||
assert.equal(targetProjection.visibleTurnItems[1]?.visibility, "inherited");
|
||||
const forkMarker = targetProjection.visibleTurnItems.find(
|
||||
(row) => row.item.type === "fork",
|
||||
);
|
||||
assert.isDefined(forkMarker, "fork target projection should include a visible fork marker");
|
||||
assert.equal(forkMarker.visibility, "synthetic");
|
||||
const targetShell = result.shellSnapshot.threads.find(
|
||||
(thread) => thread.id === materialized.targetThreadId,
|
||||
);
|
||||
assert.isDefined(targetShell, "shell snapshot should include the fork target thread");
|
||||
assert.equal(targetShell.visibleItemCount, targetProjection.visibleTurnItems.length);
|
||||
assert.equal(targetShell.lineage.relationshipToParent, "fork");
|
||||
assert.equal(targetShell.forkedFrom?.type, "run");
|
||||
|
||||
const visibleText = visibleItems
|
||||
.filter((item) => item.type === "user_message" || item.type === "assistant_message")
|
||||
.map((item) => item.text)
|
||||
.join("\n");
|
||||
assert.include(visibleText, "fork boundary alpha");
|
||||
assert.notInclude(
|
||||
visibleText,
|
||||
"fork boundary beta",
|
||||
"fork target visible projection must not inherit source turns after the fork point",
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("merges a fork delta back into the source thread through context handoff", () =>
|
||||
Effect.gen(function* () {
|
||||
const rawTranscript = yield* readTranscript(PRIOR_TURN_TRANSCRIPT_PATH);
|
||||
const forkNativeThreadId = "019dd6ba-47b7-7092-8688-9cf7fe5f6498";
|
||||
const sourceNativeThreadId = "019dd6ba-2681-7bf0-b051-141b0cbcbb27";
|
||||
const forkRepeatNativeTurnId = "019dd6ba-47eb-7041-ad45-5abe752c28c9";
|
||||
const forkPrompt =
|
||||
"Repeat the user-visible conversation so far verbatim. Include only user and assistant messages. Do not include hidden system/developer content.";
|
||||
const mergeBackPrompt = "Acknowledge the fork context with exactly: merge back acknowledged";
|
||||
const mergeBackAssistantText = "merge back acknowledged";
|
||||
const materialized = yield* Effect.gen(function* () {
|
||||
const ids = yield* IdAllocatorV2;
|
||||
const projectId = yield* ids.allocate.project({
|
||||
fixtureName: "thread-fork-native-prior-turn",
|
||||
});
|
||||
const sourceThreadId = yield* ids.allocate.thread({
|
||||
fixtureName: "thread-fork-native-prior-turn-source",
|
||||
projectId,
|
||||
});
|
||||
const targetThreadId = ThreadId.make("thread-fork-native-prior-turn-target");
|
||||
const firstRunId = ids.derive.run({ threadId: sourceThreadId, ordinal: 1 });
|
||||
const forkRunId = ids.derive.run({ threadId: targetThreadId, ordinal: 1 });
|
||||
|
||||
const commands = [
|
||||
{
|
||||
type: "thread.create",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-prior-turn",
|
||||
commandName: "thread-create-source",
|
||||
}),
|
||||
threadId: sourceThreadId,
|
||||
projectId,
|
||||
title: "Source thread",
|
||||
modelSelection: CODEX_MODEL_SELECTION,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-prior-turn",
|
||||
commandName: "source-message-alpha",
|
||||
}),
|
||||
threadId: sourceThreadId,
|
||||
messageId: MessageId.make("message-thread-fork-native-prior-turn-alpha"),
|
||||
text: "For this fork-boundary fixture, respond with exactly: fork boundary alpha",
|
||||
attachments: [],
|
||||
modelSelection: CODEX_MODEL_SELECTION,
|
||||
dispatchMode: { type: "start_immediately" },
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-prior-turn",
|
||||
commandName: "source-message-beta",
|
||||
}),
|
||||
threadId: sourceThreadId,
|
||||
messageId: MessageId.make("message-thread-fork-native-prior-turn-beta"),
|
||||
text: "For this fork-boundary fixture, respond with exactly: fork boundary beta",
|
||||
attachments: [],
|
||||
modelSelection: CODEX_MODEL_SELECTION,
|
||||
dispatchMode: { type: "start_immediately" },
|
||||
},
|
||||
{
|
||||
type: "thread.fork",
|
||||
commandId: CommandId.make("command-thread-fork-native-prior-turn"),
|
||||
sourceThreadId,
|
||||
targetThreadId,
|
||||
sourcePoint: { type: "run", runId: firstRunId },
|
||||
title: "Forked from first response",
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-prior-turn",
|
||||
commandName: "target-message-repeat",
|
||||
}),
|
||||
threadId: targetThreadId,
|
||||
messageId: MessageId.make("message-thread-fork-native-prior-turn-repeat"),
|
||||
text: forkPrompt,
|
||||
attachments: [],
|
||||
modelSelection: CODEX_MODEL_SELECTION,
|
||||
dispatchMode: { type: "start_immediately" },
|
||||
},
|
||||
{
|
||||
type: "thread.merge_back",
|
||||
commandId: CommandId.make("command-thread-merge-back-native-prior-turn-stale"),
|
||||
sourceThreadId: targetThreadId,
|
||||
targetThreadId: sourceThreadId,
|
||||
sourcePoint: { type: "run", runId: forkRunId },
|
||||
},
|
||||
{
|
||||
type: "thread.merge_back",
|
||||
commandId: CommandId.make("command-thread-merge-back-native-prior-turn"),
|
||||
sourceThreadId: targetThreadId,
|
||||
targetThreadId: sourceThreadId,
|
||||
sourcePoint: { type: "run", runId: forkRunId },
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-prior-turn",
|
||||
commandName: "source-message-merge-back",
|
||||
}),
|
||||
threadId: sourceThreadId,
|
||||
messageId: MessageId.make("message-thread-fork-native-prior-turn-merge-back"),
|
||||
text: mergeBackPrompt,
|
||||
attachments: [],
|
||||
modelSelection: CODEX_MODEL_SELECTION,
|
||||
dispatchMode: { type: "start_immediately" },
|
||||
},
|
||||
] satisfies ReadonlyArray<OrchestrationV2Command>;
|
||||
|
||||
return {
|
||||
sourceThreadId,
|
||||
targetThreadId,
|
||||
firstRunId,
|
||||
forkRunId,
|
||||
commands,
|
||||
};
|
||||
}).pipe(Effect.provide(idAllocatorLayer), provideDeterministicTestRuntime);
|
||||
const expectedSummary = makeExpectedForkDeltaSummary({
|
||||
sourceThreadId: materialized.targetThreadId,
|
||||
targetThreadId: materialized.sourceThreadId,
|
||||
forkUserText: forkPrompt,
|
||||
forkAssistantText: findCompletedAgentMessageText({
|
||||
transcript: rawTranscript,
|
||||
threadId: forkNativeThreadId,
|
||||
turnId: forkRepeatNativeTurnId,
|
||||
}),
|
||||
});
|
||||
const providerMessageText = [
|
||||
"Context handoff (merge_back / fork_delta_summary):",
|
||||
expectedSummary,
|
||||
"",
|
||||
"User message:",
|
||||
mergeBackPrompt,
|
||||
].join("\n");
|
||||
const transcript = yield* CodexOrchestratorReplayHarness.decodeTranscript(
|
||||
transcriptWithMergeBackContinuation({
|
||||
transcript: rawTranscript,
|
||||
providerMessageText,
|
||||
projectedUserText: mergeBackPrompt,
|
||||
assistantText: mergeBackAssistantText,
|
||||
}),
|
||||
);
|
||||
const cwd = yield* Effect.acquireRelease(makeCheckpointWorkspace, (directory) =>
|
||||
Effect.service(FileSystem.FileSystem).pipe(
|
||||
Effect.flatMap((fs) => fs.remove(directory, { recursive: true, force: true })),
|
||||
Effect.orDie,
|
||||
),
|
||||
);
|
||||
|
||||
const result = yield* runOrchestratorV2ProviderReplayScenario(
|
||||
{
|
||||
name: "thread_fork_native_prior_turn_merge_back/codex",
|
||||
transcript,
|
||||
commands: materialized.commands,
|
||||
steps: [
|
||||
{ type: "dispatch", command: materialized.commands[0]!, await: true },
|
||||
{ type: "advance_clock", duration: "1 millis" },
|
||||
{ type: "dispatch", command: materialized.commands[1]!, await: true },
|
||||
{ type: "await_thread_idle", threadId: materialized.sourceThreadId },
|
||||
{ type: "dispatch", command: materialized.commands[2]!, await: true },
|
||||
{ type: "await_thread_idle", threadId: materialized.sourceThreadId },
|
||||
{ type: "dispatch", command: materialized.commands[3]!, await: true },
|
||||
{ type: "dispatch", command: materialized.commands[4]!, await: true },
|
||||
{ type: "await_thread_idle", threadId: materialized.targetThreadId },
|
||||
{ type: "dispatch", command: materialized.commands[5]!, await: true },
|
||||
{ type: "dispatch", command: materialized.commands[6]!, await: true },
|
||||
{ type: "dispatch", command: materialized.commands[7]!, await: true },
|
||||
{ type: "await_thread_idle", threadId: materialized.sourceThreadId },
|
||||
],
|
||||
projectionThreadIds: [materialized.sourceThreadId, materialized.targetThreadId],
|
||||
runtimePolicyOverride: { cwd, ...CODEX_READ_ONLY_NEVER_POLICY },
|
||||
},
|
||||
CodexOrchestratorReplayHarness,
|
||||
).pipe(provideDeterministicTestRuntime);
|
||||
|
||||
const sourceProjection = result.projections.get(materialized.sourceThreadId);
|
||||
const forkProjection = result.projections.get(materialized.targetThreadId);
|
||||
assert.isDefined(sourceProjection);
|
||||
assert.isDefined(forkProjection);
|
||||
|
||||
assert.equal(
|
||||
sourceProjection.providerThreads[0]?.nativeThreadRef?.nativeId,
|
||||
sourceNativeThreadId,
|
||||
"merge-back should continue the original source provider thread",
|
||||
);
|
||||
assert.lengthOf(sourceProjection.runs, 3);
|
||||
assert.equal(
|
||||
sourceProjection.runs[2]?.contextHandoffId,
|
||||
sourceProjection.contextHandoffs[0]?.id,
|
||||
);
|
||||
assert.lengthOf(sourceProjection.contextHandoffs, 1);
|
||||
const handoff = sourceProjection.contextHandoffs[0]!;
|
||||
assert.equal(handoff.strategy, "fork_delta_summary");
|
||||
assert.equal(handoff.status, "ready");
|
||||
assert.equal(handoff.threadId, materialized.sourceThreadId);
|
||||
assert.equal(handoff.targetRunId, sourceProjection.runs[2]?.id);
|
||||
assert.deepEqual(handoff.coveredRunOrdinals, { from: 1, to: 1 });
|
||||
assert.include(handoff.summaryText, "Merge-back context from forked conversation.");
|
||||
assert.include(handoff.summaryText, "Repeat the user-visible conversation");
|
||||
assert.notInclude(
|
||||
handoff.summaryText,
|
||||
"fork boundary beta",
|
||||
"merge-back context should summarize only fork-local delta after the source point",
|
||||
);
|
||||
assert.equal(handoff.summaryText, expectedSummary);
|
||||
|
||||
const mergeBackTransfers = sourceProjection.contextTransfers.filter(
|
||||
(transfer) => transfer.type === "merge_back",
|
||||
);
|
||||
assert.lengthOf(mergeBackTransfers, 2);
|
||||
const supersededTransfer = mergeBackTransfers.find(
|
||||
(transfer) => transfer.status === "superseded",
|
||||
);
|
||||
const mergeBackTransfer = mergeBackTransfers.find(
|
||||
(transfer) => transfer.status === "consumed",
|
||||
);
|
||||
assert.isDefined(supersededTransfer);
|
||||
assert.isDefined(mergeBackTransfer);
|
||||
assert.include(
|
||||
supersededTransfer.error ?? "",
|
||||
mergeBackTransfer.id,
|
||||
"newer merge-back preparation should supersede the previous pending transfer",
|
||||
);
|
||||
assert.equal(mergeBackTransfer.sourceThreadId, materialized.targetThreadId);
|
||||
assert.equal(mergeBackTransfer.targetThreadId, materialized.sourceThreadId);
|
||||
assert.equal(mergeBackTransfer.sourcePoint.runId, materialized.forkRunId);
|
||||
assert.equal(mergeBackTransfer.basePoint?.runId, materialized.firstRunId);
|
||||
assert.equal(mergeBackTransfer.status, "consumed");
|
||||
assert.equal(mergeBackTransfer.targetRunId, sourceProjection.runs[2]?.id);
|
||||
assert.equal(mergeBackTransfer.resolution?.strategy, "fork_delta_context");
|
||||
assert.equal(
|
||||
mergeBackTransfer.resolution?.strategy === "fork_delta_context"
|
||||
? mergeBackTransfer.resolution.contextHandoffId
|
||||
: null,
|
||||
handoff.id,
|
||||
);
|
||||
|
||||
const mergeBackRunItems = sourceProjection.turnItems.filter(
|
||||
(item) => item.runId === sourceProjection.runs[2]?.id,
|
||||
);
|
||||
assert.deepEqual(
|
||||
mergeBackRunItems.map((item) => item.type),
|
||||
["handoff", "user_message", "assistant_message", "checkpoint"],
|
||||
);
|
||||
const handoffItem = mergeBackRunItems[0];
|
||||
assert.equal(handoffItem?.type, "handoff");
|
||||
assert.equal(
|
||||
handoffItem?.type === "handoff" ? handoffItem.contextHandoffId : null,
|
||||
handoff.id,
|
||||
);
|
||||
assert.equal(handoffItem?.ordinal, 299);
|
||||
const mergeUserItem = mergeBackRunItems.find((item) => item.type === "user_message");
|
||||
assert.equal(
|
||||
mergeUserItem?.type === "user_message" ? mergeUserItem.text : null,
|
||||
mergeBackPrompt,
|
||||
);
|
||||
assert.notInclude(
|
||||
sourceProjection.turnItems
|
||||
.filter((item) => item.type === "user_message")
|
||||
.map((item) => item.text)
|
||||
.join("\n"),
|
||||
"Context handoff",
|
||||
"context handoff text should be provider input only, not projected user-visible message text",
|
||||
);
|
||||
assert.include(
|
||||
sourceProjection.turnItems
|
||||
.filter((item) => item.type === "assistant_message")
|
||||
.map((item) => item.text)
|
||||
.join("\n"),
|
||||
mergeBackAssistantText,
|
||||
);
|
||||
|
||||
const visibleTypes = sourceProjection.visibleTurnItems.map((row) => row.item.type);
|
||||
assert.includeMembers(visibleTypes, ["handoff", "user_message", "assistant_message"]);
|
||||
const sourceShell = result.shellSnapshot.threads.find(
|
||||
(thread) => thread.id === materialized.sourceThreadId,
|
||||
);
|
||||
assert.isDefined(sourceShell);
|
||||
assert.equal(sourceShell.visibleItemCount, sourceProjection.visibleTurnItems.length);
|
||||
|
||||
assert.include(
|
||||
forkProjection.turnItems
|
||||
.filter((item) => item.type === "user_message")
|
||||
.map((item) => item.text)
|
||||
.join("\n"),
|
||||
forkPrompt,
|
||||
"merge-back should not remove fork-local history",
|
||||
);
|
||||
assert.equal(forkProjection.contextTransfers[0]?.resolution?.strategy, "native_fork");
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
});
|
||||
@@ -9,7 +9,9 @@ import {
|
||||
assertRuntimeRequestKinds,
|
||||
assertSemanticProjectionIntegrity,
|
||||
assertTurnItemTypes,
|
||||
assertUserMessageInputIntents,
|
||||
assertUserMessagesInclude,
|
||||
assertVisibleTurnItemsMirrorLocalTurnItems,
|
||||
projectionFor,
|
||||
TOOL_CALL_WRITE_PROMPT,
|
||||
} from "../shared.ts";
|
||||
@@ -22,6 +24,7 @@ export function assertMessageSteeringOutput(
|
||||
|
||||
const projection = projectionFor(result, transcript.scenario);
|
||||
assertSemanticProjectionIntegrity(projection);
|
||||
assertVisibleTurnItemsMirrorLocalTurnItems(projection);
|
||||
assertTurnItemTypes(projection, [
|
||||
"user_message",
|
||||
"command_execution",
|
||||
@@ -35,6 +38,7 @@ export function assertMessageSteeringOutput(
|
||||
TOOL_CALL_WRITE_PROMPT,
|
||||
"Actually, respond with exactly: steering fixture observed",
|
||||
]);
|
||||
assertUserMessageInputIntents(projection, ["turn_start", "steer"]);
|
||||
assert.equal(projection.runs.length, 1, "steering must attach to the active run");
|
||||
assert.equal(
|
||||
projection.providerTurns.length,
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
assertSemanticProjectionIntegrity,
|
||||
assertTurnItemTypes,
|
||||
assertUserMessagesInclude,
|
||||
assertVisibleTurnItemsMirrorLocalTurnItems,
|
||||
projectionFor,
|
||||
} from "../shared.ts";
|
||||
|
||||
@@ -26,6 +27,7 @@ export function assertMultiTurnOutput(
|
||||
|
||||
const projection = projectionFor(result, transcript.scenario);
|
||||
assertSemanticProjectionIntegrity(projection);
|
||||
assertVisibleTurnItemsMirrorLocalTurnItems(projection);
|
||||
assertRunOrdinals(projection, [1, 2]);
|
||||
assertConversationMessageRoles(projection, ["user", "assistant", "user", "assistant"]);
|
||||
assertTurnItemTypes(projection, ["user_message", "assistant_message"]);
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
assertSemanticProjectionIntegrity,
|
||||
assertTurnItemTypes,
|
||||
assertUserMessagesInclude,
|
||||
assertVisibleTurnItemsMirrorLocalTurnItems,
|
||||
PLAN_QUESTIONS_PROMPT,
|
||||
projectionFor,
|
||||
} from "../shared.ts";
|
||||
@@ -25,6 +26,7 @@ export function assertPlanQuestionsOutput(
|
||||
|
||||
const projection = projectionFor(result, transcript.scenario);
|
||||
assertSemanticProjectionIntegrity(projection);
|
||||
assertVisibleTurnItemsMirrorLocalTurnItems(projection);
|
||||
assertRunOrdinals(projection, [1]);
|
||||
assertExecutionNodeKinds(projection, ["root_turn", "user_input_request", "assistant_message"]);
|
||||
assertRuntimeRequestCounts(projection, { total: 1, resolved: 1 });
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
assertSemanticProjectionIntegrity,
|
||||
assertTurnItemTypes,
|
||||
assertUserMessagesInclude,
|
||||
assertVisibleTurnItemsMirrorLocalTurnItems,
|
||||
projectionFor,
|
||||
PROPOSED_PLAN_PROMPT,
|
||||
} from "../shared.ts";
|
||||
@@ -21,6 +22,7 @@ export function assertProposedPlanOutput(
|
||||
|
||||
const projection = projectionFor(result, transcript.scenario);
|
||||
assertSemanticProjectionIntegrity(projection);
|
||||
assertVisibleTurnItemsMirrorLocalTurnItems(projection);
|
||||
assertRunOrdinals(projection, [1]);
|
||||
assertExecutionNodeKinds(projection, ["root_turn", "plan"]);
|
||||
assertTurnItemTypes(projection, ["user_message", "proposed_plan"]);
|
||||
|
||||
@@ -9,7 +9,9 @@ import {
|
||||
assertRunOrdinals,
|
||||
assertSemanticProjectionIntegrity,
|
||||
assertTurnItemTypes,
|
||||
assertUserMessageInputIntents,
|
||||
assertUserMessagesInclude,
|
||||
assertVisibleTurnItemsMirrorLocalTurnItems,
|
||||
projectionFor,
|
||||
} from "../shared.ts";
|
||||
|
||||
@@ -26,6 +28,7 @@ export function assertQueuedTurnOutput(
|
||||
|
||||
const projection = projectionFor(result, transcript.scenario);
|
||||
assertSemanticProjectionIntegrity(projection);
|
||||
assertVisibleTurnItemsMirrorLocalTurnItems(projection);
|
||||
assertRunOrdinals(projection, [1, 2]);
|
||||
assertConversationMessageRoles(projection, ["user", "assistant", "user", "assistant"]);
|
||||
assertTurnItemTypes(projection, ["user_message", "assistant_message"]);
|
||||
@@ -33,6 +36,7 @@ export function assertQueuedTurnOutput(
|
||||
"Respond with exactly: first fixture turn complete",
|
||||
"Respond with exactly: second fixture turn complete",
|
||||
]);
|
||||
assertUserMessageInputIntents(projection, ["turn_start", "queued_turn"]);
|
||||
assert.equal(projection.turnItems.filter((item) => item.type === "user_message").length, 2);
|
||||
assertAssistantTextIncludes(projection, "first fixture turn complete");
|
||||
assertAssistantTextIncludes(projection, "second fixture turn complete");
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
type OrchestrationV2RunStatus,
|
||||
type OrchestrationV2ThreadProjection,
|
||||
type OrchestrationV2TurnItem,
|
||||
type OrchestrationV2UserMessageInputIntent,
|
||||
type ProviderKind,
|
||||
type ProviderInteractionMode,
|
||||
type ProviderReplayTranscript,
|
||||
@@ -532,6 +533,26 @@ export function assertTurnItemsReferenceProjection(projection: OrchestrationV2Th
|
||||
}
|
||||
}
|
||||
|
||||
export function assertVisibleTurnItemsMirrorLocalTurnItems(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
) {
|
||||
assert.lengthOf(
|
||||
projection.visibleTurnItems,
|
||||
projection.turnItems.length,
|
||||
"non-fork visible turn items must mirror local canonical turn items",
|
||||
);
|
||||
|
||||
for (const [index, item] of projection.turnItems.entries()) {
|
||||
const visibleItem = projection.visibleTurnItems[index];
|
||||
assert.isDefined(visibleItem, `missing visible turn item at position ${index}`);
|
||||
assert.equal(visibleItem.position, index);
|
||||
assert.equal(visibleItem.visibility, "local");
|
||||
assert.equal(visibleItem.sourceThreadId, item.threadId);
|
||||
assert.equal(visibleItem.sourceItemId, item.id);
|
||||
assert.deepEqual(visibleItem.item, item);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertMessagesReferenceProjection(projection: OrchestrationV2ThreadProjection) {
|
||||
for (const message of projection.messages) {
|
||||
if (message.runId !== null) {
|
||||
@@ -695,3 +716,15 @@ export function assertUserMessagesInclude(
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertUserMessageInputIntents(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
expectedIntents: ReadonlyArray<OrchestrationV2UserMessageInputIntent>,
|
||||
) {
|
||||
assert.deepEqual(
|
||||
projection.turnItems
|
||||
.filter((item) => item.type === "user_message")
|
||||
.map((item) => item.inputIntent),
|
||||
expectedIntents,
|
||||
);
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
assertSemanticProjectionIntegrity,
|
||||
assertTurnItemTypes,
|
||||
assertUserMessagesInclude,
|
||||
assertVisibleTurnItemsMirrorLocalTurnItems,
|
||||
projectionFor,
|
||||
SIMPLE_PROMPT,
|
||||
} from "../shared.ts";
|
||||
@@ -22,6 +23,7 @@ export function assertSimpleOutput(
|
||||
|
||||
const projection = projectionFor(result, transcript.scenario);
|
||||
assertSemanticProjectionIntegrity(projection);
|
||||
assertVisibleTurnItemsMirrorLocalTurnItems(projection);
|
||||
assertRunOrdinals(projection, [1]);
|
||||
assertExecutionNodeKinds(projection, ["root_turn", "assistant_message"]);
|
||||
assertConversationMessageRoles(projection, ["user", "assistant"]);
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
assertSemanticProjectionIntegrity,
|
||||
assertTurnItemTypes,
|
||||
assertUserMessagesInclude,
|
||||
assertVisibleTurnItemsMirrorLocalTurnItems,
|
||||
projectionFor,
|
||||
} from "../shared.ts";
|
||||
|
||||
@@ -24,6 +25,7 @@ export function assertThreadRollbackOutput(
|
||||
|
||||
const projection = projectionFor(result, transcript.scenario);
|
||||
assertSemanticProjectionIntegrity(projection);
|
||||
assertVisibleTurnItemsMirrorLocalTurnItems(projection);
|
||||
assertRunOrdinals(projection, [1, 2, 3]);
|
||||
assertTurnItemTypes(projection, ["user_message", "assistant_message", "checkpoint"]);
|
||||
assertUserMessagesInclude(projection, [
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
assertSemanticProjectionIntegrity,
|
||||
assertTurnItemTypes,
|
||||
assertUserMessagesInclude,
|
||||
assertVisibleTurnItemsMirrorLocalTurnItems,
|
||||
projectionFor,
|
||||
TODO_LIST_PROMPT,
|
||||
} from "../shared.ts";
|
||||
@@ -22,6 +23,7 @@ export function assertTodoListOutput(
|
||||
|
||||
const projection = projectionFor(result, transcript.scenario);
|
||||
assertSemanticProjectionIntegrity(projection);
|
||||
assertVisibleTurnItemsMirrorLocalTurnItems(projection);
|
||||
assertRunOrdinals(projection, [1]);
|
||||
assertExecutionNodeKinds(projection, ["root_turn", "todo_list", "tool_call"]);
|
||||
assertTurnItemTypes(projection, ["user_message", "todo_list", "command_execution"]);
|
||||
|
||||
+2
@@ -9,6 +9,7 @@ import {
|
||||
assertSemanticProjectionIntegrity,
|
||||
assertTurnItemTypes,
|
||||
assertUserMessagesInclude,
|
||||
assertVisibleTurnItemsMirrorLocalTurnItems,
|
||||
projectionFor,
|
||||
TOOL_CALL_WRITE_PROMPT,
|
||||
} from "../shared.ts";
|
||||
@@ -21,6 +22,7 @@ export function assertToolCallReadOnlyOnRequestOutput(
|
||||
|
||||
const projection = projectionFor(result, transcript.scenario);
|
||||
assertSemanticProjectionIntegrity(projection);
|
||||
assertVisibleTurnItemsMirrorLocalTurnItems(projection);
|
||||
assertTurnItemTypes(projection, [
|
||||
"user_message",
|
||||
"command_execution",
|
||||
|
||||
+2
@@ -9,6 +9,7 @@ import {
|
||||
assertSemanticProjectionIntegrity,
|
||||
assertTurnItemTypes,
|
||||
assertUserMessagesInclude,
|
||||
assertVisibleTurnItemsMirrorLocalTurnItems,
|
||||
projectionFor,
|
||||
TOOL_CALL_WRITE_PROMPT,
|
||||
} from "../shared.ts";
|
||||
@@ -21,6 +22,7 @@ export function assertToolCallRestrictedGranularOutput(
|
||||
|
||||
const projection = projectionFor(result, transcript.scenario);
|
||||
assertSemanticProjectionIntegrity(projection);
|
||||
assertVisibleTurnItemsMirrorLocalTurnItems(projection);
|
||||
assertTurnItemTypes(projection, [
|
||||
"user_message",
|
||||
"command_execution",
|
||||
|
||||
+2
@@ -8,6 +8,7 @@ import {
|
||||
assertSemanticProjectionIntegrity,
|
||||
assertTurnItemTypes,
|
||||
assertUserMessagesInclude,
|
||||
assertVisibleTurnItemsMirrorLocalTurnItems,
|
||||
projectionFor,
|
||||
TOOL_CALL_WRITE_PROMPT,
|
||||
} from "../shared.ts";
|
||||
@@ -20,6 +21,7 @@ export function assertToolCallWorkspaceNeverOutput(
|
||||
|
||||
const projection = projectionFor(result, transcript.scenario);
|
||||
assertSemanticProjectionIntegrity(projection);
|
||||
assertVisibleTurnItemsMirrorLocalTurnItems(projection);
|
||||
assertTurnItemTypes(projection, ["user_message", "command_execution", "assistant_message"]);
|
||||
assertUserMessagesInclude(projection, [TOOL_CALL_WRITE_PROMPT]);
|
||||
assertRuntimeRequestCounts(projection, { total: 0 });
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
assertSemanticProjectionIntegrity,
|
||||
assertTurnItemTypes,
|
||||
assertUserMessagesInclude,
|
||||
assertVisibleTurnItemsMirrorLocalTurnItems,
|
||||
projectionFor,
|
||||
TURN_INTERRUPT_PROMPT,
|
||||
} from "../shared.ts";
|
||||
@@ -19,6 +20,7 @@ export function assertTurnInterruptOutput(
|
||||
|
||||
const projection = projectionFor(result, transcript.scenario);
|
||||
assertSemanticProjectionIntegrity(projection);
|
||||
assertVisibleTurnItemsMirrorLocalTurnItems(projection);
|
||||
assertTurnItemTypes(projection, [
|
||||
"user_message",
|
||||
"run_interrupt_request",
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
assertSemanticProjectionIntegrity,
|
||||
assertTurnItemTypes,
|
||||
assertUserMessagesInclude,
|
||||
assertVisibleTurnItemsMirrorLocalTurnItems,
|
||||
projectionFor,
|
||||
WEB_SEARCH_PROMPT,
|
||||
} from "../shared.ts";
|
||||
@@ -25,6 +26,7 @@ export function assertWebSearchOutput(
|
||||
|
||||
const projection = projectionFor(result, transcript.scenario);
|
||||
assertSemanticProjectionIntegrity(projection);
|
||||
assertVisibleTurnItemsMirrorLocalTurnItems(projection);
|
||||
assertExecutionNodeKinds(projection, ["root_turn", "tool_call", "assistant_message"]);
|
||||
assertConversationMessageRoles(projection, ["user", "assistant"]);
|
||||
assertTurnItemTypes(projection, ["user_message", "web_search", "assistant_message"]);
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
TerminalNotRunningError,
|
||||
type OrchestrationCommand,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationV2ShellStreamItem,
|
||||
type OrchestrationV2ThreadStreamItem,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
type ProviderKind,
|
||||
@@ -5953,6 +5954,22 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
yield* client[ORCHESTRATION_V2_WS_METHODS.dispatchCommand](createThreadCommand);
|
||||
assert.equal(duplicateCreateResult.sequence, createResult.sequence);
|
||||
|
||||
const shellItems = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
|
||||
const shellFiber = yield* client[ORCHESTRATION_V2_WS_METHODS.subscribeShell]({}).pipe(
|
||||
Stream.runForEach((item) => Queue.offer(shellItems, item)),
|
||||
Effect.forkDetach,
|
||||
);
|
||||
const shellSnapshot = yield* takeWsItem(shellItems, "orchestration V2 shell snapshot");
|
||||
assert.equal(shellSnapshot.kind, "snapshot");
|
||||
if (shellSnapshot.kind === "snapshot") {
|
||||
const thread = shellSnapshot.snapshot.threads.find(
|
||||
(candidate) => candidate.id === createThreadCommand.threadId,
|
||||
);
|
||||
assert.isDefined(thread);
|
||||
assert.equal(thread.itemCount, 0);
|
||||
assert.equal(thread.status, "idle");
|
||||
}
|
||||
|
||||
const streamItems = yield* Queue.unbounded<OrchestrationV2ThreadStreamItem>();
|
||||
const streamFiber = yield* client[ORCHESTRATION_V2_WS_METHODS.subscribeThread]({
|
||||
threadId: createThreadCommand.threadId,
|
||||
@@ -5975,6 +5992,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
yield* client[ORCHESTRATION_V2_WS_METHODS.dispatchCommand](dispatchMessageCommand);
|
||||
|
||||
const items: Array<OrchestrationV2ThreadStreamItem> = [];
|
||||
const shellUpdates: Array<OrchestrationV2ShellStreamItem> = [];
|
||||
const turnItemTypes = new Set<string>();
|
||||
for (let index = 0; index < 20; index += 1) {
|
||||
const item = yield* takeWsItem(streamItems, `orchestration V2 event ${index + 1}`);
|
||||
@@ -5989,13 +6007,28 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (let index = 0; index < 20; index += 1) {
|
||||
const item = yield* takeWsItem(
|
||||
shellItems,
|
||||
`orchestration V2 shell update ${index + 1}`,
|
||||
);
|
||||
shellUpdates.push(item);
|
||||
if (
|
||||
item.kind === "thread.updated" &&
|
||||
item.thread.id === createThreadCommand.threadId &&
|
||||
item.thread.visibleItemCount >= 2
|
||||
) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const projection = yield* client[ORCHESTRATION_V2_WS_METHODS.getThreadProjection]({
|
||||
threadId: createThreadCommand.threadId,
|
||||
});
|
||||
yield* Fiber.interrupt(streamFiber);
|
||||
yield* Fiber.interrupt(shellFiber);
|
||||
|
||||
return { items, projection };
|
||||
return { items, shellUpdates, projection };
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -6013,6 +6046,13 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
received.projection.turnItems.map((item) => item.type),
|
||||
["user_message", "assistant_message"],
|
||||
);
|
||||
assert.isTrue(
|
||||
received.shellUpdates.some(
|
||||
(item) =>
|
||||
item.kind === "thread.updated" &&
|
||||
item.thread.visibleItemCount === received.projection.visibleTurnItems.length,
|
||||
),
|
||||
);
|
||||
assert.equal(
|
||||
received.projection.turnItems.find((item) => item.type === "assistant_message")?.text,
|
||||
"fixture simple ok",
|
||||
|
||||
+66
-4
@@ -32,6 +32,7 @@ import {
|
||||
OrchestrationGetTurnDiffError,
|
||||
ORCHESTRATION_V2_WS_METHODS,
|
||||
OrchestrationV2DispatchCommandError,
|
||||
OrchestrationV2GetShellSnapshotError,
|
||||
OrchestrationV2GetThreadProjectionError,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
type ProjectId,
|
||||
@@ -54,8 +55,7 @@ import {
|
||||
RpcClientId,
|
||||
EnvironmentAuthorizationError,
|
||||
ThreadId,
|
||||
type TerminalAttachStreamEvent,
|
||||
type TerminalError,
|
||||
type OrchestrationV2ThreadShell,
|
||||
type TerminalEvent,
|
||||
type TerminalMetadataStreamEvent,
|
||||
WS_METHODS,
|
||||
@@ -975,6 +975,58 @@ const makeWsRpcLayer = (
|
||||
},
|
||||
);
|
||||
|
||||
const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subscribeShell")(
|
||||
function* () {
|
||||
const snapshot = yield* orchestrationV2.getShellSnapshot().pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationV2GetShellSnapshotError({
|
||||
message: "Failed to load orchestration V2 shell snapshot",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const liveStream = orchestrationV2.streamDomainEvents.pipe(
|
||||
Stream.mapEffect((event) =>
|
||||
orchestrationV2.getShellSnapshot().pipe(
|
||||
Effect.map(
|
||||
(nextSnapshot) =>
|
||||
nextSnapshot.threads.find((thread) => thread.id === event.threadId) ?? null,
|
||||
),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationV2GetShellSnapshotError({
|
||||
message: `Failed while streaming orchestration V2 shell thread ${event.threadId}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Stream.filter((thread): thread is OrchestrationV2ThreadShell => thread !== null),
|
||||
Stream.map((thread) => ({
|
||||
kind: "thread.updated" as const,
|
||||
thread,
|
||||
})),
|
||||
Stream.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationV2GetShellSnapshotError({
|
||||
message: "Failed while streaming orchestration V2 shell",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return Stream.concat(
|
||||
Stream.make({
|
||||
kind: "snapshot" as const,
|
||||
snapshot,
|
||||
}),
|
||||
liveStream,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
return WsRpcGroup.of({
|
||||
[ORCHESTRATION_WS_METHODS.dispatchCommand]: (command) =>
|
||||
observeRpcEffect(
|
||||
@@ -1350,8 +1402,10 @@ const makeWsRpcLayer = (
|
||||
"orchestration_v2.command_id": command.commandId,
|
||||
"orchestration_v2.command_type": command.type,
|
||||
"orchestration_v2.thread_id":
|
||||
command.type === "thread.fork" ? command.targetThreadId : command.threadId,
|
||||
...(command.type === "thread.fork"
|
||||
command.type === "thread.fork" || command.type === "thread.merge_back"
|
||||
? command.targetThreadId
|
||||
: command.threadId,
|
||||
...(command.type === "thread.fork" || command.type === "thread.merge_back"
|
||||
? { "orchestration_v2.source_thread_id": command.sourceThreadId }
|
||||
: {}),
|
||||
},
|
||||
@@ -1374,6 +1428,14 @@ const makeWsRpcLayer = (
|
||||
"orchestration_v2.thread_id": input.threadId,
|
||||
},
|
||||
),
|
||||
[ORCHESTRATION_V2_WS_METHODS.subscribeShell]: (_input) =>
|
||||
observeRpcStreamEffect(
|
||||
ORCHESTRATION_V2_WS_METHODS.subscribeShell,
|
||||
subscribeOrchestrationV2Shell(),
|
||||
{
|
||||
"rpc.aggregate": "orchestrationV2",
|
||||
},
|
||||
),
|
||||
[ORCHESTRATION_V2_WS_METHODS.subscribeThread]: (input) =>
|
||||
observeRpcStreamEffect(
|
||||
ORCHESTRATION_V2_WS_METHODS.subscribeThread,
|
||||
|
||||
Reference in new issue
Block a user