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

AgentSessionScanner.ts

1,429 lines52.8 KB

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