Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AgentSessionScanner.ts

1,412 lines52.1 KB

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;
125​
126export interface AgentSessionThreadMessage {
127 readonly role: "user" | "assistant";
128 readonly text: string;
129 readonly createdAt: string;
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>;
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 }>;
177​
178interface TranscriptCandidate {
179 readonly filePath: string;
180 readonly mtimeMs: number;
181 readonly providerInstanceId: ProviderInstanceId;
182 readonly size: number;
184​
185interface MetadataReadBudget {
186 bytesRemaining: number;
187 operationsRemaining: number;
188 recordsRemaining: number;
189 truncated: boolean;
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;
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);
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");
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;
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;
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;
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);
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 };
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;
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 );
510​
511function normalizeForWorktreeMatch(value: string, caseFold: boolean): string {
512 const normalized = `${value.replaceAll("\\", "/")}/`;
513 return caseFold ? normalized.toLowerCase() : normalized;
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 );
527​
528function extractCwd(line: string): string | null {
529 let parsed: unknown;
530 try {
531 parsed = JSON.parse(line);
532 } catch {
533 return null;
534 }
535 if (typeof parsed !== "object" || parsed === null) return null;
536​
537 const record = parsed as Record<string, unknown>;
538 if (typeof record.cwd === "string" && record.cwd.trim().length > 0) {
539 return record.cwd;
540 }
541 const payload = record.payload;
542 if (typeof payload === "object" && payload !== null) {
543 const nested = (payload as Record<string, unknown>).cwd;
544 if (typeof nested === "string" && nested.trim().length > 0) {
545 return nested;
546 }
547 }
548 return null;
550​
551function transcriptIdentity(filePath: string, stats: FileSystem.File.Info) {
552 return {
553 filePath,
554 size: Number(stats.size),
555 mtimeMs: Option.match(stats.mtime, { onNone: () => null, onSome: (date) => date.getTime() }),
556 device: Number(stats.dev),
557 inode: Option.match(stats.ino, { onNone: () => null, onSome: Number }),
558 birthtimeMs: Option.match(stats.birthtime, {
559 onNone: () => null,
560 onSome: (date) => date.getTime(),
561 }),
562 };
564​
565function sameTranscriptIdentity(
566 left: ReturnType<typeof transcriptIdentity>,
567 right: ReturnType<typeof transcriptIdentity>,
568): boolean {
569 return (
570 left.filePath === right.filePath &&
571 left.size === right.size &&
572 left.mtimeMs === right.mtimeMs &&
573 left.device === right.device &&
574 left.inode === right.inode &&
575 left.birthtimeMs === right.birthtimeMs
576 );
578​
579/** @public Service construction is part of the canonical Effect module API. */
580export const make = Effect.gen(function* () {
581 const fileSystem = yield* FileSystem.FileSystem;
582 // Different project imports can arrive concurrently from multiple clients.
583 // Only one transcript may hold its selected-history budget at a time.
584 const importReadLock = yield* Semaphore.make(1);
585 const path = yield* Path.Path;
586 const serverConfig = yield* ServerConfig.ServerConfig;
587 const serverSettings = yield* ServerSettings.ServerSettingsService;
588 const projectStore = yield* ProjectStore.ProjectStoreV2;
589 const baseDir = path.resolve(serverConfig.baseDir);
590 const worktreesDir = path.resolve(serverConfig.worktreesDir);
591 const foldWorktreeCase = (yield* HostProcess.Platform) === "win32";
592 const hostEnvironment = yield* HostProcess.Environment;
593 const homeDir = yield* HostProcess.HomeDirectory;
594 // `/private/tmp` is what macOS reports for sessions started in `/tmp`.
595 const excludedProjectRoots = new Set(
596 [homeDir, NodeOS.tmpdir(), "/tmp", "/private/tmp"].map((directory) =>
597 normalizeProjectPathForComparison(path.resolve(directory)),
598 ),
599 );
600 const excludedProjectAncestors = [
601 path.join(homeDir, "Downloads"),
602 path.join(homeDir, "Documents", "Codex"),
603 ];
604​
605 const isExcludedProjectPath = (candidatePath: string) =>
606 excludedProjectRoots.has(normalizeProjectPathForComparison(candidatePath)) ||
607 excludedProjectAncestors.some((ancestor) =>
608 normalizeForWorktreeMatch(candidatePath, foldWorktreeCase).startsWith(
609 normalizeForWorktreeMatch(ancestor, foldWorktreeCase),
610 ),
611 ) ||
612 normalizeForWorktreeMatch(candidatePath, foldWorktreeCase).startsWith(
613 normalizeForWorktreeMatch(baseDir, foldWorktreeCase),
614 ) ||
615 isT3ManagedWorktree(candidatePath, worktreesDir, foldWorktreeCase);
616​
617 const listDirectory = (directory: string) =>
618 fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
619​
620 const statOption = (target: string) =>
621 fileSystem.stat(target).pipe(Effect.asSome, Effect.orElseSucceed(Option.none));
622​
623 const directoryIdentity = Effect.fn("AgentSessionScanner.directoryIdentity")(function* (
624 target: string,
625 knownStats?: FileSystem.File.Info,
626 ) {
627 const resolved = path.resolve(target);
628 const stats = knownStats === undefined ? yield* statOption(resolved) : Option.some(knownStats);
629 if (Option.isSome(stats) && Option.isSome(stats.value.ino) && stats.value.ino.value > 0n) {
630 return `inode:${stats.value.dev}:${stats.value.ino.value}`;
631 }
632 const realPath = yield* fileSystem
633 .realPath(resolved)
634 .pipe(Effect.orElseSucceed(() => resolved));
635 return `path:${normalizeProjectPathForComparison(realPath)}`;
636 });
637​
638 /**
639 * When it points into a `worktrees/` directory the checkout is a linked worktree, which
640 * onboarding skips because its history belongs to the main checkout. Submodules use the same
641 * pointer shape but live under `modules/`, and are offered like any other repository.
642 */
643 const readGitIdentity = Effect.fn("AgentSessionScanner.readGitIdentity")(function* (
644 directory: string,
645 ): Effect.fn.Return<
646 | { readonly _tag: "Repository"; readonly git: AgentSessionProjectGit | null }
647 | { readonly _tag: "Worktree" }
648 | { readonly _tag: "NotGit" }
649 > {
650 const gitPath = path.join(directory, ".git");
651 const gitStats = yield* statOption(gitPath);
652 if (Option.isNone(gitStats)) return { _tag: "NotGit" } as const;
653 let gitDir = gitPath;
654 if (gitStats.value.type !== "Directory") {
655 const pointer = yield* fileSystem
656 .readFileString(gitPath)
657 .pipe(Effect.orElseSucceed(() => ""));
658 const target = /^gitdir:\s*(.+)$/m.exec(pointer)?.[1]?.trim();
659 if (target === undefined || target.length === 0) return { _tag: "NotGit" } as const;
660 gitDir = path.resolve(directory, target);
661 if (/[\\/]worktrees[\\/][^\\/]+[\\/]?$/.test(gitDir)) return { _tag: "Worktree" } as const;
662 }
663 const configText = yield* fileSystem
664 .readFileString(path.join(gitDir, "config"))
665 .pipe(Effect.orElseSucceed(() => ""));
666 const originUrl = parseOriginUrlFromGitConfig(configText);
667 return {
668 _tag: "Repository",
669 git: {
670 remoteKey: originUrl === null ? null : normalizeGitRemoteUrl(originUrl),
671 repository: parseGitHubRepositoryNameWithOwnerFromRemoteUrl(originUrl),
672 },
673 } as const;
674 });
675​
676 const readCwd = Effect.fn("AgentSessionScanner.readCwd")(function* (
677 transcript: TranscriptCandidate,
678 budget: MetadataReadBudget,
679 ) {
680 if (transcript.size === 0) return null;
681 if (
682 budget.bytesRemaining === 0 ||
683 budget.operationsRemaining < 2 ||
684 budget.recordsRemaining === 0
685 ) {
686 budget.truncated = true;
687 return null;
688 }
689 budget.operationsRemaining -= 1;
690 return yield* Effect.scoped(
691 fileSystem.open(transcript.filePath, { flag: "r" }).pipe(
692 Effect.flatMap((file) =>
693 Effect.gen(function* () {
694 const decoder = new TextDecoder();
695 let remaining = "";
696 let bytesRead = 0;
697 let recordsRead = 0;
698 const maxBytes = Math.min(MAX_TRANSCRIPT_SCAN_BYTES, transcript.size);
699 const reserveRecord = () => {
700 if (
701 recordsRead === MAX_METADATA_RECORDS_PER_TRANSCRIPT ||
702 budget.recordsRemaining === 0
703 ) {
704 budget.truncated = true;
705 return false;
706 }
707 recordsRead += 1;
708 budget.recordsRemaining -= 1;
709 return true;
710 };
711 const readLastRecord = () => {
712 const record = remaining + decoder.decode();
713 return record.length === 0 || !reserveRecord() ? null : extractCwd(record.trim());
714 };
715​
716 while (bytesRead < maxBytes) {
717 if (budget.bytesRemaining === 0 || budget.operationsRemaining === 0) {
718 budget.truncated = true;
719 return null;
720 }
721 const readSize = Math.min(
722 METADATA_READ_BYTES,
723 maxBytes - bytesRead,
724 budget.bytesRemaining,
725 );
726 budget.operationsRemaining -= 1;
727 budget.bytesRemaining -= readSize;
728 const next = yield* file.readAlloc(readSize);
729 if (Option.isNone(next)) {
730 return readLastRecord();
731 }
732​
733 bytesRead += next.value.byteLength;
734 remaining += decoder.decode(next.value, { stream: true });
735 const lines = remaining.split("\n");
736 remaining = lines.pop() ?? "";
737​
738 for (const line of lines) {
739 if (!reserveRecord()) return null;
740 const cwd = extractCwd(line.trim());
741 if (cwd !== null) return cwd;
742 }
743 }
744​
745 if (bytesRead < transcript.size) {
746 budget.truncated = true;
747 return null;
748 }
749 return readLastRecord();
750 }),
751 ),
752 ),
753 ).pipe(Effect.orElseSucceed(() => null));
754 });
755​
756 const readTranscript = Effect.fn("AgentSessionScanner.readTranscript")(function* (
757 filePath: string,
758 expected: ReturnType<typeof transcriptIdentity>,
759 recordLimit: number,
760 source: AgentSessionSource,
761 ) {
762 if (expected.size > MAX_IMPORTED_TRANSCRIPT_BYTES) return null;
763​
764 return yield* Effect.scoped(
765 fileSystem.open(filePath, { flag: "r" }).pipe(
766 Effect.flatMap((file) =>
767 Effect.gen(function* () {
768 if (!sameTranscriptIdentity(expected, transcriptIdentity(filePath, yield* file.stat))) {
769 return null;
770 }
771 const records: Array<DecodedTranscriptRecord> = [];
772 let historyBytes = 0;
773 let recordBytes = 0;
774 let recordCount = 0;
775 let bytesRead = 0;
776 const reserve = (bytes: number) => {
777 recordBytes += bytes;
778 if (historyBytes + recordBytes > MAX_IMPORT_HISTORY_BYTES) {
779 throw new TranscriptJsonLimitError(
780 "Transcript selected history exceeds the 32 MiB memory budget",
781 );
782 }
783 };
784 let reader = createTranscriptJsonReader(reserve, selectTranscriptPath);
785 let decoder = new TextDecoder();
786 let recordStarted = false;
787​
788 const finishRecord = () => {
789 reader.write(decoder.decode());
790 recordCount += 1;
791 if (recordCount > recordLimit) return false;
792 const decoded = decodeTranscriptValue(reader.finish());
793 if (Option.isSome(decoded) && shouldRetainDecodedRecord(source, decoded.value)) {
794 records.push(decoded.value);
795 historyBytes += recordBytes;
796 }
797 recordBytes = 0;
798 reader = createTranscriptJsonReader(reserve, selectTranscriptPath);
799 decoder = new TextDecoder();
800 recordStarted = false;
801 return true;
802 };
803​
804 while (bytesRead < expected.size) {
805 const next = yield* file.readAlloc(
806 Math.min(TRANSCRIPT_PREFIX_BYTES, expected.size - bytesRead),
807 );
808 if (Option.isNone(next)) {
809 return null;
810 }
811​
812 bytesRead += next.value.byteLength;
813 const withinBudget = yield* Effect.try(() => {
814 let start = 0;
815 while (start < next.value.byteLength) {
816 const newline = next.value.indexOf(10, start);
817 const end = newline === -1 ? next.value.byteLength : newline;
818 recordStarted = true;
819 reader.write(decoder.decode(next.value.subarray(start, end), { stream: true }));
820 if (newline === -1) break;
821 if (!finishRecord()) return false;
822 start = newline + 1;
823 }
824 return true;
825 });
826 if (!withinBudget) return null;
827 }
828​
829 if (recordStarted && !(yield* Effect.try(finishRecord))) return null;
830 return sameTranscriptIdentity(expected, transcriptIdentity(filePath, yield* file.stat))
831 ? { records, recordCount }
832 : null;
833 }),
834 ),
835 ),
836 ).pipe(
837 Effect.catch((cause) =>
838 Effect.logWarning("Could not read imported transcript", { filePath, cause }).pipe(
839 Effect.as(null),
840 ),
841 ),
842 );
843 });
844​
845 const resolveClaudeConfigDir = (homePath: string, environmentHome?: string): string => {
846 const configured = homePath.trim();
847 if (configured.length > 0) {
848 return path.resolve(expandHomePath(configured, homeDir));
849 }
850 const fromEnvironment = environmentHome?.trim() ?? "";
851 if (fromEnvironment.length > 0) {
852 return path.resolve(expandHomePath(fromEnvironment, homeDir));
853 }
854 return path.join(homeDir, ".claude");
855 };
856​
857 const discoverClaudeTranscripts = Effect.fn("AgentSessionScanner.discoverClaudeTranscripts")(
858 function* (homePath: string, providerInstanceId: ProviderInstanceId, operationBudget: number) {
859 const projectsDir = path.join(homePath, "projects");
860 let operationsRemaining = operationBudget;
861 let truncated = false;
862 const readDirectory = (directory: string) => {
863 if (operationsRemaining <= 0) {
864 truncated = true;
865 return Effect.succeed<ReadonlyArray<string>>([]);
866 }
867 operationsRemaining -= 1;
868 return listDirectory(directory);
869 };
870 const projectDirectories = yield* readDirectory(projectsDir);
871 const transcripts: Array<TranscriptCandidate> = [];
872​
873 for (const projectDirectory of projectDirectories) {
874 if (operationsRemaining <= 0) {
875 truncated = true;
876 break;
877 }
878 const directory = path.join(projectsDir, projectDirectory);
879 const directoryTranscripts = (yield* readDirectory(directory))
880 .filter((entry) => entry.endsWith(".jsonl"))
881 .map((entry) => path.join(directory, entry));
882​
883 for (const filePath of directoryTranscripts) {
884 if (operationsRemaining <= 0) {
885 truncated = true;
886 break;
887 }
888 operationsRemaining -= 1;
889 const stats = yield* statOption(filePath);
890 if (
891 Option.isNone(stats) ||
892 stats.value.type !== "File" ||
893 Option.isNone(stats.value.mtime)
894 ) {
895 continue;
896 }
897 transcripts.push({
898 filePath,
899 mtimeMs: stats.value.mtime.value.getTime(),
900 providerInstanceId,
901 size: Number(stats.value.size),
902 });
903 }
904 }
905 return { transcripts, truncated };
906 },
907 );
908​
909 const discoverCodexTranscripts = Effect.fn("AgentSessionScanner.discoverCodexTranscripts")(
910 function* (homePath: string, providerInstanceId: ProviderInstanceId, operationBudget: number) {
911 const sessionsDir = path.join(homePath, "sessions");
912​
913 const transcripts: Array<TranscriptCandidate> = [];
914 let operationsRemaining = operationBudget;
915 let truncated = false;
916 const readDirectory = (directory: string) => {
917 if (operationsRemaining <= 0) {
918 truncated = true;
919 return Effect.succeed<ReadonlyArray<string>>([]);
920 }
921 operationsRemaining -= 1;
922 return listDirectory(directory);
923 };
924 for (const year of (yield* readDirectory(sessionsDir)).toSorted().toReversed()) {
925 if (operationsRemaining <= 0) {
926 truncated = true;
927 break;
928 }
929 for (const month of (yield* readDirectory(path.join(sessionsDir, year)))
930 .toSorted()
931 .toReversed()) {
932 if (operationsRemaining <= 0) {
933 truncated = true;
934 break;
935 }
936 for (const day of (yield* readDirectory(path.join(sessionsDir, year, month)))
937 .toSorted()
938 .toReversed()) {
939 if (operationsRemaining <= 0) {
940 truncated = true;
941 break;
942 }
943 const directory = path.join(sessionsDir, year, month, day);
944 for (const entry of (yield* readDirectory(directory)).toSorted().toReversed()) {
945 if (!entry.startsWith("rollout-") || !entry.endsWith(".jsonl")) continue;
946 if (operationsRemaining <= 0) {
947 truncated = true;
948 break;
949 }
950 const filePath = path.join(directory, entry);
951 operationsRemaining -= 1;
952 const stats = yield* statOption(filePath);
953 if (
954 Option.isSome(stats) &&
955 stats.value.type === "File" &&
956 Option.isSome(stats.value.mtime)
957 ) {
958 transcripts.push({
959 filePath,
960 mtimeMs: stats.value.mtime.value.getTime(),
961 providerInstanceId,
962 size: Number(stats.value.size),
963 });
964 }
965 }
966 }
967 }
968 }
969 return { transcripts, truncated };
970 },
971 );
972​
973 const groupTranscriptsByCwd = Effect.fn("AgentSessionScanner.groupTranscriptsByCwd")(function* (
974 source: AgentSessionSource,
975 transcripts: ReadonlyArray<TranscriptCandidate>,
976 budget: MetadataReadBudget,
977 ) {
978 const byOwnerAndCwd = new Map<
979 string,
980 {
981 cwd: string;
982 providerInstanceId: ProviderInstanceId;
983 lastActiveAtMs: number;
984 transcripts: Array<{ filePath: string; mtimeMs: number }>;
985 }
986 >();
987​
988 for (const transcript of transcripts) {
989 const cwd = yield* readCwd(transcript, budget);
990 if (cwd === null) continue;
991 const key = `${transcript.providerInstanceId}\0${cwd}`;
992 const existing = byOwnerAndCwd.get(key);
993 if (existing) {
994 existing.lastActiveAtMs = Math.max(existing.lastActiveAtMs, transcript.mtimeMs);
995 existing.transcripts.push(transcript);
996 } else {
997 byOwnerAndCwd.set(key, {
998 cwd,
999 providerInstanceId: transcript.providerInstanceId,
1000 lastActiveAtMs: transcript.mtimeMs,
1001 transcripts: [transcript],
1002 });
1005​
1006 return Array.from(byOwnerAndCwd.values(), (group): RawCandidate => ({
1007 cwd: group.cwd,
1008 source,
1009 providerInstanceId: group.providerInstanceId,
1010 threadCount: group.transcripts.length,
1011 lastActiveAtMs: group.lastActiveAtMs,
1012 transcripts: group.transcripts,
1013 }));
1014 });
1015​
1016 const collectCandidates = Effect.fn("AgentSessionScanner.collectCandidates")(function* () {
1017 const settings = yield* serverSettings.getSettings.pipe(
1018 Effect.mapError((cause) => new AgentSessionScanError({ operation: "read-settings", cause })),
1019 );
1020​
1021 const raw: Array<RawCandidate> = [];
1022 let truncated = false;
1023​
1024 for (const source of ["claudeAgent", "codex"] as const) {
1025 const instances: Array<{
1026 readonly instanceId: ProviderInstanceId;
1027 readonly config: ProviderInstanceConfig;
1028 }> = Object.entries(settings.providerInstances)
1029 .filter(
1030 ([, instance]) => instance.driver === source && resolveProviderInstanceEnabled(instance),
1032 .map(([instanceId, config]) => ({
1033 instanceId: ProviderInstanceId.make(instanceId),
1034 config,
1035 }));
1036 if (!Object.hasOwn(settings.providerInstances, source)) {
1037 const defaultInstance = {
1038 instanceId: ProviderInstanceId.make(source),
1039 config: { driver: ProviderDriverKind.make(source) },
1040 };
1041 if (resolveProviderInstanceEnabled(defaultInstance.config)) {
1042 instances.push(defaultInstance);
1045​
1046 instances.sort((left, right) => {
1047 const leftDefault = left.instanceId === source ? 0 : 1;
1048 const rightDefault = right.instanceId === source ? 0 : 1;
1049 return leftDefault - rightDefault;
1050 });
1051 const homes: Array<{ homePath: string; providerInstanceId: ProviderInstanceId }> = [];
1052 const seenHomes = new Set<string>();
1053 for (const { instanceId, config: instance } of instances) {
1054 const homeVariable = source === "claudeAgent" ? "CLAUDE_CONFIG_DIR" : "CODEX_HOME";
1055 const environmentHome =
1056 instance.environment?.findLast((variable) => variable.name === homeVariable)?.value ??
1057 hostEnvironment[homeVariable];
1058​
1059 let homePath: string;
1060 if (source === "claudeAgent") {
1061 const config = decodeClaudeSettings(instance.config ?? {});
1062 if (Option.isNone(config)) continue;
1063 homePath = resolveClaudeConfigDir(config.value.homePath, environmentHome);
1064 } else {
1065 const config = decodeCodexSettings(instance.config ?? {});
1066 if (Option.isNone(config)) continue;
1067 const codexSettings =
1068 config.value.homePath.trim().length === 0 &&
1069 config.value.shadowHomePath.trim().length === 0 &&
1070 environmentHome?.trim()
1071 ? { ...config.value, homePath: environmentHome }
1072 : config.value;
1073 const layout = yield* resolveCodexHomeLayout(codexSettings).pipe(
1074 Effect.provideService(Path.Path, path),
1075 );
1076 homePath = layout.sharedHomePath;
1078​
1079 const homeKey = `${source}\0${yield* directoryIdentity(homePath)}`;
1080 if (seenHomes.has(homeKey)) continue;
1081 seenHomes.add(homeKey);
1082 homes.push({ homePath, providerInstanceId: instanceId });
1084​
1085 const transcriptCandidates: Array<TranscriptCandidate> = [];
1086 const baseOperationBudget = Math.floor(
1087 MAX_DISCOVERY_OPERATIONS_PER_SOURCE / Math.max(1, homes.length),
1088 );
1089 const extraOperationBudgets = MAX_DISCOVERY_OPERATIONS_PER_SOURCE % Math.max(1, homes.length);
1090 for (const [index, home] of homes.entries()) {
1091 const operationBudget = baseOperationBudget + (index < extraOperationBudgets ? 1 : 0);
1092 if (operationBudget === 0) {
1093 truncated = true;
1094 continue;
1096 const discovered = yield* source === "claudeAgent"
1097 ? discoverClaudeTranscripts(home.homePath, home.providerInstanceId, operationBudget)
1098 : discoverCodexTranscripts(home.homePath, home.providerInstanceId, operationBudget);
1099 truncated ||= discovered.truncated;
1100 transcriptCandidates.push(...discovered.transcripts);
1102​
1103 transcriptCandidates.sort(
1104 (left, right) =>
1105 right.mtimeMs - left.mtimeMs || left.filePath.localeCompare(right.filePath),
1106 );
1107 if (transcriptCandidates.length > MAX_TRANSCRIPTS_PER_SOURCE) {
1108 truncated = true;
1110 const selectedTranscripts = selectMetadataTranscripts(transcriptCandidates);
1111 const metadataBudget: MetadataReadBudget = {
1112 bytesRemaining: MAX_METADATA_BYTES_PER_SOURCE,
1113 operationsRemaining: MAX_METADATA_OPERATIONS_PER_SOURCE,
1114 recordsRemaining: MAX_METADATA_RECORDS_PER_SOURCE,
1115 truncated: false,
1116 };
1117 raw.push(...(yield* groupTranscriptsByCwd(source, selectedTranscripts, metadataBudget)));
1118 truncated ||= metadataBudget.truncated;
1120​
1121 return { candidates: raw, truncated };
1122 });
1123​
1124 let cachedCandidates: ReadonlyArray<RawCandidate> | null = null;
1125​
1126 const scan: AgentSessionScanner["Service"]["scan"] = Effect.gen(function* () {
1127 const { candidates: raw, truncated } = yield* collectCandidates();
1128 cachedCandidates = raw;
1129​
1130 const merged = new Map<
1131 string,
1133 path: string;
1134 sources: Array<AgentSessionSource>;
1135 threadCount: number;
1136 lastActiveAtMs: number | null;
1137 git: AgentSessionProjectGit | null;
1139 >();
1140 const directoryKeys = new Map<string, string>();
1141 const gitIdentities = new Map<string, AgentSessionProjectGit | null>();
1142​
1143 for (const candidate of raw) {
1144 const expanded = expandHomePath(candidate.cwd.trim(), homeDir);
1145 if (!path.isAbsolute(expanded)) continue;
1146 const resolved = path.resolve(expanded);
1147 if (isExcludedProjectPath(resolved)) continue;
1148 let key = directoryKeys.get(resolved);
1149 if (key === undefined) {
1150 const stats = yield* statOption(resolved);
1151 if (Option.isNone(stats) || stats.value.type !== "Directory") {
1152 directoryKeys.set(resolved, "");
1153 continue;
1155 const realPath = yield* fileSystem
1156 .realPath(resolved)
1157 .pipe(Effect.orElseSucceed(() => resolved));
1158 // A symlink can point into the worktrees directory even when its own
1159 // spelling doesn't; check again with links resolved.
1160 if (isExcludedProjectPath(realPath)) {
1161 key = "";
1162 } else {
1163 const gitIdentity = yield* readGitIdentity(resolved);
1164 if (gitIdentity._tag === "Worktree") {
1165 key = "";
1166 } else {
1167 key = yield* directoryIdentity(resolved, stats.value);
1168 gitIdentities.set(key, gitIdentity._tag === "Repository" ? gitIdentity.git : null);
1171 directoryKeys.set(resolved, key);
1173 if (key === "") continue;
1174​
1175 const existing = merged.get(key);
1176 if (!existing) {
1177 merged.set(key, {
1178 path: resolved,
1179 sources: [candidate.source],
1180 threadCount: candidate.threadCount,
1181 lastActiveAtMs: candidate.lastActiveAtMs,
1182 git: gitIdentities.get(key) ?? null,
1183 });
1184 continue;
1186 if (!existing.sources.includes(candidate.source)) {
1187 existing.sources.push(candidate.source);
1189 existing.threadCount += candidate.threadCount;
1190 existing.lastActiveAtMs =
1191 existing.lastActiveAtMs === null || candidate.lastActiveAtMs === null
1192 ? (existing.lastActiveAtMs ?? candidate.lastActiveAtMs)
1193 : Math.max(existing.lastActiveAtMs, candidate.lastActiveAtMs);
1195​
1196 // Resolve persisted roots too. A project and a transcript can name
1197 // different symlinks to the same directory.
1198 const importedProjects = yield* projectStore
1199 .listShells()
1200 .pipe(
1201 Effect.mapError(
1202 (cause) => new AgentSessionScanError({ operation: "read-projects", cause }),
1203 ),
1204 );
1205 const importedProjectsByRoot = new Map<string, (typeof importedProjects)[number]>();
1206 for (const project of importedProjects) {
1207 const projectRoot = path.resolve(expandHomePath(project.workspaceRoot, homeDir));
1208 importedProjectsByRoot.set(normalizeProjectPathForComparison(projectRoot), project);
1209 importedProjectsByRoot.set(yield* directoryIdentity(projectRoot), project);
1211​
1212 const candidates: Array<AgentSessionProjectCandidate> = [];
1213 for (const [key, entry] of merged.entries()) {
1214 const importedProject =
1215 importedProjectsByRoot.get(normalizeProjectPathForComparison(entry.path)) ??
1216 importedProjectsByRoot.get(key);
1217 const candidatePath = importedProject?.workspaceRoot ?? entry.path;
1218 candidates.push({
1219 path: candidatePath,
1220 title: path.basename(candidatePath) || candidatePath,
1221 ...(importedProject === undefined ? {} : { projectId: importedProject.id }),
1222 sources: entry.sources,
1223 threadCount: entry.threadCount,
1224 lastActiveAt:
1225 entry.lastActiveAtMs === null
1226 ? null
1227 : DateTime.formatIso(DateTime.makeUnsafe(entry.lastActiveAtMs)),
1228 alreadyImported: importedProject !== undefined,
1229 git: entry.git,
1230 });
1232​
1233 candidates.sort((left, right) => {
1234 if (left.lastActiveAt === right.lastActiveAt) return left.path.localeCompare(right.path);
1235 if (left.lastActiveAt === null) return 1;
1236 if (right.lastActiveAt === null) return -1;
1237 return right.lastActiveAt.localeCompare(left.lastActiveAt);
1238 });
1239​
1240 return {
1241 candidates,
1242 scannedAt: DateTime.formatIso(yield* DateTime.now),
1243 ...(truncated ? { truncated: true } : {}),
1244 };
1245 });
1246​
1247 const prepareRecentThreads = Effect.fn("AgentSessionScanner.prepareRecentThreads")(function* (
1248 workspaceRoot: string,
1249 completedSources: ReadonlyArray<AgentSessionImportSource>,
1250 ) {
1251 const root = path.resolve(expandHomePath(workspaceRoot, homeDir));
1252 const realRoot = yield* fileSystem.realPath(root).pipe(Effect.orElseSucceed(() => root));
1253 if (isExcludedProjectPath(root) || isExcludedProjectPath(realRoot)) return Stream.empty;
1254 const rootIdentity = yield* directoryIdentity(root);
1255 const nowMs = DateTime.toEpochMillis(yield* DateTime.now);
1256 const cutoffMs = nowMs - RECENT_THREAD_WINDOW_MS;
1257​
1258 const candidates = cachedCandidates ?? (yield* collectCandidates()).candidates;
1259 cachedCandidates = candidates;
1260​
1261 const eligibleTranscripts: Array<{
1262 readonly candidate: RawCandidate;
1263 readonly transcript: RawCandidate["transcripts"][number] & { readonly mtimeMs: number };
1264 }> = [];
1265 for (const candidate of candidates) {
1266 const expanded = expandHomePath(candidate.cwd.trim(), homeDir);
1267 if (!path.isAbsolute(expanded)) continue;
1268 const resolved = path.resolve(expanded);
1269 if ((yield* directoryIdentity(resolved)) !== rootIdentity) continue;
1270​
1271 for (const transcript of candidate.transcripts) {
1272 if (
1273 transcript.mtimeMs === null ||
1274 transcript.mtimeMs < cutoffMs ||
1275 transcript.mtimeMs > nowMs
1276 ) {
1277 continue;
1279 eligibleTranscripts.push({
1280 candidate,
1281 transcript: { ...transcript, mtimeMs: transcript.mtimeMs },
1282 });
1285​
1286 eligibleTranscripts.sort((left, right) => {
1287 if (left.transcript.mtimeMs !== right.transcript.mtimeMs) {
1288 return right.transcript.mtimeMs - left.transcript.mtimeMs;
1290 return left.transcript.filePath.localeCompare(right.transcript.filePath);
1291 });
1292​
1293 const completedByFile = Map.groupBy(
1294 completedSources,
1295 (source) => `${source.providerInstanceId}\0${source.filePath}`,
1296 );
1297 const importedSessions = new Set<string>();
1298 let bytesRemaining = MAX_IMPORT_BYTES;
1299 let transcriptsRemaining = MAX_IMPORT_TRANSCRIPTS;
1300 let recordsRemaining = MAX_IMPORT_RECORDS;
1301 return Stream.fromIteratorSucceed(eligibleTranscripts.values(), 1).pipe(
1302 Stream.mapEffect(({ candidate, transcript }) =>
1303 Effect.gen(function* () {
1304 const completed = completedByFile.get(
1305 `${candidate.providerInstanceId}\0${transcript.filePath}`,
1306 );
1307 if (
1308 completed === undefined &&
1309 (transcriptsRemaining === 0 || bytesRemaining === 0 || recordsRemaining === 0)
1310 ) {
1311 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
1313 const stats = yield* statOption(transcript.filePath);
1314 if (Option.isNone(stats) || stats.value.type !== "File") {
1315 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
1317 const identity = transcriptIdentity(transcript.filePath, stats.value);
1318 const completedSource = completed?.find(
1319 (source) =>
1320 source.provider === candidate.source && sameTranscriptIdentity(source, identity),
1321 );
1322 if (completedSource !== undefined) {
1323 const sessionKey = `${completedSource.providerInstanceId}\0${completedSource.providerSessionId}`;
1324 if (importedSessions.has(sessionKey)) return Option.none<AgentSessionRecentThread>();
1325 importedSessions.add(sessionKey);
1326 return Option.some<AgentSessionRecentThread>({
1327 _tag: "AlreadyImported",
1328 source: completedSource,
1329 });
1331 if (
1332 transcriptsRemaining === 0 ||
1333 recordsRemaining === 0 ||
1334 identity.size > MAX_IMPORTED_TRANSCRIPT_BYTES ||
1335 identity.size > bytesRemaining
1336 ) {
1337 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
1339 transcriptsRemaining -= 1;
1340 bytesRemaining -= identity.size;
1341 const snapshot = yield* readTranscript(
1342 transcript.filePath,
1343 identity,
1344 recordsRemaining,
1345 candidate.source,
1346 );
1347 if (snapshot === null) {
1348 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
1350 recordsRemaining -= snapshot.recordCount;
1351​
1352 let snapshotCwd: string | null = null;
1353 for (const record of snapshot.records) {
1354 snapshotCwd = extractDecodedCwd(record);
1355 if (snapshotCwd !== null) break;
1357 if (snapshotCwd === null) {
1358 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
1360 const expandedCwd = expandHomePath(snapshotCwd.trim(), homeDir);
1361 if (
1362 !path.isAbsolute(expandedCwd) ||
1363 (yield* directoryIdentity(path.resolve(expandedCwd))) !== rootIdentity
1364 ) {
1365 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
1367​
1368 const parsedThread = parseAgentSessionRecords(
1370 source: candidate.source,
1371 providerInstanceId: candidate.providerInstanceId,
1372 fallbackSessionId: path.basename(transcript.filePath, ".jsonl"),
1373 lastActiveAtMs: transcript.mtimeMs,
1374 },
1375 snapshot.records,
1376 );
1377 if (parsedThread === null) {
1378 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
1380​
1381 const source: AgentSessionImportSource = {
1382 ...identity,
1383 provider: parsedThread.source,
1384 providerInstanceId: parsedThread.providerInstanceId,
1385 providerSessionId: parsedThread.providerSessionId,
1386 };
1387 const sessionKey = `${parsedThread.providerInstanceId}\0${parsedThread.providerSessionId}`;
1388 if (importedSessions.has(sessionKey)) {
1389 return Option.some<AgentSessionRecentThread>({ _tag: "Duplicate", source });
1391 importedSessions.add(sessionKey);
1392 return Option.some<AgentSessionRecentThread>({
1393 _tag: "Importable",
1394 thread: parsedThread,
1395 source,
1396 });
1397 }).pipe(importReadLock.withPermits(1)),
1398 ),
1399 Stream.map(Option.toArray),
1400 Stream.flattenIterable,
1401 );
1402 });
1403​
1404 const recentThreads: AgentSessionScanner["Service"]["recentThreads"] = (
1405 workspaceRoot,
1406 completedSources = [],
1407 ) => Stream.unwrap(prepareRecentThreads(workspaceRoot, completedSources));
1408​
1409 return AgentSessionScanner.of({ scan, recentThreads });
1410});
1411​
1412export const layer = Layer.effect(AgentSessionScanner, make);