feat: migrate v1 state into orchestrator v2 (#4400)
Co-authored-by: codex <[email protected]>
This commit is contained in:
1 parent
61b181443c
commit
fe5df2b650
32 files changed
+2277
-93
No files matched your search
@@ -127,7 +127,7 @@ const withIdentity = <A, E, R>(
|
||||
input.legacyPathProbeError
|
||||
? Effect.fail(input.legacyPathProbeError)
|
||||
: Effect.succeed(
|
||||
input.legacyPathExists === true && path.includes("T3 Code (Alpha v2)"),
|
||||
input.legacyPathExists === true && path.includes("T3 Code (Alpha)"),
|
||||
),
|
||||
readFileString: () =>
|
||||
Effect.succeed(input.packageJson ?? '{"t3codeCommitHash":"abcdef1234567890"}'),
|
||||
@@ -148,14 +148,14 @@ describe("DesktopAppIdentity", () => {
|
||||
const identity = yield* DesktopAppIdentity.DesktopAppIdentity;
|
||||
const userDataPath = yield* identity.resolveUserDataPath;
|
||||
|
||||
assert.equal(userDataPath, "/Users/alice/Library/Application Support/T3 Code (Alpha v2)");
|
||||
assert.equal(userDataPath, "/Users/alice/Library/Application Support/T3 Code (Alpha)");
|
||||
}),
|
||||
{ legacyPathExists: true },
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("preserves failures while inspecting the legacy userData path", () => {
|
||||
const legacyPath = "/Users/alice/Library/Application Support/T3 Code (Alpha v2)";
|
||||
const legacyPath = "/Users/alice/Library/Application Support/T3 Code (Alpha)";
|
||||
const cause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
|
||||
@@ -254,7 +254,7 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "readFileString",
|
||||
pathOrDescriptor: `${baseDir}/userdata-v2/connection-catalog.json`,
|
||||
pathOrDescriptor: `${baseDir}/userdata/connection-catalog.json`,
|
||||
});
|
||||
const fileSystemLayer = Layer.succeed(
|
||||
FileSystem.FileSystem,
|
||||
@@ -271,11 +271,11 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
error,
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreReadError,
|
||||
);
|
||||
assert.equal(error.catalogPath, `${baseDir}/userdata-v2/connection-catalog.json`);
|
||||
assert.equal(error.catalogPath, `${baseDir}/userdata/connection-catalog.json`);
|
||||
assert.strictEqual(error.cause, permissionError);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to read the desktop connection catalog at ${baseDir}/userdata-v2/connection-catalog.json.`,
|
||||
`Failed to read the desktop connection catalog at ${baseDir}/userdata/connection-catalog.json.`,
|
||||
);
|
||||
assert.notEqual(error.message, permissionError.message);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
@@ -291,7 +291,7 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "makeDirectory",
|
||||
pathOrDescriptor: `${baseDir}/userdata-v2`,
|
||||
pathOrDescriptor: `${baseDir}/userdata`,
|
||||
});
|
||||
const fileSystemLayer = Layer.succeed(
|
||||
FileSystem.FileSystem,
|
||||
@@ -309,11 +309,11 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreWriteError,
|
||||
);
|
||||
assert.equal(error.operation, "create-directory");
|
||||
assert.equal(error.path, `${baseDir}/userdata-v2`);
|
||||
assert.equal(error.path, `${baseDir}/userdata`);
|
||||
assert.strictEqual(error.cause, permissionError);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop connection catalog write failed during create-directory at ${baseDir}/userdata-v2.`,
|
||||
`Desktop connection catalog write failed during create-directory at ${baseDir}/userdata.`,
|
||||
);
|
||||
assert.notEqual(error.message, permissionError.message);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
@@ -398,14 +398,14 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreProtectionError,
|
||||
);
|
||||
assert.equal(error.operation, "decrypt-catalog");
|
||||
assert.equal(error.catalogPath, `${baseDir}/userdata-v2/connection-catalog.json`);
|
||||
assert.equal(error.catalogPath, `${baseDir}/userdata/connection-catalog.json`);
|
||||
assert.instanceOf(error.cause, ElectronSafeStorage.ElectronSafeStorageDecryptError);
|
||||
const decryptError = error.cause as ElectronSafeStorage.ElectronSafeStorageDecryptError;
|
||||
assert.instanceOf(decryptError.cause, Error);
|
||||
assert.equal(decryptError.cause.message, "invalid encrypted catalog");
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop connection catalog protection failed during decrypt-catalog at ${baseDir}/userdata-v2/connection-catalog.json.`,
|
||||
`Desktop connection catalog protection failed during decrypt-catalog at ${baseDir}/userdata/connection-catalog.json.`,
|
||||
);
|
||||
assert.notEqual(error.message, decryptError.message);
|
||||
yield* Ref.set(failDecrypt, false);
|
||||
|
||||
@@ -53,16 +53,16 @@ describe("DesktopEnvironment", () => {
|
||||
assert.equal(environment.isDevelopment, true);
|
||||
assert.equal(environment.appDataDirectory, "/Users/alice/Library/Application Support");
|
||||
assert.equal(environment.baseDir, "/tmp/t3");
|
||||
assert.equal(environment.stateDir, "/tmp/t3/userdata-v2");
|
||||
assert.equal(environment.desktopSettingsPath, "/tmp/t3/userdata-v2/desktop-settings.json");
|
||||
assert.equal(environment.clientSettingsPath, "/tmp/t3/userdata-v2/client-settings.json");
|
||||
assert.equal(environment.stateDir, "/tmp/t3/userdata");
|
||||
assert.equal(environment.desktopSettingsPath, "/tmp/t3/userdata/desktop-settings.json");
|
||||
assert.equal(environment.clientSettingsPath, "/tmp/t3/userdata/client-settings.json");
|
||||
assert.equal(
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
"/tmp/t3/userdata-v2/saved-environments.json",
|
||||
"/tmp/t3/userdata/saved-environments.json",
|
||||
);
|
||||
assert.equal(environment.serverSettingsPath, "/tmp/t3/userdata-v2/settings.json");
|
||||
assert.equal(environment.logDir, "/tmp/t3/userdata-v2/logs");
|
||||
assert.equal(environment.browserArtifactsDir, "/tmp/t3/userdata-v2/browser-artifacts");
|
||||
assert.equal(environment.serverSettingsPath, "/tmp/t3/userdata/settings.json");
|
||||
assert.equal(environment.logDir, "/tmp/t3/userdata/logs");
|
||||
assert.equal(environment.browserArtifactsDir, "/tmp/t3/userdata/browser-artifacts");
|
||||
assert.equal(environment.rootDir, "/repo");
|
||||
assert.equal(environment.appRoot, "/repo");
|
||||
assert.equal(environment.backendEntryPath, "/repo/apps/server/dist/bin.mjs");
|
||||
@@ -81,7 +81,7 @@ describe("DesktopEnvironment", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("derives production state paths under userdata-v2", () =>
|
||||
it.effect("stores production state under userdata in an explicit home", () =>
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* makeEnvironment(
|
||||
{},
|
||||
@@ -91,12 +91,12 @@ describe("DesktopEnvironment", () => {
|
||||
);
|
||||
|
||||
assert.equal(environment.isDevelopment, false);
|
||||
assert.equal(environment.stateDir, "/tmp/t3/userdata-v2");
|
||||
assert.equal(environment.logDir, "/tmp/t3/userdata-v2/logs");
|
||||
assert.equal(environment.browserArtifactsDir, "/tmp/t3/userdata-v2/browser-artifacts");
|
||||
assert.equal(environment.serverSettingsPath, "/tmp/t3/userdata-v2/settings.json");
|
||||
assert.equal(environment.userDataDirName, "t3code-v2");
|
||||
assert.equal(environment.legacyUserDataDirName, "T3 Code (Alpha v2)");
|
||||
assert.equal(environment.stateDir, "/tmp/t3/userdata");
|
||||
assert.equal(environment.logDir, "/tmp/t3/userdata/logs");
|
||||
assert.equal(environment.browserArtifactsDir, "/tmp/t3/userdata/browser-artifacts");
|
||||
assert.equal(environment.serverSettingsPath, "/tmp/t3/userdata/settings.json");
|
||||
assert.equal(environment.userDataDirName, "t3code");
|
||||
assert.equal(environment.legacyUserDataDirName, "T3 Code (Alpha)");
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -158,9 +158,12 @@ const make = Effect.fn("desktop.environment.make")(function* (
|
||||
appVersion: input.appVersion,
|
||||
});
|
||||
const displayName = branding.displayName;
|
||||
const stateDir = path.join(baseDir, isDevelopment ? "dev" : "userdata-v2");
|
||||
const userDataDirName = isDevelopment ? "t3code-dev" : "t3code-v2";
|
||||
const legacyUserDataDirName = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha v2)";
|
||||
const stateDir = path.join(
|
||||
baseDir,
|
||||
isDevelopment && Option.isNone(configuredBaseDir) ? "dev" : "userdata",
|
||||
);
|
||||
const userDataDirName = isDevelopment ? "t3code-dev" : "t3code";
|
||||
const legacyUserDataDirName = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const resourcesPath = input.resourcesPath;
|
||||
|
||||
return DesktopEnvironment.of({
|
||||
|
||||
@@ -359,7 +359,7 @@ describe("DesktopBackendConfiguration", () => {
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
const settingsPath = path.join(baseDir, "userdata-v2", "settings.json");
|
||||
const settingsPath = path.join(baseDir, "userdata", "settings.json");
|
||||
const cause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
|
||||
@@ -553,7 +553,7 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl
|
||||
};
|
||||
|
||||
// Forward the dev-server URL as an explicit CLI flag so the WSL backend's
|
||||
// config resolution lands in dev/ instead of userdata-v2/. Inheriting through
|
||||
// config resolution lands in dev/ instead of userdata/. Inheriting through
|
||||
// WSLENV is unreliable in practice (URL-shaped values with colons /
|
||||
// slashes get translated unpredictably depending on flags), and the
|
||||
// packaged build leaves devServerUrl as None anyway.
|
||||
|
||||
@@ -83,7 +83,7 @@ describe("DesktopClientSettings diagnostics", () => {
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "readFileString",
|
||||
pathOrDescriptor: `${baseDir}/userdata-v2/client-settings.json`,
|
||||
pathOrDescriptor: `${baseDir}/userdata/client-settings.json`,
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
|
||||
@@ -403,7 +403,7 @@ describe("DesktopSavedEnvironments", () => {
|
||||
const baseDir = yield* baseFileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-saved-environments-test-",
|
||||
});
|
||||
const registryPath = `${baseDir}/userdata-v2/saved-environments.json`;
|
||||
const registryPath = `${baseDir}/userdata/saved-environments.json`;
|
||||
const permissionError = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
@@ -439,7 +439,7 @@ describe("DesktopSavedEnvironments", () => {
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "makeDirectory",
|
||||
pathOrDescriptor: `${baseDir}/userdata-v2`,
|
||||
pathOrDescriptor: `${baseDir}/userdata`,
|
||||
});
|
||||
const fileSystemLayer = Layer.succeed(
|
||||
FileSystem.FileSystem,
|
||||
@@ -455,11 +455,11 @@ describe("DesktopSavedEnvironments", () => {
|
||||
const error = yield* savedEnvironments.setRegistry([savedRegistryRecord]).pipe(Effect.flip);
|
||||
assert.instanceOf(error, DesktopSavedEnvironments.DesktopSavedEnvironmentsWriteError);
|
||||
assert.equal(error.operation, "create-directory");
|
||||
assert.equal(error.path, `${baseDir}/userdata-v2`);
|
||||
assert.equal(error.path, `${baseDir}/userdata`);
|
||||
assert.strictEqual(error.cause, permissionError);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop saved-environment write failed during create-directory at ${baseDir}/userdata-v2.`,
|
||||
`Desktop saved-environment write failed during create-directory at ${baseDir}/userdata.`,
|
||||
);
|
||||
assert.notEqual(error.message, permissionError.message);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
|
||||
@@ -129,7 +129,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
});
|
||||
assert.equal(resolved.stateDir, join(baseDir, "userdata-v2"));
|
||||
assert.equal(resolved.stateDir, join(baseDir, "userdata"));
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -199,7 +199,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
tailscaleServeEnabled: true,
|
||||
tailscaleServePort: 8443,
|
||||
});
|
||||
assert.equal(resolved.dbPath, join(baseDir, "userdata-v2", "state.sqlite"));
|
||||
assert.equal(resolved.dbPath, join(baseDir, "userdata", "state.sqlite"));
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -351,7 +351,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
});
|
||||
assert.equal(join(baseDir, "userdata-v2"), resolved.stateDir);
|
||||
assert.equal(join(baseDir, "userdata"), resolved.stateDir);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -102,7 +102,10 @@ export const deriveServerPaths = Effect.fn(function* (
|
||||
options: DeriveServerPathsOptions = {},
|
||||
): Effect.fn.Return<ServerDerivedPaths, never, Path.Path> {
|
||||
const { join } = yield* Path.Path;
|
||||
const stateDir = join(baseDir, devUrl !== undefined ? "dev" : "userdata-v2");
|
||||
const stateDir = join(
|
||||
baseDir,
|
||||
devUrl !== undefined && !options.baseDirIsExplicit ? "dev" : "userdata",
|
||||
);
|
||||
const dbPath = join(stateDir, "state.sqlite");
|
||||
const attachmentsDir = join(stateDir, "attachments");
|
||||
const logsDir = join(stateDir, "logs");
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import {
|
||||
MessageId,
|
||||
ProviderInstanceId,
|
||||
ProviderThreadId,
|
||||
RunId,
|
||||
ThreadId,
|
||||
TurnItemId,
|
||||
type OrchestrationV2TurnItem,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import {
|
||||
ContextHandoffServiceV2,
|
||||
layer as contextHandoffServiceLayer,
|
||||
providerMessageWithContextHandoff,
|
||||
} from "./ContextHandoffService.ts";
|
||||
import { layer as idAllocatorLayer } from "./IdAllocator.ts";
|
||||
|
||||
const TestLayer = contextHandoffServiceLayer.pipe(Layer.provide(idAllocatorLayer));
|
||||
|
||||
function importedItem(
|
||||
input:
|
||||
| {
|
||||
readonly role: "user";
|
||||
readonly id: string;
|
||||
readonly text: string;
|
||||
readonly ordinal: number;
|
||||
}
|
||||
| {
|
||||
readonly role: "assistant";
|
||||
readonly id: string;
|
||||
readonly text: string;
|
||||
readonly ordinal: number;
|
||||
},
|
||||
): OrchestrationV2TurnItem {
|
||||
const now = DateTime.makeUnsafe("2026-01-01T00:00:00.000Z");
|
||||
const base = {
|
||||
id: TurnItemId.make(`turn-item:${input.id}`),
|
||||
threadId: ThreadId.make("thread:legacy-context"),
|
||||
runId: null,
|
||||
nodeId: null,
|
||||
providerThreadId: null,
|
||||
providerTurnId: null,
|
||||
nativeItemRef: null,
|
||||
parentItemId: null,
|
||||
ordinal: input.ordinal,
|
||||
status: "completed" as const,
|
||||
title: null,
|
||||
startedAt: now,
|
||||
completedAt: now,
|
||||
updatedAt: now,
|
||||
messageId: MessageId.make(`message:${input.id}`),
|
||||
text: input.text,
|
||||
};
|
||||
return input.role === "user"
|
||||
? {
|
||||
...base,
|
||||
createdBy: "user",
|
||||
creationSource: "server",
|
||||
type: "user_message",
|
||||
inputIntent: "turn_start",
|
||||
attachments: [],
|
||||
}
|
||||
: {
|
||||
...base,
|
||||
type: "assistant_message",
|
||||
streaming: false,
|
||||
};
|
||||
}
|
||||
|
||||
it.layer(TestLayer)("ContextHandoffService legacy import", (it) => {
|
||||
it.effect("prepares imported history for the first native v2 turn", () =>
|
||||
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: "user", id: "one", text: "What did we decide?", ordinal: 1 }),
|
||||
importedItem({
|
||||
role: "assistant",
|
||||
id: "two",
|
||||
text: "We decided to keep the migration lightweight.",
|
||||
ordinal: 2,
|
||||
}),
|
||||
],
|
||||
createdAt: DateTime.makeUnsafe("2026-01-02T00:00:00.000Z"),
|
||||
});
|
||||
|
||||
assert.equal(handoff.strategy, "manual_context");
|
||||
assert.deepStrictEqual(handoff.fromProviderThreadIds, []);
|
||||
assert.include(handoff.summaryText, "What did we decide?");
|
||||
assert.include(handoff.summaryText, "keep the migration lightweight");
|
||||
const providerMessage = providerMessageWithContextHandoff({
|
||||
handoff,
|
||||
userText: "Continue from there.",
|
||||
});
|
||||
assert.include(providerMessage, handoff.summaryText);
|
||||
assert.include(providerMessage, "User message:\nContinue from there.");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves role attribution when truncating imported history", () =>
|
||||
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: "user",
|
||||
id: "long",
|
||||
text: `${"x".repeat(35_000)} retained final words`,
|
||||
ordinal: 1,
|
||||
}),
|
||||
],
|
||||
createdAt: DateTime.makeUnsafe("2026-01-02T00:00:00.000Z"),
|
||||
});
|
||||
|
||||
assert.isAtMost(handoff.summaryText.length, 32_000);
|
||||
assert.include(handoff.summaryText, "User:\n... retained final words");
|
||||
assert.notMatch(handoff.summaryText, /\n+x+ retained final words/);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -33,6 +33,14 @@ export const ContextHandoffServiceV2Error = Schema.Union([ContextHandoffPrepareE
|
||||
export type ContextHandoffServiceV2Error = typeof ContextHandoffServiceV2Error.Type;
|
||||
|
||||
export interface ContextHandoffServiceV2Shape {
|
||||
readonly prepareLegacyImport: (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly targetRunId: RunId;
|
||||
readonly toProviderThreadId: ProviderThreadId;
|
||||
readonly toProviderInstanceId: ProviderInstanceId;
|
||||
readonly items: ReadonlyArray<OrchestrationV2TurnItem>;
|
||||
readonly createdAt: DateTime.Utc;
|
||||
}) => Effect.Effect<OrchestrationV2ContextHandoff, ContextHandoffServiceV2Error>;
|
||||
readonly prepare: (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly targetRunId: RunId;
|
||||
@@ -153,6 +161,56 @@ function makeProviderHandoffSummary(input: {
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
function makeLegacyImportSummary(items: ReadonlyArray<OrchestrationV2TurnItem>): string {
|
||||
const sections = items.flatMap((item) => {
|
||||
switch (item.type) {
|
||||
case "user_message":
|
||||
return [{ label: "User", body: item.text }];
|
||||
case "assistant_message":
|
||||
return [{ label: "Assistant", body: item.text }];
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
});
|
||||
const header =
|
||||
"Imported conversation history from the previous T3 Code orchestrator. Use it as context; do not repeat it unless the user asks.";
|
||||
const maxChars = 32_000;
|
||||
const selected: Array<string> = [];
|
||||
let remaining = maxChars - header.length - 2;
|
||||
for (const section of sections.toReversed()) {
|
||||
if (remaining <= 0) break;
|
||||
const fullSection = `${section.label}:\n${section.body}`;
|
||||
if (fullSection.length <= remaining) {
|
||||
selected.unshift(fullSection);
|
||||
remaining -= fullSection.length + 2;
|
||||
continue;
|
||||
}
|
||||
|
||||
const prefix = `${section.label}:\n... `;
|
||||
const bodyBudget = remaining - prefix.length;
|
||||
if (bodyBudget <= 0) continue;
|
||||
|
||||
const initialStart = section.body.length - bodyBudget;
|
||||
let bodyStart = Math.max(0, initialStart);
|
||||
if (
|
||||
bodyStart > 0 &&
|
||||
!/\s/.test(section.body[bodyStart - 1] ?? "") &&
|
||||
!/\s/.test(section.body[bodyStart] ?? "")
|
||||
) {
|
||||
const nextWhitespace = section.body.slice(bodyStart).search(/\s/);
|
||||
if (nextWhitespace === -1) continue;
|
||||
bodyStart += nextWhitespace;
|
||||
}
|
||||
const bodySuffix = section.body.slice(bodyStart).trimStart();
|
||||
if (bodySuffix.length === 0) continue;
|
||||
|
||||
const suffix = `${prefix}${bodySuffix}`;
|
||||
selected.unshift(suffix);
|
||||
remaining -= suffix.length + 2;
|
||||
}
|
||||
return [header, ...selected].join("\n\n");
|
||||
}
|
||||
|
||||
export function providerMessageWithContextHandoff(input: {
|
||||
readonly handoff: OrchestrationV2ContextHandoff;
|
||||
readonly userText: string;
|
||||
@@ -181,6 +239,52 @@ const makeContextHandoffService = Effect.fn("orchestrationV2.ContextHandoffServi
|
||||
function* () {
|
||||
const idAllocator = yield* IdAllocatorV2;
|
||||
|
||||
const prepareLegacyImport = Effect.fn("orchestrationV2.contextHandoff.prepareLegacyImport")(
|
||||
function* (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly targetRunId: RunId;
|
||||
readonly toProviderThreadId: ProviderThreadId;
|
||||
readonly toProviderInstanceId: ProviderInstanceId;
|
||||
readonly items: ReadonlyArray<OrchestrationV2TurnItem>;
|
||||
readonly createdAt: DateTime.Utc;
|
||||
}) {
|
||||
const handoffId = yield* idAllocator.allocate
|
||||
.contextHandoff({
|
||||
threadId: input.threadId,
|
||||
fromProviderInstanceId: ProviderInstanceId.make("legacy"),
|
||||
toProviderInstanceId: input.toProviderInstanceId,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ContextHandoffPrepareError({
|
||||
threadId: input.threadId,
|
||||
targetRunId: input.targetRunId,
|
||||
fromProviderThreadIds: [],
|
||||
toProviderThreadId: input.toProviderThreadId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return {
|
||||
id: handoffId,
|
||||
transferId: null,
|
||||
threadId: input.threadId,
|
||||
targetRunId: input.targetRunId,
|
||||
fromProviderThreadIds: [],
|
||||
toProviderThreadId: input.toProviderThreadId,
|
||||
coveredRunOrdinals: { from: 1, to: 1 },
|
||||
strategy: "manual_context",
|
||||
status: "ready",
|
||||
summaryMessageId: null,
|
||||
summaryText: makeLegacyImportSummary(input.items),
|
||||
createdByProviderInstanceId: null,
|
||||
createdAt: input.createdAt,
|
||||
updatedAt: input.createdAt,
|
||||
} satisfies OrchestrationV2ContextHandoff;
|
||||
},
|
||||
);
|
||||
|
||||
const prepare = Effect.fn("orchestrationV2.contextHandoff.prepare")(function* (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly targetRunId: RunId;
|
||||
@@ -330,6 +434,7 @@ const makeContextHandoffService = Effect.fn("orchestrationV2.ContextHandoffServi
|
||||
});
|
||||
|
||||
return ContextHandoffServiceV2.of({
|
||||
prepareLegacyImport,
|
||||
prepare,
|
||||
prepareForkDelta,
|
||||
prepareProviderHandoff,
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
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 { layer as eventStoreLayer } from "./EventStore.ts";
|
||||
import {
|
||||
LegacyV1ThreadImporter,
|
||||
layer as legacyV1ThreadImporterLayer,
|
||||
} from "./LegacyV1ThreadImporter.ts";
|
||||
import {
|
||||
ProjectionMaintenanceV2,
|
||||
layer as projectionMaintenanceLayer,
|
||||
} from "./ProjectionMaintenance.ts";
|
||||
import { ProjectionStoreV2, layer as projectionStoreLayer } from "./ProjectionStore.ts";
|
||||
|
||||
const databaseLayer = SqlitePersistenceMemory;
|
||||
const eventStoreProvided = eventStoreLayer.pipe(Layer.provideMerge(databaseLayer));
|
||||
const projectionStoreProvided = projectionStoreLayer.pipe(Layer.provideMerge(databaseLayer));
|
||||
const storesProvided = Layer.mergeAll(databaseLayer, eventStoreProvided, projectionStoreProvided);
|
||||
const eventSinkProvided = eventSinkLayer.pipe(Layer.provide(storesProvided));
|
||||
const importerProvided = legacyV1ThreadImporterLayer.pipe(
|
||||
Layer.provide(Layer.mergeAll(storesProvided, eventSinkProvided)),
|
||||
);
|
||||
const projectionMaintenanceProvided = projectionMaintenanceLayer.pipe(
|
||||
Layer.provide(storesProvided),
|
||||
);
|
||||
const TestLayer = Layer.mergeAll(
|
||||
storesProvided,
|
||||
eventSinkProvided,
|
||||
importerProvided,
|
||||
projectionMaintenanceProvided,
|
||||
);
|
||||
|
||||
it.layer(TestLayer)("LegacyV1ThreadImporter", (it) => {
|
||||
it.effect("imports lightweight shells, hydrates transcripts, and remains idempotent", () =>
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const importer = yield* LegacyV1ThreadImporter;
|
||||
const maintenance = yield* ProjectionMaintenanceV2;
|
||||
const projections = yield* ProjectionStoreV2;
|
||||
const threadId = ThreadId.make("thread:legacy-import");
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_projects (
|
||||
project_id,
|
||||
title,
|
||||
workspace_root,
|
||||
default_model_selection_json,
|
||||
scripts_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
) VALUES (
|
||||
'project:legacy-import',
|
||||
'Legacy project',
|
||||
'/tmp/legacy-project',
|
||||
'{"instanceId":"codex","model":"gpt-5.4"}',
|
||||
'[]',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'2026-01-04T00:00:00.000Z',
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
yield* sql`
|
||||
INSERT INTO projection_threads (
|
||||
thread_id,
|
||||
project_id,
|
||||
title,
|
||||
model_selection_json,
|
||||
runtime_mode,
|
||||
interaction_mode,
|
||||
branch,
|
||||
worktree_path,
|
||||
latest_turn_id,
|
||||
created_at,
|
||||
updated_at,
|
||||
archived_at,
|
||||
settled_override,
|
||||
settled_at,
|
||||
deleted_at
|
||||
) VALUES (
|
||||
${threadId},
|
||||
'project:legacy-import',
|
||||
'Migrated conversation',
|
||||
'{"instanceId":"codex","model":"gpt-5.4"}',
|
||||
'full-access',
|
||||
'default',
|
||||
'main',
|
||||
'/tmp/legacy-project',
|
||||
NULL,
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'2026-01-04T00:00:00.000Z',
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_messages (
|
||||
message_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
role,
|
||||
text,
|
||||
attachments_json,
|
||||
is_streaming,
|
||||
created_at,
|
||||
updated_at
|
||||
) VALUES
|
||||
(
|
||||
'message:legacy:1',
|
||||
${threadId},
|
||||
NULL,
|
||||
'user',
|
||||
'First question',
|
||||
'[]',
|
||||
0,
|
||||
'2026-01-01T01:00:00.000Z',
|
||||
'2026-01-01T01:00:00.000Z'
|
||||
),
|
||||
(
|
||||
'message:legacy:2',
|
||||
${threadId},
|
||||
NULL,
|
||||
'assistant',
|
||||
'First answer',
|
||||
'[]',
|
||||
0,
|
||||
'2026-01-02T01:00:00.000Z',
|
||||
'2026-01-02T01:00:00.000Z'
|
||||
),
|
||||
(
|
||||
'message:legacy:3',
|
||||
${threadId},
|
||||
NULL,
|
||||
'user',
|
||||
'Follow-up question',
|
||||
'[]',
|
||||
0,
|
||||
'2026-01-03T01:00:00.000Z',
|
||||
'2026-01-03T01:00:00.000Z'
|
||||
),
|
||||
(
|
||||
'message:legacy:4',
|
||||
${threadId},
|
||||
NULL,
|
||||
'assistant',
|
||||
'Partial answer',
|
||||
'[]',
|
||||
1,
|
||||
'2026-01-04T01:00:00.000Z',
|
||||
'2026-01-04T01:00:00.000Z'
|
||||
)
|
||||
`;
|
||||
|
||||
const shellImport = yield* importer.reconcileShells;
|
||||
assert.deepStrictEqual(shellImport, {
|
||||
importedThreadCount: 1,
|
||||
importedMessageCount: 2,
|
||||
});
|
||||
const shellEventCount = yield* sql<{ readonly count: number }>`
|
||||
SELECT COUNT(*) AS count
|
||||
FROM orchestration_events
|
||||
WHERE application_event_version = 2
|
||||
AND aggregate_kind = 'thread'
|
||||
AND stream_id = ${threadId}
|
||||
`;
|
||||
assert.equal(shellEventCount[0]?.count, 6);
|
||||
|
||||
const rebuilt = yield* maintenance.rebuild;
|
||||
assert.isTrue(rebuilt.valid);
|
||||
const shellProjection = yield* projections.getThreadProjection(threadId);
|
||||
assert.equal(shellProjection.thread.historyOrigin, "v1_import");
|
||||
const shellSnapshot = yield* projections.getShellSnapshot();
|
||||
assert.equal(
|
||||
shellSnapshot.threads.find((thread) => thread.id === threadId)?.historyOrigin,
|
||||
"v1_import",
|
||||
);
|
||||
assert.deepStrictEqual(
|
||||
shellProjection.messages.map((message) => message.id),
|
||||
["message:legacy:3", "message:legacy:4"],
|
||||
);
|
||||
|
||||
const transcriptImport = yield* importer.ensureTranscript(threadId);
|
||||
assert.deepStrictEqual(transcriptImport, {
|
||||
importedThreadCount: 1,
|
||||
importedMessageCount: 2,
|
||||
});
|
||||
const projection = yield* projections.getThreadProjection(threadId);
|
||||
assert.deepStrictEqual(
|
||||
projection.messages.map((message) => message.id),
|
||||
["message:legacy:1", "message:legacy:2", "message:legacy:3", "message:legacy:4"],
|
||||
);
|
||||
assert.deepStrictEqual(
|
||||
projection.turnItems
|
||||
.filter(
|
||||
(
|
||||
item,
|
||||
): item is Extract<
|
||||
(typeof projection.turnItems)[number],
|
||||
{ readonly type: "user_message" | "assistant_message" }
|
||||
> => item.type === "user_message" || item.type === "assistant_message",
|
||||
)
|
||||
.map((item) => [item.messageId, item.ordinal, item.status]),
|
||||
[
|
||||
["message:legacy:1", 1, "completed"],
|
||||
["message:legacy:2", 2, "completed"],
|
||||
["message:legacy:3", 3, "completed"],
|
||||
["message:legacy:4", 4, "interrupted"],
|
||||
],
|
||||
);
|
||||
|
||||
const eventCountBeforeRetry = yield* sql<{ readonly count: number }>`
|
||||
SELECT COUNT(*) AS count
|
||||
FROM orchestration_events
|
||||
WHERE application_event_version = 2
|
||||
AND aggregate_kind = 'thread'
|
||||
AND stream_id = ${threadId}
|
||||
`;
|
||||
assert.deepStrictEqual(yield* importer.reconcileShells, {
|
||||
importedThreadCount: 0,
|
||||
importedMessageCount: 0,
|
||||
});
|
||||
assert.deepStrictEqual(yield* importer.ensureTranscript(threadId), {
|
||||
importedThreadCount: 0,
|
||||
importedMessageCount: 0,
|
||||
});
|
||||
const eventCountAfterRetry = yield* sql<{ readonly count: number }>`
|
||||
SELECT COUNT(*) AS count
|
||||
FROM orchestration_events
|
||||
WHERE application_event_version = 2
|
||||
AND aggregate_kind = 'thread'
|
||||
AND stream_id = ${threadId}
|
||||
`;
|
||||
assert.equal(eventCountAfterRetry[0]?.count, eventCountBeforeRetry[0]?.count);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,639 @@
|
||||
import {
|
||||
ChatAttachment,
|
||||
DEFAULT_MODEL,
|
||||
EventId,
|
||||
MessageId,
|
||||
ModelSelection,
|
||||
type OrchestrationV2AppThread,
|
||||
type OrchestrationV2ConversationMessage,
|
||||
type OrchestrationV2DomainEvent,
|
||||
type OrchestrationV2TurnItem,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
TurnItemId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { EventSinkV2 } from "./EventSink.ts";
|
||||
import { EventStoreV2 } from "./EventStore.ts";
|
||||
import { makeKeyedSerialExecutor } from "./KeyedSerialExecutor.ts";
|
||||
|
||||
const IMPORT_EVENT_PREFIX = "migration:v1";
|
||||
const TRANSCRIPT_EVENT_BATCH_SIZE = 100;
|
||||
|
||||
interface LegacyThreadRow {
|
||||
readonly thread_id: string;
|
||||
readonly project_id: string;
|
||||
readonly title: string;
|
||||
readonly model_selection_json: string | null;
|
||||
readonly runtime_mode: string;
|
||||
readonly interaction_mode: string;
|
||||
readonly branch: string | null;
|
||||
readonly worktree_path: string | null;
|
||||
readonly created_at: string;
|
||||
readonly updated_at: string;
|
||||
readonly archived_at: string | null;
|
||||
readonly settled_override: string | null;
|
||||
readonly settled_at: string | null;
|
||||
readonly deleted_at: string | null;
|
||||
}
|
||||
|
||||
interface LegacyMessageRow {
|
||||
readonly message_id: string;
|
||||
readonly thread_id: string;
|
||||
readonly role: "user" | "assistant";
|
||||
readonly text: string;
|
||||
readonly attachments_json: string | null;
|
||||
readonly is_streaming: number;
|
||||
readonly created_at: string;
|
||||
readonly updated_at: string;
|
||||
readonly ordinal: number;
|
||||
}
|
||||
|
||||
interface LegacyImportRow {
|
||||
readonly thread_id: string;
|
||||
readonly transcript_imported_at: string | null;
|
||||
}
|
||||
|
||||
export interface LegacyV1ImportSummary {
|
||||
readonly importedThreadCount: number;
|
||||
readonly importedMessageCount: number;
|
||||
}
|
||||
|
||||
export class LegacyV1ThreadImportError extends Schema.TaggedErrorClass<LegacyV1ThreadImportError>()(
|
||||
"LegacyV1ThreadImportError",
|
||||
{
|
||||
operation: Schema.String,
|
||||
threadId: Schema.optional(ThreadId),
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return this.threadId === undefined
|
||||
? `Failed to ${this.operation} legacy v1 threads.`
|
||||
: `Failed to ${this.operation} legacy v1 thread ${this.threadId}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface LegacyV1ThreadImporterShape {
|
||||
readonly reconcileShells: Effect.Effect<LegacyV1ImportSummary, LegacyV1ThreadImportError>;
|
||||
readonly ensureTranscript: (
|
||||
threadId: ThreadId,
|
||||
) => Effect.Effect<LegacyV1ImportSummary, LegacyV1ThreadImportError>;
|
||||
readonly importPendingTranscripts: Effect.Effect<LegacyV1ImportSummary, never>;
|
||||
}
|
||||
|
||||
export class LegacyV1ThreadImporter extends Context.Service<
|
||||
LegacyV1ThreadImporter,
|
||||
LegacyV1ThreadImporterShape
|
||||
>()("t3/orchestration-v2/LegacyV1ThreadImporter") {}
|
||||
|
||||
const decodeModelSelection = Schema.decodeUnknownOption(ModelSelection);
|
||||
const decodeAttachments = Schema.decodeUnknownOption(Schema.Array(ChatAttachment));
|
||||
|
||||
function parseJson(json: string): unknown {
|
||||
try {
|
||||
return JSON.parse(json);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function modelSelectionFor(row: LegacyThreadRow) {
|
||||
const decoded =
|
||||
row.model_selection_json === null
|
||||
? Option.none()
|
||||
: decodeModelSelection(parseJson(row.model_selection_json));
|
||||
return Option.getOrElse(decoded, () => ({
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: DEFAULT_MODEL,
|
||||
}));
|
||||
}
|
||||
|
||||
function attachmentsFor(row: LegacyMessageRow) {
|
||||
if (row.attachments_json === null) return [];
|
||||
return Option.getOrElse(decodeAttachments(parseJson(row.attachments_json)), () => []);
|
||||
}
|
||||
|
||||
function runtimeModeFor(value: string): OrchestrationV2AppThread["runtimeMode"] {
|
||||
return value === "approval-required" ||
|
||||
value === "auto-accept-edits" ||
|
||||
value === "auto" ||
|
||||
value === "full-access"
|
||||
? value
|
||||
: "full-access";
|
||||
}
|
||||
|
||||
function interactionModeFor(value: string): OrchestrationV2AppThread["interactionMode"] {
|
||||
return value === "plan" ? "plan" : "default";
|
||||
}
|
||||
|
||||
function settledOverrideFor(value: string | null): OrchestrationV2AppThread["settledOverride"] {
|
||||
return value === "settled" || value === "active" ? value : null;
|
||||
}
|
||||
|
||||
function dateTime(value: string): DateTime.Utc {
|
||||
return DateTime.makeUnsafe(value);
|
||||
}
|
||||
|
||||
function nullableDateTime(value: string | null): DateTime.Utc | null {
|
||||
return value === null ? null : dateTime(value);
|
||||
}
|
||||
|
||||
function importedThread(row: LegacyThreadRow): OrchestrationV2AppThread {
|
||||
const threadId = ThreadId.make(row.thread_id);
|
||||
const modelSelection = modelSelectionFor(row);
|
||||
return {
|
||||
createdBy: "system",
|
||||
creationSource: "server",
|
||||
id: threadId,
|
||||
projectId: ProjectId.make(row.project_id),
|
||||
title: row.title.trim() === "" ? "Untitled thread" : row.title,
|
||||
providerInstanceId: modelSelection.instanceId,
|
||||
modelSelection,
|
||||
runtimeMode: runtimeModeFor(row.runtime_mode),
|
||||
interactionMode: interactionModeFor(row.interaction_mode),
|
||||
branch: row.branch?.trim() ? row.branch : null,
|
||||
worktreePath: row.worktree_path?.trim() ? row.worktree_path : null,
|
||||
activeProviderThreadId: null,
|
||||
historyOrigin: "v1_import",
|
||||
lineage: {
|
||||
parentThreadId: null,
|
||||
relationshipToParent: null,
|
||||
rootThreadId: threadId,
|
||||
},
|
||||
forkedFrom: null,
|
||||
createdAt: dateTime(row.created_at),
|
||||
updatedAt: dateTime(row.updated_at),
|
||||
archivedAt: nullableDateTime(row.archived_at),
|
||||
settledOverride: settledOverrideFor(row.settled_override),
|
||||
settledAt: nullableDateTime(row.settled_at),
|
||||
deletedAt: nullableDateTime(row.deleted_at),
|
||||
};
|
||||
}
|
||||
|
||||
function messageEvents(row: LegacyMessageRow): ReadonlyArray<OrchestrationV2DomainEvent> {
|
||||
const threadId = ThreadId.make(row.thread_id);
|
||||
const messageId = MessageId.make(row.message_id);
|
||||
const createdAt = dateTime(row.created_at);
|
||||
const updatedAt = dateTime(row.updated_at);
|
||||
const attachments = attachmentsFor(row);
|
||||
const message: OrchestrationV2ConversationMessage = {
|
||||
createdBy: row.role === "user" ? "user" : "agent",
|
||||
creationSource: "server",
|
||||
id: messageId,
|
||||
threadId,
|
||||
runId: null,
|
||||
nodeId: null,
|
||||
role: row.role,
|
||||
text: row.text,
|
||||
attachments,
|
||||
streaming: false,
|
||||
createdAt,
|
||||
updatedAt,
|
||||
};
|
||||
const baseTurnItem = {
|
||||
id: TurnItemId.make(`${IMPORT_EVENT_PREFIX}:turn-item:${row.message_id}`),
|
||||
threadId,
|
||||
runId: null,
|
||||
nodeId: null,
|
||||
providerThreadId: null,
|
||||
providerTurnId: null,
|
||||
nativeItemRef: null,
|
||||
parentItemId: null,
|
||||
ordinal: row.ordinal,
|
||||
status: row.is_streaming === 1 ? ("interrupted" as const) : ("completed" as const),
|
||||
title: null,
|
||||
startedAt: createdAt,
|
||||
completedAt: updatedAt,
|
||||
updatedAt,
|
||||
};
|
||||
const turnItem: OrchestrationV2TurnItem =
|
||||
row.role === "user"
|
||||
? {
|
||||
...baseTurnItem,
|
||||
createdBy: "user",
|
||||
creationSource: "server",
|
||||
type: "user_message",
|
||||
messageId,
|
||||
inputIntent: "turn_start",
|
||||
text: row.text,
|
||||
attachments,
|
||||
}
|
||||
: {
|
||||
...baseTurnItem,
|
||||
type: "assistant_message",
|
||||
messageId,
|
||||
text: row.text,
|
||||
streaming: false,
|
||||
};
|
||||
return [
|
||||
{
|
||||
id: EventId.make(`${IMPORT_EVENT_PREFIX}:message:${row.message_id}`),
|
||||
type: "message.updated",
|
||||
threadId,
|
||||
occurredAt: updatedAt,
|
||||
payload: message,
|
||||
},
|
||||
{
|
||||
id: EventId.make(`${IMPORT_EVENT_PREFIX}:turn-item:${row.message_id}`),
|
||||
type: "turn-item.updated",
|
||||
threadId,
|
||||
occurredAt: updatedAt,
|
||||
payload: turnItem,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function chunks<A>(items: ReadonlyArray<A>, size: number): Array<ReadonlyArray<A>> {
|
||||
const result: Array<ReadonlyArray<A>> = [];
|
||||
for (let index = 0; index < items.length; index += size) {
|
||||
result.push(items.slice(index, index + size));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const eventStore = yield* EventStoreV2;
|
||||
const eventSink = yield* EventSinkV2;
|
||||
const transcriptImports = yield* makeKeyedSerialExecutor<ThreadId>();
|
||||
|
||||
const listMessages = (threadId: ThreadId) =>
|
||||
sql<LegacyMessageRow>`
|
||||
SELECT
|
||||
message_id,
|
||||
thread_id,
|
||||
role,
|
||||
text,
|
||||
attachments_json,
|
||||
is_streaming,
|
||||
created_at,
|
||||
updated_at,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY thread_id
|
||||
ORDER BY created_at ASC, message_id ASC
|
||||
) AS ordinal
|
||||
FROM projection_thread_messages
|
||||
WHERE thread_id = ${threadId}
|
||||
AND role IN ('user', 'assistant')
|
||||
ORDER BY created_at ASC, message_id ASC
|
||||
`;
|
||||
|
||||
const listShellMessages = (threadId: ThreadId) =>
|
||||
Effect.gen(function* () {
|
||||
const latest = yield* sql<LegacyMessageRow>`
|
||||
SELECT
|
||||
message.message_id,
|
||||
message.thread_id,
|
||||
message.role,
|
||||
message.text,
|
||||
message.attachments_json,
|
||||
message.is_streaming,
|
||||
message.created_at,
|
||||
message.updated_at,
|
||||
(
|
||||
SELECT COUNT(*)
|
||||
FROM projection_thread_messages AS earlier
|
||||
WHERE earlier.thread_id = message.thread_id
|
||||
AND earlier.role IN ('user', 'assistant')
|
||||
AND (
|
||||
earlier.created_at < message.created_at
|
||||
OR (
|
||||
earlier.created_at = message.created_at
|
||||
AND earlier.message_id <= message.message_id
|
||||
)
|
||||
)
|
||||
) AS ordinal
|
||||
FROM projection_thread_messages AS message
|
||||
WHERE message.thread_id = ${threadId}
|
||||
AND message.role IN ('user', 'assistant')
|
||||
ORDER BY message.created_at DESC, message.message_id DESC
|
||||
LIMIT 1
|
||||
`;
|
||||
const latestUser = yield* sql<LegacyMessageRow>`
|
||||
SELECT
|
||||
message.message_id,
|
||||
message.thread_id,
|
||||
message.role,
|
||||
message.text,
|
||||
message.attachments_json,
|
||||
message.is_streaming,
|
||||
message.created_at,
|
||||
message.updated_at,
|
||||
(
|
||||
SELECT COUNT(*)
|
||||
FROM projection_thread_messages AS earlier
|
||||
WHERE earlier.thread_id = message.thread_id
|
||||
AND earlier.role IN ('user', 'assistant')
|
||||
AND (
|
||||
earlier.created_at < message.created_at
|
||||
OR (
|
||||
earlier.created_at = message.created_at
|
||||
AND earlier.message_id <= message.message_id
|
||||
)
|
||||
)
|
||||
) AS ordinal
|
||||
FROM projection_thread_messages AS message
|
||||
WHERE message.thread_id = ${threadId}
|
||||
AND message.role = 'user'
|
||||
ORDER BY message.created_at DESC, message.message_id DESC
|
||||
LIMIT 1
|
||||
`;
|
||||
return [latestUser[0], latest[0]].filter(
|
||||
(message, index, selected): message is LegacyMessageRow =>
|
||||
message !== undefined &&
|
||||
selected.findIndex((candidate) => candidate?.message_id === message.message_id) === index,
|
||||
);
|
||||
});
|
||||
|
||||
const reconcileShellsBase = Effect.gen(function* () {
|
||||
const now = DateTime.formatIso(yield* DateTime.now);
|
||||
const rows = yield* sql<LegacyThreadRow>`
|
||||
SELECT
|
||||
thread.thread_id,
|
||||
thread.project_id,
|
||||
thread.title,
|
||||
thread.model_selection_json,
|
||||
thread.runtime_mode,
|
||||
thread.interaction_mode,
|
||||
thread.branch,
|
||||
thread.worktree_path,
|
||||
thread.created_at,
|
||||
thread.updated_at,
|
||||
thread.archived_at,
|
||||
thread.settled_override,
|
||||
thread.settled_at,
|
||||
thread.deleted_at
|
||||
FROM projection_threads AS thread
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM orchestration_events AS event
|
||||
WHERE event.application_event_version = 2
|
||||
AND event.aggregate_kind = 'thread'
|
||||
AND event.stream_id = thread.thread_id
|
||||
AND event.event_type = 'thread.created'
|
||||
)
|
||||
ORDER BY thread.created_at ASC, thread.thread_id ASC
|
||||
`;
|
||||
let importedThreadCount = 0;
|
||||
let importedMessageCount = 0;
|
||||
for (const row of rows) {
|
||||
const thread = importedThread(row);
|
||||
const previews = yield* listShellMessages(thread.id);
|
||||
const events: Array<OrchestrationV2DomainEvent> = [
|
||||
{
|
||||
id: EventId.make(`${IMPORT_EVENT_PREFIX}:thread:${row.thread_id}:created`),
|
||||
type: "thread.created",
|
||||
threadId: thread.id,
|
||||
providerInstanceId: thread.providerInstanceId,
|
||||
occurredAt: thread.createdAt,
|
||||
payload: thread,
|
||||
},
|
||||
...previews.flatMap(messageEvents),
|
||||
{
|
||||
id: EventId.make(`${IMPORT_EVENT_PREFIX}:thread:${row.thread_id}:shell`),
|
||||
type: "thread.metadata-updated",
|
||||
threadId: thread.id,
|
||||
providerInstanceId: thread.providerInstanceId,
|
||||
occurredAt: thread.updatedAt,
|
||||
payload: thread,
|
||||
},
|
||||
];
|
||||
yield* sql.withTransaction(
|
||||
Effect.gen(function* () {
|
||||
yield* eventStore.append({ events });
|
||||
yield* Effect.forEach(
|
||||
previews,
|
||||
(message) =>
|
||||
sql`
|
||||
INSERT INTO orchestration_v2_turn_item_positions (
|
||||
thread_id,
|
||||
turn_item_id,
|
||||
ordinal
|
||||
)
|
||||
VALUES (
|
||||
${thread.id},
|
||||
${TurnItemId.make(`${IMPORT_EVENT_PREFIX}:turn-item:${message.message_id}`)},
|
||||
${message.ordinal}
|
||||
)
|
||||
ON CONFLICT(thread_id, turn_item_id) DO NOTHING
|
||||
`,
|
||||
{ discard: true },
|
||||
);
|
||||
yield* sql`
|
||||
INSERT INTO orchestration_v2_legacy_imports (
|
||||
thread_id,
|
||||
source_updated_at,
|
||||
shell_imported_at,
|
||||
transcript_imported_at,
|
||||
imported_message_count,
|
||||
last_error
|
||||
)
|
||||
VALUES (
|
||||
${thread.id},
|
||||
${row.updated_at},
|
||||
${now},
|
||||
NULL,
|
||||
${previews.length},
|
||||
NULL
|
||||
)
|
||||
ON CONFLICT(thread_id) DO NOTHING
|
||||
`;
|
||||
}),
|
||||
);
|
||||
importedThreadCount += 1;
|
||||
importedMessageCount += previews.length;
|
||||
}
|
||||
return { importedThreadCount, importedMessageCount };
|
||||
});
|
||||
|
||||
const reconcileShells = reconcileShellsBase.pipe(
|
||||
Effect.mapError((cause) => new LegacyV1ThreadImportError({ operation: "import", cause })),
|
||||
);
|
||||
|
||||
const ensureTranscriptBase = (threadId: ThreadId) =>
|
||||
transcriptImports.withLock(
|
||||
threadId,
|
||||
Effect.gen(function* () {
|
||||
const imports = yield* sql<LegacyImportRow>`
|
||||
SELECT thread_id, transcript_imported_at
|
||||
FROM orchestration_v2_legacy_imports
|
||||
WHERE thread_id = ${threadId}
|
||||
LIMIT 1
|
||||
`;
|
||||
const imported = imports[0];
|
||||
if (imported === undefined || imported.transcript_imported_at !== null) {
|
||||
return { importedThreadCount: 0, importedMessageCount: 0 };
|
||||
}
|
||||
const messages = yield* listMessages(threadId);
|
||||
const existingRows = yield* sql<{ readonly event_id: string }>`
|
||||
SELECT event_id
|
||||
FROM orchestration_events
|
||||
WHERE application_event_version = 2
|
||||
AND aggregate_kind = 'thread'
|
||||
AND stream_id = ${threadId}
|
||||
AND event_id LIKE ${`${IMPORT_EVENT_PREFIX}:message:%`}
|
||||
`;
|
||||
const existing = new Set(existingRows.map((row) => row.event_id));
|
||||
const missing = messages.filter(
|
||||
(message) => !existing.has(`${IMPORT_EVENT_PREFIX}:message:${message.message_id}`),
|
||||
);
|
||||
for (const batch of chunks(missing, TRANSCRIPT_EVENT_BATCH_SIZE / 2)) {
|
||||
yield* Effect.forEach(
|
||||
batch,
|
||||
(message) =>
|
||||
sql`
|
||||
INSERT INTO orchestration_v2_turn_item_positions (
|
||||
thread_id,
|
||||
turn_item_id,
|
||||
ordinal
|
||||
)
|
||||
VALUES (
|
||||
${threadId},
|
||||
${TurnItemId.make(`${IMPORT_EVENT_PREFIX}:turn-item:${message.message_id}`)},
|
||||
${message.ordinal}
|
||||
)
|
||||
ON CONFLICT(thread_id, turn_item_id) DO NOTHING
|
||||
`,
|
||||
{ discard: true },
|
||||
);
|
||||
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
|
||||
SET
|
||||
transcript_imported_at = ${now},
|
||||
imported_message_count = ${messages.length},
|
||||
last_error = NULL
|
||||
WHERE thread_id = ${threadId}
|
||||
`;
|
||||
return {
|
||||
importedThreadCount: 1,
|
||||
importedMessageCount: missing.length,
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
const ensureTranscript = (threadId: ThreadId) =>
|
||||
ensureTranscriptBase(threadId).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new LegacyV1ThreadImportError({
|
||||
operation: "hydrate transcript for",
|
||||
threadId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const importPendingTranscripts = Effect.gen(function* () {
|
||||
const rows = yield* sql<LegacyImportRow>`
|
||||
SELECT thread_id, transcript_imported_at
|
||||
FROM orchestration_v2_legacy_imports
|
||||
WHERE transcript_imported_at IS NULL
|
||||
ORDER BY shell_imported_at ASC, thread_id ASC
|
||||
`;
|
||||
let importedThreadCount = 0;
|
||||
let importedMessageCount = 0;
|
||||
for (const row of rows) {
|
||||
const result = yield* ensureTranscript(ThreadId.make(row.thread_id)).pipe(
|
||||
Effect.tapError((error) =>
|
||||
Effect.logWarning("Failed to hydrate migrated v1 thread transcript", {
|
||||
threadId: row.thread_id,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
Effect.catch(() =>
|
||||
sql`
|
||||
UPDATE orchestration_v2_legacy_imports
|
||||
SET last_error = 'Transcript hydration failed; retry on next open.'
|
||||
WHERE thread_id = ${row.thread_id}
|
||||
`.pipe(
|
||||
Effect.as({ importedThreadCount: 0, importedMessageCount: 0 }),
|
||||
Effect.orElseSucceed(() => ({
|
||||
importedThreadCount: 0,
|
||||
importedMessageCount: 0,
|
||||
})),
|
||||
),
|
||||
),
|
||||
);
|
||||
importedThreadCount += result.importedThreadCount;
|
||||
importedMessageCount += result.importedMessageCount;
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
return { importedThreadCount, importedMessageCount };
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("Legacy v1 transcript background import stopped", { cause }).pipe(
|
||||
Effect.as({ importedThreadCount: 0, importedMessageCount: 0 }),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return LegacyV1ThreadImporter.of({
|
||||
reconcileShells,
|
||||
ensureTranscript,
|
||||
importPendingTranscripts,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer: Layer.Layer<
|
||||
LegacyV1ThreadImporter,
|
||||
never,
|
||||
EventSinkV2 | EventStoreV2 | SqlClient.SqlClient
|
||||
> = Layer.effect(LegacyV1ThreadImporter, make);
|
||||
@@ -0,0 +1,49 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { ContextHandoffId } from "@t3tools/contracts";
|
||||
|
||||
import { appendContextHandoffId, shouldPrepareLegacyImportHandoff } from "./Orchestrator.ts";
|
||||
|
||||
it("reissues imported context until the provider thread is materialized", () => {
|
||||
assert.isTrue(
|
||||
shouldPrepareLegacyImportHandoff({
|
||||
historyOrigin: "v1_import",
|
||||
hasNativeThreadRef: false,
|
||||
legacyImportItemCount: 2,
|
||||
}),
|
||||
);
|
||||
assert.isFalse(
|
||||
shouldPrepareLegacyImportHandoff({
|
||||
historyOrigin: "v1_import",
|
||||
hasNativeThreadRef: true,
|
||||
legacyImportItemCount: 2,
|
||||
}),
|
||||
);
|
||||
assert.isFalse(
|
||||
shouldPrepareLegacyImportHandoff({
|
||||
historyOrigin: undefined,
|
||||
hasNativeThreadRef: false,
|
||||
legacyImportItemCount: 2,
|
||||
}),
|
||||
);
|
||||
assert.isFalse(
|
||||
shouldPrepareLegacyImportHandoff({
|
||||
historyOrigin: "v1_import",
|
||||
hasNativeThreadRef: false,
|
||||
legacyImportItemCount: 0,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("records a reissued legacy handoff on an existing provider thread", () => {
|
||||
const existingHandoffId = ContextHandoffId.make("handoff:legacy-import:existing");
|
||||
const retryHandoffId = ContextHandoffId.make("handoff:legacy-import:retry");
|
||||
|
||||
assert.deepEqual(appendContextHandoffId([existingHandoffId], retryHandoffId), [
|
||||
existingHandoffId,
|
||||
retryHandoffId,
|
||||
]);
|
||||
assert.deepEqual(appendContextHandoffId([existingHandoffId], existingHandoffId), [
|
||||
existingHandoffId,
|
||||
]);
|
||||
assert.deepEqual(appendContextHandoffId([existingHandoffId], null), [existingHandoffId]);
|
||||
});
|
||||
@@ -42,7 +42,12 @@ import { EventSinkV2 } from "./EventSink.ts";
|
||||
import type { OrchestrationEffectRequestV2, PendingOrchestrationEffectV2 } from "./EffectOutbox.ts";
|
||||
import { IdAllocatorV2 } from "./IdAllocator.ts";
|
||||
import { makeKeyedSerialExecutor } from "./KeyedSerialExecutor.ts";
|
||||
import { applyToProjection, emptyProjection, ProjectionStoreV2 } from "./ProjectionStore.ts";
|
||||
import {
|
||||
applyToProjection,
|
||||
emptyProjection,
|
||||
isTurnItemAtOrBeforeRun,
|
||||
ProjectionStoreV2,
|
||||
} from "./ProjectionStore.ts";
|
||||
import type { ProviderAdapterV2Shape } from "./ProviderAdapter.ts";
|
||||
import { ProviderAdapterRegistryV2 } from "./ProviderAdapterRegistry.ts";
|
||||
import {
|
||||
@@ -438,6 +443,25 @@ function visibleDeltaRunOrdinals(
|
||||
};
|
||||
}
|
||||
|
||||
export function shouldPrepareLegacyImportHandoff(input: {
|
||||
readonly hasNativeThreadRef: boolean;
|
||||
readonly historyOrigin: OrchestrationV2AppThread["historyOrigin"];
|
||||
readonly legacyImportItemCount: number;
|
||||
}): boolean {
|
||||
return (
|
||||
input.historyOrigin === "v1_import" &&
|
||||
!input.hasNativeThreadRef &&
|
||||
input.legacyImportItemCount > 0
|
||||
);
|
||||
}
|
||||
|
||||
export function appendContextHandoffId(
|
||||
handoffIds: OrchestrationV2ProviderThread["handoffIds"],
|
||||
handoffId: OrchestrationV2ContextHandoff["id"] | null,
|
||||
): OrchestrationV2ProviderThread["handoffIds"] {
|
||||
return handoffId === null ? handoffIds : Array.from(new Set([...handoffIds, handoffId]));
|
||||
}
|
||||
|
||||
function rootProviderThreadsForProvider(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
providerInstanceId: ModelSelection["instanceId"],
|
||||
@@ -2376,6 +2400,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
const ordinal = nextRunOrdinal(projection);
|
||||
const runId = idAllocator.derive.run({ threadId: command.threadId, ordinal });
|
||||
const latestCompletedRun = projection.runs.findLast((run) => run.status === "completed");
|
||||
const legacyImportItems =
|
||||
projection.thread.historyOrigin === "v1_import"
|
||||
? projection.turnItems.filter((item) => item.runId === null)
|
||||
: [];
|
||||
const isProviderSwitch =
|
||||
activeProviderThread !== undefined &&
|
||||
activeProviderThread.providerInstanceId !== modelSelection.instanceId;
|
||||
@@ -2410,6 +2438,23 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
driver: adapter.driver,
|
||||
nativeThreadId: `pending:${runId}`,
|
||||
});
|
||||
const legacyImportHandoff = shouldPrepareLegacyImportHandoff({
|
||||
historyOrigin: projection.thread.historyOrigin,
|
||||
hasNativeThreadRef:
|
||||
activeProviderThread !== undefined && activeProviderThread.nativeThreadRef !== null,
|
||||
legacyImportItemCount: legacyImportItems.length,
|
||||
})
|
||||
? yield* contextHandoffService
|
||||
.prepareLegacyImport({
|
||||
threadId: command.threadId,
|
||||
targetRunId: runId,
|
||||
toProviderThreadId: providerThreadId,
|
||||
toProviderInstanceId: modelSelection.instanceId,
|
||||
items: legacyImportItems,
|
||||
createdAt: now,
|
||||
})
|
||||
.pipe(mapDispatchError(command))
|
||||
: null;
|
||||
const providerThread: OrchestrationV2ProviderThread =
|
||||
activeProviderThread === undefined
|
||||
? {
|
||||
@@ -2424,7 +2469,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
status: "not_loaded",
|
||||
firstRunOrdinal: ordinal,
|
||||
lastRunOrdinal: ordinal,
|
||||
handoffIds: [],
|
||||
handoffIds: legacyImportHandoff === null ? [] : [legacyImportHandoff.id],
|
||||
forkedFrom: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -2433,6 +2478,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
...activeProviderThread,
|
||||
providerSessionId,
|
||||
lastRunOrdinal: ordinal,
|
||||
handoffIds: appendContextHandoffId(
|
||||
activeProviderThread.handoffIds,
|
||||
legacyImportHandoff?.id ?? null,
|
||||
),
|
||||
updatedAt: now,
|
||||
};
|
||||
const attemptId = idAllocator.derive.runAttempt({ runId, attemptOrdinal: 1 });
|
||||
@@ -2478,7 +2527,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
startedAt: null,
|
||||
completedAt: null,
|
||||
checkpointId: null,
|
||||
contextHandoffId: null,
|
||||
contextHandoffId: legacyImportHandoff?.id ?? null,
|
||||
...(command.sourcePlanRef === undefined ? {} : { sourcePlanRef: command.sourcePlanRef }),
|
||||
};
|
||||
const attempt: OrchestrationV2RunAttempt = {
|
||||
@@ -2581,6 +2630,16 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
occurredAt: now,
|
||||
payload: providerThread,
|
||||
});
|
||||
if (legacyImportHandoff !== null) {
|
||||
yield* emitEvent({
|
||||
type: "context-handoff.updated",
|
||||
threadId: command.threadId,
|
||||
runId,
|
||||
providerInstanceId: modelSelection.instanceId,
|
||||
occurredAt: now,
|
||||
payload: legacyImportHandoff,
|
||||
});
|
||||
}
|
||||
yield* emitEvent({
|
||||
type: "run.created",
|
||||
threadId: command.threadId,
|
||||
@@ -2822,18 +2881,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
providerSessionId,
|
||||
updatedAt: now,
|
||||
};
|
||||
const sourceRunOrdinalById = new Map(
|
||||
(sourceProjection?.runs ?? []).map((run) => [run.id, run.ordinal]),
|
||||
);
|
||||
const portableForkItems =
|
||||
!requiresPortableFork || sourceProjection === null || sourceRun === null
|
||||
? []
|
||||
: sourceProjection.turnItems.filter((item) => {
|
||||
if (item.runId === null) {
|
||||
return false;
|
||||
}
|
||||
const itemRun = sourceProjection.runs.find(
|
||||
(candidate) => candidate.id === item.runId,
|
||||
);
|
||||
return itemRun !== undefined && itemRun.ordinal <= sourceRun.ordinal;
|
||||
});
|
||||
: sourceProjection.turnItems.filter((item) =>
|
||||
isTurnItemAtOrBeforeRun({
|
||||
historyOrigin: sourceProjection.thread.historyOrigin,
|
||||
itemRunId: item.runId,
|
||||
runOrdinalById: sourceRunOrdinalById,
|
||||
sourceRunOrdinal: sourceRun.ordinal,
|
||||
}),
|
||||
);
|
||||
const portableForkHandoff =
|
||||
!requiresPortableFork ||
|
||||
pendingForkTransfer === undefined ||
|
||||
@@ -2882,11 +2943,16 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
const providerSwitchItems =
|
||||
providerSwitchCoveredRuns.length === 0
|
||||
? []
|
||||
: projection.turnItems.filter(
|
||||
(item) =>
|
||||
item.runId !== null &&
|
||||
providerSwitchCoveredRuns.some((run) => run.id === item.runId),
|
||||
);
|
||||
: [
|
||||
...(targetProviderThread === undefined || requiresFullProviderSwitchContext
|
||||
? legacyImportItems
|
||||
: []),
|
||||
...projection.turnItems.filter(
|
||||
(item) =>
|
||||
item.runId !== null &&
|
||||
providerSwitchCoveredRuns.some((run) => run.id === item.runId),
|
||||
),
|
||||
];
|
||||
const providerSwitchTransferId =
|
||||
providerSwitchCoveredRuns.length === 0 || latestCompletedRun === undefined
|
||||
? null
|
||||
@@ -2950,6 +3016,19 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
}),
|
||||
),
|
||||
);
|
||||
const legacyImportRecoveryHandoff =
|
||||
isProviderSwitch && latestCompletedRun === undefined && legacyImportItems.length > 0
|
||||
? yield* contextHandoffService
|
||||
.prepareLegacyImport({
|
||||
threadId: command.threadId,
|
||||
targetRunId: runId,
|
||||
toProviderThreadId: ensuredProviderThread.id,
|
||||
toProviderInstanceId: modelSelection.instanceId,
|
||||
items: legacyImportItems,
|
||||
createdAt: now,
|
||||
})
|
||||
.pipe(mapDispatchError(command))
|
||||
: null;
|
||||
const providerThread: OrchestrationV2ProviderThread = {
|
||||
...ensuredProviderThread,
|
||||
status: "active",
|
||||
@@ -2957,8 +3036,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
lastRunOrdinal: ordinal,
|
||||
handoffIds: [
|
||||
...ensuredProviderThread.handoffIds,
|
||||
...[portableForkHandoff, providerSwitchHandoff].flatMap((handoff) =>
|
||||
handoff === null ? [] : [handoff.id],
|
||||
...[portableForkHandoff, providerSwitchHandoff, legacyImportRecoveryHandoff].flatMap(
|
||||
(handoff) => (handoff === null ? [] : [handoff.id]),
|
||||
),
|
||||
],
|
||||
updatedAt: now,
|
||||
@@ -3102,7 +3181,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
completedAt: null,
|
||||
checkpointId: null,
|
||||
contextHandoffId:
|
||||
portableForkHandoff?.id ?? providerSwitchHandoff?.id ?? mergeBackHandoff?.id ?? null,
|
||||
portableForkHandoff?.id ??
|
||||
providerSwitchHandoff?.id ??
|
||||
mergeBackHandoff?.id ??
|
||||
legacyImportRecoveryHandoff?.id ??
|
||||
null,
|
||||
...(command.sourcePlanRef === undefined ? {} : { sourcePlanRef: command.sourcePlanRef }),
|
||||
};
|
||||
const attempt: OrchestrationV2RunAttempt = {
|
||||
@@ -3294,6 +3377,16 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
payload: portableForkHandoff,
|
||||
});
|
||||
}
|
||||
if (legacyImportRecoveryHandoff !== null) {
|
||||
yield* emitEvent({
|
||||
type: "context-handoff.updated",
|
||||
threadId: command.threadId,
|
||||
runId,
|
||||
providerInstanceId: modelSelection.instanceId,
|
||||
occurredAt: now,
|
||||
payload: legacyImportRecoveryHandoff,
|
||||
});
|
||||
}
|
||||
if (
|
||||
providerSwitchTransferId !== null &&
|
||||
providerSwitchHandoff !== null &&
|
||||
|
||||
@@ -23,7 +23,11 @@ import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
|
||||
import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
|
||||
import { ProjectionStoreV2, layer as projectionStoreLayer } from "./ProjectionStore.ts";
|
||||
import {
|
||||
isTurnItemAtOrBeforeRun,
|
||||
ProjectionStoreV2,
|
||||
layer as projectionStoreLayer,
|
||||
} from "./ProjectionStore.ts";
|
||||
|
||||
const TestLayer = Layer.mergeAll(
|
||||
projectionStoreLayer.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
|
||||
@@ -37,6 +41,48 @@ const driver = ProviderDriverKind.make("codex");
|
||||
const providerInstanceId = modelSelection.instanceId;
|
||||
const encodeUnknownJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
|
||||
|
||||
it("includes imported runless history when selecting fork context through a run", () => {
|
||||
const firstRunId = RunId.make("run:projection-imported-fork:1");
|
||||
const secondRunId = RunId.make("run:projection-imported-fork:2");
|
||||
const runOrdinalById = new Map([
|
||||
[firstRunId, 1],
|
||||
[secondRunId, 2],
|
||||
]);
|
||||
|
||||
assert.isTrue(
|
||||
isTurnItemAtOrBeforeRun({
|
||||
historyOrigin: "v1_import",
|
||||
itemRunId: null,
|
||||
runOrdinalById,
|
||||
sourceRunOrdinal: 1,
|
||||
}),
|
||||
);
|
||||
assert.isFalse(
|
||||
isTurnItemAtOrBeforeRun({
|
||||
historyOrigin: undefined,
|
||||
itemRunId: null,
|
||||
runOrdinalById,
|
||||
sourceRunOrdinal: 1,
|
||||
}),
|
||||
);
|
||||
assert.isTrue(
|
||||
isTurnItemAtOrBeforeRun({
|
||||
historyOrigin: "v1_import",
|
||||
itemRunId: firstRunId,
|
||||
runOrdinalById,
|
||||
sourceRunOrdinal: 1,
|
||||
}),
|
||||
);
|
||||
assert.isFalse(
|
||||
isTurnItemAtOrBeforeRun({
|
||||
historyOrigin: "v1_import",
|
||||
itemRunId: secondRunId,
|
||||
runOrdinalById,
|
||||
sourceRunOrdinal: 1,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(TestLayer)("ProjectionStoreV2", (it) => {
|
||||
it.effect("projects one shared provider session into multiple thread bindings", () =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -643,6 +643,19 @@ function makeForkMarkerTurnItem(input: {
|
||||
};
|
||||
}
|
||||
|
||||
export function isTurnItemAtOrBeforeRun(input: {
|
||||
readonly historyOrigin: OrchestrationV2ThreadProjection["thread"]["historyOrigin"];
|
||||
readonly itemRunId: OrchestrationV2TurnItem["runId"];
|
||||
readonly runOrdinalById: ReadonlyMap<NonNullable<OrchestrationV2TurnItem["runId"]>, number>;
|
||||
readonly sourceRunOrdinal: number;
|
||||
}): boolean {
|
||||
if (input.itemRunId === null) {
|
||||
return input.historyOrigin === "v1_import";
|
||||
}
|
||||
const ordinal = input.runOrdinalById.get(input.itemRunId);
|
||||
return ordinal !== undefined && ordinal <= input.sourceRunOrdinal;
|
||||
}
|
||||
|
||||
function visibleTurnItemsThroughRun(input: {
|
||||
readonly sourceProjection: OrchestrationV2ThreadProjection;
|
||||
readonly sourceRunId: NonNullable<OrchestrationV2TurnItem["runId"]>;
|
||||
@@ -674,11 +687,12 @@ function visibleTurnItemsThroughRun(input: {
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (item.runId === null) {
|
||||
return false;
|
||||
}
|
||||
const ordinal = runOrdinalById.get(item.runId);
|
||||
return ordinal !== undefined && ordinal <= sourceRun.ordinal;
|
||||
return isTurnItemAtOrBeforeRun({
|
||||
historyOrigin: input.sourceProjection.thread.historyOrigin,
|
||||
itemRunId: item.runId,
|
||||
runOrdinalById,
|
||||
sourceRunOrdinal: sourceRun.ordinal,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -764,6 +778,9 @@ export function threadShellFromProjection(
|
||||
lineage: projection.thread.lineage,
|
||||
forkedFrom: projection.thread.forkedFrom,
|
||||
activeProviderThreadId: projection.thread.activeProviderThreadId,
|
||||
...(projection.thread.historyOrigin === undefined
|
||||
? {}
|
||||
: { historyOrigin: projection.thread.historyOrigin }),
|
||||
latestRunId: latestRun?.id ?? null,
|
||||
activeRunId: activeRun?.id ?? null,
|
||||
status: latestRun?.status ?? "idle",
|
||||
@@ -922,6 +939,9 @@ function shellFromState(input: {
|
||||
lineage: input.state.thread.lineage,
|
||||
forkedFrom: input.state.thread.forkedFrom,
|
||||
activeProviderThreadId: input.state.thread.activeProviderThreadId,
|
||||
...(input.state.thread.historyOrigin === undefined
|
||||
? {}
|
||||
: { historyOrigin: input.state.thread.historyOrigin }),
|
||||
latestRunId: input.state.latestRunId,
|
||||
activeRunId: input.state.activeRunId,
|
||||
status: input.state.latestRunStatus,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import {
|
||||
CommandId,
|
||||
NodeId,
|
||||
type OrchestrationV2Command,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
@@ -8,7 +9,7 @@ import {
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { withCreationProvenance } from "./ThreadManagementService.ts";
|
||||
import { existingThreadIdsForCommand, withCreationProvenance } from "./ThreadManagementService.ts";
|
||||
|
||||
it("stamps authoritative provenance on commands that create threads or messages", () => {
|
||||
const command: OrchestrationV2Command = {
|
||||
@@ -55,3 +56,108 @@ it("leaves commands that do not create durable authored content unchanged", () =
|
||||
}),
|
||||
).toBe(command);
|
||||
});
|
||||
|
||||
it("identifies every existing thread that must be hydrated before dispatch", () => {
|
||||
const sourceThreadId = ThreadId.make("thread:thread-management:source");
|
||||
const targetThreadId = ThreadId.make("thread:thread-management:target");
|
||||
const parentThreadId = ThreadId.make("thread:thread-management:parent");
|
||||
|
||||
expect(
|
||||
existingThreadIdsForCommand({
|
||||
type: "thread.create",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:thread-management:create"),
|
||||
threadId: targetThreadId,
|
||||
projectId: ProjectId.make("project:thread-management"),
|
||||
title: "Created thread",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
}),
|
||||
).toEqual([]);
|
||||
|
||||
expect(
|
||||
existingThreadIdsForCommand({
|
||||
type: "thread.archive",
|
||||
commandId: CommandId.make("command:thread-management:archive"),
|
||||
threadId: targetThreadId,
|
||||
}),
|
||||
).toEqual([targetThreadId]);
|
||||
|
||||
expect(
|
||||
existingThreadIdsForCommand({
|
||||
type: "thread.fork",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:thread-management:fork"),
|
||||
sourceThreadId,
|
||||
targetThreadId,
|
||||
sourcePoint: {
|
||||
type: "run",
|
||||
runId: RunId.make("run:thread-management:source"),
|
||||
},
|
||||
}),
|
||||
).toEqual([sourceThreadId]);
|
||||
|
||||
expect(
|
||||
existingThreadIdsForCommand({
|
||||
type: "thread.merge_back",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:thread-management:merge"),
|
||||
sourceThreadId,
|
||||
targetThreadId,
|
||||
sourcePoint: {
|
||||
type: "run",
|
||||
runId: RunId.make("run:thread-management:source"),
|
||||
},
|
||||
}),
|
||||
).toEqual([sourceThreadId, targetThreadId]);
|
||||
|
||||
expect(
|
||||
existingThreadIdsForCommand({
|
||||
type: "delegated_task.request",
|
||||
createdBy: "agent",
|
||||
creationSource: "provider",
|
||||
commandId: CommandId.make("command:thread-management:delegate"),
|
||||
parentThreadId,
|
||||
parentRunId: RunId.make("run:thread-management:parent"),
|
||||
parentNodeId: NodeId.make("node:thread-management:parent"),
|
||||
task: "Inspect the migration",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
}),
|
||||
).toEqual([parentThreadId]);
|
||||
|
||||
expect(
|
||||
existingThreadIdsForCommand({
|
||||
type: "delegated_task.wake-policy",
|
||||
commandId: CommandId.make("command:thread-management:wake-policy"),
|
||||
parentThreadId,
|
||||
taskId: NodeId.make("node:thread-management:delegated"),
|
||||
completionWake: "always",
|
||||
}),
|
||||
).toEqual([parentThreadId]);
|
||||
|
||||
expect(
|
||||
existingThreadIdsForCommand({
|
||||
type: "thread.created.record",
|
||||
commandId: CommandId.make("command:thread-management:record"),
|
||||
parentThreadId,
|
||||
parentRunId: RunId.make("run:thread-management:parent"),
|
||||
parentNodeId: NodeId.make("node:thread-management:parent"),
|
||||
targetThreadId,
|
||||
targetRunId: null,
|
||||
}),
|
||||
).toEqual([parentThreadId, targetThreadId]);
|
||||
});
|
||||
@@ -25,10 +25,16 @@ import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import {
|
||||
OrchestratorDispatchError,
|
||||
OrchestratorProjectionError,
|
||||
OrchestratorV2,
|
||||
type OrchestratorV2DispatchResult,
|
||||
type OrchestratorV2Error,
|
||||
} from "./Orchestrator.ts";
|
||||
import {
|
||||
LegacyV1ThreadImporter,
|
||||
type LegacyV1ThreadImportError,
|
||||
} from "./LegacyV1ThreadImporter.ts";
|
||||
|
||||
export type ThreadManagementSendMode = "auto" | "queue" | "steer" | "restart";
|
||||
|
||||
@@ -53,6 +59,30 @@ export function withCreationProvenance(
|
||||
}
|
||||
}
|
||||
|
||||
export function existingThreadIdsForCommand(
|
||||
command: OrchestrationV2Command,
|
||||
): ReadonlyArray<ThreadId> {
|
||||
switch (command.type) {
|
||||
case "thread.create":
|
||||
return [];
|
||||
case "thread.fork":
|
||||
return [command.sourceThreadId];
|
||||
case "thread.merge_back":
|
||||
return command.sourceThreadId === command.targetThreadId
|
||||
? [command.sourceThreadId]
|
||||
: [command.sourceThreadId, command.targetThreadId];
|
||||
case "delegated_task.request":
|
||||
case "delegated_task.wake-policy":
|
||||
return [command.parentThreadId];
|
||||
case "thread.created.record":
|
||||
return command.parentThreadId === command.targetThreadId
|
||||
? [command.parentThreadId]
|
||||
: [command.parentThreadId, command.targetThreadId];
|
||||
default:
|
||||
return [command.threadId];
|
||||
}
|
||||
}
|
||||
|
||||
export type ThreadManagementTerminalRunStatus = Extract<
|
||||
OrchestrationV2Run["status"],
|
||||
"completed" | "failed" | "cancelled" | "interrupted" | "rolled_back"
|
||||
@@ -132,6 +162,9 @@ export class ThreadManagementError extends Schema.TaggedErrorClass<ThreadManagem
|
||||
type ThreadManagementFailure = ThreadManagementError | OrchestratorV2Error;
|
||||
|
||||
export interface ThreadManagementServiceShape {
|
||||
readonly ensureLegacyTranscript: (
|
||||
threadId: ThreadId,
|
||||
) => Effect.Effect<void, LegacyV1ThreadImportError>;
|
||||
readonly dispatch: (
|
||||
command: OrchestrationV2Command,
|
||||
) => Effect.Effect<OrchestratorV2DispatchResult, OrchestratorV2Error>;
|
||||
@@ -235,9 +268,66 @@ function managementError(
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const orchestrator = yield* OrchestratorV2;
|
||||
const legacyImporter = yield* LegacyV1ThreadImporter;
|
||||
|
||||
const ensureLegacyTranscript = Effect.fn(
|
||||
"orchestrationV2.threadManagement.ensureLegacyTranscript",
|
||||
)(function* (threadId: ThreadId) {
|
||||
yield* legacyImporter.ensureTranscript(threadId).pipe(
|
||||
Effect.tapError((cause) =>
|
||||
Effect.logWarning("Unable to hydrate migrated v1 thread transcript", {
|
||||
threadId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const ensureProjectionTranscript = (threadId: ThreadId) =>
|
||||
ensureLegacyTranscript(threadId).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestratorProjectionError({
|
||||
threadId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const ensureCommandTranscripts = Effect.fn(
|
||||
"orchestrationV2.threadManagement.ensureCommandTranscripts",
|
||||
)(function* (command: OrchestrationV2Command) {
|
||||
yield* Effect.forEach(
|
||||
existingThreadIdsForCommand(command),
|
||||
(threadId) => ensureLegacyTranscript(threadId),
|
||||
{ discard: true },
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestratorDispatchError({
|
||||
commandId: command.commandId,
|
||||
commandType: command.type,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const getThreadProjection: ThreadManagementServiceShape["getThreadProjection"] = (threadId) =>
|
||||
ensureProjectionTranscript(threadId).pipe(
|
||||
Effect.andThen(orchestrator.getThreadProjection(threadId)),
|
||||
);
|
||||
|
||||
const getThreadSnapshot: ThreadManagementServiceShape["getThreadSnapshot"] = (threadId) =>
|
||||
ensureProjectionTranscript(threadId).pipe(
|
||||
Effect.andThen(orchestrator.getThreadSnapshot(threadId)),
|
||||
);
|
||||
|
||||
const dispatch: ThreadManagementServiceShape["dispatch"] = (command) =>
|
||||
ensureCommandTranscripts(command).pipe(Effect.andThen(orchestrator.dispatch(command)));
|
||||
|
||||
const getProjectThread: ThreadManagementServiceShape["getProjectThread"] = (input) =>
|
||||
orchestrator.getThreadProjection(input.threadId).pipe(
|
||||
getThreadProjection(input.threadId).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
managementError(
|
||||
"thread_not_found",
|
||||
@@ -450,9 +540,10 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
return ThreadManagementService.of({
|
||||
dispatch: orchestrator.dispatch,
|
||||
getThreadProjection: orchestrator.getThreadProjection,
|
||||
getThreadSnapshot: orchestrator.getThreadSnapshot,
|
||||
ensureLegacyTranscript,
|
||||
dispatch,
|
||||
getThreadProjection,
|
||||
getThreadSnapshot,
|
||||
getProjectThread,
|
||||
getShellSnapshot: orchestrator.getShellSnapshot,
|
||||
listProjectThreads,
|
||||
@@ -466,7 +557,22 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
});
|
||||
|
||||
const legacyV1ThreadImporterNoopLayer = Layer.succeed(
|
||||
LegacyV1ThreadImporter,
|
||||
LegacyV1ThreadImporter.of({
|
||||
reconcileShells: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
|
||||
ensureTranscript: () => Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
|
||||
importPendingTranscripts: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
|
||||
}),
|
||||
);
|
||||
|
||||
export const layer: Layer.Layer<ThreadManagementService, never, OrchestratorV2> = Layer.effect(
|
||||
ThreadManagementService,
|
||||
make,
|
||||
);
|
||||
).pipe(Layer.provide(legacyV1ThreadImporterNoopLayer));
|
||||
|
||||
export const layerWithLegacyImporter: Layer.Layer<
|
||||
ThreadManagementService,
|
||||
never,
|
||||
LegacyV1ThreadImporter | OrchestratorV2
|
||||
> = Layer.effect(ThreadManagementService, make);
|
||||
@@ -30,8 +30,14 @@ import { ProviderInstanceRegistry } from "../provider/Services/ProviderInstanceR
|
||||
import type { ProviderInstance } from "../provider/ProviderDriver.ts";
|
||||
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import { OrchestratorV2 } from "./Orchestrator.ts";
|
||||
import { LegacyV1ThreadImporter, LegacyV1ThreadImportError } from "./LegacyV1ThreadImporter.ts";
|
||||
import {
|
||||
OrchestratorDispatchError,
|
||||
OrchestratorProjectionError,
|
||||
OrchestratorV2,
|
||||
} from "./Orchestrator.ts";
|
||||
import { OrchestrationEffectWorkerV2 } from "./EffectWorker.ts";
|
||||
import { ProjectionMaintenanceV2 } from "./ProjectionMaintenance.ts";
|
||||
import type { ProviderAdapterV2Shape } from "./ProviderAdapter.ts";
|
||||
import { OrchestrationV2LayerLive } from "./runtimeLayer.ts";
|
||||
import { shellStreamItemFromSnapshot } from "./ShellStream.ts";
|
||||
@@ -92,6 +98,16 @@ const TestLayer = OrchestrationV2LayerLive.pipe(
|
||||
Layer.provide(NodeServices.layer),
|
||||
);
|
||||
|
||||
const LegacyImportTestLayer = OrchestrationV2LayerLive.pipe(
|
||||
Layer.provide(mcpSessionRegistryTestLayer),
|
||||
Layer.provideMerge(SqlitePersistenceMemory),
|
||||
Layer.provide(CheckpointStoreTestLayer),
|
||||
Layer.provide(ServerConfigLayer),
|
||||
Layer.provide(ServerSettingsService.layerTest()),
|
||||
Layer.provide(TestProviderInstanceRegistry),
|
||||
Layer.provide(NodeServices.layer),
|
||||
);
|
||||
|
||||
const SharedApplicationDataPlaneTestLayer = Layer.merge(
|
||||
OrchestrationLayerLive,
|
||||
OrchestrationV2LayerLive,
|
||||
@@ -158,7 +174,210 @@ it.layer(TestLayer)("OrchestrationV2LayerLive", (it) => {
|
||||
assert.deepEqual(projection.runs, []);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(LegacyImportTestLayer)("OrchestrationV2 legacy import", (it) => {
|
||||
it.effect("hydrates imported transcripts before commands and propagates hydration failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const importer = yield* LegacyV1ThreadImporter;
|
||||
const maintenance = yield* ProjectionMaintenanceV2;
|
||||
const orchestrator = yield* OrchestratorV2;
|
||||
const threadManagement = yield* ThreadManagementService;
|
||||
const metadataThreadId = ThreadId.make("runtime-layer-legacy-metadata-thread");
|
||||
const failureThreadId = ThreadId.make("runtime-layer-legacy-failure-thread");
|
||||
const projectId = ProjectId.make("runtime-layer-legacy-project");
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_projects (
|
||||
project_id,
|
||||
title,
|
||||
workspace_root,
|
||||
default_model_selection_json,
|
||||
scripts_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
) VALUES (
|
||||
${projectId},
|
||||
'Legacy project',
|
||||
'/tmp/runtime-layer-legacy-project',
|
||||
'{"instanceId":"codex","model":"gpt-5.4"}',
|
||||
'[]',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'2026-01-04T00:00:00.000Z',
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
yield* sql`
|
||||
INSERT INTO projection_threads (
|
||||
thread_id,
|
||||
project_id,
|
||||
title,
|
||||
model_selection_json,
|
||||
runtime_mode,
|
||||
interaction_mode,
|
||||
branch,
|
||||
worktree_path,
|
||||
latest_turn_id,
|
||||
created_at,
|
||||
updated_at,
|
||||
archived_at,
|
||||
settled_override,
|
||||
settled_at,
|
||||
deleted_at
|
||||
) VALUES
|
||||
(
|
||||
${metadataThreadId},
|
||||
${projectId},
|
||||
'Legacy metadata title',
|
||||
'{"instanceId":"codex","model":"gpt-5.4"}',
|
||||
'full-access',
|
||||
'default',
|
||||
'main',
|
||||
'/tmp/runtime-layer-legacy-project',
|
||||
NULL,
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'2026-01-04T00:00:00.000Z',
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL
|
||||
),
|
||||
(
|
||||
${failureThreadId},
|
||||
${projectId},
|
||||
'Legacy failure title',
|
||||
'{"instanceId":"codex","model":"gpt-5.4"}',
|
||||
'full-access',
|
||||
'default',
|
||||
'main',
|
||||
'/tmp/runtime-layer-legacy-project',
|
||||
NULL,
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'2026-01-04T00:00:00.000Z',
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_messages (
|
||||
message_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
role,
|
||||
text,
|
||||
attachments_json,
|
||||
is_streaming,
|
||||
created_at,
|
||||
updated_at
|
||||
) VALUES
|
||||
(
|
||||
'message:runtime-layer-legacy:1',
|
||||
${metadataThreadId},
|
||||
NULL,
|
||||
'user',
|
||||
'First imported question',
|
||||
'[]',
|
||||
0,
|
||||
'2026-01-01T01:00:00.000Z',
|
||||
'2026-01-01T01:00:00.000Z'
|
||||
),
|
||||
(
|
||||
'message:runtime-layer-legacy:2',
|
||||
${metadataThreadId},
|
||||
NULL,
|
||||
'assistant',
|
||||
'First imported answer',
|
||||
'[]',
|
||||
0,
|
||||
'2026-01-02T01:00:00.000Z',
|
||||
'2026-01-02T01:00:00.000Z'
|
||||
),
|
||||
(
|
||||
'message:runtime-layer-legacy:3',
|
||||
${metadataThreadId},
|
||||
NULL,
|
||||
'user',
|
||||
'Latest imported question',
|
||||
'[]',
|
||||
0,
|
||||
'2026-01-03T01:00:00.000Z',
|
||||
'2026-01-03T01:00:00.000Z'
|
||||
),
|
||||
(
|
||||
'message:runtime-layer-legacy:failure',
|
||||
${failureThreadId},
|
||||
NULL,
|
||||
'user',
|
||||
'Imported context must load before archive',
|
||||
'[]',
|
||||
0,
|
||||
'2026-01-03T01:00:00.000Z',
|
||||
'2026-01-03T01:00:00.000Z'
|
||||
)
|
||||
`;
|
||||
|
||||
yield* importer.reconcileShells;
|
||||
const rebuilt = yield* maintenance.rebuild;
|
||||
assert.isTrue(rebuilt.valid);
|
||||
|
||||
yield* threadManagement.dispatch({
|
||||
type: "thread.metadata.update",
|
||||
commandId: CommandId.make("runtime-layer-legacy-metadata-update"),
|
||||
threadId: metadataThreadId,
|
||||
title: "Updated after import",
|
||||
});
|
||||
const updatedProjection = yield* threadManagement.getThreadProjection(metadataThreadId);
|
||||
assert.equal(updatedProjection.thread.title, "Updated after import");
|
||||
assert.deepEqual(
|
||||
updatedProjection.messages.map((message) => message.text),
|
||||
["First imported question", "First imported answer", "Latest imported question"],
|
||||
);
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_thread_messages
|
||||
RENAME TO projection_thread_messages_unavailable
|
||||
`;
|
||||
const { projectionFailure, hydrationFailure } = yield* Effect.all({
|
||||
projectionFailure: threadManagement.getThreadProjection(failureThreadId).pipe(Effect.flip),
|
||||
hydrationFailure: threadManagement
|
||||
.dispatch({
|
||||
type: "thread.archive",
|
||||
commandId: CommandId.make("runtime-layer-legacy-failed-archive"),
|
||||
threadId: failureThreadId,
|
||||
})
|
||||
.pipe(Effect.flip),
|
||||
}).pipe(
|
||||
Effect.ensuring(
|
||||
sql`
|
||||
ALTER TABLE projection_thread_messages_unavailable
|
||||
RENAME TO projection_thread_messages
|
||||
`.pipe(Effect.orDie),
|
||||
),
|
||||
);
|
||||
assert.instanceOf(projectionFailure, OrchestratorProjectionError);
|
||||
assert.instanceOf(projectionFailure.cause, LegacyV1ThreadImportError);
|
||||
assert.instanceOf(hydrationFailure, OrchestratorDispatchError);
|
||||
assert.instanceOf(hydrationFailure.cause, LegacyV1ThreadImportError);
|
||||
|
||||
const projectionAfterFailure = yield* orchestrator.getThreadProjection(failureThreadId);
|
||||
assert.isNull(projectionAfterFailure.thread.archivedAt);
|
||||
|
||||
yield* threadManagement.dispatch({
|
||||
type: "thread.archive",
|
||||
commandId: CommandId.make("runtime-layer-legacy-retried-archive"),
|
||||
threadId: failureThreadId,
|
||||
});
|
||||
const projectionAfterRetry = yield* threadManagement.getThreadProjection(failureThreadId);
|
||||
assert.isNotNull(projectionAfterRetry.thread.archivedAt);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(TestLayer)("OrchestrationV2LayerLive lifecycle", (it) => {
|
||||
it.effect("applies lifecycle commands idempotently and emits archive/removal shell deltas", () =>
|
||||
Effect.gen(function* () {
|
||||
const orchestrator = yield* OrchestratorV2;
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
import { layerFromStores as eventSinkLayer } from "./EventSink.ts";
|
||||
import { layerFromOrchestrationEventStore as eventStoreLayer } from "./EventStore.ts";
|
||||
import { layer as idAllocatorLayer } from "./IdAllocator.ts";
|
||||
import { layer as legacyV1ThreadImporterLayer } from "./LegacyV1ThreadImporter.ts";
|
||||
import { layer as orchestratorLayer } from "./Orchestrator.ts";
|
||||
import { layer as projectionStoreLayer } from "./ProjectionStore.ts";
|
||||
import { layer as projectionMaintenanceLayer } from "./ProjectionMaintenance.ts";
|
||||
@@ -36,7 +37,7 @@ import { layer as runExecutionServiceLayer } from "./RunExecutionService.ts";
|
||||
import { layer as runFinalizationServiceLayer } from "./RunFinalizationService.ts";
|
||||
import { layerFromProjectRepository as runtimePolicyLayerFromProjectRepository } from "./RuntimePolicy.ts";
|
||||
import { layer as runtimeRequestServiceLayer } from "./RuntimeRequestService.ts";
|
||||
import { layer as threadManagementServiceLayer } from "./ThreadManagementService.ts";
|
||||
import { layerWithLegacyImporter as threadManagementServiceLayer } from "./ThreadManagementService.ts";
|
||||
import { layer as threadLaunchServiceLayer } from "./ThreadLaunchService.ts";
|
||||
import { layer as threadLifecycleServiceLayer } from "./ThreadLifecycleService.ts";
|
||||
import { layer as threadForkServiceLayer } from "./ThreadForkService.ts";
|
||||
@@ -68,6 +69,9 @@ const storesLayer = Layer.mergeAll(
|
||||
|
||||
const eventSinkProvided = eventSinkLayer.pipe(Layer.provide(storesLayer));
|
||||
const projectionMaintenanceProvided = projectionMaintenanceLayer.pipe(Layer.provide(storesLayer));
|
||||
const legacyV1ThreadImporterProvided = legacyV1ThreadImporterLayer.pipe(
|
||||
Layer.provide(Layer.mergeAll(eventSinkProvided, eventStoreProvided)),
|
||||
);
|
||||
|
||||
const providerEventIngestorProvided = providerEventIngestorLayer.pipe(
|
||||
Layer.provide(Layer.mergeAll(eventSinkProvided, idAllocatorLayer)),
|
||||
@@ -211,7 +215,7 @@ const orchestratorProvided = orchestratorLayer.pipe(
|
||||
);
|
||||
|
||||
const threadManagementProvided = threadManagementServiceLayer.pipe(
|
||||
Layer.provide(orchestratorProvided),
|
||||
Layer.provide(Layer.merge(orchestratorProvided, legacyV1ThreadImporterProvided)),
|
||||
);
|
||||
export const ProjectSetupScriptRunnerLayerLive = projectSetupScriptRunnerLayer.pipe(
|
||||
Layer.provide(ProjectServiceLayerLive),
|
||||
@@ -246,6 +250,7 @@ export const OrchestrationV2LayerLive = Layer.mergeAll(
|
||||
providerSessionManagerProvided,
|
||||
providerRuntimeRecoveryProvided,
|
||||
projectionMaintenanceProvided,
|
||||
legacyV1ThreadImporterProvided,
|
||||
);
|
||||
|
||||
export const OrchestrationV2ProductionLayerLive = Layer.mergeAll(
|
||||
|
||||
@@ -17,20 +17,35 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
import { ClaudeProviderCapabilitiesV2 } from "../Adapters/ClaudeAdapterV2.ts";
|
||||
import { CodexProviderCapabilitiesV2 } from "../Adapters/CodexAdapterV2.ts";
|
||||
import { CursorProviderCapabilitiesV2 } from "../Adapters/CursorAdapterV2.ts";
|
||||
import { layer as eventSinkLayer } from "../EventSink.ts";
|
||||
import { layer as eventStoreLayer } from "../EventStore.ts";
|
||||
import {
|
||||
LegacyV1ThreadImporter,
|
||||
layer as legacyV1ThreadImporterLayer,
|
||||
} from "../LegacyV1ThreadImporter.ts";
|
||||
import { OrchestratorV2 } from "../Orchestrator.ts";
|
||||
import {
|
||||
ProjectionMaintenanceV2,
|
||||
layer as projectionMaintenanceLayer,
|
||||
} from "../ProjectionMaintenance.ts";
|
||||
import { layer as projectionStoreLayer } from "../ProjectionStore.ts";
|
||||
import {
|
||||
type ProviderAdapterV2Event,
|
||||
ProviderAdapterProtocolError,
|
||||
type ProviderAdapterV2Shape,
|
||||
} from "../ProviderAdapter.ts";
|
||||
import { makeLayer as makeProviderAdapterRegistryLayer } from "../ProviderAdapterRegistry.ts";
|
||||
import { makeProviderFailure } from "../ProviderFailure.ts";
|
||||
import {
|
||||
CLAUDE_MODEL_SELECTION,
|
||||
CODEX_MODEL_SELECTION,
|
||||
@@ -68,6 +83,7 @@ function makeTestAdapter(input: {
|
||||
readonly responseByThreadId?: Readonly<Record<string, Readonly<Record<number, string>>>>;
|
||||
readonly capturedTurns: Ref.Ref<ReadonlyArray<CapturedTurn>>;
|
||||
readonly failResume?: boolean;
|
||||
readonly failedRunOrdinals?: ReadonlySet<number>;
|
||||
}): ProviderAdapterV2Shape {
|
||||
return {
|
||||
instanceId: input.instanceId,
|
||||
@@ -143,6 +159,43 @@ function makeTestAdapter(input: {
|
||||
const providerTurnId = ProviderTurnId.make(
|
||||
`provider-turn:${input.driver}:${turnInput.threadId}:${turnInput.runOrdinal}`,
|
||||
);
|
||||
if (input.failedRunOrdinals?.has(turnInput.runOrdinal) === true) {
|
||||
yield* PubSub.publish(events, {
|
||||
type: "provider_turn.updated",
|
||||
driver: input.driver,
|
||||
providerTurn: {
|
||||
id: providerTurnId,
|
||||
providerThreadId: turnInput.providerThread.id,
|
||||
nodeId: turnInput.rootNodeId,
|
||||
runAttemptId: turnInput.attemptId,
|
||||
nativeTurnRef: {
|
||||
driver: input.driver,
|
||||
nativeId: `native-turn:${turnInput.threadId}:${turnInput.runOrdinal}`,
|
||||
strength: "strong",
|
||||
},
|
||||
ordinal: turnInput.runOrdinal,
|
||||
status: "failed",
|
||||
startedAt: eventTime,
|
||||
completedAt: eventTime,
|
||||
},
|
||||
});
|
||||
yield* PubSub.publish(events, {
|
||||
type: "turn.terminal",
|
||||
driver: input.driver,
|
||||
providerThreadId: turnInput.providerThread.id,
|
||||
providerTurnId,
|
||||
runOrdinal: turnInput.runOrdinal,
|
||||
failureItemOrdinal: turnInput.runOrdinal * 100 + 1,
|
||||
status: "failed",
|
||||
failure: makeProviderFailure({
|
||||
message: "Simulated provider failure.",
|
||||
code: "simulated_failure",
|
||||
class: "provider_error",
|
||||
}),
|
||||
threadDisposition: "reusable",
|
||||
});
|
||||
return;
|
||||
}
|
||||
const response =
|
||||
input.responseByThreadId?.[turnInput.threadId]?.[turnInput.runOrdinal] ??
|
||||
input.responseByRunOrdinal[turnInput.runOrdinal] ??
|
||||
@@ -243,6 +296,231 @@ const waitForIdle = Effect.fn("ProviderSwitchTest.waitForIdle")(function* (
|
||||
});
|
||||
|
||||
describe("orchestration v2 provider switching", () => {
|
||||
it.live("reissues imported v1 context when switching after the first provider fails", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const importedThreadId = ThreadId.make("thread:provider-switch:legacy-import");
|
||||
const importedProjectId = ProjectId.make("project:provider-switch:legacy-import");
|
||||
const failedPrompt = "This first provider attempt should fail.";
|
||||
const recoveryPrompt = "What was the imported release marker?";
|
||||
const cwd = yield* checkpointWorkspace("provider-switch-legacy-import");
|
||||
const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
|
||||
const registryLayer = makeProviderAdapterRegistryLayer([
|
||||
makeTestAdapter({
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
driver: CODEX_DRIVER,
|
||||
capabilities: CodexProviderCapabilitiesV2,
|
||||
modelSelection: CODEX_MODEL_SELECTION,
|
||||
responseByRunOrdinal: {},
|
||||
capturedTurns,
|
||||
failedRunOrdinals: new Set([1]),
|
||||
}),
|
||||
makeTestAdapter({
|
||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
||||
driver: CLAUDE_DRIVER,
|
||||
capabilities: ClaudeProviderCapabilitiesV2,
|
||||
modelSelection: CLAUDE_MODEL_SELECTION,
|
||||
responseByRunOrdinal: { 2: "The imported release marker is violet." },
|
||||
capturedTurns,
|
||||
}),
|
||||
]);
|
||||
const databaseLayer = SqlitePersistenceMemory;
|
||||
const eventStoreProvided = eventStoreLayer.pipe(Layer.provideMerge(databaseLayer));
|
||||
const projectionStoreProvided = projectionStoreLayer.pipe(
|
||||
Layer.provideMerge(databaseLayer),
|
||||
);
|
||||
const storesProvided = Layer.mergeAll(
|
||||
databaseLayer,
|
||||
eventStoreProvided,
|
||||
projectionStoreProvided,
|
||||
);
|
||||
const eventSinkProvided = eventSinkLayer.pipe(Layer.provide(storesProvided));
|
||||
const importerProvided = legacyV1ThreadImporterLayer.pipe(
|
||||
Layer.provide(Layer.mergeAll(storesProvided, eventSinkProvided)),
|
||||
);
|
||||
const maintenanceProvided = projectionMaintenanceLayer.pipe(Layer.provide(storesProvided));
|
||||
const orchestratorProvided = makeOrchestratorV2ReplayLayerWithRegistry(
|
||||
{
|
||||
name: "provider-switch-legacy-import",
|
||||
runtimePolicyOverride: {
|
||||
cwd,
|
||||
approvalPolicy: "never",
|
||||
sandboxPolicy: {
|
||||
type: "readOnly",
|
||||
access: { type: "fullAccess" },
|
||||
networkAccess: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
registryLayer,
|
||||
{ databaseLayer },
|
||||
);
|
||||
const testLayer = Layer.mergeAll(
|
||||
storesProvided,
|
||||
importerProvided,
|
||||
maintenanceProvided,
|
||||
orchestratorProvided,
|
||||
);
|
||||
|
||||
const projection = yield* Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const importer = yield* LegacyV1ThreadImporter;
|
||||
const maintenance = yield* ProjectionMaintenanceV2;
|
||||
const orchestrator = yield* OrchestratorV2;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_projects (
|
||||
project_id,
|
||||
title,
|
||||
workspace_root,
|
||||
default_model_selection_json,
|
||||
scripts_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
) VALUES (
|
||||
${importedProjectId},
|
||||
'Imported provider switch project',
|
||||
${cwd},
|
||||
'{"instanceId":"codex","model":"gpt-5.4"}',
|
||||
'[]',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
yield* sql`
|
||||
INSERT INTO projection_threads (
|
||||
thread_id,
|
||||
project_id,
|
||||
title,
|
||||
model_selection_json,
|
||||
runtime_mode,
|
||||
interaction_mode,
|
||||
branch,
|
||||
worktree_path,
|
||||
latest_turn_id,
|
||||
created_at,
|
||||
updated_at,
|
||||
archived_at,
|
||||
settled_override,
|
||||
settled_at,
|
||||
deleted_at
|
||||
) VALUES (
|
||||
${importedThreadId},
|
||||
${importedProjectId},
|
||||
'Imported provider switch thread',
|
||||
'{"instanceId":"codex","model":"gpt-5.4"}',
|
||||
'full-access',
|
||||
'default',
|
||||
'main',
|
||||
${cwd},
|
||||
NULL,
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_messages (
|
||||
message_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
role,
|
||||
text,
|
||||
attachments_json,
|
||||
is_streaming,
|
||||
created_at,
|
||||
updated_at
|
||||
) VALUES
|
||||
(
|
||||
'message:provider-switch:legacy-import:user',
|
||||
${importedThreadId},
|
||||
NULL,
|
||||
'user',
|
||||
'Remember that the imported release marker is violet.',
|
||||
'[]',
|
||||
0,
|
||||
'2026-01-01T01:00:00.000Z',
|
||||
'2026-01-01T01:00:00.000Z'
|
||||
),
|
||||
(
|
||||
'message:provider-switch:legacy-import:assistant',
|
||||
${importedThreadId},
|
||||
NULL,
|
||||
'assistant',
|
||||
'I will remember violet.',
|
||||
'[]',
|
||||
0,
|
||||
'2026-01-01T01:01:00.000Z',
|
||||
'2026-01-01T01:01:00.000Z'
|
||||
)
|
||||
`;
|
||||
|
||||
yield* importer.reconcileShells;
|
||||
yield* maintenance.rebuild;
|
||||
yield* importer.ensureTranscript(importedThreadId);
|
||||
|
||||
yield* orchestrator.dispatch({
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:provider-switch:legacy-import:failed"),
|
||||
threadId: importedThreadId,
|
||||
messageId: MessageId.make("message:provider-switch:legacy-import:failed"),
|
||||
text: failedPrompt,
|
||||
attachments: [],
|
||||
modelSelection: CODEX_MODEL_SELECTION,
|
||||
dispatchMode: { type: "start_immediately" },
|
||||
});
|
||||
yield* waitForIdle(importedThreadId);
|
||||
yield* orchestrator.dispatch({
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:provider-switch:legacy-import:recovery"),
|
||||
threadId: importedThreadId,
|
||||
messageId: MessageId.make("message:provider-switch:legacy-import:recovery"),
|
||||
text: recoveryPrompt,
|
||||
attachments: [],
|
||||
modelSelection: CLAUDE_MODEL_SELECTION,
|
||||
dispatchMode: { type: "start_immediately" },
|
||||
});
|
||||
return yield* waitForIdle(importedThreadId);
|
||||
}).pipe(Effect.provide(testLayer));
|
||||
|
||||
const turns = yield* Ref.get(capturedTurns);
|
||||
assert.deepEqual(
|
||||
projection.runs.map((run) => [run.providerInstanceId, run.status]),
|
||||
[
|
||||
["codex", "failed"],
|
||||
["claudeAgent", "completed"],
|
||||
],
|
||||
);
|
||||
assert.deepEqual(
|
||||
projection.contextHandoffs.map((handoff) => [
|
||||
handoff.targetRunId,
|
||||
handoff.strategy,
|
||||
handoff.status,
|
||||
]),
|
||||
[
|
||||
[projection.runs[0]?.id, "manual_context", "ready"],
|
||||
[projection.runs[1]?.id, "manual_context", "ready"],
|
||||
],
|
||||
);
|
||||
assert.equal(projection.runs[1]?.contextHandoffId, projection.contextHandoffs[1]?.id);
|
||||
assert.include(turns[1]?.text ?? "", "Context handoff (manual_context):");
|
||||
assert.include(turns[1]?.text ?? "", "imported release marker is violet");
|
||||
assert.include(turns[1]?.text ?? "", "I will remember violet.");
|
||||
assert.include(turns[1]?.text ?? "", recoveryPrompt);
|
||||
assert.notInclude(turns[1]?.text ?? "", failedPrompt);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.live("uses portable fallback when native resume fails after a provider switch", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -46,14 +46,16 @@ import Migration0030 from "./Migrations/030_ProjectionThreadShellArchiveIndexes.
|
||||
import Migration0031 from "./Migrations/031_AuthAuthorizationScopes.ts";
|
||||
import Migration0032 from "./Migrations/032_AuthPairingProofKeyThumbprint.ts";
|
||||
import Migration0033 from "./Migrations/033_ProjectionThreadsSettled.ts";
|
||||
import Migration0034 from "./Migrations/034_OrchestrationV2.ts";
|
||||
import Migration0035 from "./Migrations/035_OrchestrationV2Subagents.ts";
|
||||
import Migration0036 from "./Migrations/036_OrchestrationV2Foundation.ts";
|
||||
import Migration0037 from "./Migrations/037_OrchestrationV2ProviderSessionBindings.ts";
|
||||
import Migration0038 from "./Migrations/038_OrchestrationV2ThreadLaunchWorkflows.ts";
|
||||
import Migration0039 from "./Migrations/039_ApplicationEventSource.ts";
|
||||
import Migration0040 from "./Migrations/040_OrchestrationV2EffectCancellation.ts";
|
||||
import Migration0041 from "./Migrations/041_ScheduledTasks.ts";
|
||||
import Migration0034 from "./Migrations/034_ProjectionThreadsSnoozed.ts";
|
||||
import Migration0035 from "./Migrations/035_OrchestrationV2.ts";
|
||||
import Migration0036 from "./Migrations/036_OrchestrationV2Subagents.ts";
|
||||
import Migration0037 from "./Migrations/037_OrchestrationV2Foundation.ts";
|
||||
import Migration0038 from "./Migrations/038_OrchestrationV2ProviderSessionBindings.ts";
|
||||
import Migration0039 from "./Migrations/039_OrchestrationV2ThreadLaunchWorkflows.ts";
|
||||
import Migration0040 from "./Migrations/040_ApplicationEventSource.ts";
|
||||
import Migration0041 from "./Migrations/041_OrchestrationV2EffectCancellation.ts";
|
||||
import Migration0042 from "./Migrations/042_ScheduledTasks.ts";
|
||||
import Migration0043 from "./Migrations/043_LegacyV1ImportState.ts";
|
||||
|
||||
/**
|
||||
* Migration loader with all migrations defined inline.
|
||||
@@ -99,14 +101,16 @@ export const migrationEntries = [
|
||||
[31, "AuthAuthorizationScopes", Migration0031],
|
||||
[32, "AuthPairingProofKeyThumbprint", Migration0032],
|
||||
[33, "ProjectionThreadsSettled", Migration0033],
|
||||
[34, "OrchestrationV2", Migration0034],
|
||||
[35, "OrchestrationV2Subagents", Migration0035],
|
||||
[36, "OrchestrationV2Foundation", Migration0036],
|
||||
[37, "OrchestrationV2ProviderSessionBindings", Migration0037],
|
||||
[38, "OrchestrationV2ThreadLaunchWorkflows", Migration0038],
|
||||
[39, "ApplicationEventSource", Migration0039],
|
||||
[40, "OrchestrationV2EffectCancellation", Migration0040],
|
||||
[41, "ScheduledTasks", Migration0041],
|
||||
[34, "ProjectionThreadsSnoozed", Migration0034],
|
||||
[35, "OrchestrationV2", Migration0035],
|
||||
[36, "OrchestrationV2Subagents", Migration0036],
|
||||
[37, "OrchestrationV2Foundation", Migration0037],
|
||||
[38, "OrchestrationV2ProviderSessionBindings", Migration0038],
|
||||
[39, "OrchestrationV2ThreadLaunchWorkflows", Migration0039],
|
||||
[40, "ApplicationEventSource", Migration0040],
|
||||
[41, "OrchestrationV2EffectCancellation", Migration0041],
|
||||
[42, "ScheduledTasks", Migration0042],
|
||||
[43, "LegacyV1ImportState", Migration0043],
|
||||
] as const;
|
||||
|
||||
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
|
||||
|
||||
@@ -8,7 +8,16 @@ import * as NodeSqliteClient from "../NodeSqliteClient.ts";
|
||||
|
||||
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
|
||||
|
||||
layer("034_035_OrchestrationV2", (it) => {
|
||||
layer("035_036_OrchestrationV2", (it) => {
|
||||
it.effect("keeps released and private migration ids contiguous", () =>
|
||||
Effect.sync(() => {
|
||||
assert.deepStrictEqual(
|
||||
migrationEntries.map(([id]) => id),
|
||||
Array.from({ length: 43 }, (_, index) => index + 1),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("installs the orchestration v2 and subagent schemas", () =>
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
@@ -97,3 +106,57 @@ layer("034_035_OrchestrationV2", (it) => {
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("upgrades a database already at released main migration 034", () =>
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* runMigrations({ toMigrationInclusive: 34 });
|
||||
const snoozeColumns = yield* sql<{ readonly name: string }>`
|
||||
PRAGMA table_info(projection_threads)
|
||||
`;
|
||||
assert.ok(snoozeColumns.some((column) => column.name === "snoozed_until"));
|
||||
assert.ok(snoozeColumns.some((column) => column.name === "snoozed_at"));
|
||||
|
||||
yield* runMigrations({ toMigrationInclusive: 43 });
|
||||
|
||||
const migrations = yield* sql<{
|
||||
readonly migration_id: number;
|
||||
readonly name: string;
|
||||
}>`
|
||||
SELECT migration_id, name
|
||||
FROM effect_sql_migrations
|
||||
WHERE migration_id BETWEEN 34 AND 43
|
||||
ORDER BY migration_id
|
||||
`;
|
||||
assert.deepStrictEqual(
|
||||
migrations.map(({ migration_id, name }) => [migration_id, name]),
|
||||
[
|
||||
[34, "ProjectionThreadsSnoozed"],
|
||||
[35, "OrchestrationV2"],
|
||||
[36, "OrchestrationV2Subagents"],
|
||||
[37, "OrchestrationV2Foundation"],
|
||||
[38, "OrchestrationV2ProviderSessionBindings"],
|
||||
[39, "OrchestrationV2ThreadLaunchWorkflows"],
|
||||
[40, "ApplicationEventSource"],
|
||||
[41, "OrchestrationV2EffectCancellation"],
|
||||
[42, "ScheduledTasks"],
|
||||
[43, "LegacyV1ImportState"],
|
||||
],
|
||||
);
|
||||
|
||||
const v2Tables = yield* sql<{ readonly name: string }>`
|
||||
SELECT name
|
||||
FROM sqlite_master
|
||||
WHERE type = 'table' AND name = 'orchestration_v2_projection_threads'
|
||||
`;
|
||||
assert.strictEqual(v2Tables.length, 1);
|
||||
|
||||
const legacyImportTables = yield* sql<{ readonly name: string }>`
|
||||
SELECT name
|
||||
FROM sqlite_master
|
||||
WHERE type = 'table' AND name = 'orchestration_v2_legacy_imports'
|
||||
`;
|
||||
assert.strictEqual(legacyImportTables.length, 1);
|
||||
}).pipe(Effect.provide(NodeSqliteClient.layerMemory())),
|
||||
);
|
||||
@@ -0,0 +1,27 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
/**
|
||||
* Tracks the incremental import of v1 materialized thread state into the v2
|
||||
* event model. Shells are imported synchronously at startup; full transcripts
|
||||
* are hydrated on demand and by a low-priority background pass.
|
||||
*/
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`
|
||||
CREATE TABLE orchestration_v2_legacy_imports (
|
||||
thread_id TEXT PRIMARY KEY,
|
||||
source_updated_at TEXT NOT NULL,
|
||||
shell_imported_at TEXT NOT NULL,
|
||||
transcript_imported_at TEXT,
|
||||
imported_message_count INTEGER NOT NULL DEFAULT 0,
|
||||
last_error TEXT
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
CREATE INDEX orchestration_v2_legacy_imports_pending_transcript_idx
|
||||
ON orchestration_v2_legacy_imports(transcript_imported_at, shell_imported_at, thread_id)
|
||||
`;
|
||||
});
|
||||
@@ -19,6 +19,7 @@ it.effect("runs projection repair, recovery, worker startup, and bootstrap in or
|
||||
const record = (label: string) => Ref.update(calls, (current) => [...current, label]);
|
||||
|
||||
const result = yield* ServerRuntimeStartup.runOrderedV2StartupPhases({
|
||||
importLegacyShells: record("import"),
|
||||
verify: record("verify").pipe(Effect.as({ valid: false })),
|
||||
rebuild: record("rebuild").pipe(Effect.as({ valid: true })),
|
||||
recover: record("recover").pipe(Effect.as({ closedRequests: 2 })),
|
||||
@@ -27,6 +28,7 @@ it.effect("runs projection repair, recovery, worker startup, and bootstrap in or
|
||||
});
|
||||
|
||||
assert.deepEqual(yield* Ref.get(calls), [
|
||||
"import",
|
||||
"verify",
|
||||
"rebuild",
|
||||
"recover",
|
||||
@@ -44,6 +46,7 @@ it.effect("does not rebuild valid projections", () =>
|
||||
Effect.gen(function* () {
|
||||
const rebuilt = yield* Ref.make(false);
|
||||
yield* ServerRuntimeStartup.runOrderedV2StartupPhases({
|
||||
importLegacyShells: Effect.void,
|
||||
verify: Effect.succeed({ valid: true }),
|
||||
rebuild: Ref.set(rebuilt, true).pipe(Effect.as({ valid: true })),
|
||||
recover: Effect.void,
|
||||
|
||||
@@ -26,6 +26,7 @@ import * as ServerConfig from "./config.ts";
|
||||
import * as Keybindings from "./keybindings.ts";
|
||||
import * as ExternalLauncher from "./process/externalLauncher.ts";
|
||||
import * as EffectWorker from "./orchestration-v2/EffectWorker.ts";
|
||||
import * as LegacyV1ThreadImporter from "./orchestration-v2/LegacyV1ThreadImporter.ts";
|
||||
import * as ProjectionMaintenance from "./orchestration-v2/ProjectionMaintenance.ts";
|
||||
import * as ProviderRuntimeRecovery from "./orchestration-v2/ProviderRuntimeRecoveryService.ts";
|
||||
import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts";
|
||||
@@ -286,21 +287,25 @@ const runStartupPhase = <A, E, R>(phase: string, effect: Effect.Effect<A, E, R>)
|
||||
);
|
||||
|
||||
export function runOrderedV2StartupPhases<
|
||||
Import,
|
||||
Verification extends { readonly valid: boolean },
|
||||
RebuildVerification extends { readonly valid: boolean },
|
||||
Recovery,
|
||||
Bootstrap,
|
||||
ImportError,
|
||||
VerifyError,
|
||||
RebuildError,
|
||||
RecoveryError,
|
||||
WorkerError,
|
||||
BootstrapError,
|
||||
ImportContext,
|
||||
VerifyContext,
|
||||
RebuildContext,
|
||||
RecoveryContext,
|
||||
WorkerContext,
|
||||
BootstrapContext,
|
||||
>(input: {
|
||||
readonly importLegacyShells: Effect.Effect<Import, ImportError, ImportContext>;
|
||||
readonly verify: Effect.Effect<Verification, VerifyError, VerifyContext>;
|
||||
readonly rebuild: Effect.Effect<RebuildVerification, RebuildError, RebuildContext>;
|
||||
readonly recover: Effect.Effect<Recovery, RecoveryError, RecoveryContext>;
|
||||
@@ -308,6 +313,7 @@ export function runOrderedV2StartupPhases<
|
||||
readonly autoBootstrap: Effect.Effect<Bootstrap, BootstrapError, BootstrapContext>;
|
||||
}) {
|
||||
return Effect.gen(function* () {
|
||||
yield* input.importLegacyShells;
|
||||
const verification = yield* input.verify;
|
||||
if (!verification.valid) {
|
||||
const rebuilt = yield* input.rebuild;
|
||||
@@ -328,6 +334,7 @@ export const make = Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig.ServerConfig;
|
||||
const keybindings = yield* Keybindings.Keybindings;
|
||||
const projectionMaintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
|
||||
const legacyV1ThreadImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
|
||||
const providerRuntimeRecovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;
|
||||
const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
|
||||
const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
|
||||
@@ -388,6 +395,16 @@ export const make = Effect.gen(function* () {
|
||||
const welcomeBase = yield* resolveWelcomeBase;
|
||||
const environment = yield* serverEnvironment.getDescriptor;
|
||||
const { recovery, bootstrap: bootstrapTargets } = yield* runOrderedV2StartupPhases({
|
||||
importLegacyShells: runStartupPhase(
|
||||
"orchestration-v2.legacy-v1.import-shells",
|
||||
legacyV1ThreadImporter.reconcileShells.pipe(
|
||||
Effect.tap((summary) =>
|
||||
summary.importedThreadCount === 0
|
||||
? Effect.void
|
||||
: Effect.logInfo("Imported legacy v1 thread shells", summary),
|
||||
),
|
||||
),
|
||||
),
|
||||
verify: runStartupPhase(
|
||||
"orchestration-v2.projections.verify",
|
||||
projectionMaintenance.verify.pipe(
|
||||
@@ -433,6 +450,14 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
yield* Effect.logDebug("Accepting commands");
|
||||
yield* commandGate.signalCommandReady;
|
||||
yield* legacyV1ThreadImporter.importPendingTranscripts.pipe(
|
||||
Effect.tap((summary) =>
|
||||
summary.importedThreadCount === 0
|
||||
? Effect.void
|
||||
: Effect.logInfo("Hydrated legacy v1 thread transcripts", summary),
|
||||
),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
yield* Effect.logDebug("startup phase: publishing welcome event", {
|
||||
environmentId: environment.environmentId,
|
||||
|
||||
@@ -612,6 +612,16 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"orchestration_v2.thread_id": input.threadId,
|
||||
});
|
||||
yield* threadManagement.ensureLegacyTranscript(input.threadId).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationV2GetThreadProjectionError({
|
||||
threadId: input.threadId,
|
||||
message: `Failed to hydrate migrated thread ${input.threadId}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const snapshot = yield* threadManagement.getThreadSnapshot(input.threadId).pipe(
|
||||
Effect.mapError(
|
||||
|
||||
@@ -56,6 +56,9 @@ export const OrchestrationV2CreationSource = Schema.Literals([
|
||||
]);
|
||||
export type OrchestrationV2CreationSource = typeof OrchestrationV2CreationSource.Type;
|
||||
|
||||
export const OrchestrationV2ThreadHistoryOrigin = Schema.Literals(["native", "v1_import"]);
|
||||
export type OrchestrationV2ThreadHistoryOrigin = typeof OrchestrationV2ThreadHistoryOrigin.Type;
|
||||
|
||||
const OrchestrationV2CreationFields = {
|
||||
createdBy: OrchestrationV2Actor,
|
||||
creationSource: OrchestrationV2CreationSource,
|
||||
@@ -296,6 +299,7 @@ export const OrchestrationV2AppThread = Schema.Struct({
|
||||
branch: Schema.NullOr(TrimmedNonEmptyString),
|
||||
worktreePath: Schema.NullOr(TrimmedNonEmptyString),
|
||||
activeProviderThreadId: Schema.NullOr(ProviderThreadId),
|
||||
historyOrigin: Schema.optional(OrchestrationV2ThreadHistoryOrigin),
|
||||
lineage: OrchestrationV2AppThreadLineage,
|
||||
forkedFrom: Schema.NullOr(
|
||||
Schema.Union([
|
||||
@@ -1157,6 +1161,7 @@ export const OrchestrationV2ThreadShell = Schema.Struct({
|
||||
lineage: OrchestrationV2AppThreadLineage,
|
||||
forkedFrom: Schema.NullOr(OrchestrationV2AppThread.fields.forkedFrom),
|
||||
activeProviderThreadId: Schema.NullOr(ProviderThreadId),
|
||||
historyOrigin: Schema.optional(OrchestrationV2ThreadHistoryOrigin),
|
||||
latestRunId: Schema.NullOr(RunId),
|
||||
activeRunId: Schema.NullOr(RunId),
|
||||
status: OrchestrationV2ShellThreadStatus,
|
||||
|
||||
@@ -189,7 +189,7 @@ describe("ssh tunnel scripts", () => {
|
||||
assert.include(buildRemoteStopScript(target), 'rm -f "$PID_FILE" "$PORT_FILE" "$MANAGED_FILE"');
|
||||
assert.include(
|
||||
buildRemoteLaunchScript(),
|
||||
'DEFAULT_RUNTIME_FILE="$DEFAULT_SERVER_HOME/userdata-v2/server-runtime.json"',
|
||||
'DEFAULT_RUNTIME_FILE="$DEFAULT_SERVER_HOME/userdata/server-runtime.json"',
|
||||
);
|
||||
assert.include(buildRemoteLaunchScript(), "resolve_default_runtime_port()");
|
||||
assert.include(
|
||||
|
||||
@@ -440,7 +440,7 @@ export const REMOTE_LAUNCH_SCRIPT = `set -eu
|
||||
STATE_KEY="$1"
|
||||
STATE_DIR="$HOME/.t3/ssh-launch/$STATE_KEY"
|
||||
DEFAULT_SERVER_HOME="$HOME/.t3"
|
||||
DEFAULT_RUNTIME_FILE="$DEFAULT_SERVER_HOME/userdata-v2/server-runtime.json"
|
||||
DEFAULT_RUNTIME_FILE="$DEFAULT_SERVER_HOME/userdata/server-runtime.json"
|
||||
PORT_FILE="$STATE_DIR/port"
|
||||
PID_FILE="$STATE_DIR/pid"
|
||||
MANAGED_FILE="$STATE_DIR/managed"
|
||||
|
||||
Reference in new issue
Block a user