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

AgentSessionScanner.ts

1,489 lines56.5 KB

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