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

AgentSessionImporter.test.ts

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