The best way to control Claude Code, Codex and more from any computer or phone

main
ts 3,946 lines 157 KB
Raw
1 // @effect-diagnostics nodeBuiltinImport:off - FIFO gates must be released with a synchronous
2 // open on the main thread, because the Effect FileSystem queues behind the pinned libuv pool.
3 import * as NodeServices from "@effect/platform-node/NodeServices";
4 import * as NodeChildProcess from "node:child_process";
5 import * as NodeFS from "node:fs";
6 import * as NodeOS from "node:os";
7 import * as NodeSqlite from "node:sqlite";
8 import * as NodeZlib from "node:zlib";
9 import { describe, expect, it } from "@effect/vitest";
10 import {
11 AgentSessionImportSource,
12 type OrchestrationProjectShell,
13 ProjectId,
14 ProviderDriverKind,
15 ProviderInstanceId,
16 type ServerSettings as ContractServerSettings,
17 ThreadId,
18 } from "@t3tools/contracts";
19 import * as HostProcess from "@t3tools/shared/HostProcess";
20 import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
21 import * as DateTime from "effect/DateTime";
22 import * as Effect from "effect/Effect";
23 import * as Fiber from "effect/Fiber";
24 import * as FileSystem from "effect/FileSystem";
25 import * as Layer from "effect/Layer";
26 import * as Option from "effect/Option";
27 import * as Path from "effect/Path";
28 import * as Queue from "effect/Queue";
29 import * as Schema from "effect/Schema";
30 import * as Stream from "effect/Stream";
31 import * as TestClock from "effect/testing/TestClock";
32
33 import * as ServerConfig from "../config.ts";
34 import * as ProcessRunner from "../processRunner.ts";
35 import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";
36 import * as ProviderSessionRuntime from "../persistence/ProviderSessionRuntime.ts";
37 import * as ServerSettings from "../serverSettings.ts";
38 import * as AgentSessionScanner from "./AgentSessionScanner.ts";
39
40 const makeProjectShell = (workspaceRoot: string): OrchestrationProjectShell => ({
41 id: ProjectId.make("project-1"),
42 title: "Imported",
43 workspaceRoot,
44 defaultModelSelection: null,
45 scripts: [],
46 createdAt: "2026-01-01T00:00:00.000Z",
47 updatedAt: "2026-01-01T00:00:00.000Z",
48 });
49
50 const layerProjectStore = (importedWorkspaceRoots: ReadonlyArray<string>) =>
51 Layer.mock(ProjectStore.ProjectStoreV2)({
52 listShells: () =>
53 Effect.succeed(
54 importedWorkspaceRoots.map((workspaceRoot) => makeProjectShell(workspaceRoot)),
55 ),
56 });
57
58 interface ScannerTestInput {
59 readonly claudeHomePath: string;
60 readonly codexHomePath: string;
61 readonly piAgentDir?: string;
62 readonly importedWorkspaceRoots?: ReadonlyArray<string>;
63 readonly configBaseDir?: string;
64 readonly providerInstances?: ContractServerSettings["providerInstances"];
65 readonly importedTranscripts?: {
66 readonly cwd: string;
67 readonly sources: ReadonlyArray<AgentSessionImportSource>;
68 };
69 readonly processRunner?: Layer.Layer<ProcessRunner.ProcessRunner>;
70 }
71
72 const layerRuntimeRepository = (imported: ScannerTestInput["importedTranscripts"]) =>
73 Layer.mock(ProviderSessionRuntime.ProviderSessionRuntimeRepository)({
74 list: () =>
75 Effect.sync(() =>
76 (imported?.sources ?? []).map((source): ProviderSessionRuntime.ProviderSessionRuntime => ({
77 threadId: ThreadId.make(
78 `import:${source.providerInstanceId}:${source.providerSessionId}`,
79 ),
80 providerName: source.provider,
81 providerInstanceId: source.providerInstanceId,
82 adapterKey: source.provider,
83 runtimeMode: "full-access",
84 status: "stopped",
85 lastSeenAt: "2026-01-01T00:00:00.000Z",
86 resumeCursor: null,
87 runtimePayload: { cwd: imported?.cwd, importedTranscripts: [source] },
88 })),
89 ),
90 });
91
92 const layerScannerTest = (input: ScannerTestInput) =>
93 (input.processRunner === undefined
94 ? AgentSessionScanner.layer
95 : Layer.effect(AgentSessionScanner.AgentSessionScanner, AgentSessionScanner.make).pipe(
96 Layer.provide(input.processRunner),
97 )
98 ).pipe(
99 Layer.provide(
100 Layer.mergeAll(
101 ServerSettings.layerTest({
102 providerInstances: {
103 [ProviderInstanceId.make("claudeAgent")]: {
104 driver: ProviderDriverKind.make("claudeAgent"),
105 config: { homePath: input.claudeHomePath },
106 },
107 [ProviderInstanceId.make("codex")]: {
108 driver: ProviderDriverKind.make("codex"),
109 config: { homePath: input.codexHomePath },
110 },
111 // Keeps the default Pi instance off the developer's real ~/.pi.
112 [ProviderInstanceId.make("pi")]: {
113 driver: ProviderDriverKind.make("pi"),
114 enabled: true,
115 environment: [
116 {
117 name: "PI_CODING_AGENT_DIR",
118 value: input.piAgentDir ?? `${input.claudeHomePath}/pi-agent`,
119 sensitive: false,
120 },
121 { name: "PI_CODING_AGENT_SESSION_DIR", value: "", sensitive: false },
122 ],
123 config: {},
124 },
125 ...input.providerInstances,
126 },
127 }),
128 ServerConfig.layerTest(
129 input.claudeHomePath,
130 input.configBaseDir ?? { prefix: "t3code-scanner-config-" },
131 ),
132 layerProjectStore(input.importedWorkspaceRoots ?? []),
133 layerRuntimeRepository(input.importedTranscripts),
134 ),
135 ),
136 );
137
138 const runScan = (input: ScannerTestInput) =>
139 Effect.gen(function* () {
140 const scanner = yield* AgentSessionScanner.AgentSessionScanner;
141 return yield* scanner.scan;
142 }).pipe(Effect.provide(layerScannerTest(input)));
143
144 const runRecentThreadOutcomes = (input: ScannerTestInput & { readonly workspaceRoot: string }) =>
145 Effect.gen(function* () {
146 const scanner = yield* AgentSessionScanner.AgentSessionScanner;
147 return yield* scanner.recentThreads(input.workspaceRoot).pipe(
148 Stream.runCollect,
149 Effect.map((outcomes) => Array.from(outcomes)),
150 );
151 }).pipe(Effect.provide(layerScannerTest(input)));
152
153 const runRecentThreads = (input: ScannerTestInput & { readonly workspaceRoot: string }) =>
154 runRecentThreadOutcomes(input).pipe(
155 Effect.map((outcomes) =>
156 outcomes.flatMap((outcome) => (outcome._tag === "Importable" ? [outcome.thread] : [])),
157 ),
158 );
159
160 const makeTempDir = Effect.fn("AgentSessionScanner.test.makeTempDir")(function* (prefix: string) {
161 const fileSystem = yield* FileSystem.FileSystem;
162 return yield* fileSystem.makeTempDirectoryScoped({ prefix });
163 });
164
165 const writeTranscript = Effect.fn("AgentSessionScanner.test.writeTranscript")(function* (input: {
166 readonly filePath: string;
167 readonly contents: string;
168 readonly mtimeMs: number;
169 }) {
170 const fileSystem = yield* FileSystem.FileSystem;
171 const path = yield* Path.Path;
172 yield* fileSystem.makeDirectory(path.dirname(input.filePath), { recursive: true });
173 yield* fileSystem.writeFileString(input.filePath, input.contents);
174 const seconds = input.mtimeMs / 1000;
175 yield* fileSystem.utimes(input.filePath, seconds, seconds);
176 });
177
178 const writeCompressedTranscript = Effect.fn("AgentSessionScanner.test.writeCompressedTranscript")(
179 function* (input: {
180 readonly filePath: string;
181 readonly contents: string;
182 readonly mtimeMs: number;
183 }) {
184 const fileSystem = yield* FileSystem.FileSystem;
185 const path = yield* Path.Path;
186 yield* fileSystem.makeDirectory(path.dirname(input.filePath), { recursive: true });
187 yield* fileSystem.writeFile(input.filePath, NodeZlib.zstdCompressSync(input.contents));
188 const seconds = input.mtimeMs / 1000;
189 yield* fileSystem.utimes(input.filePath, seconds, seconds);
190 },
191 );
192
193 const claudeSessionLine = (cwd: string) =>
194 `${JSON.stringify({ type: "user", cwd, sessionId: "s1" })}\n${JSON.stringify({ type: "assistant" })}\n`;
195
196 const codexRolloutLine = (cwd: string) =>
197 `${JSON.stringify({ timestamp: "2026-01-01T00:00:00.000Z", type: "session_meta", payload: { id: "r1", cwd } })}\n`;
198
199 const decodeImportSource = Schema.decodeUnknownSync(AgentSessionImportSource);
200
201 const encodeTranscriptRecord = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
202
203 function makeRecordLimitTranscript(cwd: string, overflow: boolean): string {
204 const records =
205 [
206 encodeTranscriptRecord({
207 type: "session_meta",
208 payload: { id: "record-limit-session", cwd },
209 }),
210 encodeTranscriptRecord({
211 type: "event_msg",
212 payload: { type: "user_message", message: "First prompt" },
213 }),
214 ].join("\n") +
215 "\n" +
216 "{}\n".repeat(99_998);
217 return overflow
218 ? records +
219 "\n" +
220 encodeTranscriptRecord({
221 type: "event_msg",
222 payload: { type: "user_message", message: "Overflow prompt" },
223 }) +
224 "\n"
225 : records;
226 }
227
228 // Pi retains every entry, keeping tool results as links outside the history budget.
229 function makePiToolResultTranscript(sessionId: string, cwd: string, recordCount: number): string {
230 const entry = (id: number, message: { readonly role: string; readonly content: string }) =>
231 encodeTranscriptRecord({
232 type: "message",
233 id: `e${id}`,
234 parentId: id === 0 ? null : `e${id - 1}`,
235 message,
236 });
237 return [
238 encodeTranscriptRecord({ type: "session", version: 3, id: sessionId, cwd }),
239 entry(0, { role: "user", content: "Imported prompt" }),
240 ...Array.from({ length: recordCount - 2 }, (_, index) =>
241 entry(index + 1, { role: "toolResult", content: "Tool output" }),
242 ),
243 ].join("\n");
244 }
245
246 const makeFileIdentityFixture = Effect.fn("AgentSessionScanner.test.makeFileIdentityFixture")(
247 function* (originalInode = 10_000_000_000_000_001n, replacementInode = 10_000_000_000_000_000n) {
248 const path = yield* Path.Path;
249 const fileSystem = yield* FileSystem.FileSystem;
250 const nowMs = Date.parse("2026-08-24T12:00:00.000Z");
251 yield* TestClock.setTime(nowMs);
252 const claudeHomePath = yield* makeTempDir("t3code-large-id-claude-");
253 const codexHomePath = yield* makeTempDir("t3code-large-id-codex-");
254 const workspace = yield* makeTempDir("t3code-large-id-workspace-");
255 const filePath = path.join(
256 codexHomePath,
257 "sessions",
258 "2026",
259 "08",
260 "24",
261 "rollout-identity.jsonl",
262 );
263 const replacementPath = `${filePath}.replacement`;
264 const savedPath = `${filePath}.saved`;
265 for (const [target, sessionId] of [
266 [filePath, "original-session"],
267 [replacementPath, "replaced-session"],
268 ] as const) {
269 yield* writeTranscript({
270 filePath: target,
271 contents: [
272 encodeTranscriptRecord({
273 type: "session_meta",
274 payload: { id: sessionId, cwd: workspace },
275 }),
276 encodeTranscriptRecord({
277 type: "event_msg",
278 payload: { type: "user_message", message: "Imported prompt" },
279 }),
280 ].join("\n"),
281 mtimeMs: nowMs,
282 });
283 }
284
285 // Adjacent NTFS IDs round to the same number; birthtimes can also collide.
286 const birthtime = Option.some(DateTime.toDateUtc(DateTime.makeUnsafe(nowMs)));
287 const ids = new Map<bigint, bigint>();
288 const effectIdentity = (target: string, info: FileSystem.File.Info) => {
289 if (target !== filePath) return info;
290 const realInode = Option.getOrThrow(info.ino);
291 const inode = ids.get(realInode) ?? (ids.size === 0 ? originalInode : replacementInode);
292 ids.set(realInode, inode);
293 return { ...info, ino: Option.some(inode), birthtime };
294 };
295 let opens = 0;
296 const simulatedFileSystem = FileSystem.FileSystem.of({
297 ...fileSystem,
298 stat: (target) =>
299 fileSystem.stat(target).pipe(Effect.map((info) => effectIdentity(target, info))),
300 open: (target, options) => {
301 if (target === filePath) opens += 1;
302 return fileSystem.open(target, options).pipe(
303 Effect.map((file) => ({
304 ...file,
305 stat: file.stat.pipe(Effect.map((info) => effectIdentity(target, info))),
306 readAlloc: (size: number) => file.readAlloc(size),
307 })),
308 );
309 },
310 });
311 const scanner = yield* AgentSessionScanner.AgentSessionScanner.pipe(
312 Effect.provide(layerScannerTest({ claudeHomePath, codexHomePath })),
313 Effect.provideService(FileSystem.FileSystem, simulatedFileSystem),
314 );
315 return {
316 scanner,
317 workspace,
318 opens: () => opens,
319 replace: Effect.gen(function* () {
320 yield* fileSystem.rename(filePath, savedPath);
321 yield* fileSystem.rename(replacementPath, filePath);
322 }).pipe(Effect.orDie),
323 };
324 },
325 );
326
327 const LIBUV_POOL_SIZE = Number(process.env.UV_THREADPOOL_SIZE ?? 4);
328
329 /**
330 * Opening a FIFO for reading waits in `open()` until a writer appears, like a
331 * TCC-protected file in a headless macOS daemon, and pins one libuv pool thread
332 * that fiber interruption cannot free. The finalizer opens it for writing on the
333 * main thread, which releases every waiting reader even with the pool exhausted.
334 */
335 const makeOpenGate = Effect.fn("AgentSessionScanner.test.makeOpenGate")(function* (
336 gatePath: string,
337 ) {
338 NodeChildProcess.execFileSync("mkfifo", [gatePath]);
339 yield* Effect.addFinalizer(() =>
340 Effect.sync(() => {
341 try {
342 NodeFS.closeSync(
343 NodeFS.openSync(gatePath, NodeFS.constants.O_WRONLY | NodeFS.constants.O_NONBLOCK),
344 );
345 } catch {
346 // ENXIO: no reader is waiting.
347 }
348 }),
349 );
350 });
351
352 /**
353 * Resolves once a reader has opened the FIFO, so its read deadline is already
354 * scheduled on the TestClock. The writer stays open until the scope closes, so
355 * the reader sees no EOF and has to wait out that deadline.
356 */
357 const awaitGateReader = (gatePath: string) =>
358 Effect.acquireRelease(
359 Effect.promise(() => NodeFS.promises.open(gatePath, NodeFS.constants.O_WRONLY)),
360 (handle) => Effect.promise(() => handle.close()),
361 );
362
363 /**
364 * Offers each of `filePaths` to `finished` once its `cat` child has exited. A
365 * deadline fires for every read still in flight, so a test must wait for the
366 * unblocked reads before it moves the clock.
367 */
368 const layerReportingProcessRunner = (
369 filePaths: ReadonlySet<string>,
370 finished: Queue.Queue<string>,
371 ) =>
372 Layer.effect(
373 ProcessRunner.ProcessRunner,
374 Effect.gen(function* () {
375 const runner = yield* ProcessRunner.ProcessRunner;
376 return ProcessRunner.ProcessRunner.of({
377 run: (input) => {
378 const filePath = input.args.at(-1) ?? "";
379 return filePaths.has(filePath)
380 ? runner.run(input).pipe(Effect.ensuring(Queue.offer(finished, filePath)))
381 : runner.run(input);
382 },
383 });
384 }),
385 ).pipe(Layer.provide(ProcessRunner.layer), Layer.provide(NodeServices.layer));
386
387 it.layer(NodeServices.layer)("AgentSessionScanner", (it) => {
388 describe("scan", () => {
389 it.effect("reads Claude project cwds from transcripts, newest first", () =>
390 Effect.gen(function* () {
391 const path = yield* Path.Path;
392 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
393 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
394 const olderWorkspace = yield* makeTempDir("t3code-workspace-older-");
395 const newerWorkspace = yield* makeTempDir("t3code-workspace-newer-");
396
397 yield* writeTranscript({
398 filePath: path.join(claudeHomePath, "projects", "-slug-older", "a.jsonl"),
399 contents: claudeSessionLine(olderWorkspace),
400 mtimeMs: Date.parse("2026-01-01T00:00:00.000Z"),
401 });
402 yield* writeTranscript({
403 filePath: path.join(claudeHomePath, "projects", "-slug-older", "b.jsonl"),
404 contents: claudeSessionLine(olderWorkspace),
405 mtimeMs: Date.parse("2026-01-02T00:00:00.000Z"),
406 });
407 yield* writeTranscript({
408 filePath: path.join(claudeHomePath, "projects", "-slug-newer", "c.jsonl"),
409 contents: claudeSessionLine(newerWorkspace),
410 mtimeMs: Date.parse("2026-03-01T00:00:00.000Z"),
411 });
412
413 const result = yield* runScan({ claudeHomePath, codexHomePath });
414
415 expect(result.candidates).toEqual([
416 {
417 path: newerWorkspace,
418 title: path.basename(newerWorkspace),
419 sources: ["claudeAgent"],
420 threadCount: 1,
421 lastActiveAt: "2026-03-01T00:00:00.000Z",
422 alreadyImported: false,
423 git: null,
424 },
425 {
426 path: olderWorkspace,
427 title: path.basename(olderWorkspace),
428 sources: ["claudeAgent"],
429 threadCount: 2,
430 lastActiveAt: "2026-01-02T00:00:00.000Z",
431 alreadyImported: false,
432 git: null,
433 },
434 ]);
435 }),
436 );
437
438 it.effect("merges the same cwd seen by both agents and flags imported projects", () =>
439 Effect.gen(function* () {
440 const path = yield* Path.Path;
441 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
442 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
443 const workspace = yield* makeTempDir("t3code-workspace-");
444
445 yield* writeTranscript({
446 filePath: path.join(claudeHomePath, "projects", "-slug", "a.jsonl"),
447 contents: claudeSessionLine(workspace),
448 mtimeMs: Date.parse("2026-01-01T00:00:00.000Z"),
449 });
450 yield* writeTranscript({
451 filePath: path.join(
452 codexHomePath,
453 "sessions",
454 "2026",
455 "04",
456 "01",
457 "rollout-2026-04-01T09-00-00-aaa.jsonl",
458 ),
459 contents: codexRolloutLine(workspace),
460 mtimeMs: Date.parse("2026-04-01T09:00:00.000Z"),
461 });
462
463 const result = yield* runScan({
464 claudeHomePath,
465 codexHomePath,
466 importedWorkspaceRoots: [workspace],
467 });
468
469 expect(result.candidates).toEqual([
470 {
471 path: workspace,
472 title: path.basename(workspace),
473 projectId: ProjectId.make("project-1"),
474 sources: ["claudeAgent", "codex"],
475 threadCount: 2,
476 lastActiveAt: "2026-04-01T09:00:00.000Z",
477 alreadyImported: true,
478 git: null,
479 },
480 ]);
481 }),
482 );
483
484 it.effect("returns the imported project ID through a realpath alias", () =>
485 Effect.gen(function* () {
486 const path = yield* Path.Path;
487 const fileSystem = yield* FileSystem.FileSystem;
488 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
489 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
490 const workspace = yield* makeTempDir("t3code-workspace-");
491 const linkParent = yield* makeTempDir("t3code-scanner-links-");
492 const workspaceAlias = path.join(linkParent, "workspace-alias");
493 yield* fileSystem.symlink(workspace, workspaceAlias);
494
495 yield* writeTranscript({
496 filePath: path.join(claudeHomePath, "projects", "-slug", "a.jsonl"),
497 contents: claudeSessionLine(workspaceAlias),
498 mtimeMs: Date.parse("2026-01-01T00:00:00.000Z"),
499 });
500
501 const result = yield* runScan({
502 claudeHomePath,
503 codexHomePath,
504 importedWorkspaceRoots: [workspace],
505 });
506
507 expect(result.candidates[0]).toMatchObject({
508 path: workspace,
509 projectId: ProjectId.make("project-1"),
510 alreadyImported: true,
511 git: null,
512 });
513 }),
514 );
515
516 it.effect("merges case aliases and preserves the persisted project path", () =>
517 Effect.gen(function* () {
518 const path = yield* Path.Path;
519 const fileSystem = yield* FileSystem.FileSystem;
520 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
521 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
522 const workspace = yield* makeTempDir("t3code-workspace-");
523 const workspaceAlias = path.join(
524 path.dirname(workspace),
525 path.basename(workspace).toUpperCase(),
526 );
527
528 yield* writeTranscript({
529 filePath: path.join(claudeHomePath, "projects", "-slug", "a.jsonl"),
530 contents: claudeSessionLine(workspaceAlias),
531 mtimeMs: Date.parse("2026-01-01T00:00:00.000Z"),
532 });
533 yield* writeTranscript({
534 filePath: path.join(codexHomePath, "sessions", "2026", "01", "02", "rollout-b.jsonl"),
535 contents: codexRolloutLine(workspace),
536 mtimeMs: Date.parse("2026-01-02T00:00:00.000Z"),
537 });
538
539 const simulatedFileSystem = FileSystem.FileSystem.of({
540 ...fileSystem,
541 stat: (filePath) => fileSystem.stat(filePath === workspaceAlias ? workspace : filePath),
542 });
543 const result = yield* runScan({
544 claudeHomePath,
545 codexHomePath,
546 importedWorkspaceRoots: [workspace],
547 }).pipe(Effect.provideService(FileSystem.FileSystem, simulatedFileSystem));
548
549 expect(result.candidates).toEqual([
550 {
551 path: workspace,
552 title: path.basename(workspace),
553 projectId: ProjectId.make("project-1"),
554 sources: ["claudeAgent", "codex"],
555 threadCount: 2,
556 lastActiveAt: "2026-01-02T00:00:00.000Z",
557 alreadyImported: true,
558 git: null,
559 },
560 ]);
561 }),
562 );
563
564 it.effect("keeps case variants distinct when the filesystem identities differ", () =>
565 Effect.gen(function* () {
566 const path = yield* Path.Path;
567 const fileSystem = yield* FileSystem.FileSystem;
568 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
569 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
570 const backingUpper = yield* makeTempDir("t3code-backing-upper-");
571 const backingLower = yield* makeTempDir("t3code-backing-lower-");
572 const aliasParent = yield* makeTempDir("t3code-case-aliases-");
573 const upperWorkspace = path.join(aliasParent, "Repo");
574 const lowerWorkspace = path.join(aliasParent, "repo");
575
576 yield* writeTranscript({
577 filePath: path.join(claudeHomePath, "projects", "-upper", "a.jsonl"),
578 contents: claudeSessionLine(upperWorkspace),
579 mtimeMs: Date.parse("2026-01-02T00:00:00.000Z"),
580 });
581 yield* writeTranscript({
582 filePath: path.join(claudeHomePath, "projects", "-lower", "b.jsonl"),
583 contents: claudeSessionLine(lowerWorkspace),
584 mtimeMs: Date.parse("2026-01-01T00:00:00.000Z"),
585 });
586
587 const simulatedFileSystem = FileSystem.FileSystem.of({
588 ...fileSystem,
589 stat: (filePath) =>
590 fileSystem.stat(
591 filePath === upperWorkspace
592 ? backingUpper
593 : filePath === lowerWorkspace
594 ? backingLower
595 : filePath,
596 ),
597 });
598 const result = yield* runScan({ claudeHomePath, codexHomePath }).pipe(
599 Effect.provideService(FileSystem.FileSystem, simulatedFileSystem),
600 );
601
602 expect(result.candidates.map((candidate) => candidate.path)).toEqual([
603 upperWorkspace,
604 lowerWorkspace,
605 ]);
606 }),
607 );
608
609 it.effect("uses explicit default-slot homes instead of the fixture homes", () =>
610 Effect.gen(function* () {
611 const path = yield* Path.Path;
612 const claudeHomePath = yield* makeTempDir("t3code-claude-legacy-");
613 const codexHomePath = yield* makeTempDir("t3code-codex-legacy-");
614 const claudeInstanceHome = yield* makeTempDir("t3code-claude-instance-");
615 const codexInstanceHome = yield* makeTempDir("t3code-codex-instance-");
616 const legacyWorkspace = yield* makeTempDir("t3code-workspace-legacy-");
617 const claudeWorkspace = yield* makeTempDir("t3code-workspace-claude-");
618 const codexWorkspace = yield* makeTempDir("t3code-workspace-codex-");
619
620 yield* writeTranscript({
621 filePath: path.join(claudeHomePath, "projects", "-legacy", "session.jsonl"),
622 contents: claudeSessionLine(legacyWorkspace),
623 mtimeMs: Date.parse("2026-01-01T00:00:00.000Z"),
624 });
625 yield* writeTranscript({
626 filePath: path.join(claudeInstanceHome, "projects", "-actual", "session.jsonl"),
627 contents: claudeSessionLine(claudeWorkspace),
628 mtimeMs: Date.parse("2026-02-01T00:00:00.000Z"),
629 });
630 yield* writeTranscript({
631 filePath: path.join(
632 codexInstanceHome,
633 "sessions",
634 "2026",
635 "03",
636 "01",
637 "rollout-instance.jsonl",
638 ),
639 contents: codexRolloutLine(codexWorkspace),
640 mtimeMs: Date.parse("2026-03-01T00:00:00.000Z"),
641 });
642
643 const result = yield* runScan({
644 claudeHomePath,
645 codexHomePath,
646 providerInstances: {
647 [ProviderInstanceId.make("claudeAgent")]: {
648 driver: ProviderDriverKind.make("claudeAgent"),
649 config: { homePath: claudeInstanceHome },
650 },
651 [ProviderInstanceId.make("codex")]: {
652 driver: ProviderDriverKind.make("codex"),
653 config: { homePath: codexInstanceHome },
654 },
655 },
656 });
657
658 expect(result.candidates.map((candidate) => candidate.path)).toEqual([
659 codexWorkspace,
660 claudeWorkspace,
661 ]);
662 }),
663 );
664
665 it.effect("scans each distinct home across multiple instances once", () =>
666 Effect.gen(function* () {
667 const path = yield* Path.Path;
668 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
669 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
670 const otherCodexHome = yield* makeTempDir("t3code-codex-other-");
671 const workspace = yield* makeTempDir("t3code-workspace-");
672 const otherWorkspace = yield* makeTempDir("t3code-workspace-other-");
673
674 for (const [home, cwd] of [
675 [codexHomePath, workspace],
676 [otherCodexHome, otherWorkspace],
677 ] as const) {
678 yield* writeTranscript({
679 filePath: path.join(home, "sessions", "2026", "01", "01", "rollout-session.jsonl"),
680 contents: codexRolloutLine(cwd),
681 mtimeMs: Date.parse("2026-01-01T00:00:00.000Z"),
682 });
683 }
684
685 const result = yield* runScan({
686 claudeHomePath,
687 codexHomePath,
688 providerInstances: {
689 [ProviderInstanceId.make("codex-personal")]: {
690 driver: ProviderDriverKind.make("codex"),
691 config: { homePath: codexHomePath },
692 },
693 [ProviderInstanceId.make("codex-work")]: {
694 driver: ProviderDriverKind.make("codex"),
695 config: { homePath: otherCodexHome },
696 },
697 },
698 });
699
700 expect(result.candidates).toHaveLength(2);
701 expect(result.candidates.map((candidate) => candidate.threadCount)).toEqual([1, 1]);
702 expect(result.candidates.map((candidate) => candidate.path).sort()).toEqual(
703 [workspace, otherWorkspace].sort(),
704 );
705 }),
706 );
707
708 it.effect("finds the newest Claude sessions in a large home beside empty ones", () =>
709 Effect.gen(function* () {
710 const path = yield* Path.Path;
711 const claudeHomePath = yield* makeTempDir("t3code-claude-large-home-");
712 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
713 const recentWorkspace = yield* makeTempDir("t3code-workspace-recent-");
714 const olderWorkspace = yield* makeTempDir("t3code-workspace-older-");
715 // More project folders than the discovery budget reads, in an order unrelated to age.
716 const folderCount = 12_000;
717 const recentCount = 40;
718 const newestMs = Date.parse("2026-03-01T00:00:00.000Z");
719 yield* Effect.sync(() => {
720 for (let index = 0; index < folderCount; index++) {
721 const age = (index * 7_919) % folderCount;
722 const directory = path.join(claudeHomePath, "projects", `-slug-${index}`);
723 const filePath = path.join(directory, `session-${index}.jsonl`);
724 const seconds = (newestMs - age * 60_000) / 1000;
725 NodeFS.mkdirSync(directory, { recursive: true });
726 NodeFS.writeFileSync(
727 filePath,
728 claudeSessionLine(age < recentCount ? recentWorkspace : olderWorkspace),
729 );
730 NodeFS.utimesSync(filePath, seconds, seconds);
731 NodeFS.utimesSync(directory, seconds, seconds);
732 }
733 });
734 const emptyHomes = [];
735 for (let index = 0; index < 40; index++) {
736 emptyHomes.push([
737 ProviderInstanceId.make(`claude-empty-${index}`),
738 {
739 driver: ProviderDriverKind.make("claudeAgent"),
740 config: { homePath: yield* makeTempDir(`t3code-claude-empty-${index}-`) },
741 },
742 ] as const);
743 }
744
745 const result = yield* runScan({
746 claudeHomePath,
747 codexHomePath,
748 providerInstances: Object.fromEntries(emptyHomes),
749 });
750
751 expect(
752 result.candidates.find((candidate) => candidate.path === recentWorkspace)?.threadCount,
753 ).toBe(recentCount);
754 }),
755 );
756
757 it.effect("passes budget a home frees while rescanning to the homes still short", () =>
758 Effect.gen(function* () {
759 const path = yield* Path.Path;
760 const claudeHomePath = yield* makeTempDir("t3code-claude-empty-home-");
761 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
762 const mediumHomePath = yield* makeTempDir("t3code-claude-medium-home-");
763 const largeHomePath = yield* makeTempDir("t3code-claude-large-home-");
764 const olderWorkspace = yield* makeTempDir("t3code-workspace-older-");
765 const lastWorkspace = yield* makeTempDir("t3code-workspace-last-");
766 const newestMs = Date.parse("2026-03-01T00:00:00.000Z");
767 // Both homes outgrow their first share; together they fit the source's budget, but only
768 // when what the medium home leaves over on its rescan reaches the large one, which is
769 // listed first and so needs a second pass.
770 yield* Effect.sync(() => {
771 const writeSessions = (directory: string, count: number, cwd: string, ageMs: number) => {
772 NodeFS.mkdirSync(directory, { recursive: true });
773 const seconds = (newestMs - ageMs) / 1000;
774 for (let index = 0; index < count; index++) {
775 const filePath = path.join(directory, `session-${index}.jsonl`);
776 NodeFS.writeFileSync(filePath, claudeSessionLine(cwd));
777 NodeFS.utimesSync(filePath, seconds, seconds);
778 }
779 };
780 writeSessions(
781 path.join(mediumHomePath, "projects", "-medium"),
782 8_000,
783 olderWorkspace,
784 60_000,
785 );
786 writeSessions(
787 path.join(largeHomePath, "projects", "-bulk"),
788 11_000,
789 olderWorkspace,
790 60_000,
791 );
792 // Read last because its folder is oldest, yet it holds the newest session.
793 const lastDirectory = path.join(largeHomePath, "projects", "-last");
794 writeSessions(lastDirectory, 1, lastWorkspace, 0);
795 const oldSeconds = (newestMs - 3_600_000) / 1000;
796 NodeFS.utimesSync(lastDirectory, oldSeconds, oldSeconds);
797 });
798
799 const result = yield* runScan({
800 claudeHomePath,
801 codexHomePath,
802 providerInstances: {
803 [ProviderInstanceId.make("claude-large")]: {
804 driver: ProviderDriverKind.make("claudeAgent"),
805 config: { homePath: largeHomePath },
806 },
807 [ProviderInstanceId.make("claude-medium")]: {
808 driver: ProviderDriverKind.make("claudeAgent"),
809 config: { homePath: mediumHomePath },
810 },
811 },
812 });
813
814 expect(
815 result.candidates.find((candidate) => candidate.path === lastWorkspace)?.threadCount,
816 ).toBe(1);
817 }),
818 );
819
820 it.effect("honors provider instance home directory environment variables", () =>
821 Effect.gen(function* () {
822 const path = yield* Path.Path;
823 const claudeHomePath = yield* makeTempDir("t3code-claude-legacy-");
824 const codexHomePath = yield* makeTempDir("t3code-codex-legacy-");
825 const claudeEnvironmentHome = yield* makeTempDir("t3code-claude-env-");
826 const codexEnvironmentHome = yield* makeTempDir("t3code-codex-env-");
827 const piAgentDir = yield* makeTempDir("t3code-pi-agent-");
828 const piSessionDir = yield* makeTempDir("t3code-pi-sessions-");
829 const claudeWorkspace = yield* makeTempDir("t3code-workspace-claude-");
830 const codexWorkspace = yield* makeTempDir("t3code-workspace-codex-");
831 const piWorkspace = yield* makeTempDir("t3code-workspace-pi-");
832 const piFlatWorkspace = yield* makeTempDir("t3code-workspace-pi-flat-");
833 const piInstanceHome = yield* makeTempDir("t3code-pi-instance-home-");
834 const piHomeWorkspace = yield* makeTempDir("t3code-workspace-pi-home-");
835
836 // Pi nests sessions per cwd by default and keeps a custom session directory flat.
837 for (const [filePath, cwd, mtime] of [
838 [
839 path.join(piAgentDir, "sessions", "--slug--", "2026-01-03_pi.jsonl"),
840 piWorkspace,
841 "2026-01-03T00:00:00.000Z",
842 ],
843 [
844 path.join(piSessionDir, "2026-01-04_pi-flat.jsonl"),
845 piFlatWorkspace,
846 "2026-01-04T00:00:00.000Z",
847 ],
848 [
849 path.join(piInstanceHome, "custom-pi", "sessions", "--slug--", "2026-01-05_pi.jsonl"),
850 piHomeWorkspace,
851 "2026-01-05T00:00:00.000Z",
852 ],
853 ] as const) {
854 yield* writeTranscript({
855 filePath,
856 contents: `${encodeTranscriptRecord({ type: "session", version: 3, id: "pi", cwd })}\n`,
857 mtimeMs: Date.parse(mtime),
858 });
859 }
860 yield* writeTranscript({
861 filePath: path.join(claudeEnvironmentHome, "projects", "-actual", "session.jsonl"),
862 contents: claudeSessionLine(claudeWorkspace),
863 mtimeMs: Date.parse("2026-01-01T00:00:00.000Z"),
864 });
865 yield* writeTranscript({
866 filePath: path.join(
867 codexEnvironmentHome,
868 "sessions",
869 "2026",
870 "01",
871 "01",
872 "rollout-session.jsonl",
873 ),
874 contents: codexRolloutLine(codexWorkspace),
875 mtimeMs: Date.parse("2026-01-02T00:00:00.000Z"),
876 });
877
878 const result = yield* runScan({
879 claudeHomePath,
880 codexHomePath,
881 providerInstances: {
882 [ProviderInstanceId.make("claudeAgent")]: {
883 driver: ProviderDriverKind.make("claudeAgent"),
884 environment: [
885 { name: "CLAUDE_CONFIG_DIR", value: claudeEnvironmentHome, sensitive: false },
886 ],
887 config: {},
888 },
889 [ProviderInstanceId.make("codex")]: {
890 driver: ProviderDriverKind.make("codex"),
891 environment: [{ name: "CODEX_HOME", value: codexEnvironmentHome, sensitive: false }],
892 config: {},
893 },
894 [ProviderInstanceId.make("pi")]: {
895 driver: ProviderDriverKind.make("pi"),
896 enabled: true,
897 environment: [
898 { name: "PI_CODING_AGENT_DIR", value: piAgentDir, sensitive: false },
899 { name: "PI_CODING_AGENT_SESSION_DIR", value: "", sensitive: false },
900 ],
901 config: {},
902 },
903 [ProviderInstanceId.make("pi-flat")]: {
904 driver: ProviderDriverKind.make("pi"),
905 enabled: true,
906 environment: [
907 { name: "PI_CODING_AGENT_SESSION_DIR", value: piSessionDir, sensitive: false },
908 ],
909 config: {},
910 },
911 [ProviderInstanceId.make("pi-home")]: {
912 driver: ProviderDriverKind.make("pi"),
913 enabled: true,
914 environment: [
915 { name: "HOME", value: piInstanceHome, sensitive: false },
916 { name: "USERPROFILE", value: piInstanceHome, sensitive: false },
917 { name: "PI_CODING_AGENT_DIR", value: "~/custom-pi", sensitive: false },
918 { name: "PI_CODING_AGENT_SESSION_DIR", value: "", sensitive: false },
919 ],
920 config: {},
921 },
922 },
923 });
924
925 expect(result.candidates.map((candidate) => [candidate.path, candidate.sources])).toEqual([
926 [piHomeWorkspace, ["pi"]],
927 [piFlatWorkspace, ["pi"]],
928 [piWorkspace, ["pi"]],
929 [codexWorkspace, ["codex"]],
930 [claudeWorkspace, ["claudeAgent"]],
931 ]);
932 }),
933 );
934
935 it.effect("does not scan provider instances disabled by the envelope or config", () =>
936 Effect.gen(function* () {
937 const path = yield* Path.Path;
938 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
939 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
940 const envelopeDisabledHome = yield* makeTempDir("t3code-codex-disabled-envelope-");
941 const configDisabledHome = yield* makeTempDir("t3code-codex-disabled-config-");
942 const envelopeWorkspace = yield* makeTempDir("t3code-workspace-disabled-envelope-");
943 const configWorkspace = yield* makeTempDir("t3code-workspace-disabled-config-");
944
945 for (const [home, workspace, session] of [
946 [envelopeDisabledHome, envelopeWorkspace, "envelope-disabled"],
947 [configDisabledHome, configWorkspace, "config-disabled"],
948 ] as const) {
949 yield* writeTranscript({
950 filePath: path.join(home, "sessions", "2026", "08", "24", `rollout-${session}.jsonl`),
951 contents: codexRolloutLine(workspace),
952 mtimeMs: Date.parse("2026-08-24T12:00:00.000Z"),
953 });
954 }
955
956 const result = yield* runScan({
957 claudeHomePath,
958 codexHomePath,
959 providerInstances: {
960 [ProviderInstanceId.make("codex-envelope-disabled")]: {
961 driver: ProviderDriverKind.make("codex"),
962 enabled: false,
963 config: { homePath: envelopeDisabledHome },
964 },
965 [ProviderInstanceId.make("codex-config-disabled")]: {
966 driver: ProviderDriverKind.make("codex"),
967 config: { enabled: false, homePath: configDisabledHome },
968 },
969 },
970 });
971
972 expect(result.candidates).toEqual([]);
973 }),
974 );
975
976 it.effect("drops candidates whose directory no longer exists", () =>
977 Effect.gen(function* () {
978 const path = yield* Path.Path;
979 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
980 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
981
982 yield* writeTranscript({
983 filePath: path.join(claudeHomePath, "projects", "-slug", "a.jsonl"),
984 contents: claudeSessionLine(path.join(claudeHomePath, "does-not-exist")),
985 mtimeMs: Date.parse("2026-01-01T00:00:00.000Z"),
986 });
987
988 const result = yield* runScan({ claudeHomePath, codexHomePath });
989
990 expect(result.candidates).toEqual([]);
991 }),
992 );
993
994 it.effect("excludes the home directory, temporary root, and T3 data directory", () =>
995 Effect.gen(function* () {
996 const path = yield* Path.Path;
997 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
998 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
999 const configBaseDir = yield* makeTempDir("t3code-scanner-base-");
1000 const workspace = yield* makeTempDir("t3code-workspace-");
1001
1002 for (const [index, cwd] of [
1003 NodeOS.homedir(),
1004 NodeOS.tmpdir(),
1005 configBaseDir,
1006 workspace,
1007 ].entries()) {
1008 yield* writeTranscript({
1009 filePath: path.join(claudeHomePath, "projects", `-slug-${index}`, "session.jsonl"),
1010 contents: claudeSessionLine(cwd),
1011 mtimeMs: Date.parse("2026-01-01T00:00:00.000Z") + index,
1012 });
1013 }
1014
1015 const result = yield* runScan({ claudeHomePath, codexHomePath, configBaseDir });
1016
1017 expect(result.candidates.map((candidate) => candidate.path)).toEqual([workspace]);
1018 }),
1019 );
1020
1021 it.effect("excludes T3-managed worktree sandboxes", () =>
1022 Effect.gen(function* () {
1023 const path = yield* Path.Path;
1024 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
1025 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
1026 const fileSystem = yield* FileSystem.FileSystem;
1027
1028 const worktreeCwd = path.join(claudeHomePath, ".t3", "worktrees", "t3code", "wt-1");
1029 yield* fileSystem.makeDirectory(worktreeCwd, { recursive: true });
1030 yield* writeTranscript({
1031 filePath: path.join(claudeHomePath, "projects", "-slug", "a.jsonl"),
1032 contents: claudeSessionLine(worktreeCwd),
1033 mtimeMs: Date.parse("2026-01-01T00:00:00.000Z"),
1034 });
1035
1036 const result = yield* runScan({ claudeHomePath, codexHomePath });
1037
1038 expect(result.candidates).toEqual([]);
1039 }),
1040 );
1041
1042 it.effect("folds linked git worktrees into their checkout and reports real origins", () =>
1043 Effect.gen(function* () {
1044 const path = yield* Path.Path;
1045 const fileSystem = yield* FileSystem.FileSystem;
1046 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
1047 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
1048 const repo = yield* makeTempDir("t3code-workspace-repo-");
1049 const worktree = yield* makeTempDir("t3code-workspace-worktree-");
1050 const plain = yield* makeTempDir("t3code-workspace-plain-");
1051 const noRemote = yield* makeTempDir("t3code-workspace-noremote-");
1052 const submodule = yield* makeTempDir("t3code-workspace-submodule-");
1053
1054 yield* fileSystem.makeDirectory(path.join(repo, ".git"));
1055 yield* fileSystem.writeFileString(
1056 path.join(repo, ".git", "config"),
1057 '[core]\n\tbare = false\n[remote "origin"]\n\turl = git@github.com:pingdotgg/t3code.git\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n',
1058 );
1059 const worktreeGitDir = path.join(repo, ".git", "worktrees", "wt");
1060 yield* fileSystem.makeDirectory(worktreeGitDir, { recursive: true });
1061 yield* fileSystem.writeFileString(path.join(worktreeGitDir, "commondir"), "../..\n");
1062 yield* fileSystem.writeFileString(
1063 path.join(worktree, ".git"),
1064 `gitdir: ${worktreeGitDir}\n`,
1065 );
1066 yield* fileSystem.makeDirectory(path.join(noRemote, ".git"));
1067 yield* fileSystem.writeFileString(path.join(noRemote, ".git", "config"), "[core]\n");
1068 const submoduleGitDir = path.join(repo, ".git", "modules", "vendor");
1069 yield* fileSystem.makeDirectory(submoduleGitDir, { recursive: true });
1070 yield* fileSystem.writeFileString(
1071 path.join(submoduleGitDir, "config"),
1072 '[remote "origin"]\n\turl = ssh://gitlab.com/pingdotgg/libs/vendor.git\n',
1073 );
1074 yield* fileSystem.writeFileString(
1075 path.join(submodule, ".git"),
1076 `gitdir: ${submoduleGitDir}\n`,
1077 );
1078 // A repository whose sessions all ran in a linked worktree is still offered.
1079 const worktreeOnly = yield* makeTempDir("t3code-workspace-worktree-only-");
1080 const worktreeOnlyCheckout = yield* makeTempDir("t3code-workspace-worktree-only-wt-");
1081 const worktreeOnlyGitDir = path.join(worktreeOnly, ".git", "worktrees", "wt");
1082 yield* fileSystem.makeDirectory(worktreeOnlyGitDir, { recursive: true });
1083 yield* fileSystem.writeFileString(
1084 path.join(worktreeOnly, ".git", "config"),
1085 '[remote "origin"]\n\turl = git@github.com:pingdotgg/other.git\n',
1086 );
1087 yield* fileSystem.writeFileString(path.join(worktreeOnlyGitDir, "commondir"), "../..\n");
1088 yield* fileSystem.writeFileString(
1089 path.join(worktreeOnlyCheckout, ".git"),
1090 `gitdir: ${worktreeOnlyGitDir}\n`,
1091 );
1092
1093 // Not offered: the config is unreadable, so the repository could be bare; and
1094 // the main checkout is reached through a symlink into T3's own state.
1095 const configBaseDir = yield* fileSystem.realPath(
1096 yield* makeTempDir("t3code-scanner-base-"),
1097 );
1098 const links = yield* makeTempDir("t3code-workspace-links-");
1099 const unknown = yield* makeTempDir("t3code-workspace-unknown-");
1100 yield* fileSystem.makeDirectory(path.join(configBaseDir, "state-repo"));
1101 yield* fileSystem.symlink(path.join(configBaseDir, "state-repo"), path.join(links, "repo"));
1102 const hiddenCheckouts: Array<string> = [];
1103 for (const [main, config] of [
1104 [unknown, null],
1105 [path.join(links, "repo"), "[core]\n"],
1106 ] as const) {
1107 const gitDir = path.join(main, ".git", "worktrees", "wt");
1108 yield* fileSystem.makeDirectory(gitDir, { recursive: true });
1109 if (config !== null) {
1110 yield* fileSystem.writeFileString(path.join(main, ".git", "config"), config);
1111 }
1112 yield* fileSystem.writeFileString(path.join(gitDir, "commondir"), "../..\n");
1113 const checkout = yield* makeTempDir("t3code-workspace-hidden-wt-");
1114 yield* fileSystem.writeFileString(path.join(checkout, ".git"), `gitdir: ${gitDir}\n`);
1115 hiddenCheckouts.push(checkout);
1116 }
1117
1118 const sessionDirectories = [
1119 repo,
1120 worktree,
1121 plain,
1122 noRemote,
1123 submodule,
1124 worktreeOnlyCheckout,
1125 ...hiddenCheckouts,
1126 ];
1127 for (const [index, cwd] of sessionDirectories.entries()) {
1128 yield* writeTranscript({
1129 filePath: path.join(claudeHomePath, "projects", `-slug-${index}`, "a.jsonl"),
1130 contents: claudeSessionLine(cwd),
1131 mtimeMs: Date.parse(`2026-01-0${index + 1}T00:00:00.000Z`),
1132 });
1133 }
1134
1135 const result = yield* runScan({ claudeHomePath, codexHomePath, configBaseDir });
1136
1137 expect(
1138 result.candidates.map((candidate) => ({
1139 path: candidate.path,
1140 git: candidate.git,
1141 threadCount: candidate.threadCount,
1142 })),
1143 ).toEqual([
1144 {
1145 path: worktreeOnly,
1146 git: { remoteKey: "github.com/pingdotgg/other", repository: "pingdotgg/other" },
1147 threadCount: 1,
1148 },
1149 {
1150 path: submodule,
1151 git: {
1152 remoteKey: "gitlab.com/pingdotgg/libs/vendor",
1153 repository: "pingdotgg/libs/vendor",
1154 },
1155 threadCount: 1,
1156 },
1157 { path: noRemote, git: { remoteKey: null, repository: null }, threadCount: 1 },
1158 { path: plain, git: null, threadCount: 1 },
1159 {
1160 path: repo,
1161 git: { remoteKey: "github.com/pingdotgg/t3code", repository: "pingdotgg/t3code" },
1162 threadCount: 2,
1163 },
1164 ]);
1165 }),
1166 );
1167
1168 it.effect(
1169 "offers bare-repository worktrees separately and imports only their own sessions",
1170 () =>
1171 Effect.gen(function* () {
1172 const path = yield* Path.Path;
1173 const fileSystem = yield* FileSystem.FileSystem;
1174 const nowMs = Date.parse("2026-08-24T12:00:00.000Z");
1175 yield* TestClock.setTime(nowMs);
1176 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
1177 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
1178 const configBaseDir = yield* makeTempDir("t3code-scanner-base-");
1179 const bare = yield* makeTempDir("t3code-workspace-bare-");
1180 const bareGitDir = path.join(bare, ".git");
1181 yield* fileSystem.makeDirectory(bareGitDir);
1182 yield* fileSystem.writeFileString(
1183 path.join(bareGitDir, "config"),
1184 '[core] bare = "true" ; bare repository\n[remote "origin"]\nurl = git@github.com:pingdotgg/t3code.git\n',
1185 );
1186 const dev = path.join(bare, "dev");
1187 const prod = path.join(bare, "prod");
1188 const managed = path.join(configBaseDir, "worktrees", "t3code", "sandbox");
1189 for (const [index, cwd] of [bare, dev, prod, managed].entries()) {
1190 if (cwd !== bare) {
1191 const gitDir = path.join(bareGitDir, "worktrees", path.basename(cwd));
1192 yield* fileSystem.makeDirectory(gitDir, { recursive: true });
1193 yield* fileSystem.writeFileString(path.join(gitDir, "commondir"), "../..\n");
1194 yield* fileSystem.makeDirectory(cwd, { recursive: true });
1195 yield* fileSystem.writeFileString(path.join(cwd, ".git"), `gitdir: ${gitDir}\n`);
1196 }
1197 yield* writeTranscript({
1198 filePath: path.join(
1199 codexHomePath,
1200 "sessions",
1201 "2026",
1202 "08",
1203 "24",
1204 `rollout-${index}.jsonl`,
1205 ),
1206 contents: [
1207 encodeTranscriptRecord({
1208 type: "session_meta",
1209 payload: { id: `session-${index}`, cwd },
1210 }),
1211 encodeTranscriptRecord({
1212 type: "event_msg",
1213 payload: { type: "user_message", message: `Work in ${cwd}` },
1214 }),
1215 ].join("\n"),
1216 mtimeMs: nowMs - index * 1_000,
1217 });
1218 }
1219
1220 const input = { claudeHomePath, codexHomePath, configBaseDir };
1221 const result = yield* runScan(input);
1222 const git = { remoteKey: "github.com/pingdotgg/t3code", repository: "pingdotgg/t3code" };
1223 expect(
1224 result.candidates.map((candidate) => ({ path: candidate.path, git: candidate.git })),
1225 ).toEqual([
1226 { path: bare, git },
1227 { path: dev, git },
1228 { path: prod, git },
1229 ]);
1230 const threads = yield* runRecentThreads({ ...input, workspaceRoot: dev });
1231 expect(threads.map((thread) => thread.providerSessionId)).toEqual(["session-1"]);
1232 const managedThreads = yield* runRecentThreads({ ...input, workspaceRoot: managed });
1233 expect(managedThreads).toEqual([]);
1234 }),
1235 );
1236
1237 it.effect("imports a checkout's sessions from the linked worktrees the scan counts", () =>
1238 Effect.gen(function* () {
1239 const path = yield* Path.Path;
1240 const fileSystem = yield* FileSystem.FileSystem;
1241 const nowMs = Date.parse("2026-08-24T12:00:00.000Z");
1242 yield* TestClock.setTime(nowMs);
1243 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
1244 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
1245 const repo = yield* makeTempDir("t3code-workspace-repo-");
1246 yield* fileSystem.makeDirectory(path.join(repo, ".git"));
1247 yield* fileSystem.writeFileString(path.join(repo, ".git", "config"), "[core]\n");
1248 const worktreeGitDir = path.join(repo, ".git", "worktrees", "feature");
1249 yield* fileSystem.makeDirectory(worktreeGitDir, { recursive: true });
1250 yield* fileSystem.writeFileString(path.join(worktreeGitDir, "commondir"), "../..\n");
1251 yield* fileSystem.writeFileString(
1252 path.join(worktreeGitDir, "HEAD"),
1253 "ref: refs/heads/feature\n",
1254 );
1255 const worktree = path.join(repo, ".claude", "worktrees", "feature");
1256 yield* fileSystem.makeDirectory(worktree, { recursive: true });
1257 yield* fileSystem.writeFileString(
1258 path.join(worktree, ".git"),
1259 `gitdir: ${worktreeGitDir}\n`,
1260 );
1261
1262 for (const [index, [cwd, sessionId]] of [
1263 [repo, "at-root"],
1264 [worktree, "in-worktree"],
1265 ].entries()) {
1266 yield* writeTranscript({
1267 filePath: path.join(claudeHomePath, "projects", `-slug-${index}`, `${sessionId}.jsonl`),
1268 contents: `${JSON.stringify({
1269 type: "user",
1270 cwd,
1271 sessionId,
1272 message: { role: "user", content: "Fix the project" },
1273 })}\n${JSON.stringify({
1274 type: "assistant",
1275 sessionId,
1276 message: { role: "assistant", content: [{ type: "text", text: "Done" }] },
1277 })}\n`,
1278 mtimeMs: nowMs - (index + 1) * 60 * 60 * 1000,
1279 });
1280 }
1281
1282 const input = { claudeHomePath, codexHomePath };
1283 const { candidates } = yield* runScan(input);
1284 expect(candidates.map(({ path, threadCount }) => ({ path, threadCount }))).toEqual([
1285 { path: repo, threadCount: 2 },
1286 ]);
1287 const outcomes = yield* runRecentThreadOutcomes({ ...input, workspaceRoot: repo });
1288 expect(
1289 outcomes.flatMap((outcome) =>
1290 outcome._tag === "Importable"
1291 ? [{ sessionId: outcome.thread.providerSessionId, worktree: outcome.worktree }]
1292 : [],
1293 ),
1294 ).toEqual([
1295 { sessionId: "at-root", worktree: null },
1296 { sessionId: "in-worktree", worktree: { path: worktree, branch: "feature" } },
1297 ]);
1298 }),
1299 );
1300
1301 it.effect("excludes sandboxes under the configured worktrees dir without .t3 in the path", () =>
1302 Effect.gen(function* () {
1303 const path = yield* Path.Path;
1304 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
1305 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
1306 const configBaseDir = yield* makeTempDir("t3code-scanner-base-");
1307 const fileSystem = yield* FileSystem.FileSystem;
1308
1309 const worktreeCwd = path.join(configBaseDir, "worktrees", "t3code", "wt-2");
1310 yield* fileSystem.makeDirectory(worktreeCwd, { recursive: true });
1311 yield* writeTranscript({
1312 filePath: path.join(claudeHomePath, "projects", "-slug", "a.jsonl"),
1313 contents: claudeSessionLine(worktreeCwd),
1314 mtimeMs: Date.parse("2026-01-01T00:00:00.000Z"),
1315 });
1316
1317 const result = yield* runScan({ claudeHomePath, codexHomePath, configBaseDir });
1318
1319 expect(result.candidates).toEqual([]);
1320 }),
1321 );
1322
1323 it.effect("excludes sandboxes reached through a symlink into the worktrees dir", () =>
1324 Effect.gen(function* () {
1325 const path = yield* Path.Path;
1326 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
1327 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
1328 const configBaseDir = yield* makeTempDir("t3code-scanner-base-");
1329 const linkParent = yield* makeTempDir("t3code-scanner-links-");
1330 const fileSystem = yield* FileSystem.FileSystem;
1331
1332 const worktreeCwd = path.join(configBaseDir, "worktrees", "t3code", "wt-3");
1333 yield* fileSystem.makeDirectory(worktreeCwd, { recursive: true });
1334 const symlinkCwd = path.join(linkParent, "innocent-project");
1335 yield* fileSystem.symlink(worktreeCwd, symlinkCwd);
1336 yield* writeTranscript({
1337 filePath: path.join(claudeHomePath, "projects", "-slug", "a.jsonl"),
1338 contents: claudeSessionLine(symlinkCwd),
1339 mtimeMs: Date.parse("2026-01-01T00:00:00.000Z"),
1340 });
1341
1342 const result = yield* runScan({ claudeHomePath, codexHomePath, configBaseDir });
1343
1344 expect(result.candidates).toEqual([]);
1345 }),
1346 );
1347
1348 it.effect("finds the cwd on a later line when the first records carry none", () =>
1349 Effect.gen(function* () {
1350 const path = yield* Path.Path;
1351 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
1352 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
1353 const workspace = yield* makeTempDir("t3code-workspace-");
1354
1355 const contents = `{"type":"file-history-snapshot","messageId":"m1"}\n{"type":"queue-operation","operation":"enqueue"}\n${claudeSessionLine(workspace)}`;
1356 yield* writeTranscript({
1357 filePath: path.join(claudeHomePath, "projects", "-slug", "a.jsonl"),
1358 contents,
1359 mtimeMs: Date.parse("2026-01-01T00:00:00.000Z"),
1360 });
1361
1362 const result = yield* runScan({ claudeHomePath, codexHomePath });
1363
1364 expect(result.candidates.map((candidate) => candidate.path)).toEqual([workspace]);
1365 }),
1366 );
1367
1368 it.effect("reads a complete transcript record at the exact chunk boundary", () =>
1369 Effect.gen(function* () {
1370 const path = yield* Path.Path;
1371 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
1372 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
1373 const workspace = yield* makeTempDir("t3code-workspace-");
1374 const record = claudeSessionLine(workspace).split("\n")[0]!;
1375 const prefix = '{"padding":"';
1376 const suffix = `",${record.slice(1)}`;
1377 const contents = `${prefix}${"x".repeat(32 * 1024 - prefix.length - suffix.length)}${suffix}`;
1378
1379 yield* writeTranscript({
1380 filePath: path.join(claudeHomePath, "projects", "-exact", "session.jsonl"),
1381 contents,
1382 mtimeMs: Date.parse("2026-01-01T00:00:00.000Z"),
1383 });
1384
1385 const result = yield* runScan({ claudeHomePath, codexHomePath });
1386
1387 expect(contents).toHaveLength(32 * 1024);
1388 expect(result.candidates.map((candidate) => candidate.path)).toEqual([workspace]);
1389 }),
1390 );
1391
1392 it.effect("skips malformed transcripts without failing the scan", () =>
1393 Effect.gen(function* () {
1394 const path = yield* Path.Path;
1395 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
1396 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
1397 const workspace = yield* makeTempDir("t3code-workspace-");
1398
1399 yield* writeTranscript({
1400 filePath: path.join(claudeHomePath, "projects", "-broken", "a.jsonl"),
1401 contents: "not json at all\n",
1402 mtimeMs: Date.parse("2026-05-01T00:00:00.000Z"),
1403 });
1404 yield* writeTranscript({
1405 filePath: path.join(claudeHomePath, "projects", "-no-cwd", "a.jsonl"),
1406 contents: `{"type":"summary"}\n`,
1407 mtimeMs: Date.parse("2026-05-02T00:00:00.000Z"),
1408 });
1409 yield* writeTranscript({
1410 filePath: path.join(claudeHomePath, "projects", "-good", "a.jsonl"),
1411 contents: claudeSessionLine(workspace),
1412 mtimeMs: Date.parse("2026-05-03T00:00:00.000Z"),
1413 });
1414
1415 const result = yield* runScan({ claudeHomePath, codexHomePath });
1416
1417 expect(result.candidates).toEqual([
1418 {
1419 path: workspace,
1420 title: path.basename(workspace),
1421 sources: ["claudeAgent"],
1422 threadCount: 1,
1423 lastActiveAt: "2026-05-03T00:00:00.000Z",
1424 alreadyImported: false,
1425 git: null,
1426 },
1427 ]);
1428 }),
1429 );
1430
1431 it.effect("keeps Codex rollout cwds when the Codex state database is unreadable", () =>
1432 Effect.gen(function* () {
1433 const fileSystem = yield* FileSystem.FileSystem;
1434 const path = yield* Path.Path;
1435 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
1436 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
1437 const workspace = yield* makeTempDir("t3code-workspace-");
1438 yield* writeTranscript({
1439 filePath: path.join(
1440 codexHomePath,
1441 "sessions",
1442 "2026",
1443 "05",
1444 "03",
1445 "rollout-2026-05-03T00-00-00-019a5f00-0000-7000-8000-00000000000a.jsonl",
1446 ),
1447 contents: codexRolloutLine(workspace),
1448 mtimeMs: Date.parse("2026-05-03T00:00:00.000Z"),
1449 });
1450 yield* fileSystem.writeFileString(
1451 path.join(codexHomePath, "state_5.sqlite"),
1452 "not a database",
1453 );
1454
1455 const result = yield* runScan({ claudeHomePath, codexHomePath });
1456
1457 expect(result.candidates.map(({ path, threadCount }) => ({ path, threadCount }))).toEqual([
1458 { path: workspace, threadCount: 1 },
1459 ]);
1460 }),
1461 );
1462 it.effect("discovers projects whose Codex rollouts are zstd-compressed", () =>
1463 Effect.gen(function* () {
1464 const path = yield* Path.Path;
1465 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
1466 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
1467 const workspace = yield* makeTempDir("t3code-workspace-");
1468 yield* writeCompressedTranscript({
1469 filePath: path.join(
1470 codexHomePath,
1471 "sessions",
1472 "2026",
1473 "05",
1474 "03",
1475 "rollout-2026-05-03T00-00-00-019a5f00-0000-7000-8000-00000000000b.jsonl.zst",
1476 ),
1477 contents: codexRolloutLine(workspace),
1478 mtimeMs: Date.parse("2026-05-03T00:00:00.000Z"),
1479 });
1480
1481 const result = yield* runScan({ claudeHomePath, codexHomePath });
1482
1483 expect(result.candidates.map(({ path, threadCount }) => ({ path, threadCount }))).toEqual([
1484 { path: workspace, threadCount: 1 },
1485 ]);
1486 }),
1487 );
1488 });
1489
1490 describe("recentThreads", () => {
1491 it.effect("imports Codex conversations stored only as zstd-compressed rollouts", () =>
1492 Effect.gen(function* () {
1493 const path = yield* Path.Path;
1494 const nowMs = Date.parse("2026-08-24T12:00:00.000Z");
1495 yield* TestClock.setTime(nowMs);
1496 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
1497 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
1498 const workspace = yield* makeTempDir("t3code-workspace-");
1499 yield* writeCompressedTranscript({
1500 filePath: path.join(
1501 codexHomePath,
1502 "sessions",
1503 "2026",
1504 "08",
1505 "20",
1506 "rollout-2026-08-20T10-00-00-019a5f00-0000-7000-8000-00000000000c.jsonl.zst",
1507 ),
1508 contents: [
1509 encodeTranscriptRecord({
1510 type: "session_meta",
1511 payload: { id: "019a5f00-0000-7000-8000-00000000000c", cwd: workspace },
1512 }),
1513 encodeTranscriptRecord({
1514 type: "event_msg",
1515 timestamp: "2026-08-20T10:00:00.000Z",
1516 payload: { type: "user_message", message: "Compressed prompt" },
1517 }),
1518 encodeTranscriptRecord({
1519 type: "response_item",
1520 timestamp: "2026-08-20T10:01:00.000Z",
1521 payload: {
1522 type: "message",
1523 role: "assistant",
1524 content: [{ type: "output_text", text: "Compressed answer" }],
1525 },
1526 }),
1527 ].join("\n"),
1528 mtimeMs: nowMs - 4 * 24 * 60 * 60 * 1000,
1529 });
1530
1531 const threads = yield* runRecentThreads({
1532 claudeHomePath,
1533 codexHomePath,
1534 workspaceRoot: workspace,
1535 });
1536
1537 expect(
1538 threads.map((thread) => ({
1539 id: thread.providerSessionId,
1540 messages: thread.messages.map((message) => message.text),
1541 })),
1542 ).toEqual([
1543 {
1544 id: "019a5f00-0000-7000-8000-00000000000c",
1545 messages: ["Compressed prompt", "Compressed answer"],
1546 },
1547 ]);
1548 }),
1549 );
1550
1551 it.effect("imports recent Claude, Codex, and Pi sessions for the selected project only", () =>
1552 Effect.gen(function* () {
1553 const path = yield* Path.Path;
1554 const nowMs = Date.parse("2026-08-24T12:00:00.000Z");
1555 yield* TestClock.setTime(nowMs);
1556 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
1557 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
1558 const piAgentDir = yield* makeTempDir("t3code-pi-agent-");
1559 const workspace = yield* makeTempDir("t3code-workspace-");
1560 const otherWorkspace = yield* makeTempDir("t3code-workspace-other-");
1561
1562 const claudeTranscript = (cwd: string, sessionId: string) =>
1563 `${JSON.stringify({
1564 type: "user",
1565 cwd,
1566 sessionId,
1567 timestamp: "2026-08-23T12:00:00.000Z",
1568 message: { role: "user", content: "Fix the project" },
1569 })}\n${JSON.stringify({
1570 type: "assistant",
1571 sessionId,
1572 timestamp: "2026-08-23T12:01:00.000Z",
1573 message: { role: "assistant", content: [{ type: "text", text: "Done" }] },
1574 })}\n`;
1575
1576 yield* writeTranscript({
1577 filePath: path.join(claudeHomePath, "projects", "-selected", "claude-recent.jsonl"),
1578 contents: claudeTranscript(workspace, "claude-recent"),
1579 mtimeMs: nowMs - 24 * 60 * 60 * 1000,
1580 });
1581 yield* writeTranscript({
1582 filePath: path.join(claudeHomePath, "projects", "-selected", "claude-old.jsonl"),
1583 contents: claudeTranscript(workspace, "claude-old"),
1584 mtimeMs: nowMs - 31 * 24 * 60 * 60 * 1000,
1585 });
1586 yield* writeTranscript({
1587 filePath: path.join(claudeHomePath, "projects", "-other", "claude-other.jsonl"),
1588 contents: claudeTranscript(otherWorkspace, "claude-other"),
1589 mtimeMs: nowMs - 24 * 60 * 60 * 1000,
1590 });
1591 yield* writeTranscript({
1592 filePath: path.join(
1593 codexHomePath,
1594 "sessions",
1595 "2026",
1596 "08",
1597 "24",
1598 "rollout-codex-recent.jsonl",
1599 ),
1600 contents: [
1601 encodeTranscriptRecord({
1602 type: "session_meta",
1603 payload: { id: "codex-recent", cwd: workspace },
1604 }),
1605 encodeTranscriptRecord({
1606 type: "event_msg",
1607 timestamp: "2026-08-24T10:00:00.000Z",
1608 payload: { type: "user_message", message: "Review this code" },
1609 }),
1610 encodeTranscriptRecord({
1611 type: "response_item",
1612 timestamp: "2026-08-24T10:01:00.000Z",
1613 payload: {
1614 type: "message",
1615 role: "assistant",
1616 content: [{ type: "output_text", text: "Looks good" }],
1617 },
1618 }),
1619 ].join("\n"),
1620 mtimeMs: nowMs - 60 * 60 * 1000,
1621 });
1622 const piMessage = (
1623 id: string,
1624 parentId: string | null,
1625 message: { readonly role: string; readonly content: unknown },
1626 ) =>
1627 encodeTranscriptRecord({
1628 type: "message",
1629 id,
1630 parentId,
1631 timestamp: "2026-08-24T11:00:00.000Z",
1632 message,
1633 });
1634 // The user rewound to the first prompt; the abandoned branch stays in the file.
1635 yield* writeTranscript({
1636 filePath: path.join(piAgentDir, "sessions", "--selected--", "2026-08-24_pi.jsonl"),
1637 contents: [
1638 encodeTranscriptRecord({
1639 type: "session",
1640 version: 3,
1641 id: "pi-recent",
1642 cwd: workspace,
1643 }),
1644 piMessage("a1", null, { role: "user", content: "Plan the change" }),
1645 piMessage("a2", "a1", {
1646 role: "assistant",
1647 content: [{ type: "text", text: "Abandoned answer" }],
1648 }),
1649 piMessage("a3", "a2", { role: "user", content: "Abandoned follow-up" }),
1650 piMessage("b1", "a1", {
1651 role: "assistant",
1652 content: [
1653 { type: "thinking", thinking: "Hidden reasoning" },
1654 { type: "toolCall", id: "call-1", name: "bash", arguments: {} },
1655 ],
1656 }),
1657 piMessage("bn", "b1", { role: "toolResult", content: null }),
1658 piMessage("b2", "bn", {
1659 role: "toolResult",
1660 content: [{ type: "text", text: "Tool output" }],
1661 }),
1662 piMessage("b3", "b2", {
1663 role: "assistant",
1664 content: [{ type: "text", text: "Active answer" }],
1665 }),
1666 encodeTranscriptRecord({
1667 type: "session_info",
1668 id: "b4",
1669 parentId: "b3",
1670 name: "Pi refactor",
1671 }),
1672 ].join("\n"),
1673 mtimeMs: nowMs - 30 * 60 * 1000,
1674 });
1675 // Version 1 sessions predate the entry tree.
1676 yield* writeTranscript({
1677 filePath: path.join(piAgentDir, "sessions", "--selected--", "2025-01-01_pi-v1.jsonl"),
1678 contents: [
1679 encodeTranscriptRecord({ type: "session", id: "pi-v1", cwd: workspace }),
1680 encodeTranscriptRecord({
1681 type: "message",
1682 message: { role: "user", content: "Legacy prompt" },
1683 }),
1684 encodeTranscriptRecord({
1685 type: "message",
1686 message: { role: "assistant", content: [{ type: "text", text: "Legacy answer" }] },
1687 }),
1688 ].join("\n"),
1689 mtimeMs: nowMs - 2 * 24 * 60 * 60 * 1000,
1690 });
1691
1692 const threads = yield* runRecentThreads({
1693 claudeHomePath,
1694 codexHomePath,
1695 piAgentDir,
1696 workspaceRoot: workspace,
1697 });
1698
1699 expect(threads.map((thread) => thread.providerSessionId)).toEqual([
1700 "pi-recent",
1701 "codex-recent",
1702 "claude-recent",
1703 "pi-v1",
1704 ]);
1705 expect(threads.map((thread) => thread.messages.map((message) => message.text))).toEqual([
1706 ["Plan the change", "Active answer"],
1707 ["Review this code", "Looks good"],
1708 ["Fix the project", "Done"],
1709 ["Legacy prompt", "Legacy answer"],
1710 ]);
1711 expect(threads[0]).toMatchObject({ source: "pi", title: "Pi refactor" });
1712 }),
1713 );
1714
1715 it.effect("keeps the provider instance that owns a custom session home", () =>
1716 Effect.gen(function* () {
1717 const path = yield* Path.Path;
1718 const nowMs = Date.parse("2026-08-24T12:00:00.000Z");
1719 yield* TestClock.setTime(nowMs);
1720 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
1721 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
1722 const customHome = yield* makeTempDir("t3code-codex-custom-");
1723 const workspace = yield* makeTempDir("t3code-workspace-");
1724
1725 yield* writeTranscript({
1726 filePath: path.join(customHome, "sessions", "2026", "08", "24", "rollout-custom.jsonl"),
1727 contents: [
1728 encodeTranscriptRecord({
1729 type: "session_meta",
1730 payload: { id: "custom-session", cwd: workspace },
1731 }),
1732 encodeTranscriptRecord({
1733 type: "event_msg",
1734 payload: { type: "user_message", message: "Use my work account" },
1735 }),
1736 ].join("\n"),
1737 mtimeMs: nowMs,
1738 });
1739
1740 const threads = yield* runRecentThreads({
1741 claudeHomePath,
1742 codexHomePath,
1743 workspaceRoot: workspace,
1744 providerInstances: {
1745 [ProviderInstanceId.make("codex-work")]: {
1746 driver: ProviderDriverKind.make("codex"),
1747 config: { homePath: customHome },
1748 },
1749 },
1750 });
1751
1752 expect(threads[0]?.providerInstanceId).toBe("codex-work");
1753 }),
1754 );
1755
1756 it.effect("titles Codex sessions with their newest saved Codex name", () =>
1757 Effect.gen(function* () {
1758 const fileSystem = yield* FileSystem.FileSystem;
1759 const path = yield* Path.Path;
1760 const nowMs = Date.parse("2026-08-24T12:00:00.000Z");
1761 yield* TestClock.setTime(nowMs);
1762 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
1763 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
1764 const workspace = yield* makeTempDir("t3code-workspace-");
1765
1766 yield* writeTranscript({
1767 filePath: path.join(codexHomePath, "sessions", "2026", "08", "24", "rollout-named.jsonl"),
1768 contents: [
1769 encodeTranscriptRecord({
1770 type: "session_meta",
1771 payload: { id: "named-session", cwd: workspace },
1772 }),
1773 encodeTranscriptRecord({
1774 type: "event_msg",
1775 payload: {
1776 type: "user_message",
1777 message:
1778 '<external_codex_apps_open_page>{"page_id":null}</external_codex_apps_open_page>\nHey, what\'s up?',
1779 },
1780 }),
1781 ].join("\n"),
1782 mtimeMs: nowMs,
1783 });
1784 yield* fileSystem.writeFileString(
1785 path.join(codexHomePath, "session_index.jsonl"),
1786 [
1787 { id: "named-session", thread_name: "First name" },
1788 { id: "other-session", thread_name: "Other chat" },
1789 { id: "named-session", thread_name: "Renamed chat" },
1790 { id: "named-session", thread_name: " " },
1791 ]
1792 .map((entry) => `${encodeTranscriptRecord({ ...entry, updated_at: "unknown" })}\n`)
1793 .join(""),
1794 );
1795
1796 const threads = yield* runRecentThreads({
1797 claudeHomePath,
1798 codexHomePath,
1799 workspaceRoot: workspace,
1800 });
1801
1802 expect(threads.map((thread) => thread.title)).toEqual(["Renamed chat"]);
1803 }),
1804 );
1805
1806 it.effect("imports Codex chats moved from a scratch folder into a Codex project", () =>
1807 Effect.gen(function* () {
1808 const fileSystem = yield* FileSystem.FileSystem;
1809 const path = yield* Path.Path;
1810 const nowMs = Date.parse("2026-11-08T12:00:00.000Z");
1811 yield* TestClock.setTime(nowMs);
1812 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
1813 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
1814 const homeDir = yield* makeTempDir("t3code-home-");
1815 const projectDir = path.join(homeDir, "code", "my-project");
1816 const scratchDir = path.join(homeDir, "Documents", "Codex", "2026-11-08", "new-chat");
1817 const otherDir = path.join(homeDir, "code", "other-project");
1818 yield* fileSystem.makeDirectory(projectDir, { recursive: true });
1819 yield* fileSystem.makeDirectory(scratchDir, { recursive: true });
1820 yield* fileSystem.makeDirectory(otherDir, { recursive: true });
1821
1822 const projectId = "019a5f00-0000-7000-8000-000000000001";
1823 const chats = [
1824 {
1825 id: "019a5f00-0000-7000-8000-00000000000a",
1826 cwd: scratchDir,
1827 message: "Started with no project",
1828 },
1829 {
1830 id: "019a5f00-0000-7000-8000-00000000000b",
1831 cwd: projectDir,
1832 message: "Started in the project",
1833 },
1834 {
1835 id: "019a5f00-0000-7000-8000-00000000000c",
1836 cwd: otherDir,
1837 message: "Started in another folder",
1838 },
1839 {
1840 id: "019a5f00-0000-7000-8000-00000000000d",
1841 rolloutId: "019a5f00-0000-7000-8000-0000000000d1",
1842 cwd: scratchDir,
1843 message: "Rewound with no project",
1844 },
1845 ];
1846 const rolloutPaths: Array<string> = [];
1847 for (const [index, chat] of chats.entries()) {
1848 const filePath = path.join(
1849 codexHomePath,
1850 "sessions",
1851 "2026",
1852 "11",
1853 "08",
1854 `rollout-2026-11-08T08-0${index}-00-${"rolloutId" in chat ? `${chat.id}_${chat.rolloutId}` : chat.id}.jsonl`,
1855 );
1856 rolloutPaths.push(filePath);
1857 yield* writeTranscript({
1858 filePath,
1859 contents: [
1860 encodeTranscriptRecord({
1861 type: "session_meta",
1862 payload: { id: chat.id, cwd: chat.cwd },
1863 }),
1864 encodeTranscriptRecord({ type: "turn_context", payload: { cwd: chat.cwd } }),
1865 encodeTranscriptRecord({
1866 type: "event_msg",
1867 payload: { type: "user_message", message: chat.message },
1868 }),
1869 ].join("\n"),
1870 mtimeMs: nowMs - 60_000 + index,
1871 });
1872 }
1873 // Codex records a chat's project only in its state DB; the rollout keeps the original cwd.
1874 yield* Effect.sync(() => {
1875 const db = new NodeSqlite.DatabaseSync(path.join(codexHomePath, "state_5.sqlite"));
1876 try {
1877 db.exec(`
1878 CREATE TABLE projects (
1879 id TEXT PRIMARY KEY,
1880 name TEXT NOT NULL,
1881 metadata TEXT NOT NULL DEFAULT '{}',
1882 position INTEGER NOT NULL,
1883 created_at_ms INTEGER NOT NULL,
1884 updated_at_ms INTEGER NOT NULL
1885 );
1886 CREATE TABLE project_roots (
1887 project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
1888 position INTEGER NOT NULL,
1889 path TEXT NOT NULL,
1890 PRIMARY KEY (project_id, position)
1891 );
1892 CREATE TABLE threads (
1893 id TEXT PRIMARY KEY,
1894 rollout_path TEXT NOT NULL,
1895 cwd TEXT NOT NULL,
1896 project_id TEXT REFERENCES projects(id) ON DELETE SET NULL
1897 );
1898 `);
1899 db.prepare("INSERT INTO projects VALUES (?, ?, '{}', 0, ?, ?)").run(
1900 projectId,
1901 "my-project",
1902 nowMs,
1903 nowMs,
1904 );
1905 db.prepare("INSERT INTO project_roots VALUES (?, 0, ?)").run(projectId, projectDir);
1906 const insertThread = db.prepare("INSERT INTO threads VALUES (?, ?, ?, ?)");
1907 for (const [index, chat] of chats.entries()) {
1908 insertThread.run(chat.id, rolloutPaths[index]!, chat.cwd, projectId);
1909 }
1910 } finally {
1911 db.close();
1912 }
1913 });
1914
1915 const threads = yield* runRecentThreads({
1916 claudeHomePath,
1917 codexHomePath,
1918 workspaceRoot: projectDir,
1919 }).pipe(Effect.provideService(HostProcess.HomeDirectory, homeDir));
1920 expect(threads.map((thread) => thread.title).toSorted()).toEqual([
1921 "Rewound with no project",
1922 "Started in the project",
1923 "Started with no project",
1924 ]);
1925
1926 const result = yield* runScan({ claudeHomePath, codexHomePath }).pipe(
1927 Effect.provideService(HostProcess.HomeDirectory, homeDir),
1928 );
1929 expect(
1930 result.candidates
1931 .map(({ path, threadCount }) => ({ path, threadCount }))
1932 .toSorted((left, right) => left.path.localeCompare(right.path)),
1933 ).toEqual([
1934 { path: projectDir, threadCount: 3 },
1935 { path: otherDir, threadCount: 1 },
1936 ]);
1937 }),
1938 );
1939
1940 it.effect("imports a rewound Codex thread with the history its new rollout inherits", () =>
1941 Effect.gen(function* () {
1942 const path = yield* Path.Path;
1943 const nowMs = Date.parse("2026-08-24T12:00:00.000Z");
1944 yield* TestClock.setTime(nowMs);
1945 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
1946 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
1947 const workspace = yield* makeTempDir("t3code-workspace-");
1948 const threadId = "019a0000-0000-7000-8000-000000000001";
1949 const rolloutId = "019a0000-0000-7000-8000-000000000002";
1950 const sessionsDir = path.join(codexHomePath, "sessions", "2026", "08", "24");
1951 const prompt = (message: string) =>
1952 encodeTranscriptRecord({ type: "event_msg", payload: { type: "user_message", message } });
1953 const reply = (text: string) =>
1954 encodeTranscriptRecord({
1955 type: "response_item",
1956 payload: {
1957 type: "message",
1958 role: "assistant",
1959 content: [{ type: "output_text", text }],
1960 },
1961 });
1962 const keptHistory = [
1963 encodeTranscriptRecord({
1964 type: "session_meta",
1965 payload: { id: threadId, cwd: workspace, history_mode: "paginated" },
1966 }),
1967 prompt("Keep the first request"),
1968 reply("First reply"),
1969 ]
1970 .map((record) => `${record}\n`)
1971 .join("");
1972
1973 yield* writeTranscript({
1974 filePath: path.join(sessionsDir, `rollout-2026-08-24T10-00-00-${threadId}.jsonl`),
1975 contents: `${keptHistory}${prompt("Rewound request")}\n${reply("Rewound reply")}\n`,
1976 mtimeMs: nowMs - 60_000,
1977 });
1978 yield* writeTranscript({
1979 filePath: path.join(
1980 sessionsDir,
1981 `rollout-2026-08-24T11-00-00-${threadId}_${rolloutId}.jsonl`,
1982 ),
1983 contents: [
1984 encodeTranscriptRecord({
1985 type: "session_meta",
1986 payload: {
1987 id: threadId,
1988 cwd: workspace,
1989 history_mode: "paginated",
1990 history_base: {
1991 thread_id: threadId,
1992 end_ordinal_exclusive: 3,
1993 end_byte_offset: Buffer.byteLength(keptHistory),
1994 },
1995 },
1996 }),
1997 prompt("Ask again"),
1998 reply("Final reply"),
1999 ].join("\n"),
2000 mtimeMs: nowMs,
2001 });
2002
2003 const threads = yield* runRecentThreads({
2004 claudeHomePath,
2005 codexHomePath,
2006 workspaceRoot: workspace,
2007 });
2008
2009 expect(
2010 threads.map((thread) => ({
2011 id: thread.providerSessionId,
2012 title: thread.title,
2013 messages: thread.messages.map((message) => message.text),
2014 })),
2015 ).toEqual([
2016 {
2017 id: threadId,
2018 title: "Keep the first request",
2019 messages: ["Keep the first request", "First reply", "Ask again", "Final reply"],
2020 },
2021 ]);
2022 }),
2023 );
2024
2025 it.effect("excludes Codex subagents from discovery and the recent-thread budget", () =>
2026 Effect.gen(function* () {
2027 const path = yield* Path.Path;
2028 const nowMs = Date.parse("2026-08-24T12:00:00.000Z");
2029 yield* TestClock.setTime(nowMs);
2030 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
2031 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
2032 const workspace = yield* makeTempDir("t3code-workspace-");
2033 const subagentSources = [
2034 { subagent: { thread_spawn: { parent_thread_id: "session-100", depth: 1 } } },
2035 { subagent: "review" },
2036 { subagent: { other: "guardian" } },
2037 { subAgent: "compact" },
2038 ];
2039 // Newer subagents would exhaust the 100-transcript import budget before any parent.
2040 const sources = [
2041 ...Array.from({ length: 100 }, (_, index) => subagentSources[index % 4]),
2042 "vscode",
2043 undefined,
2044 null,
2045 { custom: "launcher" },
2046 ];
2047 const fileSystem = yield* FileSystem.FileSystem;
2048 // Rollouts imported before subagents were excluded still have import records.
2049 const legacyImports: Array<AgentSessionImportSource> = [];
2050 for (const [index, source] of sources.entries()) {
2051 const filePath = path.join(
2052 codexHomePath,
2053 "sessions",
2054 "2026",
2055 "08",
2056 "24",
2057 `rollout-${index}.jsonl`,
2058 );
2059 yield* writeTranscript({
2060 filePath,
2061 contents: [
2062 { type: "session_meta", payload: { id: `session-${index}`, cwd: workspace, source } },
2063 // A later cwd must not make an excluded rollout eligible again.
2064 { type: "turn_context", payload: { cwd: workspace } },
2065 {
2066 type: "event_msg",
2067 payload: { type: "user_message", message: "Import this prompt" },
2068 },
2069 ]
2070 .map((record) => encodeTranscriptRecord(record))
2071 .join("\n"),
2072 mtimeMs: nowMs - index * 60_000,
2073 });
2074 if (index >= 100) continue;
2075 const stats = yield* fileSystem.stat(filePath);
2076 legacyImports.push(
2077 decodeImportSource({
2078 provider: "codex",
2079 providerInstanceId: "codex",
2080 providerSessionId: `session-${index}`,
2081 filePath,
2082 size: Number(stats.size),
2083 mtimeMs: Option.getOrNull(Option.map(stats.mtime, (date) => date.getTime())),
2084 device: Number(stats.dev),
2085 inode: Option.getOrNull(Option.map(stats.ino, String)),
2086 birthtimeMs: Option.getOrNull(Option.map(stats.birthtime, (date) => date.getTime())),
2087 }),
2088 );
2089 }
2090
2091 yield* Effect.gen(function* () {
2092 const scanner = yield* AgentSessionScanner.AgentSessionScanner;
2093 const scan = yield* scanner.scan;
2094 expect.soft(scan.candidates.map((candidate) => candidate.threadCount)).toEqual([4]);
2095 const outcomes = yield* Stream.runCollect(scanner.recentThreads(workspace));
2096 expect(
2097 outcomes.map((outcome) =>
2098 outcome._tag === "Importable" ? outcome.thread.providerSessionId : outcome._tag,
2099 ),
2100 ).toEqual(["session-100", "session-101", "session-102", "session-103"]);
2101 }).pipe(
2102 Effect.provide(
2103 layerScannerTest({
2104 claudeHomePath,
2105 codexHomePath,
2106 importedTranscripts: { cwd: workspace, sources: legacyImports },
2107 }),
2108 ),
2109 );
2110 }),
2111 );
2112
2113 it.effect("suppresses duplicate session copies without reporting a skipped import", () =>
2114 Effect.gen(function* () {
2115 const path = yield* Path.Path;
2116 const nowMs = Date.parse("2026-08-24T12:00:00.000Z");
2117 yield* TestClock.setTime(nowMs);
2118 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
2119 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
2120 const workspace = yield* makeTempDir("t3code-workspace-");
2121 const contents = [
2122 encodeTranscriptRecord({
2123 type: "session_meta",
2124 payload: { id: "copied-session", cwd: workspace },
2125 }),
2126 encodeTranscriptRecord({
2127 type: "event_msg",
2128 payload: { type: "user_message", message: "Import this session once" },
2129 }),
2130 ].join("\n");
2131
2132 for (const [name, mtimeMs] of [
2133 ["rollout-copy-a.jsonl", nowMs],
2134 ["rollout-copy-b.jsonl", nowMs - 1],
2135 ] as const) {
2136 yield* writeTranscript({
2137 filePath: path.join(codexHomePath, "sessions", "2026", "08", "24", name),
2138 contents,
2139 mtimeMs,
2140 });
2141 }
2142
2143 const outcomes = yield* runRecentThreadOutcomes({
2144 claudeHomePath,
2145 codexHomePath,
2146 workspaceRoot: workspace,
2147 });
2148
2149 expect(outcomes.map((outcome) => outcome._tag)).toEqual(["Importable", "Duplicate"]);
2150 expect(outcomes[0]).toMatchObject({
2151 _tag: "Importable",
2152 thread: { providerSessionId: "copied-session" },
2153 });
2154 }),
2155 );
2156
2157 it.effect("ignores sessions without visible messages without spending the import budget", () =>
2158 Effect.gen(function* () {
2159 const path = yield* Path.Path;
2160 const nowMs = Date.parse("2026-08-24T12:00:00.000Z");
2161 yield* TestClock.setTime(nowMs);
2162 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
2163 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
2164 const workspace = yield* makeTempDir("t3code-workspace-");
2165 const codexRollout = (name: string) =>
2166 path.join(codexHomePath, "sessions", "2026", "08", "24", `rollout-${name}.jsonl`);
2167 // Newer empty sessions would exhaust the 100-transcript import budget before any real one.
2168 const emptySessions = Array.from({ length: 100 }, (_, index) =>
2169 index % 2 === 0
2170 ? {
2171 filePath: codexRollout(`empty-${index}`),
2172 records: [
2173 {
2174 type: "session_meta",
2175 payload: { id: `codex-empty-${index}`, cwd: workspace, source: "vscode" },
2176 },
2177 {
2178 type: "event_msg",
2179 payload: {
2180 type: "thread_settings_applied",
2181 thread_settings: { cwd: workspace },
2182 },
2183 },
2184 ],
2185 }
2186 : {
2187 filePath: path.join(
2188 claudeHomePath,
2189 "projects",
2190 "-slug",
2191 `claude-empty-${index}.jsonl`,
2192 ),
2193 records: [
2194 { type: "system", subtype: "informational", content: "Status", cwd: workspace },
2195 {
2196 type: "user",
2197 isMeta: true,
2198 message: {
2199 role: "user",
2200 content: "<local-command-caveat>Caveat</local-command-caveat>",
2201 },
2202 cwd: workspace,
2203 },
2204 ],
2205 },
2206 );
2207 const transcripts = [
2208 ...emptySessions,
2209 {
2210 // Without session_meta there is no resumable session ID.
2211 filePath: codexRollout("unusable"),
2212 records: [
2213 { type: "turn_context", payload: { cwd: workspace } },
2214 {
2215 type: "event_msg",
2216 payload: { type: "user_message", message: "Import this prompt" },
2217 },
2218 ],
2219 },
2220 {
2221 filePath: codexRollout("real"),
2222 records: [
2223 { type: "session_meta", payload: { id: "real-session", cwd: workspace } },
2224 {
2225 type: "event_msg",
2226 payload: { type: "user_message", message: "Import this prompt" },
2227 },
2228 ],
2229 },
2230 ];
2231 for (const [index, { filePath, records }] of transcripts.entries()) {
2232 yield* writeTranscript({
2233 filePath,
2234 contents: records.map((record) => encodeTranscriptRecord(record)).join("\n"),
2235 mtimeMs: nowMs - index * 60_000,
2236 });
2237 }
2238
2239 const outcomes = yield* runRecentThreadOutcomes({
2240 claudeHomePath,
2241 codexHomePath,
2242 workspaceRoot: workspace,
2243 });
2244
2245 expect(
2246 outcomes.map((outcome) =>
2247 outcome._tag === "Importable" ? outcome.thread.providerSessionId : outcome._tag,
2248 ),
2249 ).toEqual(["Skipped", "real-session"]);
2250 }),
2251 );
2252
2253 it.effect("skips a rewound Codex rollout whose inherited history is unavailable", () =>
2254 Effect.gen(function* () {
2255 const path = yield* Path.Path;
2256 const nowMs = Date.parse("2026-08-24T12:00:00.000Z");
2257 yield* TestClock.setTime(nowMs);
2258 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
2259 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
2260 const workspace = yield* makeTempDir("t3code-workspace-");
2261 const threadId = "019a0000-0000-7000-8000-000000000001";
2262 const rolloutId = "019a0000-0000-7000-8000-000000000002";
2263 // The ancestor rollout is missing, and this rollout added no messages of its own.
2264 yield* writeTranscript({
2265 filePath: path.join(
2266 codexHomePath,
2267 "sessions",
2268 "2026",
2269 "08",
2270 "24",
2271 `rollout-2026-08-24T11-00-00-${threadId}_${rolloutId}.jsonl`,
2272 ),
2273 contents: encodeTranscriptRecord({
2274 type: "session_meta",
2275 payload: {
2276 id: threadId,
2277 cwd: workspace,
2278 history_mode: "paginated",
2279 history_base: { thread_id: threadId, end_ordinal_exclusive: 3, end_byte_offset: 512 },
2280 },
2281 }),
2282 mtimeMs: nowMs,
2283 });
2284
2285 const outcomes = yield* runRecentThreadOutcomes({
2286 claudeHomePath,
2287 codexHomePath,
2288 workspaceRoot: workspace,
2289 });
2290
2291 expect(outcomes).toEqual([{ _tag: "Skipped" }]);
2292 }),
2293 );
2294
2295 it.effect("skips excessive records without blocking an older valid transcript", () =>
2296 Effect.gen(function* () {
2297 const path = yield* Path.Path;
2298 const nowMs = Date.parse("2026-08-24T12:00:00.000Z");
2299 yield* TestClock.setTime(nowMs);
2300 const claudeHomePath = yield* makeTempDir("t3code-record-budget-claude-");
2301 const codexHomePath = yield* makeTempDir("t3code-record-budget-codex-");
2302 const workspace = yield* makeTempDir("t3code-record-budget-workspace-");
2303 // The newer transcript retains 100,001 records; the older one exactly 100,000.
2304 for (const [sessionId, recordCount, mtimeMs] of [
2305 ["excessive", 100_001, nowMs],
2306 ["older", 100_000, nowMs - 1_000],
2307 ] as const) {
2308 yield* writeTranscript({
2309 filePath: path.join(
2310 claudeHomePath,
2311 "pi-agent",
2312 "sessions",
2313 "--workspace--",
2314 `${sessionId}.jsonl`,
2315 ),
2316 contents: makePiToolResultTranscript(sessionId, workspace, recordCount),
2317 mtimeMs,
2318 });
2319 }
2320 const outcomes = yield* runRecentThreadOutcomes({
2321 claudeHomePath,
2322 codexHomePath,
2323 workspaceRoot: workspace,
2324 });
2325 expect(outcomes.map((outcome) => outcome._tag)).toEqual(["Skipped", "Importable"]);
2326 expect(outcomes[1]).toMatchObject({ thread: { providerSessionId: "older" } });
2327 }),
2328 );
2329
2330 it.effect("imports every transcript that fits the per-file record limit", () =>
2331 Effect.gen(function* () {
2332 const path = yield* Path.Path;
2333 const nowMs = Date.parse("2026-08-24T12:00:00.000Z");
2334 yield* TestClock.setTime(nowMs);
2335 const claudeHomePath = yield* makeTempDir("t3code-shared-records-claude-");
2336 const codexHomePath = yield* makeTempDir("t3code-shared-records-codex-");
2337 const workspace = yield* makeTempDir("t3code-shared-records-workspace-");
2338 // Together these exceed 100,000 records, but each one is individually valid.
2339 const recordCounts = [20_000, 20_000, 20_000, 58_000];
2340 for (const [index, recordCount] of recordCounts.entries()) {
2341 yield* writeTranscript({
2342 filePath: path.join(
2343 claudeHomePath,
2344 "pi-agent",
2345 "sessions",
2346 "--workspace--",
2347 `${index}.jsonl`,
2348 ),
2349 contents: makePiToolResultTranscript(`session-${index}`, workspace, recordCount),
2350 mtimeMs: nowMs - index * 1_000,
2351 });
2352 }
2353 const outcomes = yield* runRecentThreadOutcomes({
2354 claudeHomePath,
2355 codexHomePath,
2356 workspaceRoot: workspace,
2357 });
2358 expect(
2359 outcomes.map((outcome) =>
2360 outcome._tag === "Importable" ? outcome.thread.providerSessionId : outcome._tag,
2361 ),
2362 ).toEqual(["session-0", "session-1", "session-2", "session-3"]);
2363 }),
2364 );
2365
2366 it.effect("repeated imports reach older transcripts behind already-imported ones", () =>
2367 Effect.gen(function* () {
2368 const path = yield* Path.Path;
2369 const nowMs = Date.parse("2026-08-24T12:00:00.000Z");
2370 yield* TestClock.setTime(nowMs);
2371 const claudeHomePath = yield* makeTempDir("t3code-repeat-import-claude-");
2372 const codexHomePath = yield* makeTempDir("t3code-repeat-import-codex-");
2373 const workspace = yield* makeTempDir("t3code-repeat-import-workspace-");
2374 const sessionIds = Array.from(
2375 { length: 102 },
2376 (_, index) => `00000000-0000-4000-8000-${String(index).padStart(12, "0")}`,
2377 );
2378 for (const [index, sessionId] of sessionIds.entries()) {
2379 yield* writeTranscript({
2380 filePath: path.join(claudeHomePath, "projects", "p", `${sessionId}.jsonl`),
2381 // 999 cwd-less records cost 1,000 metadata records, so 100 newer transcripts
2382 // exhaust MAX_METADATA_RECORDS_PER_SOURCE.
2383 contents:
2384 "{}\n".repeat(999) +
2385 `${encodeTranscriptRecord({
2386 type: "user",
2387 cwd: workspace,
2388 sessionId,
2389 timestamp: "2026-08-23T12:00:00.000Z",
2390 message: { role: "user", content: `Prompt ${index}` },
2391 })}\n`,
2392 mtimeMs: nowMs - (index + 1) * 60_000,
2393 });
2394 }
2395
2396 const completed: Array<AgentSessionImportSource> = [];
2397 const imported = yield* Effect.gen(function* () {
2398 const scanner = yield* AgentSessionScanner.AgentSessionScanner;
2399 while (true) {
2400 const outcomes = yield* scanner
2401 .recentThreads(workspace, completed)
2402 .pipe(Stream.runCollect);
2403 const added = Array.from(outcomes).flatMap((outcome) =>
2404 outcome._tag === "Importable" ? [outcome.source] : [],
2405 );
2406 if (added.length === 0) return completed;
2407 completed.push(...added);
2408 }
2409 }).pipe(
2410 Effect.provide(
2411 layerScannerTest({
2412 claudeHomePath,
2413 codexHomePath,
2414 importedTranscripts: { cwd: workspace, sources: completed },
2415 }),
2416 ),
2417 );
2418
2419 expect(imported.map((source) => source.providerSessionId).toSorted()).toEqual(sessionIds);
2420 }),
2421 );
2422
2423 it.effect("lists projects whose transcripts sit behind already-imported ones", () =>
2424 Effect.gen(function* () {
2425 const path = yield* Path.Path;
2426 const nowMs = Date.parse("2026-08-24T12:00:00.000Z");
2427 yield* TestClock.setTime(nowMs);
2428 const claudeHomePath = yield* makeTempDir("t3code-hidden-project-claude-");
2429 const codexHomePath = yield* makeTempDir("t3code-hidden-project-codex-");
2430 const imported = yield* makeTempDir("t3code-hidden-project-imported-");
2431 const hidden = yield* makeTempDir("t3code-hidden-project-hidden-");
2432 const hiddenSessionId = "00000000-0000-4000-8000-000000000100";
2433 for (const index of Array.from({ length: 101 }, (_, value) => value)) {
2434 const sessionId = `00000000-0000-4000-8000-${String(index).padStart(12, "0")}`;
2435 yield* writeTranscript({
2436 filePath: path.join(claudeHomePath, "projects", "p", `${sessionId}.jsonl`),
2437 contents:
2438 "{}\n".repeat(999) +
2439 `${encodeTranscriptRecord({
2440 type: "user",
2441 cwd: index === 100 ? hidden : imported,
2442 sessionId,
2443 message: { role: "user", content: `Prompt ${index}` },
2444 })}\n`,
2445 mtimeMs: nowMs - (index + 1) * 60_000,
2446 });
2447 }
2448
2449 const completed: Array<AgentSessionImportSource> = [];
2450 const scans = yield* Effect.gen(function* () {
2451 const scanner = yield* AgentSessionScanner.AgentSessionScanner;
2452 const before = yield* scanner.scan;
2453 const outcomes = yield* scanner.recentThreads(imported).pipe(Stream.runCollect);
2454 const sources = Array.from(outcomes).flatMap((outcome) =>
2455 outcome._tag === "Importable" ? [outcome.source] : [],
2456 );
2457 // A record whose file identity no longer matches must not lend its cwd.
2458 const newest = sources[0]!;
2459 completed.push(...sources, {
2460 ...newest,
2461 providerSessionId: hiddenSessionId,
2462 filePath: path.join(claudeHomePath, "projects", "p", `${hiddenSessionId}.jsonl`),
2463 });
2464 return { before, after: yield* scanner.scan };
2465 }).pipe(
2466 Effect.provide(
2467 layerScannerTest({
2468 claudeHomePath,
2469 codexHomePath,
2470 importedTranscripts: { cwd: imported, sources: completed },
2471 }),
2472 ),
2473 );
2474
2475 expect(scans.before.candidates.map((candidate) => candidate.path)).toEqual([imported]);
2476 expect(scans.after.candidates.map((candidate) => candidate.path)).toEqual([
2477 imported,
2478 hidden,
2479 ]);
2480 }),
2481 );
2482
2483 for (const source of ["claudeAgent", "codex"] as const) {
2484 for (const replacement of [
2485 "same root",
2486 "other root",
2487 "symlink alias",
2488 "other then same",
2489 ] as const) {
2490 it.effect.skipIf(replacement === "symlink alias" && !symlinksSupported)(
2491 `rechecks ${source} snapshot cwd after replacement with ${replacement}`,
2492 () =>
2493 Effect.gen(function* () {
2494 const path = yield* Path.Path;
2495 const fileSystem = yield* FileSystem.FileSystem;
2496 const nowMs = Date.parse("2026-08-24T12:00:00.000Z");
2497 yield* TestClock.setTime(nowMs);
2498 const fixture = yield* makeTempDir("t3code-replaced-cwd-");
2499 const workspace = path.join(fixture, "original");
2500 const otherWorkspace = path.join(fixture, "other");
2501 const alias = path.join(fixture, "alias");
2502 const claudeHomePath = path.join(fixture, "claude");
2503 const codexHomePath = path.join(fixture, "codex");
2504 yield* fileSystem.makeDirectory(workspace);
2505 yield* fileSystem.makeDirectory(otherWorkspace);
2506 if (replacement === "symlink alias") yield* fileSystem.symlink(workspace, alias);
2507 const filePath =
2508 source === "codex"
2509 ? path.join(
2510 codexHomePath,
2511 "sessions",
2512 "2026",
2513 "08",
2514 "24",
2515 "rollout-replaced.jsonl",
2516 )
2517 : path.join(claudeHomePath, "projects", "p", "replaced.jsonl");
2518 const makeContents = (cwd: string, text: string, laterCwd?: string) =>
2519 [
2520 ...(source === "codex"
2521 ? [
2522 { type: "session_meta", payload: { id: "replacement-session", cwd } },
2523 { type: "event_msg", payload: { type: "user_message", message: text } },
2524 ]
2525 : [
2526 {
2527 type: "user",
2528 cwd,
2529 sessionId: "replacement-session",
2530 message: { content: text },
2531 },
2532 ]),
2533 ...(laterCwd === undefined ? [] : [{ cwd: laterCwd }]),
2534 ]
2535 .map((record) => encodeTranscriptRecord(record))
2536 .join("\n");
2537 yield* writeTranscript({
2538 filePath,
2539 contents: makeContents(workspace, "Original prompt"),
2540 mtimeMs: nowMs,
2541 });
2542
2543 yield* Effect.gen(function* () {
2544 const scanner = yield* AgentSessionScanner.AgentSessionScanner;
2545 const scan = yield* scanner.scan;
2546 expect(scan.candidates.map((candidate) => candidate.path)).toEqual([workspace]);
2547 const replacementCwd =
2548 replacement === "symlink alias"
2549 ? alias
2550 : replacement === "same root"
2551 ? workspace
2552 : otherWorkspace;
2553 yield* fileSystem.remove(filePath);
2554 yield* writeTranscript({
2555 filePath,
2556 contents: makeContents(
2557 replacementCwd,
2558 "Replacement prompt",
2559 replacement === "other then same" ? workspace : undefined,
2560 ),
2561 mtimeMs: nowMs,
2562 });
2563 const outcomes = yield* scanner.recentThreads(workspace).pipe(Stream.runCollect);
2564 if (replacement === "same root" || replacement === "symlink alias") {
2565 expect(outcomes).toHaveLength(1);
2566 expect(outcomes[0]).toMatchObject({
2567 _tag: "Importable",
2568 thread: { messages: [{ text: "Replacement prompt" }] },
2569 });
2570 } else {
2571 expect(outcomes).toEqual([{ _tag: "Skipped" }]);
2572 }
2573 }).pipe(Effect.provide(layerScannerTest({ claudeHomePath, codexHomePath })));
2574 }),
2575 );
2576 }
2577 }
2578
2579 it.effect("checks file identity and provider before skipping completed history", () =>
2580 Effect.gen(function* () {
2581 const fixture = yield* makeFileIdentityFixture(42n, 43n);
2582 const { scanner, workspace } = fixture;
2583 const initial = yield* scanner.recentThreads(workspace).pipe(Stream.runCollect);
2584 const imported = initial[0];
2585 expect(imported?._tag).toBe("Importable");
2586 if (imported?._tag !== "Importable") return;
2587 const legacy = decodeImportSource({ ...imported.source, inode: 42 });
2588 const opensBeforeCompleted = fixture.opens();
2589 const completed = yield* scanner.recentThreads(workspace, [legacy]).pipe(Stream.runCollect);
2590 expect(completed[0]?._tag).toBe("AlreadyImported");
2591 expect(fixture.opens()).toBe(opensBeforeCompleted);
2592 const wrongProvider = yield* scanner
2593 .recentThreads(workspace, [{ ...imported.source, provider: "claudeAgent" }])
2594 .pipe(Stream.runCollect);
2595 expect(wrongProvider[0]?._tag).toBe("Importable");
2596
2597 yield* fixture.replace;
2598 const replaced = yield* scanner
2599 .recentThreads(workspace, [imported.source])
2600 .pipe(Stream.runCollect);
2601 expect(replaced[0]).toMatchObject({
2602 _tag: "Importable",
2603 thread: { providerSessionId: "replaced-session" },
2604 source: { size: imported.source.size, mtimeMs: imported.source.mtimeMs },
2605 });
2606 }),
2607 );
2608
2609 it.effect(
2610 "imports same-metadata replacements with exact large file IDs and backfills legacy IDs once",
2611 () =>
2612 Effect.gen(function* () {
2613 const fixture = yield* makeFileIdentityFixture();
2614 const { scanner, workspace } = fixture;
2615 const initial = yield* scanner.recentThreads(workspace).pipe(Stream.runCollect);
2616 const imported = initial[0];
2617 expect(imported?._tag).toBe("Importable");
2618 if (imported?._tag !== "Importable") return;
2619
2620 yield* fixture.replace;
2621 const replaced = yield* scanner
2622 .recentThreads(workspace, [imported.source])
2623 .pipe(Stream.runCollect);
2624 expect(replaced[0]).toMatchObject({
2625 _tag: "Importable",
2626 thread: { providerSessionId: "replaced-session" },
2627 source: {
2628 ...imported.source,
2629 providerSessionId: "replaced-session",
2630 inode: "10000000000000000",
2631 },
2632 });
2633 expect(imported.source.inode).toBe("10000000000000001");
2634 if (replaced[0]?._tag !== "Importable") return;
2635
2636 const roundedInode = Number(imported.source.inode);
2637 expect(Number.isSafeInteger(roundedInode)).toBe(false);
2638 expect(String(roundedInode)).toBe(replaced[0].source.inode);
2639 for (const inode of [null, roundedInode]) {
2640 const legacy = decodeImportSource({ ...imported.source, inode });
2641 const opensBeforeBackfill = fixture.opens();
2642 const backfilled = yield* scanner
2643 .recentThreads(workspace, [legacy])
2644 .pipe(Stream.runCollect);
2645 expect(backfilled[0]).toMatchObject({
2646 _tag: "Importable",
2647 thread: { providerSessionId: "replaced-session" },
2648 source: replaced[0].source,
2649 });
2650 expect(fixture.opens()).toBe(opensBeforeBackfill + 1);
2651 if (backfilled[0]?._tag !== "Importable") return;
2652 const completed = yield* scanner
2653 .recentThreads(workspace, [backfilled[0].source])
2654 .pipe(Stream.runCollect);
2655 expect(completed[0]?._tag).toBe("AlreadyImported");
2656 expect(fixture.opens()).toBe(opensBeforeBackfill + 1);
2657 }
2658 }),
2659 );
2660
2661 it.effect("imports long Claude tool history with metadata from discarded records", () =>
2662 Effect.gen(function* () {
2663 const path = yield* Path.Path;
2664 const nowMs = Date.parse("2026-08-24T12:00:00.000Z");
2665 yield* TestClock.setTime(nowMs);
2666 const claudeHomePath = yield* makeTempDir("t3code-long-claude-");
2667 const codexHomePath = yield* makeTempDir("t3code-long-codex-");
2668 const workspace = yield* makeTempDir("t3code-long-workspace-");
2669 const record = (fields: Record<string, unknown>) =>
2670 encodeTranscriptRecord({ sessionId: "first-session", ...fields });
2671 const toolResult = record({
2672 type: "user",
2673 cwd: path.join(workspace, "later-cwd"),
2674 message: {
2675 role: "user",
2676 content: [{ type: "tool_result", tool_use_id: "toolu_1", content: "ok" }],
2677 },
2678 });
2679 // Claude Code's own command output is not a message and must not take a history slot.
2680 const commandOutput = record({
2681 type: "user",
2682 message: {
2683 role: "user",
2684 content: "<local-command-stdout>Compacted</local-command-stdout>",
2685 },
2686 });
2687 yield* writeTranscript({
2688 filePath: path.join(claudeHomePath, "projects", "-slug", "long-session.jsonl"),
2689 contents: [
2690 record({ type: "attachment", cwd: workspace, aiTitle: "Old title" }),
2691 commandOutput,
2692 record({ type: "user", message: { role: "user", content: "First prompt" } }),
2693 record({
2694 type: "assistant",
2695 message: { role: "assistant", model: "claude-opus-5-5", content: "First reply" },
2696 }),
2697 ...Array.from({ length: 200 }, () => commandOutput),
2698 // Small tool records exceed the real 32 MiB selected-history budget in aggregate.
2699 ...Array.from({ length: 20_000 }, () => toolResult),
2700 record({ type: "user", message: { role: "user", content: "Latest prompt" } }),
2701 record({
2702 type: "assistant",
2703 message: {
2704 role: "assistant",
2705 model: "claude-sonnet-5-5",
2706 content: [{ type: "tool_use", id: "toolu_1", name: "Bash", input: {} }],
2707 },
2708 }),
2709 record({ type: "custom-title", customTitle: "Renamed conversation" }),
2710 record({ type: "ai-title", aiTitle: "Newest title" }),
2711 record({ type: "attachment", sessionId: "latest-session" }),
2712 ].join("\n"),
2713 mtimeMs: nowMs,
2714 });
2715
2716 const threads = yield* runRecentThreads({
2717 claudeHomePath,
2718 codexHomePath,
2719 workspaceRoot: workspace,
2720 });
2721
2722 expect(threads).toMatchObject([
2723 {
2724 providerSessionId: "latest-session",
2725 title: "Renamed conversation",
2726 model: "claude-sonnet-5-5",
2727 messages: [
2728 { role: "user", text: "First prompt" },
2729 { role: "assistant", text: "First reply" },
2730 { role: "user", text: "Latest prompt" },
2731 ],
2732 },
2733 ]);
2734 }),
2735 );
2736
2737 it.effect("imports long Claude history beyond the selected-history and record limits", () =>
2738 Effect.gen(function* () {
2739 const path = yield* Path.Path;
2740 const nowMs = Date.parse("2026-08-24T12:00:00.000Z");
2741 yield* TestClock.setTime(nowMs);
2742 const claudeHomePath = yield* makeTempDir("t3code-long-conversation-claude-");
2743 const codexHomePath = yield* makeTempDir("t3code-long-conversation-codex-");
2744 const workspace = yield* makeTempDir("t3code-long-conversation-workspace-");
2745 const record = (fields: Record<string, unknown>) =>
2746 encodeTranscriptRecord({ sessionId: "claude-long", ...fields });
2747 const longText = "x".repeat(64 * 1024);
2748 const middleCount = 600;
2749 yield* writeTranscript({
2750 filePath: path.join(claudeHomePath, "projects", "-slug", "claude-long.jsonl"),
2751 contents: [
2752 record({
2753 type: "user",
2754 cwd: workspace,
2755 message: { role: "user", content: "First prompt" },
2756 }),
2757 // 600 x 64 KiB exceeds the 32 MiB selected-history budget; the shown window fits.
2758 ...Array.from({ length: middleCount }, (_, index) => {
2759 const role = index % 2 === 0 ? "assistant" : "user";
2760 return record({ type: role, message: { role, content: longText } });
2761 }),
2762 // Tool and progress records push the file past the 100,000-record limit.
2763 ...Array.from({ length: 100_000 }, () => "{}"),
2764 record({ type: "user", message: { role: "user", content: "Latest prompt" } }),
2765 ].join("\n"),
2766 mtimeMs: nowMs - 60_000,
2767 });
2768
2769 const outcomes = yield* runRecentThreadOutcomes({
2770 claudeHomePath,
2771 codexHomePath,
2772 workspaceRoot: workspace,
2773 });
2774
2775 expect(outcomes.map((outcome) => outcome._tag)).toEqual(["Importable"]);
2776 const thread = outcomes[0]?._tag === "Importable" ? outcomes[0].thread : undefined;
2777 expect(thread?.messages[0]).toMatchObject({ role: "user", text: "First prompt" });
2778 expect(thread?.messages.at(-1)).toMatchObject({ role: "user", text: "Latest prompt" });
2779 expect(thread?.messages).toHaveLength(200);
2780 expect(thread?.omittedMessageCount).toBe(middleCount + 2 - 200);
2781 }),
2782 );
2783
2784 it.effect("imports a late first Claude prompt once when older replies are dropped", () =>
2785 Effect.gen(function* () {
2786 const path = yield* Path.Path;
2787 const nowMs = Date.parse("2026-08-24T12:00:00.000Z");
2788 yield* TestClock.setTime(nowMs);
2789 const claudeHomePath = yield* makeTempDir("t3code-late-prompt-claude-");
2790 const codexHomePath = yield* makeTempDir("t3code-late-prompt-codex-");
2791 const workspace = yield* makeTempDir("t3code-late-prompt-workspace-");
2792 const contents = [
2793 encodeTranscriptRecord({ type: "attachment", sessionId: "late-prompt", cwd: workspace }),
2794 // The first prompt is still among the latest 200 messages after older replies drop out.
2795 ...Array.from({ length: 250 }, (_, index) => {
2796 const role = index < 60 || index % 2 === 1 ? "assistant" : "user";
2797 return encodeTranscriptRecord({
2798 type: role,
2799 sessionId: "late-prompt",
2800 message: { role, content: `${role} ${index}` },
2801 });
2802 }),
2803 ].join("\n");
2804 const filePath = path.join(claudeHomePath, "projects", "-slug", "late-prompt.jsonl");
2805 yield* writeTranscript({ filePath, contents, mtimeMs: nowMs - 60_000 });
2806
2807 const [thread] = yield* runRecentThreads({
2808 claudeHomePath,
2809 codexHomePath,
2810 workspaceRoot: workspace,
2811 });
2812
2813 expect(thread?.messages[0]).toMatchObject({ role: "assistant", text: "assistant 50" });
2814 expect(thread).toEqual(
2815 AgentSessionScanner.parseAgentSessionTranscript({
2816 source: "claudeAgent",
2817 providerInstanceId: ProviderInstanceId.make("claudeAgent"),
2818 fallbackSessionId: "late-prompt",
2819 lastActiveAtMs: nowMs - 60_000,
2820 contents,
2821 }),
2822 );
2823 }),
2824 );
2825
2826 it.effect("skips growth during reading without exceeding the reserved bytes", () =>
2827 Effect.gen(function* () {
2828 const path = yield* Path.Path;
2829 const fileSystem = yield* FileSystem.FileSystem;
2830 const nowMs = Date.parse("2026-08-24T12:00:00.000Z");
2831 yield* TestClock.setTime(nowMs);
2832 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
2833 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
2834 const workspace = yield* makeTempDir("t3code-workspace-");
2835 const transcriptPath = path.join(
2836 codexHomePath,
2837 "sessions",
2838 "2026",
2839 "08",
2840 "24",
2841 "rollout-growing.jsonl",
2842 );
2843 const contents = [
2844 encodeTranscriptRecord({
2845 type: "session_meta",
2846 payload: { id: "growing-session", cwd: workspace },
2847 }),
2848 encodeTranscriptRecord({
2849 type: "event_msg",
2850 payload: { type: "user_message", message: "Do not import a changing file" },
2851 }),
2852 ].join("\n");
2853 yield* writeTranscript({ filePath: transcriptPath, contents, mtimeMs: nowMs });
2854 let transcriptOpenCount = 0;
2855 let fullReadBytes = 0;
2856 let grew = false;
2857 const simulatedFileSystem = FileSystem.FileSystem.of({
2858 ...fileSystem,
2859 open: (filePath, options) => {
2860 if (filePath !== transcriptPath) return fileSystem.open(filePath, options);
2861 transcriptOpenCount += 1;
2862 if (transcriptOpenCount === 1) return fileSystem.open(filePath, options);
2863 return fileSystem.open(filePath, options).pipe(
2864 Effect.map((file) => ({
2865 ...file,
2866 stat: file.stat,
2867 readAlloc: (size: number) =>
2868 file.readAlloc(size).pipe(
2869 Effect.tap((chunk) =>
2870 Effect.gen(function* () {
2871 if (chunk._tag === "None") return;
2872 fullReadBytes += chunk.value.byteLength;
2873 if (!grew) {
2874 grew = true;
2875 yield* fileSystem.writeFileString(filePath, `${contents}\nchanged`);
2876 }
2877 }),
2878 ),
2879 ),
2880 })),
2881 );
2882 },
2883 });
2884
2885 const outcomes = yield* runRecentThreadOutcomes({
2886 claudeHomePath,
2887 codexHomePath,
2888 workspaceRoot: workspace,
2889 }).pipe(Effect.provideService(FileSystem.FileSystem, simulatedFileSystem));
2890
2891 expect(transcriptOpenCount).toBe(2);
2892 expect(fullReadBytes).toBe(new TextEncoder().encode(contents).byteLength);
2893 expect(outcomes).toEqual([{ _tag: "Skipped" }]);
2894 }),
2895 );
2896
2897 it.effect("uses configured order when custom instances share a session home", () =>
2898 Effect.gen(function* () {
2899 const path = yield* Path.Path;
2900 const nowMs = Date.parse("2026-08-24T12:00:00.000Z");
2901 yield* TestClock.setTime(nowMs);
2902 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
2903 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
2904 const sharedHome = yield* makeTempDir("t3code-codex-shared-");
2905 const workspace = yield* makeTempDir("t3code-workspace-");
2906
2907 yield* writeTranscript({
2908 filePath: path.join(sharedHome, "sessions", "2026", "08", "24", "rollout-shared.jsonl"),
2909 contents: [
2910 encodeTranscriptRecord({
2911 type: "session_meta",
2912 payload: { id: "shared-session", cwd: workspace },
2913 }),
2914 encodeTranscriptRecord({
2915 type: "event_msg",
2916 payload: { type: "user_message", message: "Use the first account" },
2917 }),
2918 ].join("\n"),
2919 mtimeMs: nowMs,
2920 });
2921
2922 const threads = yield* runRecentThreads({
2923 claudeHomePath,
2924 codexHomePath,
2925 workspaceRoot: workspace,
2926 providerInstances: {
2927 [ProviderInstanceId.make("codex-work")]: {
2928 driver: ProviderDriverKind.make("codex"),
2929 config: { homePath: sharedHome },
2930 },
2931 [ProviderInstanceId.make("codex-personal")]: {
2932 driver: ProviderDriverKind.make("codex"),
2933 config: { homePath: sharedHome },
2934 },
2935 },
2936 });
2937
2938 expect(threads.map((thread) => thread.providerInstanceId)).toEqual(["codex-work"]);
2939 }),
2940 );
2941 });
2942 });
2943
2944 describe.skipIf(HostProcess.Platform.defaultValue() === "win32")(
2945 "AgentSessionScanner scan with a git config open() that never returns",
2946 () => {
2947 it.effect(
2948 "completes every scan and leaves the libuv pool free when .git/config is a FIFO",
2949 () =>
2950 Effect.gen(function* () {
2951 const path = yield* Path.Path;
2952 const fileSystem = yield* FileSystem.FileSystem;
2953 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
2954 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
2955 const repo = yield* makeTempDir("t3code-workspace-fifo-config-");
2956 yield* fileSystem.makeDirectory(path.join(repo, ".git"));
2957 yield* makeOpenGate(path.join(repo, ".git", "config"));
2958 const transcriptPath = path.join(claudeHomePath, "projects", "-fifo", "a.jsonl");
2959 yield* writeTranscript({
2960 filePath: transcriptPath,
2961 contents: claudeSessionLine(repo),
2962 mtimeMs: Date.parse("2026-05-03T00:00:00.000Z"),
2963 });
2964
2965 for (let attempt = 1; attempt <= LIBUV_POOL_SIZE + 1; attempt++) {
2966 const scan = yield* Effect.forkChild(
2967 runScan({ claudeHomePath, codexHomePath }).pipe(
2968 Effect.map(({ candidates }) => candidates.map(({ path }) => path)),
2969 ),
2970 );
2971 yield* Effect.scoped(
2972 Effect.gen(function* () {
2973 yield* awaitGateReader(path.join(repo, ".git", "config"));
2974 yield* TestClock.adjust("2 seconds");
2975 expect(yield* Fiber.join(scan), `scan ${attempt}`).toEqual([repo]);
2976 }),
2977 );
2978 }
2979 // Hangs if the scans left libuv pool threads stuck in open().
2980 yield* fileSystem.readFileString(transcriptPath);
2981 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
2982 );
2983
2984 it.effect("still reads the git identity of repositories next to a blocked one", () =>
2985 Effect.gen(function* () {
2986 const path = yield* Path.Path;
2987 const fileSystem = yield* FileSystem.FileSystem;
2988 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
2989 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
2990 const repos = [
2991 yield* makeTempDir("t3code-workspace-before-"),
2992 yield* makeTempDir("t3code-workspace-blocked-"),
2993 yield* makeTempDir("t3code-workspace-after-"),
2994 ] as const;
2995 for (const [index, repo] of repos.entries()) {
2996 yield* fileSystem.makeDirectory(path.join(repo, ".git"));
2997 const configPath = path.join(repo, ".git", "config");
2998 if (index === 1) yield* makeOpenGate(configPath);
2999 else
3000 yield* fileSystem.writeFileString(
3001 configPath,
3002 `[remote "origin"]\n\turl = git@github.com:pingdotgg/repo-${index}.git\n`,
3003 );
3004 yield* writeTranscript({
3005 filePath: path.join(claudeHomePath, "projects", `-slug-${index}`, "a.jsonl"),
3006 contents: claudeSessionLine(repo),
3007 mtimeMs: Date.parse(`2026-01-0${index + 1}T00:00:00.000Z`),
3008 });
3009 }
3010
3011 const finishedNeighbourReads = yield* Queue.unbounded<string>();
3012 const processRunner = layerReportingProcessRunner(
3013 new Set([repos[0], repos[2]].map((repo) => path.join(repo, ".git", "config"))),
3014 finishedNeighbourReads,
3015 );
3016
3017 for (let attempt = 1; attempt <= 2; attempt++) {
3018 const scan = yield* Effect.forkChild(
3019 runScan({ claudeHomePath, codexHomePath, processRunner }),
3020 );
3021 const result = yield* Effect.scoped(
3022 Effect.gen(function* () {
3023 yield* awaitGateReader(path.join(repos[1], ".git", "config"));
3024 yield* Queue.take(finishedNeighbourReads);
3025 yield* Queue.take(finishedNeighbourReads);
3026 yield* TestClock.adjust("2 seconds");
3027 return yield* Fiber.join(scan);
3028 }),
3029 );
3030 expect(
3031 result.candidates.map((candidate) => ({ path: candidate.path, git: candidate.git })),
3032 `scan ${attempt}`,
3033 ).toEqual([
3034 {
3035 path: repos[2],
3036 git: { remoteKey: "github.com/pingdotgg/repo-2", repository: "pingdotgg/repo-2" },
3037 },
3038 { path: repos[1], git: { remoteKey: null, repository: null } },
3039 {
3040 path: repos[0],
3041 git: { remoteKey: "github.com/pingdotgg/repo-0", repository: "pingdotgg/repo-0" },
3042 },
3043 ]);
3044 }
3045 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
3046 );
3047
3048 it.effect("reads every blocked git config of a scan under one deadline", () =>
3049 Effect.gen(function* () {
3050 const path = yield* Path.Path;
3051 const fileSystem = yield* FileSystem.FileSystem;
3052 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
3053 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
3054 const root = yield* makeTempDir("t3code-workspace-blocked-configs-");
3055 const repos = [path.join(root, "repo-a"), path.join(root, "repo-b")];
3056 for (const repo of repos) {
3057 yield* fileSystem.makeDirectory(path.join(repo, ".git"), { recursive: true });
3058 yield* makeOpenGate(path.join(repo, ".git", "config"));
3059 }
3060 // Two linked worktrees of one bare repository share its blocked config.
3061 const bareGitDir = path.join(root, "bare.git");
3062 yield* fileSystem.makeDirectory(bareGitDir);
3063 yield* makeOpenGate(path.join(bareGitDir, "config"));
3064 const worktrees = [path.join(root, "wt-1"), path.join(root, "wt-2")];
3065 for (const worktree of worktrees) {
3066 const gitDir = path.join(bareGitDir, "worktrees", path.basename(worktree));
3067 yield* fileSystem.makeDirectory(gitDir, { recursive: true });
3068 yield* fileSystem.writeFileString(path.join(gitDir, "commondir"), "../..\n");
3069 yield* fileSystem.makeDirectory(worktree);
3070 yield* fileSystem.writeFileString(path.join(worktree, ".git"), `gitdir: ${gitDir}\n`);
3071 }
3072 for (const [index, cwd] of [...repos, ...worktrees].entries()) {
3073 yield* writeTranscript({
3074 filePath: path.join(claudeHomePath, "projects", `-slug-${index}`, "a.jsonl"),
3075 contents: claudeSessionLine(cwd),
3076 mtimeMs: Date.parse(`2026-01-0${index + 1}T00:00:00.000Z`),
3077 });
3078 }
3079
3080 const scan = yield* Effect.forkChild(
3081 runScan({ claudeHomePath, codexHomePath }).pipe(
3082 Effect.map(({ candidates }) => candidates.map(({ path }) => path).toSorted()),
3083 ),
3084 );
3085 // Every blocked config is open before any deadline passes; reading them
3086 // one after another would leave the later ones unopened.
3087 yield* Effect.forEach(
3088 [...repos.map((repo) => path.join(repo, ".git")), bareGitDir],
3089 (gitDir) => awaitGateReader(path.join(gitDir, "config")),
3090 { concurrency: "unbounded" },
3091 );
3092 yield* TestClock.adjust("2 seconds");
3093 expect(yield* Fiber.join(scan)).toEqual(repos);
3094 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
3095 );
3096
3097 it.effect("completes every scan when a .git pointer file or commondir never opens", () =>
3098 Effect.gen(function* () {
3099 const path = yield* Path.Path;
3100 const fileSystem = yield* FileSystem.FileSystem;
3101 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
3102 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
3103 const root = yield* makeTempDir("t3code-workspace-blocked-pointers-");
3104 const pointerCheckout = path.join(root, "pointer");
3105 yield* fileSystem.makeDirectory(pointerCheckout);
3106 yield* makeOpenGate(path.join(pointerCheckout, ".git"));
3107 const worktree = path.join(root, "worktree");
3108 const worktreeGitDir = path.join(root, "main", ".git", "worktrees", "worktree");
3109 yield* fileSystem.makeDirectory(worktreeGitDir, { recursive: true });
3110 yield* makeOpenGate(path.join(worktreeGitDir, "commondir"));
3111 yield* fileSystem.makeDirectory(worktree);
3112 yield* fileSystem.writeFileString(
3113 path.join(worktree, ".git"),
3114 `gitdir: ${worktreeGitDir}\n`,
3115 );
3116 for (const [index, cwd] of [pointerCheckout, worktree].entries()) {
3117 yield* writeTranscript({
3118 filePath: path.join(claudeHomePath, "projects", `-slug-${index}`, "a.jsonl"),
3119 contents: claudeSessionLine(cwd),
3120 mtimeMs: Date.parse(`2026-01-0${index + 1}T00:00:00.000Z`),
3121 });
3122 }
3123
3124 const finishedPointerReads = yield* Queue.unbounded<string>();
3125 const processRunner = layerReportingProcessRunner(
3126 new Set([path.join(worktree, ".git")]),
3127 finishedPointerReads,
3128 );
3129
3130 // One scanner across scans: later scans skip the files that blocked.
3131 yield* Effect.gen(function* () {
3132 const scanner = yield* AgentSessionScanner.AgentSessionScanner;
3133 const scanPaths = scanner.scan.pipe(
3134 Effect.map(({ candidates }) => candidates.map(({ path }) => path)),
3135 );
3136 const first = yield* Effect.forkChild(scanPaths);
3137 // Pointer files are read first, then the commondir files they lead to.
3138 yield* Effect.scoped(
3139 Effect.gen(function* () {
3140 yield* awaitGateReader(path.join(pointerCheckout, ".git"));
3141 yield* Queue.take(finishedPointerReads);
3142 yield* TestClock.adjust("2 seconds");
3143 }),
3144 );
3145 yield* Effect.scoped(
3146 Effect.gen(function* () {
3147 yield* awaitGateReader(path.join(worktreeGitDir, "commondir"));
3148 yield* TestClock.adjust("2 seconds");
3149 }),
3150 );
3151 expect(yield* Fiber.join(first)).toEqual([pointerCheckout]);
3152 for (let attempt = 2; attempt <= LIBUV_POOL_SIZE + 1; attempt++) {
3153 expect(yield* scanPaths, `scan ${attempt}`).toEqual([pointerCheckout]);
3154 }
3155 }).pipe(Effect.provide(layerScannerTest({ claudeHomePath, codexHomePath, processRunner })));
3156 // Hangs if the scans left libuv pool threads stuck in open().
3157 yield* fileSystem.readFileString(path.join(worktree, ".git"));
3158 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
3159 );
3160
3161 it.effect("reads a once-blocked git config again after the retry interval", () =>
3162 Effect.gen(function* () {
3163 const path = yield* Path.Path;
3164 const fileSystem = yield* FileSystem.FileSystem;
3165 const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
3166 const codexHomePath = yield* makeTempDir("t3code-codex-home-");
3167 const repo = yield* makeTempDir("t3code-workspace-unblocked-config-");
3168 yield* fileSystem.makeDirectory(path.join(repo, ".git"));
3169 const configPath = path.join(repo, ".git", "config");
3170 yield* makeOpenGate(configPath);
3171 yield* writeTranscript({
3172 filePath: path.join(claudeHomePath, "projects", "-unblocked", "a.jsonl"),
3173 contents: claudeSessionLine(repo),
3174 mtimeMs: Date.parse("2026-05-03T00:00:00.000Z"),
3175 });
3176 const gitOfScan = (scan: AgentSessionScanner.AgentSessionScanner["Service"]["scan"]) =>
3177 scan.pipe(Effect.map(({ candidates }) => candidates.map(({ git }) => git)));
3178
3179 yield* Effect.gen(function* () {
3180 const scanner = yield* AgentSessionScanner.AgentSessionScanner;
3181 const blockedScan = yield* Effect.forkChild(gitOfScan(scanner.scan));
3182 yield* Effect.scoped(
3183 Effect.gen(function* () {
3184 yield* awaitGateReader(configPath);
3185 yield* TestClock.adjust("2 seconds");
3186 expect(yield* Fiber.join(blockedScan)).toEqual([
3187 { remoteKey: null, repository: null },
3188 ]);
3189 }),
3190 );
3191
3192 yield* fileSystem.remove(configPath);
3193 yield* fileSystem.writeFileString(
3194 configPath,
3195 `[remote "origin"]\n\turl = git@github.com:pingdotgg/unblocked.git\n`,
3196 );
3197 expect(yield* gitOfScan(scanner.scan), "a blocked path is skipped for a while").toEqual([
3198 { remoteKey: null, repository: null },
3199 ]);
3200
3201 yield* TestClock.adjust("10 minutes");
3202 expect(yield* gitOfScan(scanner.scan)).toEqual([
3203 { remoteKey: "github.com/pingdotgg/unblocked", repository: "pingdotgg/unblocked" },
3204 ]);
3205 }).pipe(Effect.provide(layerScannerTest({ claudeHomePath, codexHomePath })));
3206 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
3207 );
3208 },
3209 );
3210
3211 describe("parseAgentSessionTranscript", () => {
3212 it.each([false, true])(
3213 "handles the exact record limit and an interior blank overflow=%s",
3214 (overflow) => {
3215 const thread = AgentSessionScanner.parseAgentSessionTranscript({
3216 contents: makeRecordLimitTranscript("/project", overflow),
3217 source: "codex",
3218 providerInstanceId: ProviderInstanceId.make("codex"),
3219 fallbackSessionId: "unused",
3220 lastActiveAtMs: Date.parse("2026-08-24T12:00:00.000Z"),
3221 });
3222 if (overflow) expect(thread).toBeNull();
3223 else expect(thread?.messages.map((message) => message.text)).toEqual(["First prompt"]);
3224 },
3225 );
3226
3227 it.each([199, 200, 201, 205])(
3228 "counts only omitted conversation messages for a %s-message Claude transcript",
3229 (count) => {
3230 const thread = AgentSessionScanner.parseAgentSessionTranscript({
3231 contents: [
3232 ...Array.from({ length: count }, (_, index) =>
3233 encodeTranscriptRecord({
3234 type: index === 0 ? "user" : "assistant",
3235 sessionId: "claude-session",
3236 message: { content: `Message ${index}` },
3237 }),
3238 ),
3239 encodeTranscriptRecord({ type: "user", isMeta: true, message: { content: "Setup" } }),
3240 encodeTranscriptRecord({
3241 type: "user",
3242 isCompactSummary: true,
3243 message: { content: "Summary" },
3244 }),
3245 encodeTranscriptRecord({
3246 type: "assistant",
3247 isSidechain: true,
3248 message: { content: "Sidechain" },
3249 }),
3250 encodeTranscriptRecord({
3251 type: "assistant",
3252 message: { content: [{ type: "tool_use" }] },
3253 }),
3254 "malformed",
3255 ].join("\n"),
3256 source: "claudeAgent",
3257 providerInstanceId: ProviderInstanceId.make("claudeAgent"),
3258 fallbackSessionId: "fallback",
3259 lastActiveAtMs: Date.parse("2026-08-24T12:00:00.000Z"),
3260 });
3261
3262 expect(thread?.omittedMessageCount).toBe(Math.max(0, count - 200));
3263 expect(thread?.messages).toHaveLength(Math.min(200, count));
3264 expect(thread?.messages[0]?.text).toBe("Message 0");
3265 expect(thread?.messages.at(-1)?.text).toBe(`Message ${count - 1}`);
3266 },
3267 );
3268
3269 it("keeps Claude text and titles while dropping malformed and tool records", () => {
3270 const thread = AgentSessionScanner.parseAgentSessionTranscript({
3271 contents: [
3272 "not valid json",
3273 JSON.stringify({ type: "ai-title", aiTitle: "Fix authentication" }),
3274 JSON.stringify({
3275 type: "user",
3276 sessionId: "claude-session",
3277 isMeta: true,
3278 message: { role: "user", content: "Injected skill instructions" },
3279 }),
3280 JSON.stringify({
3281 type: "user",
3282 sessionId: "claude-session",
3283 isCompactSummary: true,
3284 message: { role: "user", content: "Injected compaction summary" },
3285 }),
3286 JSON.stringify({
3287 type: "user",
3288 sessionId: "claude-session",
3289 timestamp: "2026-08-24T10:00:00.000Z",
3290 message: { role: "user", content: [{ type: "text", text: "Fix authentication" }] },
3291 }),
3292 JSON.stringify({
3293 type: "user",
3294 sessionId: "claude-session",
3295 message: { role: "user", content: [{ type: "tool_result", text: "hidden" }] },
3296 }),
3297 ...[
3298 "<command-name>/review</command-name>\n<command-message>review</command-message>\n<command-args>the login flow</command-args>",
3299 "<local-command-stdout>Enabled plan mode</local-command-stdout>",
3300 "<bash-input>npm test</bash-input>",
3301 "<bash-stdout>1 passed</bash-stdout><bash-stderr></bash-stderr>",
3302 "<task-notification>\n<task-id>a1</task-id>\n<status>completed</status>\n</task-notification>",
3303 "[Request interrupted by user for tool use]",
3304 ].map((content) =>
3305 JSON.stringify({
3306 type: "user",
3307 sessionId: "claude-session",
3308 message: { role: "user", content },
3309 }),
3310 ),
3311 JSON.stringify({
3312 type: "assistant",
3313 sessionId: "claude-session",
3314 message: {
3315 role: "assistant",
3316 model: "claude-sonnet-5",
3317 content: [{ type: "text", text: "Updated the login flow" }],
3318 },
3319 }),
3320 JSON.stringify({
3321 type: "assistant",
3322 sessionId: "claude-session",
3323 message: {
3324 role: "assistant",
3325 model: "<synthetic>",
3326 content: [{ type: "text", text: "The provider request failed" }],
3327 },
3328 }),
3329 ].join("\n"),
3330 source: "claudeAgent",
3331 providerInstanceId: ProviderInstanceId.make("claudeAgent"),
3332 fallbackSessionId: "fallback",
3333 lastActiveAtMs: Date.parse("2026-08-24T12:00:00.000Z"),
3334 });
3335
3336 expect(thread).toMatchObject({
3337 providerSessionId: "claude-session",
3338 title: "Fix authentication",
3339 model: "claude-sonnet-5",
3340 messages: [
3341 { role: "user", text: "Fix authentication" },
3342 { role: "user", text: "/review the login flow" },
3343 { role: "user", text: "!npm test" },
3344 { role: "assistant", text: "Updated the login flow" },
3345 { role: "assistant", text: "The provider request failed" },
3346 ],
3347 });
3348 });
3349
3350 it.each([
3351 { customTitles: ["Refactor auth module"], expected: "Refactor auth module" },
3352 // Claude writes an empty customTitle when the user clears a rename.
3353 { customTitles: ["Refactor auth module", ""], expected: "Generated title" },
3354 // Some launchers rename the session to the raw markup of its opening command.
3355 {
3356 customTitles: ["<command-message>pstack:poteto-mode</command-message>"],
3357 expected: "Generated title",
3358 },
3359 {
3360 customTitles: ["<local-command-stdout>Enabled plan mode</local-command-stdout>"],
3361 expected: "Generated title",
3362 },
3363 { customTitles: ["<bash-input>npm test</bash-input>"], expected: "Generated title" },
3364 ])("uses Claude custom titles $customTitles over the AI title", ({ customTitles, expected }) => {
3365 const aiTitle = JSON.stringify({
3366 type: "ai-title",
3367 aiTitle: "Generated title",
3368 sessionId: "claude-session",
3369 });
3370 const thread = AgentSessionScanner.parseAgentSessionTranscript({
3371 contents: [
3372 JSON.stringify({
3373 type: "user",
3374 sessionId: "claude-session",
3375 timestamp: "2026-08-24T10:00:00.000Z",
3376 message: { role: "user", content: "Tighten the session checks" },
3377 }),
3378 // Claude rewrites both records on every metadata flush with ai-title
3379 // last, so a later ai-title must not override the user's rename.
3380 ...customTitles.flatMap((customTitle) => [
3381 JSON.stringify({ type: "custom-title", customTitle, sessionId: "claude-session" }),
3382 aiTitle,
3383 ]),
3384 ].join("\n"),
3385 source: "claudeAgent",
3386 providerInstanceId: ProviderInstanceId.make("claudeAgent"),
3387 fallbackSessionId: "fallback",
3388 lastActiveAtMs: Date.parse("2026-08-24T12:00:00.000Z"),
3389 });
3390
3391 expect(thread?.title).toBe(expected);
3392 });
3393
3394 it.each([
3395 {
3396 first:
3397 "<command-name>/pstack:arena</command-name><command-args>Compare designs</command-args>",
3398 title: "Compare designs",
3399 },
3400 {
3401 first: "<command-name>/clear</command-name><command-message>clear</command-message>",
3402 title: "Plan the release",
3403 },
3404 { first: "/Users/me/app fails to build", title: "/Users/me/app fails to build" },
3405 ])("titles a Claude thread after its request, not command markup: $title", ({ first, title }) => {
3406 const thread = AgentSessionScanner.parseAgentSessionTranscript({
3407 contents: [first, "Plan the release"]
3408 .map((content) =>
3409 JSON.stringify({ type: "user", sessionId: "claude-session", message: { content } }),
3410 )
3411 .join("\n"),
3412 source: "claudeAgent",
3413 providerInstanceId: ProviderInstanceId.make("claudeAgent"),
3414 fallbackSessionId: "fallback",
3415 lastActiveAtMs: Date.parse("2026-08-24T12:00:00.000Z"),
3416 });
3417
3418 expect(thread?.title).toBe(title);
3419 });
3420
3421 it.each([199, 200])("keeps the canonical first prompt with %s later Codex messages", (count) => {
3422 const canonicalPrompt = "\n Keep the canonical prompt \n";
3423 const canonicalTimestamp = "2026-08-24T10:01:00.000Z";
3424 const laterAssistantMessages = Array.from({ length: count }, (_, index) =>
3425 encodeTranscriptRecord({
3426 type: "response_item",
3427 timestamp: `2026-08-24T11:${String(index % 60).padStart(2, "0")}:00.000Z`,
3428 payload: {
3429 type: "message",
3430 role: "assistant",
3431 content: [{ type: "output_text", text: `Assistant message ${index}` }],
3432 },
3433 }),
3434 );
3435 const thread = AgentSessionScanner.parseAgentSessionTranscript({
3436 contents: [
3437 encodeTranscriptRecord({ type: "session_meta", payload: { id: "codex-session" } }),
3438 encodeTranscriptRecord({
3439 type: "response_item",
3440 timestamp: "2026-08-24T10:00:00.000Z",
3441 payload: {
3442 type: "message",
3443 role: "user",
3444 content: [{ type: "input_text", text: "Keep the canonical prompt" }],
3445 },
3446 }),
3447 encodeTranscriptRecord({
3448 type: "event_msg",
3449 timestamp: canonicalTimestamp,
3450 payload: { type: "user_message", message: canonicalPrompt },
3451 }),
3452 ...laterAssistantMessages,
3453 ].join("\n"),
3454 source: "codex",
3455 providerInstanceId: ProviderInstanceId.make("codex"),
3456 fallbackSessionId: "fallback",
3457 lastActiveAtMs: Date.parse("2026-08-24T12:00:00.000Z"),
3458 });
3459
3460 expect(thread?.omittedMessageCount).toBe(count - 199);
3461 expect(thread?.messages).toHaveLength(200);
3462 expect(thread?.messages[0]).toMatchObject({
3463 role: "user",
3464 text: canonicalPrompt,
3465 createdAt: canonicalTimestamp,
3466 });
3467 });
3468
3469 it("restores the canonical first prompt when a later user message remains", () => {
3470 const canonicalPrompt = "\n Keep the canonical prompt \n";
3471 const canonicalTimestamp = "2026-08-24T10:01:00.000Z";
3472 const assistantMessages = Array.from({ length: 198 }, (_, index) =>
3473 encodeTranscriptRecord({
3474 type: "response_item",
3475 timestamp: `2026-08-24T11:${String(index % 60).padStart(2, "0")}:00.000Z`,
3476 payload: {
3477 type: "message",
3478 role: "assistant",
3479 content: [{ type: "output_text", text: `Assistant message ${index}` }],
3480 },
3481 }),
3482 );
3483 const thread = AgentSessionScanner.parseAgentSessionTranscript({
3484 contents: [
3485 encodeTranscriptRecord({ type: "session_meta", payload: { id: "codex-session" } }),
3486 encodeTranscriptRecord({
3487 type: "response_item",
3488 timestamp: "2026-08-24T10:00:00.000Z",
3489 payload: {
3490 type: "message",
3491 role: "user",
3492 internal_chat_message_metadata_passthrough: { turn_id: "turn-1" },
3493 content: [{ type: "input_text", text: "Keep the canonical prompt" }],
3494 },
3495 }),
3496 encodeTranscriptRecord({
3497 type: "event_msg",
3498 timestamp: canonicalTimestamp,
3499 payload: { type: "user_message", message: canonicalPrompt },
3500 }),
3501 ...assistantMessages,
3502 encodeTranscriptRecord({
3503 type: "event_msg",
3504 timestamp: "2026-08-24T11:58:30.000Z",
3505 payload: { type: "user_message", message: "Keep this later prompt" },
3506 }),
3507 encodeTranscriptRecord({
3508 type: "response_item",
3509 timestamp: "2026-08-24T11:59:00.000Z",
3510 payload: {
3511 type: "message",
3512 role: "assistant",
3513 content: [{ type: "output_text", text: "Keep this latest response" }],
3514 },
3515 }),
3516 ].join("\n"),
3517 source: "codex",
3518 providerInstanceId: ProviderInstanceId.make("codex"),
3519 fallbackSessionId: "fallback",
3520 lastActiveAtMs: Date.parse("2026-08-24T12:00:00.000Z"),
3521 });
3522
3523 expect(thread?.omittedMessageCount).toBe(1);
3524 expect(thread?.messages).toHaveLength(200);
3525 expect(thread?.messages[0]).toMatchObject({
3526 role: "user",
3527 text: canonicalPrompt,
3528 createdAt: canonicalTimestamp,
3529 });
3530 expect(
3531 thread?.messages.filter((message) => message.text.trim() === canonicalPrompt.trim()),
3532 ).toHaveLength(1);
3533 expect(thread?.messages.some((message) => message.text === "Keep this later prompt")).toBe(
3534 true,
3535 );
3536 expect(thread?.messages.at(-1)?.text).toBe("Keep this latest response");
3537 });
3538
3539 it("keeps mixed-format response users when turn IDs repeat after an assistant", () => {
3540 const thread = AgentSessionScanner.parseAgentSessionTranscript({
3541 contents: [
3542 encodeTranscriptRecord({ type: "session_meta", payload: { id: "codex-session" } }),
3543 encodeTranscriptRecord({
3544 type: "response_item",
3545 payload: {
3546 type: "message",
3547 role: "user",
3548 internal_chat_message_metadata_passthrough: { turn_id: "turn-older" },
3549 content: [{ type: "input_text", text: "Keep this older prompt" }],
3550 },
3551 }),
3552 encodeTranscriptRecord({
3553 type: "event_msg",
3554 payload: { type: "user_message", message: "Keep this newer prompt" },
3555 }),
3556 encodeTranscriptRecord({
3557 type: "response_item",
3558 payload: {
3559 type: "message",
3560 role: "user",
3561 internal_chat_message_metadata_passthrough: { turn_id: "turn-newer" },
3562 content: [{ type: "input_text", text: "Keep this newer prompt" }],
3563 },
3564 }),
3565 encodeTranscriptRecord({
3566 type: "response_item",
3567 payload: {
3568 type: "message",
3569 role: "assistant",
3570 content: [{ type: "output_text", text: "Ask again when needed" }],
3571 },
3572 }),
3573 encodeTranscriptRecord({
3574 type: "response_item",
3575 payload: {
3576 type: "message",
3577 role: "user",
3578 internal_chat_message_metadata_passthrough: { turn_id: "turn-newer" },
3579 content: [{ type: "input_text", text: "Keep this newer prompt" }],
3580 },
3581 }),
3582 ].join("\n"),
3583 source: "codex",
3584 providerInstanceId: ProviderInstanceId.make("codex"),
3585 fallbackSessionId: "fallback",
3586 lastActiveAtMs: Date.parse("2026-08-24T12:00:00.000Z"),
3587 });
3588
3589 expect(thread?.messages.map((message) => message.text)).toEqual([
3590 "Keep this older prompt",
3591 "Keep this newer prompt",
3592 "Ask again when needed",
3593 "Keep this newer prompt",
3594 ]);
3595 });
3596
3597 it("preserves response user text when Codex turn metadata is ambiguous", () => {
3598 const thread = AgentSessionScanner.parseAgentSessionTranscript({
3599 contents: [
3600 encodeTranscriptRecord({ type: "session_meta", payload: { id: "codex-session" } }),
3601 encodeTranscriptRecord({
3602 type: "response_item",
3603 payload: {
3604 type: "message",
3605 role: "user",
3606 internal_chat_message_metadata_passthrough: ["unexpected"],
3607 content: [{ type: "input_text", text: "Keep this legacy prompt" }],
3608 },
3609 }),
3610 encodeTranscriptRecord({
3611 type: "response_item",
3612 payload: {
3613 type: "message",
3614 role: "user",
3615 internal_chat_message_metadata_passthrough: { turn_id: " " },
3616 content: [{ type: "input_text", text: "Keep this prompt with a blank turn ID" }],
3617 },
3618 }),
3619 ].join("\n"),
3620 source: "codex",
3621 providerInstanceId: ProviderInstanceId.make("codex"),
3622 fallbackSessionId: "fallback",
3623 lastActiveAtMs: Date.parse("2026-08-24T12:00:00.000Z"),
3624 });
3625
3626 expect(thread?.messages.map((message) => message.text)).toEqual([
3627 "Keep this legacy prompt",
3628 "Keep this prompt with a blank turn ID",
3629 ]);
3630 });
3631
3632 it("uses the first valid Codex session ID when a fork copies ancestor metadata", () => {
3633 const thread = AgentSessionScanner.parseAgentSessionTranscript({
3634 contents: [
3635 encodeTranscriptRecord({
3636 type: "session_meta",
3637 payload: { id: "fork-session", forked_from_id: "parent-session" },
3638 }),
3639 encodeTranscriptRecord({
3640 type: "session_meta",
3641 payload: { id: "parent-session" },
3642 }),
3643 encodeTranscriptRecord({
3644 type: "event_msg",
3645 payload: { type: "user_message", message: "Continue in the fork" },
3646 }),
3647 ].join("\n"),
3648 source: "codex",
3649 providerInstanceId: ProviderInstanceId.make("codex"),
3650 fallbackSessionId: "fallback",
3651 lastActiveAtMs: Date.parse("2026-08-24T12:00:00.000Z"),
3652 });
3653
3654 expect(thread?.providerSessionId).toBe("fork-session");
3655 });
3656
3657 it("skips Codex transcripts without a resumable session ID", () => {
3658 const thread = AgentSessionScanner.parseAgentSessionTranscript({
3659 contents: encodeTranscriptRecord({
3660 type: "event_msg",
3661 payload: { type: "user_message", message: "This transcript has no session metadata" },
3662 }),
3663 source: "codex",
3664 providerInstanceId: ProviderInstanceId.make("codex"),
3665 fallbackSessionId: "rollout-2026-08-24T12-00-00-not-a-session-id",
3666 lastActiveAtMs: Date.parse("2026-08-24T12:00:00.000Z"),
3667 });
3668
3669 expect(thread).toBeNull();
3670 });
3671
3672 it("uses the canonical Codex event when its turn has generated response context", () => {
3673 const thread = AgentSessionScanner.parseAgentSessionTranscript({
3674 contents: [
3675 encodeTranscriptRecord({ type: "session_meta", payload: { id: "codex-session" } }),
3676 encodeTranscriptRecord({
3677 type: "response_item",
3678 payload: {
3679 type: "message",
3680 role: "user",
3681 internal_chat_message_metadata_passthrough: { turn_id: "turn-1" },
3682 content: [
3683 {
3684 type: "input_text",
3685 text: "<environment_context>\n<cwd>/tmp/project</cwd>\n<shell>zsh</shell>\n</environment_context>",
3686 },
3687 ],
3688 },
3689 }),
3690 encodeTranscriptRecord({
3691 type: "response_item",
3692 payload: {
3693 type: "message",
3694 role: "user",
3695 internal_chat_message_metadata_passthrough: { turn_id: "turn-1" },
3696 content: [
3697 {
3698 type: "input_text",
3699 text: "# AGENTS.md instructions for /tmp/project\n\n<INSTRUCTIONS>\nPrivate project rules\n</INSTRUCTIONS>",
3700 },
3701 ],
3702 },
3703 }),
3704 encodeTranscriptRecord({
3705 type: "event_msg",
3706 payload: {
3707 type: "user_message",
3708 message: "Do something here so it looks like a real project.",
3709 },
3710 }),
3711 encodeTranscriptRecord({
3712 type: "response_item",
3713 payload: {
3714 type: "message",
3715 role: "user",
3716 internal_chat_message_metadata_passthrough: { turn_id: "turn-1" },
3717 content: [
3718 {
3719 type: "input_text",
3720 text: "Do something here so it looks like a real project.",
3721 },
3722 ],
3723 },
3724 }),
3725 encodeTranscriptRecord({
3726 type: "response_item",
3727 payload: {
3728 type: "message",
3729 role: "assistant",
3730 content: [{ type: "output_text", text: "Created the project." }],
3731 },
3732 }),
3733 ].join("\n"),
3734 source: "codex",
3735 providerInstanceId: ProviderInstanceId.make("codex"),
3736 fallbackSessionId: "fallback",
3737 lastActiveAtMs: Date.parse("2026-08-25T08:00:00.000Z"),
3738 });
3739
3740 expect(thread?.title).toBe("Do something here so it looks like a real project.");
3741 expect(thread?.messages.map((message) => message.text)).toEqual([
3742 "Do something here so it looks like a real project.",
3743 "Created the project.",
3744 ]);
3745 });
3746
3747 it("preserves context markup in response-only Codex messages", () => {
3748 const context = "<environment_context>\n<cwd>/tmp/project</cwd>\n</environment_context>";
3749 const thread = AgentSessionScanner.parseAgentSessionTranscript({
3750 contents: [
3751 encodeTranscriptRecord({ type: "session_meta", payload: { id: "codex-session" } }),
3752 encodeTranscriptRecord({
3753 type: "response_item",
3754 payload: {
3755 type: "message",
3756 role: "user",
3757 content: [
3758 {
3759 type: "input_text",
3760 text: context,
3761 },
3762 ],
3763 },
3764 }),
3765 encodeTranscriptRecord({
3766 type: "response_item",
3767 payload: {
3768 type: "message",
3769 role: "user",
3770 content: [{ type: "input_text", text: "Initialize Git and add a README." }],
3771 },
3772 }),
3773 ].join("\n"),
3774 source: "codex",
3775 providerInstanceId: ProviderInstanceId.make("codex"),
3776 fallbackSessionId: "fallback",
3777 lastActiveAtMs: Date.parse("2026-08-25T08:00:00.000Z"),
3778 });
3779
3780 expect(thread?.title).toBe("Initialize Git and add a README.");
3781 expect(thread?.messages.map((message) => message.text)).toEqual([
3782 context,
3783 "Initialize Git and add a README.",
3784 ]);
3785 });
3786
3787 it("titles a Codex event after the request that follows injected setup blocks", () => {
3788 const prompt = [
3789 "<recommended_plugins>\nGitHub\n</recommended_plugins>",
3790 "# AGENTS.md instructions for /tmp/project\n\n<INSTRUCTIONS>\nRules\n</INSTRUCTIONS>",
3791 '<in-app-browser-context source="ambient-ui-state">\nTab\n</in-app-browser-context>',
3792 '<external_codex_apps_open_page>{"page_id":null}</external_codex_apps_open_page>',
3793 "Fix the import titles",
3794 ].join("\n");
3795 const thread = AgentSessionScanner.parseAgentSessionTranscript({
3796 contents: [
3797 encodeTranscriptRecord({ type: "session_meta", payload: { id: "codex-session" } }),
3798 encodeTranscriptRecord({
3799 type: "event_msg",
3800 payload: { type: "user_message", message: prompt },
3801 }),
3802 ].join("\n"),
3803 source: "codex",
3804 providerInstanceId: ProviderInstanceId.make("codex"),
3805 fallbackSessionId: "fallback",
3806 lastActiveAtMs: Date.parse("2026-08-25T08:00:00.000Z"),
3807 });
3808
3809 expect(thread?.title).toBe("Fix the import titles");
3810 expect(thread?.messages.map((message) => message.text)).toEqual([prompt]);
3811 });
3812
3813 it("titles a Claude session after the prompt inside a wake envelope", () => {
3814 const thread = AgentSessionScanner.parseAgentSessionTranscript({
3815 contents: JSON.stringify({
3816 type: "user",
3817 sessionId: "claude-session",
3818 timestamp: "2026-08-25T08:00:00.000Z",
3819 message: {
3820 role: "user",
3821 content:
3822 '<wake reason="mention" current-time="2026-08-25T08:00:00Z">\nFix the flaky login test\n</wake>',
3823 },
3824 }),
3825 source: "claudeAgent",
3826 providerInstanceId: ProviderInstanceId.make("claudeAgent"),
3827 fallbackSessionId: "fallback",
3828 lastActiveAtMs: Date.parse("2026-08-25T08:00:00.000Z"),
3829 });
3830
3831 expect(thread?.title).toBe("Fix the flaky login test");
3832 });
3833
3834 it("does not split an emoji when shortening a long first message into a title", () => {
3835 const prompt = `${"a".repeat(99)}🚀 then deploy`;
3836 const thread = AgentSessionScanner.parseAgentSessionTranscript({
3837 contents: [
3838 encodeTranscriptRecord({ type: "session_meta", payload: { id: "codex-session" } }),
3839 encodeTranscriptRecord({
3840 type: "event_msg",
3841 payload: { type: "user_message", message: prompt },
3842 }),
3843 ].join("\n"),
3844 source: "codex",
3845 providerInstanceId: ProviderInstanceId.make("codex"),
3846 fallbackSessionId: "fallback",
3847 lastActiveAtMs: Date.parse("2026-08-25T08:00:00.000Z"),
3848 });
3849
3850 expect(thread?.title).toBe("a".repeat(99));
3851 });
3852
3853 it.each([
3854 "Explain <external_codex_apps_open_page> in this transcript",
3855 "<external_codex_apps_open_page>Keep this incomplete example",
3856 ])("keeps Codex page markup that is not a complete leading block: %s", (prompt) => {
3857 const thread = AgentSessionScanner.parseAgentSessionTranscript({
3858 contents: [
3859 encodeTranscriptRecord({ type: "session_meta", payload: { id: "codex-session" } }),
3860 encodeTranscriptRecord({
3861 type: "event_msg",
3862 payload: { type: "user_message", message: prompt },
3863 }),
3864 ].join("\n"),
3865 source: "codex",
3866 providerInstanceId: ProviderInstanceId.make("codex"),
3867 fallbackSessionId: "fallback",
3868 lastActiveAtMs: Date.parse("2026-08-25T08:00:00.000Z"),
3869 });
3870
3871 expect(thread?.title).toBe(prompt);
3872 });
3873
3874 it.each([
3875 {
3876 name: "only an assistant reply",
3877 records: [{ type: "assistant", message: { content: "Done" } }],
3878 expected: null,
3879 },
3880 {
3881 name: "only a bare command",
3882 records: [{ type: "user", message: { content: "<command-name>/clear</command-name>" } }],
3883 expected: null,
3884 },
3885 {
3886 name: "a bare command the agent answered",
3887 records: [
3888 { type: "user", message: { content: "<command-name>/review</command-name>" } },
3889 { type: "assistant", message: { content: "Found two issues" } },
3890 ],
3891 expected: { title: "/review", texts: ["/review", "Found two issues"] },
3892 },
3893 {
3894 name: "a prompt answered only by Claude's own sign-in error",
3895 records: [
3896 { type: "user", message: { role: "user", content: "plugin" } },
3897 {
3898 type: "assistant",
3899 message: {
3900 role: "assistant",
3901 model: "<synthetic>",
3902 content: [{ type: "text", text: "Invalid API key · Please run /login" }],
3903 },
3904 },
3905 ],
3906 expected: null,
3907 },
3908 {
3909 name: "a conversation that ends in Claude's own sign-in error",
3910 records: [
3911 { type: "user", message: { role: "user", content: "plugin" } },
3912 {
3913 type: "assistant",
3914 message: { role: "assistant", model: "claude-sonnet-4-5", content: "Which plugin?" },
3915 },
3916 { type: "user", message: { role: "user", content: "GitHub" } },
3917 {
3918 type: "assistant",
3919 message: {
3920 role: "assistant",
3921 model: "<synthetic>",
3922 content: [{ type: "text", text: "Invalid API key · Please run /login" }],
3923 },
3924 },
3925 ],
3926 expected: {
3927 title: "plugin",
3928 texts: ["plugin", "Which plugin?", "GitHub", "Invalid API key · Please run /login"],
3929 },
3930 },
3931 ])("imports a Claude session only if it got a request: $name", ({ records, expected }) => {
3932 const thread = AgentSessionScanner.parseAgentSessionTranscript({
3933 contents: records.map((record) => JSON.stringify(record)).join("\n"),
3934 source: "claudeAgent",
3935 providerInstanceId: ProviderInstanceId.make("claudeAgent"),
3936 fallbackSessionId: "claude-session",
3937 lastActiveAtMs: Date.parse("2026-08-24T12:00:00.000Z"),
3938 });
3939
3940 expect(
3941 thread === null
3942 ? null
3943 : { title: thread.title, texts: thread.messages.map((message) => message.text) },
3944 ).toEqual(expected);
3945 });
3946 });