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

AgentSessionScanner.ts

1,475 lines55.1 KB

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