fix(orchestration): preserve imported conversation state

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex authored and maria-rcks committed 2026-08-03 11:45:12 -04:00
1 parent b6d7072140
commit eca5fd07e9
10 files changed
+250 -62

No files matched your search

@@ -129,4 +129,36 @@ it.layer(TestLayer)("ContextHandoffService legacy import", (it) => {
assert.notMatch(handoff.summaryText, /\n+x+ retained final words/);
}),
);
it.effect("retains the newest oversized import even when it has no whitespace", () =>
Effect.gen(function* () {
const service = yield* ContextHandoffServiceV2;
const handoff = yield* service.prepareLegacyImport({
threadId: ThreadId.make("thread:legacy-context"),
targetRunId: RunId.make("run:first-v2"),
toProviderThreadId: ProviderThreadId.make("provider-thread:first-v2"),
toProviderInstanceId: ProviderInstanceId.make("codex"),
items: [
importedItem({
role: "assistant",
id: "older",
text: "older message",
ordinal: 1,
}),
importedItem({
role: "user",
id: "long-single-token",
text: `${"🧪".repeat(20_000)}LATEST_SINGLE_TOKEN`,
ordinal: 2,
}),
],
createdAt: DateTime.makeUnsafe("2026-01-02T00:00:00.000Z"),
});
assert.isAtMost(handoff.summaryText.length, 32_000);
assert.include(handoff.summaryText, "User:\n... ");
assert.include(handoff.summaryText, "LATEST_SINGLE_TOKEN");
assert.notInclude(handoff.summaryText, "\ufffd");
}),
);
});
@@ -198,8 +198,19 @@ function makeLegacyImportSummary(items: ReadonlyArray<OrchestrationV2TurnItem>):
!/\s/.test(section.body[bodyStart] ?? "")
) {
const nextWhitespace = section.body.slice(bodyStart).search(/\s/);
if (nextWhitespace === -1) continue;
bodyStart += nextWhitespace;
if (nextWhitespace !== -1) {
bodyStart += nextWhitespace;
}
}
const codeUnitAtStart = section.body.charCodeAt(bodyStart);
const codeUnitBeforeStart = section.body.charCodeAt(bodyStart - 1);
if (
codeUnitAtStart >= 0xdc00 &&
codeUnitAtStart <= 0xdfff &&
codeUnitBeforeStart >= 0xd800 &&
codeUnitBeforeStart <= 0xdbff
) {
bodyStart += 1;
}
const bodySuffix = section.body.slice(bodyStart).trimStart();
if (bodySuffix.length === 0) continue;
@@ -1,11 +1,12 @@
import { assert, it } from "@effect/vitest";
import { ThreadId } from "@t3tools/contracts";
import { EventId, ThreadId } from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
import { layer as eventSinkLayer } from "./EventSink.ts";
import { EventSinkV2, layer as eventSinkLayer } from "./EventSink.ts";
import { layer as eventStoreLayer } from "./EventStore.ts";
import {
LegacyV1ThreadImporter,
@@ -42,6 +43,7 @@ it.layer(TestLayer)("LegacyV1ThreadImporter", (it) => {
const importer = yield* LegacyV1ThreadImporter;
const maintenance = yield* ProjectionMaintenanceV2;
const projections = yield* ProjectionStoreV2;
const eventSink = yield* EventSinkV2;
const threadId = ThreadId.make("thread:legacy-import");
yield* sql`
@@ -186,12 +188,41 @@ it.layer(TestLayer)("LegacyV1ThreadImporter", (it) => {
["message:legacy:3", "message:legacy:4"],
);
const renamedAt = DateTime.makeUnsafe("2026-01-05T00:00:00.000Z");
yield* eventSink.write({
events: [
{
id: EventId.make("event:legacy-import:metadata-after-shell"),
type: "thread.metadata-updated",
threadId,
providerInstanceId: shellProjection.thread.providerInstanceId,
occurredAt: renamedAt,
payload: {
...shellProjection.thread,
title: "Renamed after shell import",
runtimeMode: "approval-required",
interactionMode: "plan",
archivedAt: renamedAt,
settledOverride: "settled",
settledAt: renamedAt,
updatedAt: renamedAt,
},
},
],
});
const transcriptImport = yield* importer.ensureTranscript(threadId);
assert.deepStrictEqual(transcriptImport, {
importedThreadCount: 1,
importedMessageCount: 2,
});
const projection = yield* projections.getThreadProjection(threadId);
assert.equal(projection.thread.title, "Renamed after shell import");
assert.equal(projection.thread.runtimeMode, "approval-required");
assert.equal(projection.thread.interactionMode, "plan");
assert.deepEqual(projection.thread.archivedAt, renamedAt);
assert.equal(projection.thread.settledOverride, "settled");
assert.deepEqual(projection.thread.settledAt, renamedAt);
assert.deepStrictEqual(
projection.messages.map((message) => message.id),
["message:legacy:1", "message:legacy:2", "message:legacy:3", "message:legacy:4"],
@@ -508,51 +508,6 @@ const make = Effect.gen(function* () {
yield* eventSink.write({ events: batch.flatMap(messageEvents) });
yield* Effect.yieldNow;
}
const threadRows = yield* sql<LegacyThreadRow>`
SELECT
thread_id,
project_id,
title,
model_selection_json,
runtime_mode,
interaction_mode,
branch,
worktree_path,
created_at,
updated_at,
archived_at,
settled_override,
settled_at,
deleted_at
FROM projection_threads
WHERE thread_id = ${threadId}
LIMIT 1
`;
const source = threadRows[0];
if (source !== undefined) {
const marker = `${IMPORT_EVENT_PREFIX}:thread:${threadId}:transcript`;
const markerRows = yield* sql<{ readonly event_id: string }>`
SELECT event_id
FROM orchestration_events
WHERE event_id = ${marker}
LIMIT 1
`;
if (markerRows.length === 0) {
const thread = importedThread(source);
yield* eventSink.write({
events: [
{
id: EventId.make(marker),
type: "thread.metadata-updated",
threadId,
providerInstanceId: thread.providerInstanceId,
occurredAt: thread.updatedAt,
payload: thread,
},
],
});
}
}
const now = DateTime.formatIso(yield* DateTime.now);
yield* sql`
UPDATE orchestration_v2_legacy_imports
@@ -3,32 +3,32 @@ import { ContextHandoffId } from "@t3tools/contracts";
import { appendContextHandoffId, shouldPrepareLegacyImportHandoff } from "./Orchestrator.ts";
it("reissues imported context until the provider thread is materialized", () => {
it("reissues imported context until a V2 run completes", () => {
assert.isTrue(
shouldPrepareLegacyImportHandoff({
historyOrigin: "v1_import",
hasNativeThreadRef: false,
hasCompletedRun: false,
legacyImportItemCount: 2,
}),
);
assert.isFalse(
shouldPrepareLegacyImportHandoff({
historyOrigin: "v1_import",
hasNativeThreadRef: true,
hasCompletedRun: true,
legacyImportItemCount: 2,
}),
);
assert.isFalse(
shouldPrepareLegacyImportHandoff({
historyOrigin: undefined,
hasNativeThreadRef: false,
hasCompletedRun: false,
legacyImportItemCount: 2,
}),
);
assert.isFalse(
shouldPrepareLegacyImportHandoff({
historyOrigin: "v1_import",
hasNativeThreadRef: false,
hasCompletedRun: false,
legacyImportItemCount: 0,
}),
);
@@ -444,14 +444,12 @@ function visibleDeltaRunOrdinals(
}
export function shouldPrepareLegacyImportHandoff(input: {
readonly hasNativeThreadRef: boolean;
readonly hasCompletedRun: boolean;
readonly historyOrigin: OrchestrationV2AppThread["historyOrigin"];
readonly legacyImportItemCount: number;
}): boolean {
return (
input.historyOrigin === "v1_import" &&
!input.hasNativeThreadRef &&
input.legacyImportItemCount > 0
input.historyOrigin === "v1_import" && !input.hasCompletedRun && input.legacyImportItemCount > 0
);
}
@@ -2449,8 +2447,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
});
const legacyImportHandoff = shouldPrepareLegacyImportHandoff({
historyOrigin: projection.thread.historyOrigin,
hasNativeThreadRef:
activeProviderThread !== undefined && activeProviderThread.nativeThreadRef !== null,
hasCompletedRun: latestCompletedRun !== undefined,
legacyImportItemCount: legacyImportItems.length,
})
? yield* contextHandoffService
@@ -319,6 +319,156 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
}),
);
it.effect("counts imported runless history inherited by fork shells", () =>
Effect.gen(function* () {
const projectionStore = yield* ProjectionStoreV2;
const now = yield* DateTime.now;
const projectId = ProjectId.make("project:projection-imported-fork-shell");
const sourceThreadId = ThreadId.make("thread:projection-imported-fork-shell:source");
const targetThreadId = ThreadId.make("thread:projection-imported-fork-shell:target");
const sourceRunId = RunId.make("run:projection-imported-fork-shell:source");
const rootNodeId = NodeId.make("node:projection-imported-fork-shell:source");
yield* projectionStore.apply({
id: EventId.make("event:projection-imported-fork-shell:source-thread"),
type: "thread.created",
threadId: sourceThreadId,
occurredAt: now,
payload: {
createdBy: "system",
creationSource: "server",
id: sourceThreadId,
projectId,
title: "Imported fork source",
providerInstanceId,
modelSelection,
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
activeProviderThreadId: null,
historyOrigin: "v1_import",
lineage: {
parentThreadId: null,
relationshipToParent: null,
rootThreadId: sourceThreadId,
},
forkedFrom: null,
createdAt: now,
updatedAt: now,
archivedAt: null,
settledOverride: null,
settledAt: null,
deletedAt: null,
},
});
yield* projectionStore.apply({
id: EventId.make("event:projection-imported-fork-shell:target-thread"),
type: "thread.created",
threadId: targetThreadId,
occurredAt: now,
payload: {
createdBy: "user",
creationSource: "web",
id: targetThreadId,
projectId,
title: "Imported fork target",
providerInstanceId,
modelSelection,
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
activeProviderThreadId: null,
lineage: {
parentThreadId: sourceThreadId,
relationshipToParent: "fork",
rootThreadId: sourceThreadId,
},
forkedFrom: {
type: "run",
threadId: sourceThreadId,
runId: sourceRunId,
},
createdAt: now,
updatedAt: now,
archivedAt: null,
settledOverride: null,
settledAt: null,
deletedAt: null,
},
});
yield* projectionStore.apply({
id: EventId.make("event:projection-imported-fork-shell:source-run"),
type: "run.created",
threadId: sourceThreadId,
runId: sourceRunId,
nodeId: rootNodeId,
driver,
occurredAt: now,
payload: {
id: sourceRunId,
threadId: sourceThreadId,
ordinal: 1,
providerInstanceId,
modelSelection,
providerThreadId: null,
userMessageId: MessageId.make("message:projection-imported-fork-shell:run"),
rootNodeId,
activeAttemptId: null,
status: "completed",
requestedAt: now,
startedAt: now,
completedAt: now,
checkpointId: null,
contextHandoffId: null,
},
});
const applyAssistantItem = (suffix: string, runId: RunId | null, ordinal: number) =>
projectionStore.apply({
id: EventId.make(`event:projection-imported-fork-shell:item:${suffix}`),
type: "turn-item.updated",
threadId: sourceThreadId,
...(runId === null ? {} : { runId }),
occurredAt: now,
payload: {
id: TurnItemId.make(`turn-item:projection-imported-fork-shell:${suffix}`),
threadId: sourceThreadId,
runId,
nodeId: null,
providerThreadId: null,
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
ordinal,
status: "completed",
title: null,
startedAt: now,
completedAt: now,
updatedAt: now,
type: "assistant_message",
messageId: MessageId.make(`message:projection-imported-fork-shell:${suffix}`),
text: suffix,
streaming: false,
},
});
yield* applyAssistantItem("imported-one", null, 1);
yield* applyAssistantItem("imported-two", null, 2);
yield* applyAssistantItem("native-run", sourceRunId, 3);
const shell = yield* projectionStore.getShellSnapshot();
const targetShell = shell.threads.find((thread) => thread.id === targetThreadId);
const targetProjection = yield* projectionStore.getThreadProjection(targetThreadId);
assert.isDefined(targetShell);
assert.equal(targetShell.itemCount, 0);
assert.equal(targetShell.visibleItemCount, 4);
assert.equal(targetProjection.visibleTurnItems.length, 4);
}),
);
it.effect("removes rolled back runs from the active visible projection", () =>
Effect.gen(function* () {
const projectionStore = yield* ProjectionStoreV2;
@@ -392,6 +392,7 @@ type ShellThreadRow = {
readonly latest_user_message_at: string | null;
readonly has_actionable_proposed_plan: number;
readonly item_count: number;
readonly runless_item_count: number;
};
type ShellRunRow = {
@@ -843,6 +844,7 @@ type ShellThreadState = {
readonly latestUserMessageAt: DateTime.Utc | null;
readonly hasActionableProposedPlan: boolean;
readonly itemCount: number;
readonly runlessItemCount: number;
readonly updatedAt: OrchestrationV2ThreadProjection["updatedAt"];
readonly runOrdinalById: ReadonlyMap<RunId, number>;
readonly itemCountByRunId: ReadonlyMap<RunId, number>;
@@ -877,7 +879,7 @@ function itemCountThroughRun(input: {
return 0;
}
let count = 0;
let count = input.state.thread.historyOrigin === "v1_import" ? input.state.runlessItemCount : 0;
for (const [runId, itemCount] of input.state.itemCountByRunId) {
const itemRunOrdinal = input.state.runOrdinalById.get(runId);
if (itemRunOrdinal !== undefined && itemRunOrdinal <= runOrdinal) {
@@ -2137,7 +2139,13 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
ON r.run_id = i.run_id
WHERE i.thread_id = t.thread_id
AND (i.run_id IS NULL OR r.status <> 'rolled_back')
) AS item_count
) AS item_count,
(
SELECT COUNT(*)
FROM orchestration_v2_projection_turn_items i
WHERE i.thread_id = t.thread_id
AND i.run_id IS NULL
) AS runless_item_count
FROM orchestration_v2_projection_threads t
WHERE t.deleted_at IS NULL
ORDER BY t.updated_at ASC, t.thread_id ASC
@@ -2203,6 +2211,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
: DateTime.makeUnsafe(row.latest_user_message_at),
hasActionableProposedPlan: row.has_actionable_proposed_plan === 1,
itemCount: row.item_count,
runlessItemCount: row.runless_item_count,
updatedAt: thread.updatedAt,
runOrdinalById:
runOrdinalsByThreadId.get(ThreadId.make(row.thread_id)) ?? new Map(),
@@ -57,6 +57,7 @@ function makeParentThread(): OrchestrationV2AppThread {
snoozedUntil,
snoozedAt,
deletedAt: null,
historyOrigin: "v1_import",
};
}
@@ -87,6 +88,7 @@ it("keeps a subagent child awake when its parent thread is snoozed", () => {
assert.equal(childThread.providerInstanceId, childProviderInstanceId);
assert.deepEqual(childThread.modelSelection, childModelSelection);
assert.equal(childThread.activeProviderThreadId, childProviderThreadId);
assert.isUndefined(childThread.historyOrigin);
assert.deepEqual(childThread.lineage, {
parentThreadId,
relationshipToParent: "subagent",
@@ -55,6 +55,7 @@ export function makeSubagentChildThread(input: {
creationSource: input.creationSource,
id: input.childThreadId,
title: input.title,
historyOrigin: undefined,
providerInstanceId: input.providerInstanceId,
modelSelection: input.modelSelection,
activeProviderThreadId: input.activeProviderThreadId,