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