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

AgentSessionScanner.ts

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