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