Open History to see the last commit
1/**
2 * AgentSessionScanner - discovery of projects a user already works on.
3 *
4 * Claude Code and Codex both keep a per-session transcript on disk, and each
5 * transcript records the directory the session ran in. Reading those `cwd`
6 * values gives us the set of directories worth offering as projects during
7 * onboarding, without asking the user to browse the filesystem.
8 *
9 * The scan is read-only and best-effort: an unreadable home, a malformed
10 * transcript, or a directory that has since been deleted is skipped rather
11 * than failing the scan. Project creation stays with the client, which
12 * dispatches `project.create` for whichever candidates the user picks.
13 *
14 * @module project/AgentSessionScanner
15 */
16import * as NodeOS from "node:os";
17
18import {
19 AgentSessionScanError,
20 ClaudeSettings,
21 CodexSettings,
22 ProviderDriverKind,
23 ProviderInstanceId,
24 resolveProviderInstanceEnabled,
25 type AgentSessionImportSource,
26 type AgentSessionProjectCandidate,
27 type AgentSessionScanResult,
28 type ProviderInstanceConfig,
29} from "@t3tools/contracts";
30import * as Context from "effect/Context";
31import * as DateTime from "effect/DateTime";
32import * as Effect from "effect/Effect";
33import * as FileSystem from "effect/FileSystem";
34import * as Layer from "effect/Layer";
35import * as Option from "effect/Option";
36import * as Path from "effect/Path";
37import * as Schema from "effect/Schema";
38import * as Semaphore from "effect/Semaphore";
39import * as Stream from "effect/Stream";
40
41import {
42 normalizeGitRemoteUrl,
43 parseGitHubRepositoryNameWithOwnerFromRemoteUrl,
44 parseOriginUrlFromGitConfig,
45} from "@t3tools/shared/git";
46import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hostProcess";
47import { normalizeProjectPathForComparison } from "@t3tools/shared/path";
48
49import * as ServerConfig from "../config.ts";
50import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
51import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts";
52import { expandHomePath } from "../pathExpansion.ts";
53import * as ServerSettings from "../serverSettings.ts";
54import {
55 createTranscriptJsonReader,
56 createTranscriptJsonSelector,
57 TranscriptJsonLimitError,
58} from "./AgentSessionJson.ts";
59
60/** Chunk size for full transcript reads. */
61const TRANSCRIPT_PREFIX_BYTES = 32 * 1024;
62/** Small reads avoid wasting the metadata budget on long Codex instruction headers. */
63const METADATA_READ_BYTES = 8 * 1024;
64/** Prevent malformed transcripts from turning project discovery into a full file scan. */
65const MAX_TRANSCRIPT_SCAN_BYTES = 1024 * 1024;
66
67/**
68 * Upper bound on transcripts inspected (first line read) per source.
69 * Newest-first ordering means the cap drops only stale sessions when a home
70 * directory is unusually large.
71 */
72const MAX_TRANSCRIPTS_PER_SOURCE = 5000;
73
74/**
75 * Upper bound on discovery filesystem operations per source. Newest-first
76 * ordering needs mtimes before the read cap can be applied, so directory reads
77 * and candidate stats share a larger budget. Once it runs out the scan stops.
78 */
79const MAX_DISCOVERY_OPERATIONS_PER_SOURCE = MAX_TRANSCRIPTS_PER_SOURCE * 4;
80const MAX_METADATA_BYTES_PER_SOURCE = 64 * 1024 * 1024;
81const MAX_METADATA_OPERATIONS_PER_SOURCE = MAX_TRANSCRIPTS_PER_SOURCE * 4;
82const MAX_METADATA_RECORDS_PER_SOURCE = 100_000;
83const MAX_METADATA_RECORDS_PER_TRANSCRIPT = 1_000;
84const RECENT_THREAD_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;
85/**
86 * Large tool results (especially screenshots) can make an otherwise ordinary
87 * Codex transcript several GiB. Streaming field selection avoids allocating
88 * those payloads. Raw I/O and selected history have separate budgets.
89 */
90const MAX_IMPORTED_TRANSCRIPT_BYTES = 4 * 1024 * 1024 * 1024;
91const MAX_IMPORTED_MESSAGES = 200;
92const MAX_IMPORT_HISTORY_BYTES = 32 * 1024 * 1024;
93const MAX_IMPORT_BYTES = 4 * 1024 * 1024 * 1024;
94const MAX_IMPORT_TRANSCRIPTS = 100;
95const MAX_IMPORT_RECORDS = 100_000;
96
97const TranscriptContentBlock = Schema.Struct({
98 type: Schema.optional(Schema.String),
99 text: Schema.optional(Schema.String),
100});
101
102const TranscriptMessage = Schema.Struct({
103 role: Schema.optional(Schema.String),
104 content: Schema.optional(Schema.Union([Schema.String, Schema.Array(TranscriptContentBlock)])),
105 model: Schema.optional(Schema.String),
106});
107
108const CodexTurnMetadata = Schema.Struct({
109 turn_id: Schema.optional(Schema.Union([Schema.String, Schema.Null])),
110});
111
112const TranscriptRecord = Schema.Struct({
113 type: Schema.optional(Schema.String),
114 timestamp: Schema.optional(Schema.String),
115 cwd: Schema.optional(Schema.String),
116 sessionId: Schema.optional(Schema.String),
117 aiTitle: Schema.optional(Schema.String),
118 isSidechain: Schema.optional(Schema.Boolean),
119 isMeta: Schema.optional(Schema.Boolean),
120 isCompactSummary: Schema.optional(Schema.Boolean),
121 message: Schema.optional(TranscriptMessage),
122 payload: Schema.optional(
123 Schema.Struct({
124 id: Schema.optional(Schema.String),
125 session_id: Schema.optional(Schema.String),
126 type: Schema.optional(Schema.String),
127 role: Schema.optional(Schema.String),
128 message: Schema.optional(Schema.String),
129 model: Schema.optional(Schema.String),
130 cwd: Schema.optional(Schema.String),
131 content: Schema.optional(Schema.Array(TranscriptContentBlock)),
132 internal_chat_message_metadata_passthrough: Schema.optional(Schema.Unknown),
133 }),
134 ),
135});
136
137const decodeClaudeSettings = Schema.decodeUnknownOption(ClaudeSettings);
138const decodeCodexSettings = Schema.decodeUnknownOption(CodexSettings);
139const decodeTranscriptRecord = Schema.decodeUnknownOption(Schema.fromJsonString(TranscriptRecord));
140const decodeTranscriptValue = Schema.decodeUnknownOption(TranscriptRecord);
141const selectTranscriptPath = createTranscriptJsonSelector(TranscriptRecord);
142const decodeCodexTurnMetadata = Schema.decodeUnknownOption(CodexTurnMetadata);
143
144type DecodedTranscriptRecord = typeof TranscriptRecord.Type;
145
146interface AgentSessionTranscriptMetadata {
147 readonly source: AgentSessionSource;
148 readonly providerInstanceId: ProviderInstanceId;
149 readonly fallbackSessionId: string;
150 readonly lastActiveAtMs: number;
151}
152
153export interface AgentSessionThreadMessage {
154 readonly role: "user" | "assistant";
155 readonly text: string;
156 readonly createdAt: string;
157}
158
159export interface AgentSessionThread {
160 readonly source: AgentSessionSource;
161 readonly providerInstanceId: ProviderInstanceId;
162 readonly providerSessionId: string;
163 readonly title: string;
164 readonly model: string | null;
165 readonly createdAt: string;
166 readonly updatedAt: string;
167 readonly messages: ReadonlyArray<AgentSessionThreadMessage>;
168}
169
170export type AgentSessionRecentThread =
171 | {
172 readonly _tag: "Importable";
173 readonly thread: AgentSessionThread;
174 readonly source: AgentSessionImportSource;
175 }
176 | { readonly _tag: "AlreadyImported"; readonly source: AgentSessionImportSource }
177 | { readonly _tag: "Duplicate"; readonly source: AgentSessionImportSource }
178 | { readonly _tag: "Skipped" };
179
180/** Service tag for agent session discovery. */
181export class AgentSessionScanner extends Context.Service<
182 AgentSessionScanner,
183 {
184 /**
185 * Discover every directory the configured Claude and Codex homes have run
186 * a session in. Candidates are returned newest-first; the client decides
187 * which ones to import and how far back to look. Fails with the contract
188 * error directly — there is no server-local context worth wrapping.
189 */
190 readonly scan: Effect.Effect<AgentSessionScanResult, AgentSessionScanError>;
191 readonly recentThreads: (
192 workspaceRoot: string,
193 completedSources?: ReadonlyArray<AgentSessionImportSource>,
194 ) => Stream.Stream<AgentSessionRecentThread, AgentSessionScanError>;
195 }
196>()("t3/project/AgentSessionScanner") {}
197
198type AgentSessionSource = AgentSessionProjectCandidate["sources"][number];
199
200/** A single directory's worth of evidence from one source. */
201interface RawCandidate {
202 readonly cwd: string;
203 readonly source: AgentSessionSource;
204 readonly providerInstanceId: ProviderInstanceId;
205 readonly threadCount: number;
206 readonly lastActiveAtMs: number | null;
207 readonly transcripts: ReadonlyArray<{
208 readonly filePath: string;
209 readonly mtimeMs: number | null;
210 }>;
211}
212
213interface TranscriptCandidate {
214 readonly filePath: string;
215 readonly mtimeMs: number;
216 readonly providerInstanceId: ProviderInstanceId;
217 readonly size: number;
218}
219
220interface MetadataReadBudget {
221 bytesRemaining: number;
222 operationsRemaining: number;
223 recordsRemaining: number;
224 truncated: boolean;
225}
226
227function selectMetadataTranscripts(transcripts: ReadonlyArray<TranscriptCandidate>) {
228 const selected: Array<TranscriptCandidate> = [];
229 let pending = Array.from(
230 Map.groupBy(transcripts, (transcript) => transcript.providerInstanceId).values(),
231 (entries) => entries.values(),
232 );
233 while (pending.length > 0 && selected.length < MAX_TRANSCRIPTS_PER_SOURCE) {
234 const nextRound: typeof pending = [];
235 for (const iterator of pending) {
236 if (selected.length === MAX_TRANSCRIPTS_PER_SOURCE) break;
237 const next = iterator.next();
238 if (next.done) continue;
239 selected.push(next.value);
240 nextRound.push(iterator);
241 }
242 pending = nextRound;
243 }
244 return selected;
245}
246
247function splitTranscriptRecords(contents: string, limit: number): string[] {
248 const records = contents.endsWith("\n") ? contents.slice(0, -1) : contents;
249 return records.split("\n", limit);
250}
251
252function extractText(
253 content: string | ReadonlyArray<typeof TranscriptContentBlock.Type> | undefined,
254): string {
255 if (typeof content === "string") return content.trim();
256 if (content === undefined) return "";
257 return content
258 .filter(
259 (block) =>
260 block.type === "text" || block.type === "input_text" || block.type === "output_text",
261 )
262 .map((block) => block.text?.trim() ?? "")
263 .filter((text) => text.length > 0)
264 .join("\n");
265}
266
267function normalizeTimestamp(value: string | undefined, fallback: string): string {
268 if (value === undefined) return fallback;
269 const parsed = DateTime.make(value);
270 return Option.isSome(parsed) ? DateTime.formatIso(parsed.value) : fallback;
271}
272
273function codexTurnId(metadata: unknown): string | null {
274 const decoded = decodeCodexTurnMetadata(metadata);
275 if (
276 Option.isNone(decoded) ||
277 typeof decoded.value.turn_id !== "string" ||
278 decoded.value.turn_id.trim().length === 0
279 ) {
280 return null;
281 }
282 return decoded.value.turn_id;
283}
284
285/** Keep visible user and assistant text while ignoring tools, reasoning, and malformed records. */
286export function parseAgentSessionTranscript(
287 input: AgentSessionTranscriptMetadata & {
288 readonly contents: string;
289 },
290 lines = splitTranscriptRecords(input.contents, MAX_IMPORT_RECORDS + 1),
291): AgentSessionThread | null {
292 if (lines.length > MAX_IMPORT_RECORDS) return null;
293 const records = lines.flatMap((line) => Option.toArray(decodeTranscriptRecord(line)));
294 return parseAgentSessionRecords(input, records);
295}
296
297function parseAgentSessionRecords(
298 input: AgentSessionTranscriptMetadata,
299 records: ReadonlyArray<DecodedTranscriptRecord>,
300): AgentSessionThread | null {
301 const fallbackTimestamp = DateTime.formatIso(DateTime.makeUnsafe(input.lastActiveAtMs));
302 // Claude filenames are session IDs. Codex rollout filenames include extra
303 // timestamp text, so only transcript metadata can provide a resumable ID.
304 let providerSessionId = input.source === "codex" ? "" : input.fallbackSessionId;
305 let title: string | null = null;
306 let model: string | null = null;
307 let hasCodexSessionId = false;
308 const messages: Array<AgentSessionThreadMessage & { readonly codexResponseUser: boolean }> = [];
309 let firstUserMessage:
310 | (AgentSessionThreadMessage & { readonly codexResponseUser: boolean })
311 | undefined;
312 // A Codex response item can include generated setup text beside the real
313 // prompt. Suppress response-user records only when the shared turn ID and a
314 // verbatim event copy prove which prompt the user submitted.
315 const canonicalCodexResponseUserIndices = new Set<number>();
316 let canonicalUserTextsInTurn = new Set<string>();
317 let responseUsersInTurn: Array<{
318 readonly index: number;
319 readonly turnId: string;
320 readonly text: string;
321 }> = [];
322 const finishCodexTurn = () => {
323 const canonicalTurnIds = new Set(
324 responseUsersInTurn.flatMap((responseUser) =>
325 canonicalUserTextsInTurn.has(responseUser.text) ? [responseUser.turnId] : [],
326 ),
327 );
328 for (const responseUser of responseUsersInTurn) {
329 if (canonicalTurnIds.has(responseUser.turnId)) {
330 canonicalCodexResponseUserIndices.add(responseUser.index);
331 }
332 }
333 canonicalUserTextsInTurn = new Set();
334 responseUsersInTurn = [];
335 };
336 if (input.source === "codex") {
337 let recordIndex = -1;
338 for (const record of records) {
339 recordIndex += 1;
340 if (
341 record.type === "response_item" &&
342 record.payload?.type === "message" &&
343 record.payload.role === "assistant"
344 ) {
345 finishCodexTurn();
346 continue;
347 }
348 if (record.type === "event_msg" && record.payload?.type === "user_message") {
349 const text = record.payload.message?.trim() ?? "";
350 if (text.length > 0) canonicalUserTextsInTurn.add(text);
351 continue;
352 }
353 if (
354 record.type === "response_item" &&
355 record.payload?.type === "message" &&
356 record.payload.role === "user"
357 ) {
358 const turnId = codexTurnId(record.payload.internal_chat_message_metadata_passthrough);
359 const text = extractText(record.payload.content);
360 if (turnId !== null && text.length > 0) {
361 responseUsersInTurn.push({ index: recordIndex, turnId, text });
362 }
363 }
364 }
365 finishCodexTurn();
366 }
367
368 const retainMessage = (
369 message: AgentSessionThreadMessage & { readonly codexResponseUser: boolean },
370 ) => {
371 if (firstUserMessage === undefined && message.role === "user") {
372 firstUserMessage = message;
373 }
374 messages.push(message);
375 if (messages.length > MAX_IMPORTED_MESSAGES) messages.shift();
376 };
377
378 const hasMatchingCodexEventInTurn = (text: string) => {
379 const comparisonText = text.trim();
380 for (let index = messages.length - 1; index >= 0; index--) {
381 const message = messages[index];
382 if (message?.role === "assistant") return false;
383 if (
384 message?.role === "user" &&
385 !message.codexResponseUser &&
386 message.text.trim() === comparisonText
387 ) {
388 return true;
389 }
390 }
391 return false;
392 };
393
394 let recordIndex = -1;
395 for (const record of records) {
396 recordIndex += 1;
397 if (input.source === "claudeAgent") {
398 if (
399 record.isSidechain === true ||
400 record.isMeta === true ||
401 record.isCompactSummary === true
402 ) {
403 continue;
404 }
405 if (record.sessionId?.trim()) providerSessionId = record.sessionId.trim();
406 if (record.aiTitle?.trim()) title = record.aiTitle.trim();
407 const messageModel = record.message?.model?.trim();
408 // Claude uses this sentinel for local error responses. It is not a
409 // model ID that can be selected when the imported session resumes.
410 if (messageModel && messageModel !== "<synthetic>") model = messageModel;
411 if (record.type !== "user" && record.type !== "assistant") {
412 continue;
413 }
414
415 const text = extractText(record.message?.content);
416 if (text.length === 0) continue;
417 retainMessage({
418 role: record.type,
419 text,
420 createdAt: normalizeTimestamp(record.timestamp, fallbackTimestamp),
421 codexResponseUser: false,
422 });
423 continue;
424 }
425
426 if (record.type === "session_meta") {
427 const sessionId = record.payload?.id?.trim() || record.payload?.session_id?.trim();
428 if (!hasCodexSessionId && sessionId) {
429 providerSessionId = sessionId;
430 hasCodexSessionId = true;
431 }
432 continue;
433 }
434 if (record.type === "turn_context" && record.payload?.model?.trim()) {
435 model = record.payload.model.trim();
436 continue;
437 }
438 if (record.type === "event_msg" && record.payload?.type === "user_message") {
439 const text = record.payload.message ?? "";
440 if (text.trim().length === 0) continue;
441 // Codex can write the same prompt as both a response item and an event.
442 // Remove only the matching response copy so mixed-format logs keep every
443 // distinct user message.
444 for (let index = messages.length - 1; index >= 0; index--) {
445 const message = messages[index];
446 if (message?.role === "assistant") break;
447 if (message?.codexResponseUser === true && message.text.trim() === text.trim()) {
448 if (firstUserMessage === message) firstUserMessage = undefined;
449 messages.splice(index, 1);
450 break;
451 }
452 }
453 retainMessage({
454 role: "user",
455 text,
456 createdAt: normalizeTimestamp(record.timestamp, fallbackTimestamp),
457 codexResponseUser: false,
458 });
459 continue;
460 }
461 if (
462 record.type !== "response_item" ||
463 record.payload?.type !== "message" ||
464 (record.payload.role !== "user" && record.payload.role !== "assistant")
465 ) {
466 continue;
467 }
468
469 const extractedText = extractText(record.payload.content);
470 if (extractedText.length === 0) continue;
471 if (record.payload.role === "user" && canonicalCodexResponseUserIndices.has(recordIndex)) {
472 continue;
473 }
474 if (record.payload.role === "user" && hasMatchingCodexEventInTurn(extractedText)) {
475 continue;
476 }
477 retainMessage({
478 role: record.payload.role,
479 text: extractedText,
480 createdAt: normalizeTimestamp(record.timestamp, fallbackTimestamp),
481 codexResponseUser: record.payload.role === "user",
482 });
483 }
484
485 const visibleMessages = messages.map(
486 ({ codexResponseUser: _codexResponseUser, ...message }) => message,
487 );
488 if (providerSessionId.trim().length === 0 || firstUserMessage === undefined) return null;
489 const firstUserMessageRetained = messages.includes(firstUserMessage);
490 const { codexResponseUser: _codexResponseUser, ...visibleFirstUserMessage } = firstUserMessage;
491 const retainedMessages = firstUserMessageRetained
492 ? visibleMessages
493 : [visibleFirstUserMessage, ...visibleMessages.slice(-(MAX_IMPORTED_MESSAGES - 1))];
494 const derivedTitle = visibleFirstUserMessage.text.trim().split("\n")[0]?.slice(0, 100).trim();
495
496 return {
497 source: input.source,
498 providerInstanceId: input.providerInstanceId,
499 providerSessionId,
500 title: title ?? (derivedTitle && derivedTitle.length > 0 ? derivedTitle : "Imported thread"),
501 model,
502 createdAt: retainedMessages[0]?.createdAt ?? fallbackTimestamp,
503 updatedAt: fallbackTimestamp,
504 messages: retainedMessages,
505 };
506}
507
508function extractDecodedCwd(record: DecodedTranscriptRecord): string | null {
509 const cwd = record.cwd?.trim() || record.payload?.cwd?.trim();
510 return cwd && cwd.length > 0 ? cwd : null;
511}
512
513function shouldRetainDecodedRecord(
514 source: AgentSessionSource,
515 record: DecodedTranscriptRecord,
516): boolean {
517 if (extractDecodedCwd(record) !== null) return true;
518 if (source === "claudeAgent") {
519 return (
520 record.type === "user" ||
521 record.type === "assistant" ||
522 record.sessionId !== undefined ||
523 record.aiTitle !== undefined ||
524 record.message?.model !== undefined
525 );
526 }
527 return (
528 record.type === "session_meta" ||
529 record.type === "turn_context" ||
530 (record.type === "event_msg" && record.payload?.type === "user_message") ||
531 (record.type === "response_item" &&
532 record.payload?.type === "message" &&
533 (record.payload.role === "user" || record.payload.role === "assistant"))
534 );
535}
536
537/**
538 * T3 Code runs its own agent sessions inside disposable worktrees. Their
539 * transcripts look exactly like user sessions, but re-importing the app's own
540 * sandboxes as projects is never right. Matches this server's configured
541 * worktrees directory plus the conventional `.t3/worktrees` layout, which
542 * also catches sandboxes from other T3 homes on the same machine. Separators
543 * are normalized (and, on Windows, case folded) so the prefix match holds
544 * there too. Callers check both the recorded spelling and its realpath so a
545 * symlink into the worktrees directory cannot bypass the filter.
546 */
547function normalizeForWorktreeMatch(value: string, caseFold: boolean): string {
548 const normalized = `${value.replaceAll("\\", "/")}/`;
549 return caseFold ? normalized.toLowerCase() : normalized;
550}
551
552function isT3ManagedWorktree(
553 candidatePath: string,
554 worktreesDir: string,
555 caseFold: boolean,
556): boolean {
557 const normalized = normalizeForWorktreeMatch(candidatePath, caseFold);
558 return (
559 normalized.startsWith(normalizeForWorktreeMatch(worktreesDir, caseFold)) ||
560 normalized.includes("/.t3/worktrees/")
561 );
562}
563
564/** Extract `cwd` from a session-meta record, tolerating the shapes each CLI writes. */
565function extractCwd(line: string): string | null {
566 let parsed: unknown;
567 try {
568 parsed = JSON.parse(line);
569 } catch {
570 return null;
571 }
572 if (typeof parsed !== "object" || parsed === null) return null;
573
574 const record = parsed as Record<string, unknown>;
575 if (typeof record.cwd === "string" && record.cwd.trim().length > 0) {
576 return record.cwd;
577 }
578 // Codex nests session metadata under `payload`.
579 const payload = record.payload;
580 if (typeof payload === "object" && payload !== null) {
581 const nested = (payload as Record<string, unknown>).cwd;
582 if (typeof nested === "string" && nested.trim().length > 0) {
583 return nested;
584 }
585 }
586 return null;
587}
588
589function transcriptIdentity(filePath: string, stats: FileSystem.File.Info) {
590 return {
591 filePath,
592 size: Number(stats.size),
593 mtimeMs: Option.match(stats.mtime, { onNone: () => null, onSome: (date) => date.getTime() }),
594 device: stats.dev,
595 inode: Option.getOrNull(stats.ino),
596 birthtimeMs: Option.match(stats.birthtime, {
597 onNone: () => null,
598 onSome: (date) => date.getTime(),
599 }),
600 };
601}
602
603function sameTranscriptIdentity(
604 left: ReturnType<typeof transcriptIdentity>,
605 right: ReturnType<typeof transcriptIdentity>,
606): boolean {
607 return (
608 left.filePath === right.filePath &&
609 left.size === right.size &&
610 left.mtimeMs === right.mtimeMs &&
611 left.device === right.device &&
612 left.inode === right.inode &&
613 left.birthtimeMs === right.birthtimeMs
614 );
615}
616
617export const make = Effect.gen(function* () {
618 const fileSystem = yield* FileSystem.FileSystem;
619 // Different project imports can arrive concurrently from multiple clients.
620 // Only one transcript may hold its selected-history budget at a time.
621 const importReadLock = yield* Semaphore.make(1);
622 const path = yield* Path.Path;
623 const serverConfig = yield* ServerConfig.ServerConfig;
624 const serverSettings = yield* ServerSettings.ServerSettingsService;
625 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
626 const baseDir = path.resolve(serverConfig.baseDir);
627 const worktreesDir = path.resolve(serverConfig.worktreesDir);
628 // Windows filesystems are case-insensitive, so path prefix checks there
629 // must case fold.
630 const foldWorktreeCase = (yield* HostProcessPlatform) === "win32";
631 const hostEnvironment = yield* HostProcessEnvironment;
632 const homeDir = NodeOS.homedir();
633 // `/private/tmp` is what macOS reports for sessions started in `/tmp`.
634 const excludedProjectRoots = new Set(
635 [homeDir, NodeOS.tmpdir(), "/tmp", "/private/tmp"].map((directory) =>
636 normalizeProjectPathForComparison(path.resolve(directory)),
637 ),
638 );
639 // Codex creates one scratch directory per conversation under
640 // ~/Documents/Codex/<date>/<slug>. Neither those nor anything a user
641 // unpacked into Downloads is a project.
642 const excludedProjectAncestors = [
643 path.join(homeDir, "Downloads"),
644 path.join(homeDir, "Documents", "Codex"),
645 ];
646
647 const isExcludedProjectPath = (candidatePath: string) =>
648 excludedProjectRoots.has(normalizeProjectPathForComparison(candidatePath)) ||
649 excludedProjectAncestors.some((ancestor) =>
650 normalizeForWorktreeMatch(candidatePath, foldWorktreeCase).startsWith(
651 normalizeForWorktreeMatch(ancestor, foldWorktreeCase),
652 ),
653 ) ||
654 normalizeForWorktreeMatch(candidatePath, foldWorktreeCase).startsWith(
655 normalizeForWorktreeMatch(baseDir, foldWorktreeCase),
656 ) ||
657 isT3ManagedWorktree(candidatePath, worktreesDir, foldWorktreeCase);
658
659 const listDirectory = (directory: string) =>
660 fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
661
662 const statOption = (target: string) =>
663 fileSystem.stat(target).pipe(Effect.map(Option.some), Effect.orElseSucceed(Option.none));
664
665 /** Match directory aliases without assuming the host volume is case-insensitive. */
666 const directoryIdentity = Effect.fn("AgentSessionScanner.directoryIdentity")(function* (
667 target: string,
668 knownStats?: FileSystem.File.Info,
669 ) {
670 const resolved = path.resolve(target);
671 const stats = knownStats === undefined ? yield* statOption(resolved) : Option.some(knownStats);
672 if (
673 Option.isSome(stats) &&
674 Option.isSome(stats.value.ino) &&
675 Number.isSafeInteger(stats.value.ino.value) &&
676 stats.value.ino.value > 0
677 ) {
678 return `inode:${stats.value.dev}:${stats.value.ino.value}`;
679 }
680 const realPath = yield* fileSystem
681 .realPath(resolved)
682 .pipe(Effect.orElseSucceed(() => resolved));
683 return `path:${normalizeProjectPathForComparison(realPath)}`;
684 });
685
686 /**
687 * Git identity of a directory, or the reason it has none. Reads `.git`
688 * directly instead of spawning git so a scan over hundreds of candidates
689 * stays cheap. A `.git` file is a `gitdir:` pointer. When it points into a
690 * `worktrees/` directory the checkout is a linked worktree, which
691 * onboarding skips because its history belongs to the main checkout.
692 * Submodules use the same pointer shape but live under `modules/`, and
693 * are offered like any other repository.
694 */
695 const readGitIdentity = Effect.fn("AgentSessionScanner.readGitIdentity")(function* (
696 directory: string,
697 ): Effect.fn.Return<
698 | { readonly _tag: "Repository"; readonly git: AgentSessionProjectCandidate["git"] }
699 | { readonly _tag: "Worktree" }
700 | { readonly _tag: "NotGit" }
701 > {
702 const gitPath = path.join(directory, ".git");
703 const gitStats = yield* statOption(gitPath);
704 if (Option.isNone(gitStats)) return { _tag: "NotGit" } as const;
705 let gitDir = gitPath;
706 if (gitStats.value.type !== "Directory") {
707 const pointer = yield* fileSystem
708 .readFileString(gitPath)
709 .pipe(Effect.orElseSucceed(() => ""));
710 const target = /^gitdir:\s*(.+)$/m.exec(pointer)?.[1]?.trim();
711 if (target === undefined || target.length === 0) return { _tag: "NotGit" } as const;
712 gitDir = path.resolve(directory, target);
713 if (/[\\/]worktrees[\\/][^\\/]+[\\/]?$/.test(gitDir)) return { _tag: "Worktree" } as const;
714 }
715 const configText = yield* fileSystem
716 .readFileString(path.join(gitDir, "config"))
717 .pipe(Effect.orElseSucceed(() => ""));
718 const originUrl = parseOriginUrlFromGitConfig(configText);
719 return {
720 _tag: "Repository",
721 git: {
722 remoteKey: originUrl === null ? null : normalizeGitRemoteUrl(originUrl),
723 repository: parseGitHubRepositoryNameWithOwnerFromRemoteUrl(originUrl),
724 },
725 } as const;
726 });
727
728 // A large history snapshot can precede session metadata. Read bounded
729 // chunks until a complete record names its cwd or the safety budget ends.
730 const readCwd = Effect.fn("AgentSessionScanner.readCwd")(function* (
731 transcript: TranscriptCandidate,
732 budget: MetadataReadBudget,
733 ) {
734 if (transcript.size === 0) return null;
735 if (
736 budget.bytesRemaining === 0 ||
737 budget.operationsRemaining < 2 ||
738 budget.recordsRemaining === 0
739 ) {
740 budget.truncated = true;
741 return null;
742 }
743 budget.operationsRemaining -= 1;
744 return yield* Effect.scoped(
745 fileSystem.open(transcript.filePath, { flag: "r" }).pipe(
746 Effect.flatMap((file) =>
747 Effect.gen(function* () {
748 const decoder = new TextDecoder();
749 let remaining = "";
750 let bytesRead = 0;
751 let recordsRead = 0;
752 const maxBytes = Math.min(MAX_TRANSCRIPT_SCAN_BYTES, transcript.size);
753 const reserveRecord = () => {
754 if (
755 recordsRead === MAX_METADATA_RECORDS_PER_TRANSCRIPT ||
756 budget.recordsRemaining === 0
757 ) {
758 budget.truncated = true;
759 return false;
760 }
761 recordsRead += 1;
762 budget.recordsRemaining -= 1;
763 return true;
764 };
765 const readLastRecord = () => {
766 const record = remaining + decoder.decode();
767 return record.length === 0 || !reserveRecord() ? null : extractCwd(record.trim());
768 };
769
770 while (bytesRead < maxBytes) {
771 if (budget.bytesRemaining === 0 || budget.operationsRemaining === 0) {
772 budget.truncated = true;
773 return null;
774 }
775 const readSize = Math.min(
776 METADATA_READ_BYTES,
777 maxBytes - bytesRead,
778 budget.bytesRemaining,
779 );
780 budget.operationsRemaining -= 1;
781 budget.bytesRemaining -= readSize;
782 const next = yield* file.readAlloc(readSize);
783 if (Option.isNone(next)) {
784 return readLastRecord();
785 }
786
787 bytesRead += next.value.byteLength;
788 remaining += decoder.decode(next.value, { stream: true });
789 const lines = remaining.split("\n");
790 remaining = lines.pop() ?? "";
791
792 for (const line of lines) {
793 if (!reserveRecord()) return null;
794 const cwd = extractCwd(line.trim());
795 if (cwd !== null) return cwd;
796 }
797 }
798
799 if (bytesRead < transcript.size) {
800 budget.truncated = true;
801 return null;
802 }
803 return readLastRecord();
804 }),
805 ),
806 ),
807 ).pipe(Effect.orElseSucceed(() => null));
808 });
809
810 /**
811 * Project history fields while reading, before allocating whole JSON records.
812 * Check the file identity on both sides of the read. A selected-history budget
813 * failure rejects the entire transcript before any imported messages persist.
814 */
815 const readTranscript = Effect.fn("AgentSessionScanner.readTranscript")(function* (
816 filePath: string,
817 expected: ReturnType<typeof transcriptIdentity>,
818 recordLimit: number,
819 source: AgentSessionSource,
820 ) {
821 if (expected.size > MAX_IMPORTED_TRANSCRIPT_BYTES) return null;
822
823 return yield* Effect.scoped(
824 fileSystem.open(filePath, { flag: "r" }).pipe(
825 Effect.flatMap((file) =>
826 Effect.gen(function* () {
827 if (!sameTranscriptIdentity(expected, transcriptIdentity(filePath, yield* file.stat))) {
828 return null;
829 }
830 const records: Array<DecodedTranscriptRecord> = [];
831 let historyBytes = 0;
832 let recordBytes = 0;
833 let recordCount = 0;
834 let bytesRead = 0;
835 const reserve = (bytes: number) => {
836 recordBytes += bytes;
837 if (historyBytes + recordBytes > MAX_IMPORT_HISTORY_BYTES) {
838 throw new TranscriptJsonLimitError(
839 "Transcript selected history exceeds the 32 MiB memory budget",
840 );
841 }
842 };
843 let reader = createTranscriptJsonReader(reserve, selectTranscriptPath);
844 let decoder = new TextDecoder();
845 let recordStarted = false;
846
847 const finishRecord = () => {
848 reader.write(decoder.decode());
849 recordCount += 1;
850 if (recordCount > recordLimit) return false;
851 const decoded = decodeTranscriptValue(reader.finish());
852 if (Option.isSome(decoded) && shouldRetainDecodedRecord(source, decoded.value)) {
853 records.push(decoded.value);
854 historyBytes += recordBytes;
855 }
856 recordBytes = 0;
857 reader = createTranscriptJsonReader(reserve, selectTranscriptPath);
858 decoder = new TextDecoder();
859 recordStarted = false;
860 return true;
861 };
862
863 while (bytesRead < expected.size) {
864 const next = yield* file.readAlloc(
865 Math.min(TRANSCRIPT_PREFIX_BYTES, expected.size - bytesRead),
866 );
867 if (Option.isNone(next)) {
868 return null;
869 }
870
871 bytesRead += next.value.byteLength;
872 const withinBudget = yield* Effect.try(() => {
873 let start = 0;
874 while (start < next.value.byteLength) {
875 const newline = next.value.indexOf(10, start);
876 const end = newline === -1 ? next.value.byteLength : newline;
877 recordStarted = true;
878 reader.write(decoder.decode(next.value.subarray(start, end), { stream: true }));
879 if (newline === -1) break;
880 if (!finishRecord()) return false;
881 start = newline + 1;
882 }
883 return true;
884 });
885 if (!withinBudget) return null;
886 }
887
888 if (recordStarted && !(yield* Effect.try(finishRecord))) return null;
889 return sameTranscriptIdentity(expected, transcriptIdentity(filePath, yield* file.stat))
890 ? { records, recordCount }
891 : null;
892 }),
893 ),
894 ),
895 ).pipe(
896 Effect.catch((cause) =>
897 Effect.logWarning("Could not read imported transcript", { filePath, cause }).pipe(
898 Effect.as(null),
899 ),
900 ),
901 );
902 });
903
904 /**
905 * Resolve the Claude config directory the CLI would use, matching the
906 * precedence the spawned CLI sees: the instance's `homePath` (exported as
907 * `CLAUDE_CONFIG_DIR`), then a `CLAUDE_CONFIG_DIR` already in the
908 * environment, then `~/.claude`.
909 */
910 const resolveClaudeConfigDir = (homePath: string, environmentHome?: string): string => {
911 const configured = homePath.trim();
912 if (configured.length > 0) {
913 return path.resolve(expandHomePath(configured));
914 }
915 const fromEnvironment = environmentHome?.trim() ?? "";
916 if (fromEnvironment.length > 0) {
917 return path.resolve(expandHomePath(fromEnvironment));
918 }
919 return path.join(NodeOS.homedir(), ".claude");
920 };
921
922 const discoverClaudeTranscripts = Effect.fn("AgentSessionScanner.discoverClaudeTranscripts")(
923 function* (homePath: string, providerInstanceId: ProviderInstanceId, operationBudget: number) {
924 const projectsDir = path.join(homePath, "projects");
925 let operationsRemaining = operationBudget;
926 let truncated = false;
927 const readDirectory = (directory: string) => {
928 if (operationsRemaining <= 0) {
929 truncated = true;
930 return Effect.succeed<ReadonlyArray<string>>([]);
931 }
932 operationsRemaining -= 1;
933 return listDirectory(directory);
934 };
935 const projectDirectories = yield* readDirectory(projectsDir);
936 const transcripts: Array<TranscriptCandidate> = [];
937
938 for (const projectDirectory of projectDirectories) {
939 if (operationsRemaining <= 0) {
940 truncated = true;
941 break;
942 }
943 const directory = path.join(projectsDir, projectDirectory);
944 const directoryTranscripts = (yield* readDirectory(directory))
945 .filter((entry) => entry.endsWith(".jsonl"))
946 .map((entry) => path.join(directory, entry));
947
948 for (const filePath of directoryTranscripts) {
949 if (operationsRemaining <= 0) {
950 truncated = true;
951 break;
952 }
953 operationsRemaining -= 1;
954 const stats = yield* statOption(filePath);
955 if (
956 Option.isNone(stats) ||
957 stats.value.type !== "File" ||
958 Option.isNone(stats.value.mtime)
959 ) {
960 continue;
961 }
962 transcripts.push({
963 filePath,
964 mtimeMs: stats.value.mtime.value.getTime(),
965 providerInstanceId,
966 size: Number(stats.value.size),
967 });
968 }
969 }
970 return { transcripts, truncated };
971 },
972 );
973
974 const discoverCodexTranscripts = Effect.fn("AgentSessionScanner.discoverCodexTranscripts")(
975 function* (homePath: string, providerInstanceId: ProviderInstanceId, operationBudget: number) {
976 const sessionsDir = path.join(homePath, "sessions");
977
978 const transcripts: Array<TranscriptCandidate> = [];
979 let operationsRemaining = operationBudget;
980 let truncated = false;
981 const readDirectory = (directory: string) => {
982 if (operationsRemaining <= 0) {
983 truncated = true;
984 return Effect.succeed<ReadonlyArray<string>>([]);
985 }
986 operationsRemaining -= 1;
987 return listDirectory(directory);
988 };
989 // Date-partitioned directories sort chronologically, so walking them in
990 // reverse spends each home's share of the operation budget on recent sessions.
991 for (const year of (yield* readDirectory(sessionsDir)).toSorted().toReversed()) {
992 if (operationsRemaining <= 0) {
993 truncated = true;
994 break;
995 }
996 for (const month of (yield* readDirectory(path.join(sessionsDir, year)))
997 .toSorted()
998 .toReversed()) {
999 if (operationsRemaining <= 0) {
1000 truncated = true;
1001 break;
1002 }
1003 for (const day of (yield* readDirectory(path.join(sessionsDir, year, month)))
1004 .toSorted()
1005 .toReversed()) {
1006 if (operationsRemaining <= 0) {
1007 truncated = true;
1008 break;
1009 }
1010 const directory = path.join(sessionsDir, year, month, day);
1011 for (const entry of (yield* readDirectory(directory)).toSorted().toReversed()) {
1012 if (!entry.startsWith("rollout-") || !entry.endsWith(".jsonl")) continue;
1013 if (operationsRemaining <= 0) {
1014 truncated = true;
1015 break;
1016 }
1017 const filePath = path.join(directory, entry);
1018 operationsRemaining -= 1;
1019 const stats = yield* statOption(filePath);
1020 if (
1021 Option.isSome(stats) &&
1022 stats.value.type === "File" &&
1023 Option.isSome(stats.value.mtime)
1024 ) {
1025 transcripts.push({
1026 filePath,
1027 mtimeMs: stats.value.mtime.value.getTime(),
1028 providerInstanceId,
1029 size: Number(stats.value.size),
1030 });
1031 }
1032 }
1033 }
1034 }
1035 }
1036 return { transcripts, truncated };
1037 },
1038 );
1039
1040 const groupTranscriptsByCwd = Effect.fn("AgentSessionScanner.groupTranscriptsByCwd")(function* (
1041 source: AgentSessionSource,
1042 transcripts: ReadonlyArray<TranscriptCandidate>,
1043 budget: MetadataReadBudget,
1044 ) {
1045 const byOwnerAndCwd = new Map<
1046 string,
1047 {
1048 cwd: string;
1049 providerInstanceId: ProviderInstanceId;
1050 lastActiveAtMs: number;
1051 transcripts: Array<{ filePath: string; mtimeMs: number }>;
1052 }
1053 >();
1054
1055 for (const transcript of transcripts) {
1056 const cwd = yield* readCwd(transcript, budget);
1057 if (cwd === null) continue;
1058 const key = `${transcript.providerInstanceId}\0${cwd}`;
1059 const existing = byOwnerAndCwd.get(key);
1060 if (existing) {
1061 existing.lastActiveAtMs = Math.max(existing.lastActiveAtMs, transcript.mtimeMs);
1062 existing.transcripts.push(transcript);
1063 } else {
1064 byOwnerAndCwd.set(key, {
1065 cwd,
1066 providerInstanceId: transcript.providerInstanceId,
1067 lastActiveAtMs: transcript.mtimeMs,
1068 transcripts: [transcript],
1069 });
1070 }
1071 }
1072
1073 return Array.from(byOwnerAndCwd.values(), (group): RawCandidate => ({
1074 cwd: group.cwd,
1075 source,
1076 providerInstanceId: group.providerInstanceId,
1077 threadCount: group.transcripts.length,
1078 lastActiveAtMs: group.lastActiveAtMs,
1079 transcripts: group.transcripts,
1080 }));
1081 });
1082
1083 const collectCandidates = Effect.fn("AgentSessionScanner.collectCandidates")(function* () {
1084 const settings = yield* serverSettings.getSettings.pipe(
1085 Effect.mapError((cause) => new AgentSessionScanError({ operation: "read-settings", cause })),
1086 );
1087
1088 const raw: Array<RawCandidate> = [];
1089 let truncated = false;
1090
1091 for (const source of ["claudeAgent", "codex"] as const) {
1092 const instances: Array<{
1093 readonly instanceId: ProviderInstanceId;
1094 readonly config: ProviderInstanceConfig;
1095 }> = Object.entries(settings.providerInstances)
1096 .filter(
1097 ([, instance]) => instance.driver === source && resolveProviderInstanceEnabled(instance),
1098 )
1099 .map(([instanceId, config]) => ({
1100 instanceId: ProviderInstanceId.make(instanceId),
1101 config,
1102 }));
1103 if (!Object.hasOwn(settings.providerInstances, source)) {
1104 const legacyInstance = {
1105 instanceId: ProviderInstanceId.make(source),
1106 config: {
1107 driver: ProviderDriverKind.make(source),
1108 config: settings.providers[source],
1109 },
1110 };
1111 if (resolveProviderInstanceEnabled(legacyInstance.config)) {
1112 instances.push(legacyInstance);
1113 }
1114 }
1115
1116 // A shared home contains one copy of each session. Prefer the built-in
1117 // instance as its owner, then keep configured order for custom accounts.
1118 instances.sort((left, right) => {
1119 const leftDefault = left.instanceId === source ? 0 : 1;
1120 const rightDefault = right.instanceId === source ? 0 : 1;
1121 return leftDefault - rightDefault;
1122 });
1123 const homes: Array<{ homePath: string; providerInstanceId: ProviderInstanceId }> = [];
1124 const seenHomes = new Set<string>();
1125 for (const { instanceId, config: instance } of instances) {
1126 const homeVariable = source === "claudeAgent" ? "CLAUDE_CONFIG_DIR" : "CODEX_HOME";
1127 const environmentHome =
1128 instance.environment?.findLast((variable) => variable.name === homeVariable)?.value ??
1129 hostEnvironment[homeVariable];
1130
1131 let homePath: string;
1132 if (source === "claudeAgent") {
1133 const config = decodeClaudeSettings(instance.config ?? {});
1134 if (Option.isNone(config)) continue;
1135 homePath = resolveClaudeConfigDir(config.value.homePath, environmentHome);
1136 } else {
1137 const config = decodeCodexSettings(instance.config ?? {});
1138 if (Option.isNone(config)) continue;
1139 const codexSettings =
1140 config.value.homePath.trim().length === 0 &&
1141 config.value.shadowHomePath.trim().length === 0 &&
1142 environmentHome?.trim()
1143 ? { ...config.value, homePath: environmentHome }
1144 : config.value;
1145 const layout = yield* resolveCodexHomeLayout(codexSettings).pipe(
1146 Effect.provideService(Path.Path, path),
1147 );
1148 homePath = layout.sharedHomePath;
1149 }
1150
1151 const homeKey = `${source}\0${yield* directoryIdentity(homePath)}`;
1152 if (seenHomes.has(homeKey)) continue;
1153 seenHomes.add(homeKey);
1154 homes.push({ homePath, providerInstanceId: instanceId });
1155 }
1156
1157 const transcriptCandidates: Array<TranscriptCandidate> = [];
1158 const baseOperationBudget = Math.floor(
1159 MAX_DISCOVERY_OPERATIONS_PER_SOURCE / Math.max(1, homes.length),
1160 );
1161 const extraOperationBudgets = MAX_DISCOVERY_OPERATIONS_PER_SOURCE % Math.max(1, homes.length);
1162 for (const [index, home] of homes.entries()) {
1163 const operationBudget = baseOperationBudget + (index < extraOperationBudgets ? 1 : 0);
1164 if (operationBudget === 0) {
1165 truncated = true;
1166 continue;
1167 }
1168 const discovered = yield* source === "claudeAgent"
1169 ? discoverClaudeTranscripts(home.homePath, home.providerInstanceId, operationBudget)
1170 : discoverCodexTranscripts(home.homePath, home.providerInstanceId, operationBudget);
1171 truncated ||= discovered.truncated;
1172 transcriptCandidates.push(...discovered.transcripts);
1173 }
1174
1175 transcriptCandidates.sort(
1176 (left, right) =>
1177 right.mtimeMs - left.mtimeMs || left.filePath.localeCompare(right.filePath),
1178 );
1179 if (transcriptCandidates.length > MAX_TRANSCRIPTS_PER_SOURCE) {
1180 truncated = true;
1181 }
1182 // Give each account a turn before taking another file from the same home.
1183 const selectedTranscripts = selectMetadataTranscripts(transcriptCandidates);
1184 const metadataBudget: MetadataReadBudget = {
1185 bytesRemaining: MAX_METADATA_BYTES_PER_SOURCE,
1186 operationsRemaining: MAX_METADATA_OPERATIONS_PER_SOURCE,
1187 recordsRemaining: MAX_METADATA_RECORDS_PER_SOURCE,
1188 truncated: false,
1189 };
1190 raw.push(...(yield* groupTranscriptsByCwd(source, selectedTranscripts, metadataBudget)));
1191 truncated ||= metadataBudget.truncated;
1192 }
1193
1194 return { candidates: raw, truncated };
1195 });
1196
1197 let cachedCandidates: ReadonlyArray<RawCandidate> | null = null;
1198
1199 const scan: AgentSessionScanner["Service"]["scan"] = Effect.gen(function* () {
1200 const { candidates: raw, truncated } = yield* collectCandidates();
1201 cachedCandidates = raw;
1202
1203 // Filesystem identity merges symlinks and case aliases without collapsing
1204 // distinct case-sensitive directories.
1205 const merged = new Map<
1206 string,
1207 {
1208 path: string;
1209 sources: Array<AgentSessionSource>;
1210 threadCount: number;
1211 lastActiveAtMs: number | null;
1212 git: AgentSessionProjectCandidate["git"];
1213 }
1214 >();
1215 const directoryKeys = new Map<string, string>();
1216 const gitIdentities = new Map<string, AgentSessionProjectCandidate["git"]>();
1217
1218 for (const candidate of raw) {
1219 const expanded = expandHomePath(candidate.cwd.trim());
1220 if (!path.isAbsolute(expanded)) continue;
1221 const resolved = path.resolve(expanded);
1222 if (isExcludedProjectPath(resolved)) continue;
1223 let key = directoryKeys.get(resolved);
1224 if (key === undefined) {
1225 const stats = yield* statOption(resolved);
1226 // Directories that no longer exist can't be imported.
1227 if (Option.isNone(stats) || stats.value.type !== "Directory") {
1228 directoryKeys.set(resolved, "");
1229 continue;
1230 }
1231 const realPath = yield* fileSystem
1232 .realPath(resolved)
1233 .pipe(Effect.orElseSucceed(() => resolved));
1234 // A symlink can point into the worktrees directory even when its own
1235 // spelling doesn't; check again with links resolved.
1236 if (isExcludedProjectPath(realPath)) {
1237 key = "";
1238 } else {
1239 const gitIdentity = yield* readGitIdentity(resolved);
1240 if (gitIdentity._tag === "Worktree") {
1241 key = "";
1242 } else {
1243 key = yield* directoryIdentity(resolved, stats.value);
1244 gitIdentities.set(key, gitIdentity._tag === "Repository" ? gitIdentity.git : null);
1245 }
1246 }
1247 directoryKeys.set(resolved, key);
1248 }
1249 if (key === "") continue;
1250
1251 const existing = merged.get(key);
1252 if (!existing) {
1253 merged.set(key, {
1254 path: resolved,
1255 sources: [candidate.source],
1256 threadCount: candidate.threadCount,
1257 lastActiveAtMs: candidate.lastActiveAtMs,
1258 git: gitIdentities.get(key) ?? null,
1259 });
1260 continue;
1261 }
1262 if (!existing.sources.includes(candidate.source)) {
1263 existing.sources.push(candidate.source);
1264 }
1265 existing.threadCount += candidate.threadCount;
1266 existing.lastActiveAtMs =
1267 existing.lastActiveAtMs === null || candidate.lastActiveAtMs === null
1268 ? (existing.lastActiveAtMs ?? candidate.lastActiveAtMs)
1269 : Math.max(existing.lastActiveAtMs, candidate.lastActiveAtMs);
1270 }
1271
1272 // Resolve persisted roots too. A project and a transcript can name
1273 // different symlinks to the same directory.
1274 const shellSnapshot = yield* projectionSnapshotQuery
1275 .getShellSnapshot()
1276 .pipe(
1277 Effect.mapError(
1278 (cause) => new AgentSessionScanError({ operation: "read-projects", cause }),
1279 ),
1280 );
1281 const importedProjectsByRoot = new Map<string, (typeof shellSnapshot.projects)[number]>();
1282 for (const project of shellSnapshot.projects) {
1283 const projectRoot = path.resolve(expandHomePath(project.workspaceRoot));
1284 importedProjectsByRoot.set(normalizeProjectPathForComparison(projectRoot), project);
1285 importedProjectsByRoot.set(yield* directoryIdentity(projectRoot), project);
1286 }
1287
1288 const candidates: Array<AgentSessionProjectCandidate> = [];
1289 for (const [key, entry] of merged.entries()) {
1290 // Keep the path key for missing roots and use filesystem identity for
1291 // aliases that resolve to the same directory.
1292 const importedProject =
1293 importedProjectsByRoot.get(normalizeProjectPathForComparison(entry.path)) ??
1294 importedProjectsByRoot.get(key);
1295 const candidatePath = importedProject?.workspaceRoot ?? entry.path;
1296 candidates.push({
1297 path: candidatePath,
1298 title: path.basename(candidatePath) || candidatePath,
1299 ...(importedProject === undefined ? {} : { projectId: importedProject.id }),
1300 sources: entry.sources,
1301 threadCount: entry.threadCount,
1302 lastActiveAt:
1303 entry.lastActiveAtMs === null
1304 ? null
1305 : DateTime.formatIso(DateTime.makeUnsafe(entry.lastActiveAtMs)),
1306 alreadyImported: importedProject !== undefined,
1307 git: entry.git,
1308 });
1309 }
1310
1311 // Newest first, undated candidates last.
1312 candidates.sort((left, right) => {
1313 if (left.lastActiveAt === right.lastActiveAt) return left.path.localeCompare(right.path);
1314 if (left.lastActiveAt === null) return 1;
1315 if (right.lastActiveAt === null) return -1;
1316 return right.lastActiveAt.localeCompare(left.lastActiveAt);
1317 });
1318
1319 return {
1320 candidates,
1321 scannedAt: DateTime.formatIso(yield* DateTime.now),
1322 ...(truncated ? { truncated: true } : {}),
1323 };
1324 });
1325
1326 const prepareRecentThreads = Effect.fn("AgentSessionScanner.prepareRecentThreads")(function* (
1327 workspaceRoot: string,
1328 completedSources: ReadonlyArray<AgentSessionImportSource>,
1329 ) {
1330 const root = path.resolve(expandHomePath(workspaceRoot));
1331 const realRoot = yield* fileSystem.realPath(root).pipe(Effect.orElseSucceed(() => root));
1332 if (isExcludedProjectPath(root) || isExcludedProjectPath(realRoot)) return Stream.empty;
1333 const rootIdentity = yield* directoryIdentity(root);
1334 const nowMs = DateTime.toEpochMillis(yield* DateTime.now);
1335 const cutoffMs = nowMs - RECENT_THREAD_WINDOW_MS;
1336
1337 const candidates = cachedCandidates ?? (yield* collectCandidates()).candidates;
1338 cachedCandidates = candidates;
1339
1340 const eligibleTranscripts: Array<{
1341 readonly candidate: RawCandidate;
1342 readonly transcript: RawCandidate["transcripts"][number] & { readonly mtimeMs: number };
1343 }> = [];
1344 for (const candidate of candidates) {
1345 const expanded = expandHomePath(candidate.cwd.trim());
1346 if (!path.isAbsolute(expanded)) continue;
1347 const resolved = path.resolve(expanded);
1348 if ((yield* directoryIdentity(resolved)) !== rootIdentity) continue;
1349
1350 for (const transcript of candidate.transcripts) {
1351 if (
1352 transcript.mtimeMs === null ||
1353 transcript.mtimeMs < cutoffMs ||
1354 transcript.mtimeMs > nowMs
1355 ) {
1356 continue;
1357 }
1358 eligibleTranscripts.push({
1359 candidate,
1360 transcript: { ...transcript, mtimeMs: transcript.mtimeMs },
1361 });
1362 }
1363 }
1364
1365 eligibleTranscripts.sort((left, right) => {
1366 if (left.transcript.mtimeMs !== right.transcript.mtimeMs) {
1367 return right.transcript.mtimeMs - left.transcript.mtimeMs;
1368 }
1369 return left.transcript.filePath.localeCompare(right.transcript.filePath);
1370 });
1371
1372 const completedByFile = Map.groupBy(
1373 completedSources,
1374 (source) => `${source.providerInstanceId}\0${source.filePath}`,
1375 );
1376 const importedSessions = new Set<string>();
1377 let bytesRemaining = MAX_IMPORT_BYTES;
1378 let transcriptsRemaining = MAX_IMPORT_TRANSCRIPTS;
1379 let recordsRemaining = MAX_IMPORT_RECORDS;
1380 return Stream.fromIteratorSucceed(eligibleTranscripts.values(), 1).pipe(
1381 Stream.mapEffect(({ candidate, transcript }) =>
1382 Effect.gen(function* () {
1383 const completed = completedByFile.get(
1384 `${candidate.providerInstanceId}\0${transcript.filePath}`,
1385 );
1386 if (
1387 completed === undefined &&
1388 (transcriptsRemaining === 0 || bytesRemaining === 0 || recordsRemaining === 0)
1389 ) {
1390 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
1391 }
1392 const stats = yield* statOption(transcript.filePath);
1393 if (Option.isNone(stats) || stats.value.type !== "File") {
1394 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
1395 }
1396 const identity = transcriptIdentity(transcript.filePath, stats.value);
1397 const completedSource = completed?.find(
1398 (source) =>
1399 source.provider === candidate.source && sameTranscriptIdentity(source, identity),
1400 );
1401 if (completedSource !== undefined) {
1402 const sessionKey = `${completedSource.providerInstanceId}\0${completedSource.providerSessionId}`;
1403 if (importedSessions.has(sessionKey)) return Option.none<AgentSessionRecentThread>();
1404 importedSessions.add(sessionKey);
1405 return Option.some<AgentSessionRecentThread>({
1406 _tag: "AlreadyImported",
1407 source: completedSource,
1408 });
1409 }
1410 if (
1411 transcriptsRemaining === 0 ||
1412 recordsRemaining === 0 ||
1413 identity.size > MAX_IMPORTED_TRANSCRIPT_BYTES ||
1414 identity.size > bytesRemaining
1415 ) {
1416 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
1417 }
1418 // Reserve the whole file even if its read or parse fails.
1419 transcriptsRemaining -= 1;
1420 bytesRemaining -= identity.size;
1421 const snapshot = yield* readTranscript(
1422 transcript.filePath,
1423 identity,
1424 recordsRemaining,
1425 candidate.source,
1426 );
1427 if (snapshot === null) {
1428 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
1429 }
1430 recordsRemaining -= snapshot.recordCount;
1431
1432 // A stable replacement file can belong to a different project than the cached candidate.
1433 let snapshotCwd: string | null = null;
1434 for (const record of snapshot.records) {
1435 snapshotCwd = extractDecodedCwd(record);
1436 if (snapshotCwd !== null) break;
1437 }
1438 if (snapshotCwd === null) {
1439 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
1440 }
1441 const expandedCwd = expandHomePath(snapshotCwd.trim());
1442 if (
1443 !path.isAbsolute(expandedCwd) ||
1444 (yield* directoryIdentity(path.resolve(expandedCwd))) !== rootIdentity
1445 ) {
1446 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
1447 }
1448
1449 const parsedThread = parseAgentSessionRecords(
1450 {
1451 source: candidate.source,
1452 providerInstanceId: candidate.providerInstanceId,
1453 fallbackSessionId: path.basename(transcript.filePath, ".jsonl"),
1454 lastActiveAtMs: transcript.mtimeMs,
1455 },
1456 snapshot.records,
1457 );
1458 if (parsedThread === null) {
1459 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
1460 }
1461
1462 const source: AgentSessionImportSource = {
1463 ...identity,
1464 provider: parsedThread.source,
1465 providerInstanceId: parsedThread.providerInstanceId,
1466 providerSessionId: parsedThread.providerSessionId,
1467 };
1468 const sessionKey = `${parsedThread.providerInstanceId}\0${parsedThread.providerSessionId}`;
1469 if (importedSessions.has(sessionKey)) {
1470 return Option.some<AgentSessionRecentThread>({ _tag: "Duplicate", source });
1471 }
1472 importedSessions.add(sessionKey);
1473 return Option.some<AgentSessionRecentThread>({
1474 _tag: "Importable",
1475 thread: parsedThread,
1476 source,
1477 });
1478 }).pipe(importReadLock.withPermits(1)),
1479 ),
1480 Stream.map(Option.toArray),
1481 Stream.flattenIterable,
1482 );
1483 });
1484
1485 const recentThreads: AgentSessionScanner["Service"]["recentThreads"] = (
1486 workspaceRoot,
1487 completedSources = [],
1488 ) => Stream.unwrap(prepareRecentThreads(workspaceRoot, completedSources));
1489
1490 return AgentSessionScanner.of({ scan, recentThreads });
1491});
1492
1493export const layer = Layer.effect(AgentSessionScanner, make);