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

AgentSessionScanner.ts

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