Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AgentSessionImporter.test.ts

1,319 lines51.5 KB

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