The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 2 | import { expect, it } from "@effect/vitest"; |
| 3 | import { |
| 4 | type AgentSessionSource, |
| 5 | type ServerSettingsError, |
| 6 | EventId, |
| 7 | ProjectId, |
| 8 | ProviderDriverKind, |
| 9 | ProviderInstanceId, |
| 10 | MessageId, |
| 11 | RunId, |
| 12 | ThreadId, |
| 13 | type ApplicationStoredEvent, |
| 14 | type OrchestrationV2AppThread, |
| 15 | type OrchestrationV2DomainEvent, |
| 16 | type OrchestrationV2ProviderThread, |
| 17 | } from "@t3tools/contracts"; |
| 18 | import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; |
| 19 | import * as AcpRegistryRuntimeCoordinator from "@t3tools/provider-acp-registry/server/AcpRegistryRuntimeCoordinator"; |
| 20 | import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; |
| 21 | import * as Context from "effect/Context"; |
| 22 | import * as DateTime from "effect/DateTime"; |
| 23 | import * as Deferred from "effect/Deferred"; |
| 24 | import * as Effect from "effect/Effect"; |
| 25 | import * as FileSystem from "effect/FileSystem"; |
| 26 | import * as Fiber from "effect/Fiber"; |
| 27 | import * as Layer from "effect/Layer"; |
| 28 | import * as Option from "effect/Option"; |
| 29 | import * as Path from "effect/Path"; |
| 30 | import * as Stream from "effect/Stream"; |
| 31 | import * as SqlClient from "effect/sql/SqlClient"; |
| 32 | import * as TestClock from "effect/testing/TestClock"; |
| 33 | |
| 34 | import * as ServerConfig from "../config.ts"; |
| 35 | import * as EventSink from "../orchestration-v2/EventSink.ts"; |
| 36 | import * as EventStore from "../orchestration-v2/EventStore.ts"; |
| 37 | import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; |
| 38 | import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; |
| 39 | import * as ProjectStore from "../orchestration-v2/ProjectStore.ts"; |
| 40 | import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts"; |
| 41 | import * as ThreadCommandExecutor from "../orchestration-v2/ThreadCommandExecutor.ts"; |
| 42 | import { |
| 43 | CLAUDE_MODEL_SELECTION, |
| 44 | CODEX_MODEL_SELECTION, |
| 45 | } from "../orchestration-v2/testkit/fixtures/shared.ts"; |
| 46 | import * as ProviderSessionRuntime from "../persistence/ProviderSessionRuntime.ts"; |
| 47 | import * as SqlitePersistence from "../persistence/Sqlite.ts"; |
| 48 | import * as ServerSettings from "../serverSettings.ts"; |
| 49 | import * as AgentSessionImporter from "./AgentSessionImporter.ts"; |
| 50 | import * as AgentSessionScanner from "./AgentSessionScanner.ts"; |
| 51 | import * as ProjectService from "./ProjectService.ts"; |
| 52 | |
| 53 | const projectId = ProjectId.make("agent-session-import-project"); |
| 54 | const timestamp = "2026-09-01T10:00:00.000Z"; |
| 55 | const now = DateTime.makeUnsafe(timestamp); |
| 56 | const stores = Layer.mergeAll(EventStore.layer, ProjectionStore.layer).pipe( |
| 57 | Layer.provideMerge(SqlitePersistence.layerMemory), |
| 58 | ); |
| 59 | const persistence = Layer.mergeAll( |
| 60 | stores, |
| 61 | EventSink.layer.pipe(Layer.provide(stores)), |
| 62 | ProviderSessionRuntime.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)), |
| 63 | IdAllocator.layer, |
| 64 | ); |
| 65 | |
| 66 | function candidate( |
| 67 | modelSelection: typeof CODEX_MODEL_SELECTION, |
| 68 | providerSessionId: string, |
| 69 | provider: AgentSessionSource = "codex", |
| 70 | ) { |
| 71 | const providerInstanceId = modelSelection.instanceId; |
| 72 | return { |
| 73 | _tag: "Importable" as const, |
| 74 | source: { |
| 75 | provider, |
| 76 | providerInstanceId, |
| 77 | providerSessionId, |
| 78 | filePath: `/tmp/${providerInstanceId}/${providerSessionId}.jsonl`, |
| 79 | size: 100, |
| 80 | mtimeMs: 2, |
| 81 | device: 3, |
| 82 | inode: 4, |
| 83 | birthtimeMs: 1, |
| 84 | }, |
| 85 | thread: { |
| 86 | source: provider, |
| 87 | providerInstanceId, |
| 88 | providerSessionId, |
| 89 | title: "Imported thread", |
| 90 | model: modelSelection.model, |
| 91 | createdAt: timestamp, |
| 92 | updatedAt: timestamp, |
| 93 | omittedMessageCount: 0, |
| 94 | messages: [ |
| 95 | { role: "user" as const, text: "Fix it", createdAt: timestamp }, |
| 96 | { role: "assistant" as const, text: "Fixed", createdAt: timestamp }, |
| 97 | ], |
| 98 | }, |
| 99 | worktree: null as { path: string; branch: string | null } | null, |
| 100 | } satisfies AgentSessionScanner.AgentSessionRecentThread; |
| 101 | } |
| 102 | |
| 103 | const PI_MODEL_SELECTION = { instanceId: ProviderInstanceId.make("pi"), model: "default" }; |
| 104 | |
| 105 | // Pi threads are owned by their session file path, not the session UUID. |
| 106 | const nativeId = ({ source }: ReturnType<typeof candidate>) => |
| 107 | source.provider === "pi" ? source.filePath : source.providerSessionId; |
| 108 | |
| 109 | function importId(source: ReturnType<typeof candidate>) { |
| 110 | return ThreadId.make( |
| 111 | `import:${source.source.providerInstanceId}:${source.source.providerSessionId}`, |
| 112 | ); |
| 113 | } |
| 114 | |
| 115 | const seedOwner = Effect.fn(function* ( |
| 116 | source: ReturnType<typeof candidate>, |
| 117 | lifecycle: "active" | "archived" | "deleted" = "active", |
| 118 | ) { |
| 119 | const sink = yield* EventSink.EventSinkV2; |
| 120 | const ids = yield* IdAllocator.IdAllocatorV2; |
| 121 | const { providerInstanceId, providerSessionId, provider } = source.source; |
| 122 | const nativeThreadId = nativeId(source); |
| 123 | const threadId = ThreadId.make(`owner:${providerInstanceId}:${providerSessionId}`); |
| 124 | const driver = ProviderDriverKind.make(provider); |
| 125 | const providerThread: OrchestrationV2ProviderThread = { |
| 126 | id: ids.derive.providerThread({ driver, nativeThreadId }), |
| 127 | driver, |
| 128 | providerInstanceId, |
| 129 | providerSessionId: null, |
| 130 | appThreadId: threadId, |
| 131 | ownerNodeId: null, |
| 132 | nativeThreadRef: { driver, nativeId: nativeThreadId, strength: "strong" }, |
| 133 | nativeConversationHeadRef: null, |
| 134 | status: "idle", |
| 135 | firstRunOrdinal: 1, |
| 136 | lastRunOrdinal: 1, |
| 137 | handoffIds: [], |
| 138 | forkedFrom: null, |
| 139 | createdAt: now, |
| 140 | updatedAt: now, |
| 141 | }; |
| 142 | const thread: OrchestrationV2AppThread = { |
| 143 | createdBy: "user", |
| 144 | creationSource: "web", |
| 145 | id: threadId, |
| 146 | projectId, |
| 147 | title: "Native thread", |
| 148 | providerInstanceId, |
| 149 | modelSelection: { instanceId: providerInstanceId, model: source.thread.model }, |
| 150 | runtimeMode: "full-access", |
| 151 | interactionMode: "default", |
| 152 | branch: null, |
| 153 | worktreePath: null, |
| 154 | activeProviderThreadId: providerThread.id, |
| 155 | lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, |
| 156 | forkedFrom: null, |
| 157 | createdAt: now, |
| 158 | updatedAt: now, |
| 159 | archivedAt: lifecycle === "archived" ? now : null, |
| 160 | deletedAt: lifecycle === "deleted" ? now : null, |
| 161 | settledOverride: null, |
| 162 | settledAt: null, |
| 163 | lastVisitedAt: null, |
| 164 | }; |
| 165 | yield* sink.write({ |
| 166 | events: [ |
| 167 | { |
| 168 | id: EventId.make(`${threadId}:created`), |
| 169 | type: "thread.created", |
| 170 | threadId, |
| 171 | occurredAt: now, |
| 172 | payload: thread, |
| 173 | }, |
| 174 | { |
| 175 | id: EventId.make(`${threadId}:provider`), |
| 176 | type: "provider-thread.updated", |
| 177 | threadId, |
| 178 | occurredAt: now, |
| 179 | payload: providerThread, |
| 180 | }, |
| 181 | ], |
| 182 | }); |
| 183 | return threadId; |
| 184 | }); |
| 185 | |
| 186 | const makeImporter = Effect.fn(function* ( |
| 187 | candidates: ReadonlyArray<AgentSessionScanner.AgentSessionRecentThread>, |
| 188 | beforeTransaction: Effect.Effect<void> = Effect.void, |
| 189 | getAdapter?: ProviderAdapterRegistry.ProviderAdapterRegistryV2Shape["get"], |
| 190 | threadCommands?: ThreadCommandExecutor.ThreadCommandExecutor["Service"], |
| 191 | settings: Layer.Layer< |
| 192 | ServerSettings.ServerSettingsService, |
| 193 | ServerSettingsError |
| 194 | > = ServerSettings.layerTest(), |
| 195 | realScan?: { |
| 196 | readonly workspaceRoot: string; |
| 197 | readonly scanner: AgentSessionScanner.AgentSessionScanner["Service"]; |
| 198 | }, |
| 199 | ) { |
| 200 | const sql = yield* SqlClient.SqlClient; |
| 201 | const events = yield* EventStore.EventStoreV2; |
| 202 | const projections = yield* ProjectionStore.ProjectionStoreV2; |
| 203 | const published: Array<ApplicationStoredEvent> = []; |
| 204 | const withTransaction: typeof sql.withTransaction = (effect) => |
| 205 | beforeTransaction.pipe(Effect.andThen(sql.withTransaction(effect))); |
| 206 | const importSql = new Proxy(sql, { |
| 207 | get: (target, key, receiver) => |
| 208 | key === "withTransaction" ? withTransaction : Reflect.get(target, key, receiver), |
| 209 | }); |
| 210 | const sinkLayer = Layer.fresh(EventSink.layer).pipe( |
| 211 | Layer.provide( |
| 212 | Layer.mergeAll( |
| 213 | Layer.succeed(SqlClient.SqlClient, importSql), |
| 214 | Layer.succeed(ProjectionStore.ProjectionStoreV2, projections), |
| 215 | Layer.succeed(EventStore.EventStoreV2, { |
| 216 | ...events, |
| 217 | publishCommitted: (batch) => |
| 218 | events.publishCommitted(batch).pipe( |
| 219 | Effect.tap(() => |
| 220 | Effect.sync(() => { |
| 221 | published.push(...batch); |
| 222 | }), |
| 223 | ), |
| 224 | ), |
| 225 | }), |
| 226 | ), |
| 227 | ), |
| 228 | ); |
| 229 | const context = yield* Layer.build( |
| 230 | AgentSessionImporter.layer.pipe( |
| 231 | Layer.provide( |
| 232 | Layer.mergeAll( |
| 233 | sinkLayer, |
| 234 | settings, |
| 235 | Layer.succeed(IdAllocator.IdAllocatorV2, yield* IdAllocator.IdAllocatorV2), |
| 236 | Layer.succeed( |
| 237 | ProviderSessionRuntime.ProviderSessionRuntimeRepository, |
| 238 | yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository, |
| 239 | ), |
| 240 | realScan === undefined |
| 241 | ? Layer.mock(AgentSessionScanner.AgentSessionScanner)({ |
| 242 | recentThreads: () => Stream.fromIterable(candidates), |
| 243 | }) |
| 244 | : Layer.succeed(AgentSessionScanner.AgentSessionScanner, realScan.scanner), |
| 245 | Layer.mock(ProjectService.ProjectService)({ |
| 246 | getById: () => |
| 247 | Effect.succeedSome({ |
| 248 | id: projectId, |
| 249 | title: "Project", |
| 250 | workspaceRoot: realScan?.workspaceRoot ?? "/workspace/project", |
| 251 | defaultModelSelection: null, |
| 252 | scripts: [], |
| 253 | createdAt: timestamp, |
| 254 | updatedAt: timestamp, |
| 255 | deletedAt: null, |
| 256 | }), |
| 257 | }), |
| 258 | Layer.mock(Orchestrator.OrchestratorV2)({ |
| 259 | getThreadRecords: (threadId, fields) => |
| 260 | projections |
| 261 | .getThreadRecords(threadId, fields) |
| 262 | .pipe( |
| 263 | Effect.mapError( |
| 264 | (cause) => new Orchestrator.OrchestratorProjectionError({ threadId, cause }), |
| 265 | ), |
| 266 | ), |
| 267 | }), |
| 268 | Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)( |
| 269 | getAdapter === undefined ? {} : { get: getAdapter }, |
| 270 | ), |
| 271 | Layer.succeed( |
| 272 | ThreadCommandExecutor.ThreadCommandExecutor, |
| 273 | threadCommands ?? (yield* ThreadCommandExecutor.make), |
| 274 | ), |
| 275 | ), |
| 276 | ), |
| 277 | ), |
| 278 | ); |
| 279 | const importer = Context.get(context, AgentSessionImporter.AgentSessionImporter); |
| 280 | return { |
| 281 | run: importer.importRecentAgentThreads({ projectId }), |
| 282 | importNativeHistory: importer.importNativeHistory, |
| 283 | published, |
| 284 | }; |
| 285 | }); |
| 286 | |
| 287 | it.effect( |
| 288 | "ignores owned sessions, including archived and deleted threads, but imports other instances and unowned sessions", |
| 289 | () => |
| 290 | Effect.gen(function* () { |
| 291 | const projections = yield* ProjectionStore.ProjectionStoreV2; |
| 292 | const events = yield* EventStore.EventStoreV2; |
| 293 | const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; |
| 294 | const active = candidate(CODEX_MODEL_SELECTION, "active"); |
| 295 | const archived = candidate( |
| 296 | CLAUDE_MODEL_SELECTION, |
| 297 | "020e7f00-dce6-406b-8ec6-ed90498945d6", |
| 298 | "claudeAgent", |
| 299 | ); |
| 300 | const deleted = candidate(CODEX_MODEL_SELECTION, "deleted"); |
| 301 | const ownedPi = candidate(PI_MODEL_SELECTION, "owned-pi", "pi"); |
| 302 | const owners = [ |
| 303 | yield* seedOwner(active), |
| 304 | yield* seedOwner(archived, "archived"), |
| 305 | yield* seedOwner(deleted, "deleted"), |
| 306 | yield* seedOwner(ownedPi), |
| 307 | ]; |
| 308 | const before = yield* Effect.forEach(owners, (id) => |
| 309 | projections.getThreadRecords(id, ["providerThreads"]), |
| 310 | ); |
| 311 | const otherInstance = candidate( |
| 312 | { ...CLAUDE_MODEL_SELECTION, instanceId: ProviderInstanceId.make("claude-other") }, |
| 313 | archived.source.providerSessionId, |
| 314 | "claudeAgent", |
| 315 | ); |
| 316 | const unowned = candidate(CODEX_MODEL_SELECTION, "unowned"); |
| 317 | unowned.thread.omittedMessageCount = 1; |
| 318 | unowned.worktree = { path: "/workspace/project/.claude/worktrees/feat", branch: "feat" }; |
| 319 | const unownedPi = candidate(PI_MODEL_SELECTION, "unowned-pi", "pi"); |
| 320 | const importer = yield* makeImporter([ |
| 321 | active, |
| 322 | archived, |
| 323 | deleted, |
| 324 | ownedPi, |
| 325 | otherInstance, |
| 326 | unowned, |
| 327 | unownedPi, |
| 328 | ]); |
| 329 | |
| 330 | expect(yield* importer.run).toEqual({ importedCount: 3, skippedCount: 0 }); |
| 331 | for (const source of [active, archived, deleted, ownedPi]) { |
| 332 | const threadId = importId(source); |
| 333 | expect(yield* Effect.option(projections.getThread(threadId))).toEqual(Option.none()); |
| 334 | expect(yield* events.read({ threadId }).pipe(Stream.runCollect)).toEqual([]); |
| 335 | expect(yield* runtimes.getByThreadId({ threadId })).toEqual(Option.none()); |
| 336 | } |
| 337 | expect( |
| 338 | yield* Effect.forEach(owners, (id) => |
| 339 | projections.getThreadRecords(id, ["providerThreads"]), |
| 340 | ), |
| 341 | ).toEqual(before); |
| 342 | expect( |
| 343 | new Set( |
| 344 | importer.published.flatMap((stored) => |
| 345 | "event" in stored ? [stored.event.threadId] : [], |
| 346 | ), |
| 347 | ), |
| 348 | ).toEqual(new Set([importId(otherInstance), importId(unowned), importId(unownedPi)])); |
| 349 | for (const source of [otherInstance, unowned, unownedPi]) { |
| 350 | const threadId = importId(source); |
| 351 | const records = yield* projections.getThreadRecords(threadId, [ |
| 352 | "messages", |
| 353 | "turnItems", |
| 354 | "providerThreads", |
| 355 | ]); |
| 356 | expect(records.messages.map((message) => message.text)).toEqual(["Fix it", "Fixed"]); |
| 357 | const notices = records.turnItems.filter((item) => item.type === "system_notice"); |
| 358 | if (source === unowned) { |
| 359 | expect(records.turnItems[0]).toBe(notices[0]); |
| 360 | expect(notices).toMatchObject([ |
| 361 | { |
| 362 | ordinal: 1, |
| 363 | runId: null, |
| 364 | message: expect.stringContaining("1 earlier message was not imported"), |
| 365 | }, |
| 366 | ]); |
| 367 | } else { |
| 368 | expect(notices).toEqual([]); |
| 369 | } |
| 370 | expect(records.thread.historyOrigin).toBe("v1_import"); |
| 371 | expect(records.thread.worktreePath).toBe(source.worktree?.path ?? null); |
| 372 | expect(records.thread.branch).toBe(source.worktree?.branch ?? null); |
| 373 | expect(records.thread.activeProviderThreadId).toBe(records.providerThreads[0]?.id); |
| 374 | expect(records.providerThreads[0]?.nativeThreadRef?.nativeId).toBe(nativeId(source)); |
| 375 | expect(Option.getOrThrow(yield* runtimes.getByThreadId({ threadId }))).toMatchObject({ |
| 376 | providerInstanceId: source.source.providerInstanceId, |
| 377 | resumeCursor: |
| 378 | source.source.provider === "claudeAgent" |
| 379 | ? { threadId, resume: source.source.providerSessionId } |
| 380 | : { threadId: nativeId(source) }, |
| 381 | runtimePayload: { |
| 382 | cwd: source.worktree?.path ?? "/workspace/project", |
| 383 | importedTranscripts: [source.source], |
| 384 | }, |
| 385 | }); |
| 386 | } |
| 387 | }).pipe(Effect.scoped, Effect.provide(persistence)), |
| 388 | ); |
| 389 | |
| 390 | it.effect("tolerates a missing transcript owner but propagates failed ownership reads", () => |
| 391 | Effect.gen(function* () { |
| 392 | const sql = yield* SqlClient.SqlClient; |
| 393 | const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; |
| 394 | const source = candidate(CODEX_MODEL_SELECTION, "ownership-read"); |
| 395 | const threadId = importId(source); |
| 396 | yield* runtimes.upsert({ |
| 397 | threadId: ThreadId.make("missing-owner"), |
| 398 | providerName: "codex", |
| 399 | providerInstanceId: source.source.providerInstanceId, |
| 400 | adapterKey: "codex", |
| 401 | runtimeMode: "full-access", |
| 402 | status: "stopped", |
| 403 | lastSeenAt: timestamp, |
| 404 | resumeCursor: null, |
| 405 | runtimePayload: { importedTranscripts: [source.source] }, |
| 406 | }); |
| 407 | yield* runtimes.recordImportedTranscript({ |
| 408 | threadId: ThreadId.make("missing-owner"), |
| 409 | source: source.source, |
| 410 | }); |
| 411 | const importer = yield* makeImporter([source]); |
| 412 | expect(yield* importer.run).toEqual({ importedCount: 1, skippedCount: 0 }); |
| 413 | |
| 414 | yield* sql`UPDATE orchestration_v2_projection_threads SET payload_json = '{}' WHERE thread_id = ${threadId}`; |
| 415 | expect(yield* Effect.flip(importer.run)).toMatchObject({ |
| 416 | _tag: "AgentSessionScanError", |
| 417 | operation: "read-projects", |
| 418 | cause: { |
| 419 | _tag: "OrchestratorProjectionError", |
| 420 | threadId, |
| 421 | cause: { _tag: "ProjectionStoreReadError" }, |
| 422 | }, |
| 423 | }); |
| 424 | }).pipe(Effect.scoped, Effect.provide(persistence)), |
| 425 | ); |
| 426 | |
| 427 | it.effect("rechecks ownership after the import reaches the commit transaction", () => |
| 428 | Effect.gen(function* () { |
| 429 | const enteringTransaction = yield* Deferred.make<void>(); |
| 430 | const continueTransaction = yield* Deferred.make<void>(); |
| 431 | const source = candidate(CODEX_MODEL_SELECTION, "claimed-during-import"); |
| 432 | const importer = yield* makeImporter( |
| 433 | [source], |
| 434 | Deferred.succeed(enteringTransaction, undefined).pipe( |
| 435 | Effect.andThen(Deferred.await(continueTransaction)), |
| 436 | ), |
| 437 | ); |
| 438 | const pending = yield* Effect.forkScoped(importer.run); |
| 439 | yield* Deferred.await(enteringTransaction); |
| 440 | // Commit ownership after all pre-transaction reads, before the import acquires SQLite. |
| 441 | const ownerId = yield* seedOwner(source); |
| 442 | yield* Deferred.succeed(continueTransaction, undefined); |
| 443 | expect(yield* Fiber.join(pending)).toEqual({ importedCount: 0, skippedCount: 0 }); |
| 444 | expect(yield* importer.run).toEqual({ importedCount: 0, skippedCount: 0 }); |
| 445 | const projections = yield* ProjectionStore.ProjectionStoreV2; |
| 446 | const events = yield* EventStore.EventStoreV2; |
| 447 | const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; |
| 448 | expect(yield* Effect.option(projections.getThread(importId(source)))).toEqual(Option.none()); |
| 449 | expect(yield* events.read({ threadId: importId(source) }).pipe(Stream.runCollect)).toEqual([]); |
| 450 | expect(yield* runtimes.list()).toEqual([]); |
| 451 | expect(importer.published).toEqual([]); |
| 452 | expect( |
| 453 | (yield* projections.getThreadRecords(ownerId, ["providerThreads"])).providerThreads[0] |
| 454 | ?.appThreadId, |
| 455 | ).toBe(ownerId); |
| 456 | }).pipe(Effect.scoped, Effect.provide(persistence)), |
| 457 | ); |
| 458 | |
| 459 | it.effect( |
| 460 | "retries failed commits and runtime persistence without replaying committed history", |
| 461 | () => |
| 462 | Effect.gen(function* () { |
| 463 | const sql = yield* SqlClient.SqlClient; |
| 464 | const events = yield* EventStore.EventStoreV2; |
| 465 | const projections = yield* ProjectionStore.ProjectionStoreV2; |
| 466 | const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; |
| 467 | const source = candidate(CODEX_MODEL_SELECTION, "retry"); |
| 468 | const threadId = importId(source); |
| 469 | const importer = yield* makeImporter([source]); |
| 470 | yield* sql`CREATE TEMP TRIGGER fail_import BEFORE INSERT ON orchestration_events WHEN NEW.event_type = 'message.updated' BEGIN SELECT RAISE(ABORT, 'test publication failure'); END`; |
| 471 | expect(yield* importer.run).toEqual({ importedCount: 0, skippedCount: 1 }); |
| 472 | expect(yield* events.read({ threadId }).pipe(Stream.runCollect)).toEqual([]); |
| 473 | expect(yield* Effect.option(projections.getThread(threadId))).toEqual(Option.none()); |
| 474 | expect(yield* runtimes.list()).toEqual([]); |
| 475 | expect(importer.published).toEqual([]); |
| 476 | yield* sql`DROP TRIGGER fail_import`; |
| 477 | |
| 478 | yield* sql`CREATE TEMP TRIGGER fail_runtime BEFORE INSERT ON provider_session_runtime BEGIN SELECT RAISE(ABORT, 'test runtime failure'); END`; |
| 479 | expect(yield* importer.run).toEqual({ importedCount: 0, skippedCount: 1 }); |
| 480 | const committed = yield* events.read({ threadId }).pipe(Stream.runCollect); |
| 481 | expect(committed).toHaveLength(6); |
| 482 | expect(importer.published).toHaveLength(6); |
| 483 | expect(yield* runtimes.list()).toEqual([]); |
| 484 | yield* sql`DROP TRIGGER fail_runtime`; |
| 485 | |
| 486 | expect(yield* importer.run).toEqual({ importedCount: 0, skippedCount: 0 }); |
| 487 | expect(yield* importer.run).toEqual({ importedCount: 0, skippedCount: 0 }); |
| 488 | expect(yield* events.read({ threadId }).pipe(Stream.runCollect)).toEqual(committed); |
| 489 | expect(importer.published).toHaveLength(6); |
| 490 | expect( |
| 491 | (yield* projections.getThreadRecords(threadId, ["messages"])).messages.map( |
| 492 | (message) => message.text, |
| 493 | ), |
| 494 | ).toEqual(["Fix it", "Fixed"]); |
| 495 | expect(Option.getOrThrow(yield* runtimes.getByThreadId({ threadId }))).toMatchObject({ |
| 496 | providerInstanceId: source.source.providerInstanceId, |
| 497 | resumeCursor: { threadId: source.source.providerSessionId }, |
| 498 | runtimePayload: { importedTranscripts: [source.source] }, |
| 499 | }); |
| 500 | }).pipe(Effect.scoped, Effect.provide(persistence)), |
| 501 | ); |
| 502 | |
| 503 | it.effect("counts only new threads when re-importing cached and recovered transcripts", () => |
| 504 | Effect.gen(function* () { |
| 505 | const events = yield* EventStore.EventStoreV2; |
| 506 | const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; |
| 507 | const cached = candidate( |
| 508 | CLAUDE_MODEL_SELECTION, |
| 509 | "020e7f00-dce6-406b-8ec6-ed90498945d6", |
| 510 | "claudeAgent", |
| 511 | ); |
| 512 | const recovered = candidate(CODEX_MODEL_SELECTION, "recovered"); |
| 513 | const initial = yield* makeImporter([cached, recovered]); |
| 514 | expect(yield* initial.run).toEqual({ importedCount: 2, skippedCount: 0 }); |
| 515 | const before = yield* events.read({ threadId: importId(recovered) }).pipe(Stream.runCollect); |
| 516 | // The file changed on disk but still holds the imported messages. |
| 517 | recovered.source.size += 100; |
| 518 | recovered.source.mtimeMs += 1; |
| 519 | const duplicate = { ...recovered.source, filePath: "/tmp/duplicate.jsonl" }; |
| 520 | const fresh = candidate(CODEX_MODEL_SELECTION, "fresh"); |
| 521 | const repeated = yield* makeImporter([ |
| 522 | { _tag: "AlreadyImported", source: cached.source }, |
| 523 | recovered, |
| 524 | { _tag: "Duplicate", source: duplicate }, |
| 525 | fresh, |
| 526 | { _tag: "Skipped" }, |
| 527 | ]); |
| 528 | |
| 529 | expect(yield* repeated.run).toEqual({ importedCount: 1, skippedCount: 1 }); |
| 530 | expect(yield* events.read({ threadId: importId(recovered) }).pipe(Stream.runCollect)).toEqual( |
| 531 | before, |
| 532 | ); |
| 533 | expect( |
| 534 | new Set( |
| 535 | repeated.published.flatMap((stored) => ("event" in stored ? [stored.event.threadId] : [])), |
| 536 | ), |
| 537 | ).toEqual(new Set([importId(fresh)])); |
| 538 | expect( |
| 539 | Option.getOrThrow(yield* runtimes.getByThreadId({ threadId: importId(recovered) })), |
| 540 | ).toMatchObject({ |
| 541 | runtimePayload: { importedTranscripts: [recovered.source, duplicate] }, |
| 542 | }); |
| 543 | }).pipe(Effect.scoped, Effect.provide(persistence)), |
| 544 | ); |
| 545 | |
| 546 | it.effect("does not certify new native history after a partial import retry", () => |
| 547 | Effect.gen(function* () { |
| 548 | const sql = yield* SqlClient.SqlClient; |
| 549 | const projections = yield* ProjectionStore.ProjectionStoreV2; |
| 550 | const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; |
| 551 | const original = candidate(CODEX_MODEL_SELECTION, "partial-retry"); |
| 552 | const threadId = importId(original); |
| 553 | const importer = yield* makeImporter([original]); |
| 554 | yield* sql`CREATE TEMP TRIGGER fail_runtime BEFORE INSERT ON provider_session_runtime BEGIN SELECT RAISE(ABORT, 'test runtime failure'); END`; |
| 555 | expect(yield* importer.run).toEqual({ importedCount: 0, skippedCount: 1 }); |
| 556 | yield* sql`DROP TRIGGER fail_runtime`; |
| 557 | expect(yield* runtimes.list()).toEqual([]); |
| 558 | const continued = candidate(CODEX_MODEL_SELECTION, original.source.providerSessionId); |
| 559 | continued.source.size = 200; |
| 560 | continued.source.mtimeMs = 3; |
| 561 | continued.thread.messages.push( |
| 562 | { role: "user", text: "Continue outside T3", createdAt: timestamp }, |
| 563 | { role: "assistant", text: "Native continuation", createdAt: timestamp }, |
| 564 | ); |
| 565 | // The thread holds only the original messages, so the continued transcript stays unrecorded. |
| 566 | expect(yield* (yield* makeImporter([continued])).run).toEqual({ |
| 567 | importedCount: 0, |
| 568 | skippedCount: 1, |
| 569 | }); |
| 570 | expect(yield* runtimes.list()).toEqual([]); |
| 571 | expect( |
| 572 | (yield* projections.getThreadRecords(threadId, ["messages"])).messages.map( |
| 573 | (message) => message.text, |
| 574 | ), |
| 575 | ).toEqual(["Fix it", "Fixed"]); |
| 576 | }).pipe(Effect.scoped, Effect.provide(persistence)), |
| 577 | ); |
| 578 | |
| 579 | it.effect("does not record a changed transcript as imported without its new messages", () => |
| 580 | Effect.gen(function* () { |
| 581 | const projections = yield* ProjectionStore.ProjectionStoreV2; |
| 582 | const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; |
| 583 | const first = candidate( |
| 584 | CLAUDE_MODEL_SELECTION, |
| 585 | "6f1c2a7e-3b4d-4e5f-9a8b-1c2d3e4f5a6b", |
| 586 | "claudeAgent", |
| 587 | ); |
| 588 | const threadId = importId(first); |
| 589 | expect(yield* (yield* makeImporter([first])).run).toEqual({ |
| 590 | importedCount: 1, |
| 591 | skippedCount: 0, |
| 592 | }); |
| 593 | |
| 594 | const continued = candidate( |
| 595 | CLAUDE_MODEL_SELECTION, |
| 596 | first.source.providerSessionId, |
| 597 | "claudeAgent", |
| 598 | ); |
| 599 | continued.source.size = 200; |
| 600 | continued.source.mtimeMs = 3; |
| 601 | continued.thread.messages.push( |
| 602 | { role: "user", text: "Continue", createdAt: timestamp }, |
| 603 | { role: "assistant", text: "Continued", createdAt: timestamp }, |
| 604 | ); |
| 605 | yield* (yield* makeImporter([continued])).run; |
| 606 | |
| 607 | const recorded = AgentSessionScanner.decodeImportedTranscriptPayload( |
| 608 | Option.getOrThrow(yield* runtimes.getByThreadId({ threadId })).runtimePayload, |
| 609 | ).pipe(Option.getOrThrow).importedTranscripts; |
| 610 | const texts = (yield* projections.getThreadRecords(threadId, ["messages"])).messages.map( |
| 611 | (message) => message.text, |
| 612 | ); |
| 613 | expect({ |
| 614 | recordsChangedTranscript: recorded?.some((source) => source.size === 200) ?? false, |
| 615 | showsNewMessages: texts.includes("Continued"), |
| 616 | }).not.toEqual({ recordsChangedTranscript: true, showsNewMessages: false }); |
| 617 | }).pipe(Effect.scoped, Effect.provide(persistence)), |
| 618 | ); |
| 619 | |
| 620 | it.effect( |
| 621 | "copies native session history into the imported thread once, retrying a failed read", |
| 622 | () => |
| 623 | Effect.gen(function* () { |
| 624 | const projections = yield* ProjectionStore.ProjectionStoreV2; |
| 625 | const source = candidate(CODEX_MODEL_SELECTION, "native-history"); |
| 626 | const threadId = yield* seedOwner(source); |
| 627 | const resolved: Array<ProviderInstanceId> = []; |
| 628 | const opened: Array<ProviderAdapter.ProviderAdapterV2OpenSessionInput> = []; |
| 629 | let closed = false; |
| 630 | let failRead = true; |
| 631 | const replayed = (role: "user" | "assistant", text: string) => ({ |
| 632 | createdBy: role === "user" ? ("user" as const) : ("agent" as const), |
| 633 | creationSource: "provider" as const, |
| 634 | id: MessageId.make(`replayed:${text}`), |
| 635 | threadId, |
| 636 | runId: null, |
| 637 | nodeId: null, |
| 638 | role, |
| 639 | text, |
| 640 | attachments: [], |
| 641 | streaming: false, |
| 642 | createdAt: now, |
| 643 | updatedAt: now, |
| 644 | }); |
| 645 | const adapter = { |
| 646 | openSession: (input: ProviderAdapter.ProviderAdapterV2OpenSessionInput) => |
| 647 | Effect.acquireRelease( |
| 648 | Effect.sync(() => { |
| 649 | opened.push(input); |
| 650 | return { |
| 651 | readThreadSnapshot: ({ providerThread }) => |
| 652 | failRead |
| 653 | ? Effect.fail( |
| 654 | new ProviderAdapter.ProviderAdapterReadThreadSnapshotError({ |
| 655 | driver: providerThread.driver, |
| 656 | providerThreadId: providerThread.id, |
| 657 | }), |
| 658 | ) |
| 659 | : Effect.succeed({ |
| 660 | providerThread, |
| 661 | providerTurns: [], |
| 662 | runtimeRequests: [], |
| 663 | reasoningMessageIds: [MessageId.make("replayed:Check the build log")], |
| 664 | messages: [ |
| 665 | replayed("user", "Fix the build"), |
| 666 | replayed("assistant", "Check the build log"), |
| 667 | replayed("assistant", "Fixed it"), |
| 668 | replayed("assistant", " "), |
| 669 | ], |
| 670 | }), |
| 671 | } as Pick<ProviderAdapter.ProviderAdapterV2SessionRuntime, "readThreadSnapshot">; |
| 672 | }), |
| 673 | () => |
| 674 | Effect.sync(() => { |
| 675 | closed = true; |
| 676 | }), |
| 677 | ), |
| 678 | } as unknown as ProviderAdapter.ProviderAdapterV2["Service"]; |
| 679 | const importer = yield* makeImporter([], Effect.void, (instanceId) => |
| 680 | Effect.sync(() => { |
| 681 | resolved.push(instanceId); |
| 682 | return adapter; |
| 683 | }), |
| 684 | ); |
| 685 | |
| 686 | const importHistory = importer.importNativeHistory({ |
| 687 | threadId, |
| 688 | workspaceRoot: "/workspace/project", |
| 689 | }); |
| 690 | |
| 691 | expect((yield* Effect.flip(importHistory))._tag).toBe( |
| 692 | "ProviderAdapterReadThreadSnapshotError", |
| 693 | ); |
| 694 | expect(closed).toBe(true); |
| 695 | expect( |
| 696 | (yield* projections.getThreadRecords(threadId, [])).thread.historyOrigin, |
| 697 | ).toBeUndefined(); |
| 698 | |
| 699 | failRead = false; |
| 700 | expect(yield* importHistory).toBe(3); |
| 701 | expect(resolved).toEqual([ |
| 702 | CODEX_MODEL_SELECTION.instanceId, |
| 703 | CODEX_MODEL_SELECTION.instanceId, |
| 704 | ]); |
| 705 | expect(opened[1]).toMatchObject({ |
| 706 | threadId, |
| 707 | initialNativeThreadId: source.source.providerSessionId, |
| 708 | runtimePolicy: { cwd: "/workspace/project" }, |
| 709 | }); |
| 710 | // Forks keep run-less history only for this origin. |
| 711 | expect((yield* projections.getThreadRecords(threadId, [])).thread.historyOrigin).toBe( |
| 712 | "v1_import", |
| 713 | ); |
| 714 | expect(yield* importHistory).toBe(0); |
| 715 | expect(opened).toHaveLength(2); |
| 716 | const page = yield* projections.getTimelinePage(threadId, { view: "activity", limit: 10 }); |
| 717 | expect( |
| 718 | page.items.map(({ item }) => [ |
| 719 | item.type, |
| 720 | item.runId, |
| 721 | "text" in item ? item.text : undefined, |
| 722 | ]), |
| 723 | ).toEqual([ |
| 724 | ["user_message", null, "Fix the build"], |
| 725 | ["reasoning", null, "Check the build log"], |
| 726 | ["assistant_message", null, "Fixed it"], |
| 727 | ]); |
| 728 | }).pipe(Effect.scoped, Effect.provide(persistence)), |
| 729 | ); |
| 730 | |
| 731 | it.effect("releases the ACP import lock when a native session never answers", () => |
| 732 | Effect.gen(function* () { |
| 733 | const projections = yield* ProjectionStore.ProjectionStoreV2; |
| 734 | const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; |
| 735 | const threadId = yield* seedOwner(candidate(CODEX_MODEL_SELECTION, "native-history-hang")); |
| 736 | const opened = yield* Deferred.make<void>(); |
| 737 | let closed = false; |
| 738 | // An agent that only resumes sessions and never answers its first session/resume. |
| 739 | const adapter = { |
| 740 | openSession: () => |
| 741 | Effect.suspend(() => { |
| 742 | if (!closed) { |
| 743 | return Effect.addFinalizer(() => |
| 744 | Effect.sync(() => { |
| 745 | closed = true; |
| 746 | }), |
| 747 | ).pipe( |
| 748 | Effect.andThen(Deferred.succeed(opened, undefined)), |
| 749 | Effect.andThen(Effect.never), |
| 750 | ); |
| 751 | } |
| 752 | return Effect.succeed({ |
| 753 | readThreadSnapshot: ({ providerThread }) => |
| 754 | Effect.succeed({ |
| 755 | providerThread, |
| 756 | providerTurns: [], |
| 757 | runtimeRequests: [], |
| 758 | messages: [ |
| 759 | { |
| 760 | createdBy: "user", |
| 761 | creationSource: "provider", |
| 762 | id: MessageId.make("replayed:hang"), |
| 763 | threadId, |
| 764 | runId: null, |
| 765 | nodeId: null, |
| 766 | role: "user", |
| 767 | text: "Fix the build", |
| 768 | attachments: [], |
| 769 | streaming: false, |
| 770 | createdAt: now, |
| 771 | updatedAt: now, |
| 772 | }, |
| 773 | ], |
| 774 | }), |
| 775 | } as Pick<ProviderAdapter.ProviderAdapterV2SessionRuntime, "readThreadSnapshot">); |
| 776 | }), |
| 777 | } as unknown as ProviderAdapter.ProviderAdapterV2["Service"]; |
| 778 | const importer = yield* makeImporter([], Effect.void, () => Effect.succeed(adapter)); |
| 779 | const importHistory = coordinator.withSessionMutation( |
| 780 | importer.importNativeHistory({ threadId, workspaceRoot: "/workspace/project" }), |
| 781 | ); |
| 782 | |
| 783 | const importing = yield* importHistory.pipe(Effect.flip, Effect.forkChild); |
| 784 | yield* Deferred.await(opened); |
| 785 | // Any other ACP import or delete waits for the same lock. |
| 786 | const next = yield* coordinator |
| 787 | .withSessionMutation(Effect.succeed("next")) |
| 788 | .pipe(Effect.forkChild); |
| 789 | yield* TestClock.adjust("2 minutes"); |
| 790 | |
| 791 | expect((yield* Fiber.join(importing))._tag).toBe("TimeoutError"); |
| 792 | expect(closed).toBe(true); |
| 793 | expect(yield* Fiber.join(next)).toBe("next"); |
| 794 | expect( |
| 795 | (yield* projections.getThreadRecords(threadId, [])).thread.historyOrigin, |
| 796 | ).toBeUndefined(); |
| 797 | expect(yield* importHistory).toBe(1); |
| 798 | expect((yield* projections.getThreadRecords(threadId, [])).thread.historyOrigin).toBe( |
| 799 | "v1_import", |
| 800 | ); |
| 801 | }).pipe( |
| 802 | Effect.scoped, |
| 803 | Effect.provide(Layer.merge(persistence, AcpRegistryRuntimeCoordinator.layer)), |
| 804 | ), |
| 805 | ); |
| 806 | |
| 807 | /** |
| 808 | * Runs a thread command that read the thread before the history load ended and |
| 809 | * writes once the importer is about to commit, as an unserialized write would. |
| 810 | */ |
| 811 | const importDuringCommand = Effect.fn(function* ( |
| 812 | name: string, |
| 813 | command: (thread: OrchestrationV2AppThread) => ReadonlyArray<OrchestrationV2DomainEvent>, |
| 814 | ) { |
| 815 | const projections = yield* ProjectionStore.ProjectionStoreV2; |
| 816 | const sink = yield* EventSink.EventSinkV2; |
| 817 | const threadId = yield* seedOwner(candidate(CODEX_MODEL_SELECTION, name)); |
| 818 | const lock = yield* ThreadCommandExecutor.make; |
| 819 | const loaded = yield* Deferred.make<void>(); |
| 820 | const importerCommitting = yield* Deferred.make<void>(); |
| 821 | const commandWritten = yield* Deferred.make<void>(); |
| 822 | const committing = Deferred.succeed(importerCommitting, undefined); |
| 823 | const adapter = { |
| 824 | openSession: () => |
| 825 | Effect.succeed({ |
| 826 | readThreadSnapshot: ({ providerThread }) => |
| 827 | Deferred.await(loaded).pipe( |
| 828 | Effect.as({ |
| 829 | providerThread, |
| 830 | providerTurns: [], |
| 831 | runtimeRequests: [], |
| 832 | messages: [ |
| 833 | { |
| 834 | createdBy: "user" as const, |
| 835 | creationSource: "provider" as const, |
| 836 | id: MessageId.make(`replayed:${name}`), |
| 837 | threadId, |
| 838 | runId: null, |
| 839 | nodeId: null, |
| 840 | role: "user" as const, |
| 841 | text: "Fix the build", |
| 842 | attachments: [], |
| 843 | streaming: false, |
| 844 | createdAt: now, |
| 845 | updatedAt: now, |
| 846 | }, |
| 847 | ], |
| 848 | }), |
| 849 | ), |
| 850 | } as Pick<ProviderAdapter.ProviderAdapterV2SessionRuntime, "readThreadSnapshot">), |
| 851 | } as unknown as ProviderAdapter.ProviderAdapterV2["Service"]; |
| 852 | const importer = yield* makeImporter( |
| 853 | [], |
| 854 | committing.pipe(Effect.andThen(Deferred.await(commandWritten))), |
| 855 | () => Effect.succeed(adapter), |
| 856 | { |
| 857 | ...lock, |
| 858 | withLock: (key, effect) => committing.pipe(Effect.andThen(lock.withLock(key, effect))), |
| 859 | }, |
| 860 | ); |
| 861 | const commanding = yield* Effect.forkScoped( |
| 862 | lock.withLock( |
| 863 | threadId, |
| 864 | Effect.gen(function* () { |
| 865 | const { thread } = yield* projections.getThreadRecords(threadId, []); |
| 866 | yield* Deferred.succeed(loaded, undefined); |
| 867 | yield* Deferred.await(importerCommitting); |
| 868 | yield* sink.write({ events: command(thread) }); |
| 869 | yield* Deferred.succeed(commandWritten, undefined); |
| 870 | }), |
| 871 | ), |
| 872 | ); |
| 873 | const imported = yield* importer.importNativeHistory({ |
| 874 | threadId, |
| 875 | workspaceRoot: "/workspace/project", |
| 876 | }); |
| 877 | yield* Fiber.join(commanding); |
| 878 | const records = yield* projections.getThreadRecords(threadId, ["runs"]); |
| 879 | const page = yield* projections.getTimelinePage(threadId, { view: "messages", limit: 10 }); |
| 880 | return { imported, thread: records.thread, runs: records.runs, items: page.items }; |
| 881 | }); |
| 882 | |
| 883 | it.effect("keeps a thread edit made while the native history loads", () => |
| 884 | Effect.gen(function* () { |
| 885 | const result = yield* importDuringCommand("renamed-during-load", (thread) => [ |
| 886 | { |
| 887 | id: EventId.make(`${thread.id}:renamed`), |
| 888 | type: "thread.metadata-updated", |
| 889 | threadId: thread.id, |
| 890 | occurredAt: now, |
| 891 | payload: { ...thread, title: "Renamed" }, |
| 892 | }, |
| 893 | ]); |
| 894 | expect(result.imported).toBe(1); |
| 895 | expect(result.thread.title).toBe("Renamed"); |
| 896 | expect(result.thread.historyOrigin).toBe("v1_import"); |
| 897 | expect(result.items).toHaveLength(1); |
| 898 | }).pipe(Effect.scoped, Effect.provide(persistence)), |
| 899 | ); |
| 900 | |
| 901 | it.effect("skips the native history when a run starts while it loads", () => |
| 902 | Effect.gen(function* () { |
| 903 | const result = yield* importDuringCommand("run-during-load", (thread) => [ |
| 904 | { |
| 905 | id: EventId.make(`${thread.id}:run`), |
| 906 | type: "run.updated", |
| 907 | threadId: thread.id, |
| 908 | occurredAt: now, |
| 909 | payload: { |
| 910 | id: RunId.make(`${thread.id}:run`), |
| 911 | threadId: thread.id, |
| 912 | ordinal: 1, |
| 913 | providerInstanceId: thread.providerInstanceId, |
| 914 | modelSelection: thread.modelSelection, |
| 915 | providerThreadId: null, |
| 916 | userMessageId: MessageId.make(`${thread.id}:prompt`), |
| 917 | rootNodeId: null, |
| 918 | activeAttemptId: null, |
| 919 | status: "queued", |
| 920 | requestedAt: now, |
| 921 | startedAt: null, |
| 922 | completedAt: null, |
| 923 | checkpointId: null, |
| 924 | contextHandoffId: null, |
| 925 | }, |
| 926 | }, |
| 927 | ]); |
| 928 | expect(result.imported).toBe(0); |
| 929 | expect(result.runs).toHaveLength(1); |
| 930 | expect(result.thread.historyOrigin).toBeUndefined(); |
| 931 | expect(result.items).toEqual([]); |
| 932 | }).pipe(Effect.scoped, Effect.provide(persistence)), |
| 933 | ); |
| 934 | |
| 935 | it.effect("imports under a policy ceiling in the project's default, kept under the ceiling", () => |
| 936 | Effect.gen(function* () { |
| 937 | const projections = yield* ProjectionStore.ProjectionStoreV2; |
| 938 | const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; |
| 939 | const source = candidate(CODEX_MODEL_SELECTION, "ceiling"); |
| 940 | const threadId = importId(source); |
| 941 | const importer = yield* makeImporter( |
| 942 | [source], |
| 943 | Effect.void, |
| 944 | undefined, |
| 945 | undefined, |
| 946 | ServerSettings.layerTest( |
| 947 | { defaultRuntimeMode: "full-access" }, |
| 948 | { |
| 949 | organization: "Example Corp", |
| 950 | lockedSettings: [], |
| 951 | limits: { maxRuntimeMode: "auto-accept-edits" }, |
| 952 | }, |
| 953 | ), |
| 954 | ); |
| 955 | expect(yield* importer.run).toEqual({ importedCount: 1, skippedCount: 0 }); |
| 956 | expect((yield* projections.getThread(threadId)).runtimeMode).toBe("auto-accept-edits"); |
| 957 | expect(Option.getOrThrow(yield* runtimes.getByThreadId({ threadId })).runtimeMode).toBe( |
| 958 | "auto-accept-edits", |
| 959 | ); |
| 960 | }).pipe(Effect.scoped, Effect.provide(persistence)), |
| 961 | ); |
| 962 | |
| 963 | it.effect("repeated imports reach linked-worktree sessions behind the scan budget", () => |
| 964 | Effect.gen(function* () { |
| 965 | const fs = yield* FileSystem.FileSystem; |
| 966 | const path = yield* Path.Path; |
| 967 | const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-import-worktree-budget-" }); |
| 968 | const repo = path.join(root, "repo"); |
| 969 | const worktree = path.join(root, "feature"); |
| 970 | const worktreeGitDir = path.join(repo, ".git", "worktrees", "feature"); |
| 971 | yield* fs.makeDirectory(worktreeGitDir, { recursive: true }); |
| 972 | yield* fs.makeDirectory(worktree); |
| 973 | yield* fs.writeFileString(path.join(repo, ".git", "config"), "[core]\n"); |
| 974 | yield* fs.writeFileString(path.join(worktreeGitDir, "commondir"), "../..\n"); |
| 975 | yield* fs.writeFileString(path.join(worktreeGitDir, "HEAD"), "ref: refs/heads/feature\n"); |
| 976 | yield* fs.writeFileString(path.join(worktree, ".git"), `gitdir: ${worktreeGitDir}\n`); |
| 977 | |
| 978 | const claudeHome = path.join(root, "claude"); |
| 979 | const codexHome = path.join(root, "codex"); |
| 980 | const sessions = path.join(codexHome, "sessions", "2026", "09", "01"); |
| 981 | yield* fs.makeDirectory(sessions, { recursive: true }); |
| 982 | const nowMs = DateTime.toEpochMillis(now); |
| 983 | yield* TestClock.setTime(nowMs); |
| 984 | // One more session than the 100-transcript scan budget, all run in the linked worktree. |
| 985 | for (let index = 0; index < 101; index++) { |
| 986 | const file = path.join(sessions, `rollout-${String(index).padStart(3, "0")}.jsonl`); |
| 987 | const records = [ |
| 988 | { type: "session_meta", payload: { id: `session-${index}`, cwd: worktree } }, |
| 989 | { type: "event_msg", payload: { type: "user_message", message: `Request ${index}` } }, |
| 990 | { |
| 991 | type: "response_item", |
| 992 | payload: { |
| 993 | type: "message", |
| 994 | role: "assistant", |
| 995 | content: [{ type: "output_text", text: "Done" }], |
| 996 | }, |
| 997 | }, |
| 998 | ]; |
| 999 | yield* fs.writeFileString( |
| 1000 | file, |
| 1001 | records.map((record) => JSON.stringify(record) + "\n").join(""), |
| 1002 | ); |
| 1003 | const modifiedAtSeconds = nowMs / 1000 - (index + 1); |
| 1004 | yield* fs.utimes(file, modifiedAtSeconds, modifiedAtSeconds); |
| 1005 | } |
| 1006 | |
| 1007 | const scannerContext = yield* Layer.build( |
| 1008 | AgentSessionScanner.layer.pipe( |
| 1009 | Layer.provide( |
| 1010 | Layer.mergeAll( |
| 1011 | ServerConfig.layerTest(claudeHome, { prefix: "t3-import-budget-config-" }), |
| 1012 | ServerSettings.layerTest({ |
| 1013 | providerInstances: { |
| 1014 | [ProviderInstanceId.make("claudeAgent")]: { |
| 1015 | driver: ProviderDriverKind.make("claudeAgent"), |
| 1016 | config: { homePath: claudeHome }, |
| 1017 | }, |
| 1018 | [ProviderInstanceId.make("codex")]: { |
| 1019 | driver: ProviderDriverKind.make("codex"), |
| 1020 | config: { homePath: codexHome }, |
| 1021 | }, |
| 1022 | // Keeps the default Pi instance off the developer's real ~/.pi. |
| 1023 | [ProviderInstanceId.make("pi")]: { |
| 1024 | driver: ProviderDriverKind.make("pi"), |
| 1025 | enabled: false, |
| 1026 | config: {}, |
| 1027 | }, |
| 1028 | }, |
| 1029 | }), |
| 1030 | Layer.mock(ProjectStore.ProjectStoreV2)({ listShells: () => Effect.succeed([]) }), |
| 1031 | Layer.succeed( |
| 1032 | ProviderSessionRuntime.ProviderSessionRuntimeRepository, |
| 1033 | yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository, |
| 1034 | ), |
| 1035 | ), |
| 1036 | ), |
| 1037 | ), |
| 1038 | ); |
| 1039 | const importer = yield* makeImporter([], Effect.void, undefined, undefined, undefined, { |
| 1040 | workspaceRoot: repo, |
| 1041 | scanner: Context.get(scannerContext, AgentSessionScanner.AgentSessionScanner), |
| 1042 | }); |
| 1043 | |
| 1044 | expect(yield* importer.run).toEqual({ importedCount: 100, skippedCount: 1 }); |
| 1045 | expect(yield* importer.run).toEqual({ importedCount: 1, skippedCount: 0 }); |
| 1046 | const oldest = yield* ProjectionStore.ProjectionStoreV2.pipe( |
| 1047 | Effect.flatMap((projections) => |
| 1048 | projections.getThread(ThreadId.make("import:codex:session-100")), |
| 1049 | ), |
| 1050 | ); |
| 1051 | expect(oldest.worktreePath).toBe(worktree); |
| 1052 | }).pipe(Effect.scoped, Effect.provide(Layer.merge(persistence, NodeServices.layer))), |
| 1053 | ); |