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

AgentSessionScanner.ts

1,466 lines54.7 KB

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