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