TypeScript
fix(server): agent session scans no longer hang the server on an unreadable .git/config (#23690)
Julius Marminge71a7bf9516e3
diff --git a/apps/server/src/project/AgentSessionScanner.test.ts b/apps/server/src/project/AgentSessionScanner.test.tsindex 688b974e765..88408c69c7b 100644--- a/apps/server/src/project/AgentSessionScanner.test.ts+++ b/apps/server/src/project/AgentSessionScanner.test.ts@@ -1,4 +1,8 @@+// @effect-diagnostics nodeBuiltinImport:off - FIFO gates must be released with a synchronous+// open on the main thread, because the Effect FileSystem queues behind the pinned libuv pool.import * as NodeServices from "@effect/platform-node/NodeServices";+import * as NodeChildProcess from "node:child_process";+import * as NodeFS from "node:fs";import * as NodeOS from "node:os";import { describe, expect, it } from "@effect/vitest";import {@@ -9,9 +13,11 @@ import {ProviderInstanceId,type ServerSettings as ContractServerSettings,} from "@t3tools/contracts";+import * as HostProcess from "@t3tools/shared/HostProcess";import { symlinksSupported } from "@t3tools/shared/testing/symlinks";import * as DateTime from "effect/DateTime";import * as Effect from "effect/Effect";+import * as Fiber from "effect/Fiber";import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";import * as Option from "effect/Option";@@ -248,6 +254,42 @@ const makeFileIdentityFixture = Effect.fn("AgentSessionScanner.test.makeFileIden},);+const LIBUV_POOL_SIZE = Number(process.env.UV_THREADPOOL_SIZE ?? 4);++/**+ * Opening a FIFO for reading waits in `open()` until a writer appears, like a+ * TCC-protected file in a headless macOS daemon, and pins one libuv pool thread+ * that fiber interruption cannot free. The finalizer opens it for writing on the+ * main thread, which releases every waiting reader even with the pool exhausted.+ */+const makeOpenGate = Effect.fn("AgentSessionScanner.test.makeOpenGate")(function* (+ gatePath: string,+) {+ NodeChildProcess.execFileSync("mkfifo", [gatePath]);+ yield* Effect.addFinalizer(() =>+ Effect.sync(() => {+ try {+ NodeFS.closeSync(+ NodeFS.openSync(gatePath, NodeFS.constants.O_WRONLY | NodeFS.constants.O_NONBLOCK),+ );+ } catch {+ // ENXIO: no reader is waiting.+ }+ }),+ );+});++/**+ * Resolves once a reader has opened the FIFO, so its read deadline is already+ * scheduled on the TestClock. The writer stays open until the scope closes, so+ * the reader sees no EOF and has to wait out that deadline.+ */+const awaitGateReader = (gatePath: string) =>+ Effect.acquireRelease(+ Effect.promise(() => NodeFS.promises.open(gatePath, NodeFS.constants.O_WRONLY)),+ (handle) => Effect.promise(() => handle.close()),+ );+it.layer(NodeServices.layer)("AgentSessionScanner", (it) => {describe("scan", () => {it.effect("reads Claude project cwds from transcripts, newest first", () =>@@ -1807,6 +1849,255 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => {});});+describe.skipIf(HostProcess.Platform.defaultValue() === "win32")(+ "AgentSessionScanner scan with a git config open() that never returns",+ () => {+ it.effect(+ "completes every scan and leaves the libuv pool free when .git/config is a FIFO",+ () =>+ Effect.gen(function* () {+ const path = yield* Path.Path;+ const fileSystem = yield* FileSystem.FileSystem;+ const claudeHomePath = yield* makeTempDir("t3code-claude-home-");+ const codexHomePath = yield* makeTempDir("t3code-codex-home-");+ const repo = yield* makeTempDir("t3code-workspace-fifo-config-");+ yield* fileSystem.makeDirectory(path.join(repo, ".git"));+ yield* makeOpenGate(path.join(repo, ".git", "config"));+ const transcriptPath = path.join(claudeHomePath, "projects", "-fifo", "a.jsonl");+ yield* writeTranscript({+ filePath: transcriptPath,+ contents: claudeSessionLine(repo),+ mtimeMs: Date.parse("2026-05-03T00:00:00.000Z"),+ });++ for (let attempt = 1; attempt <= LIBUV_POOL_SIZE + 1; attempt++) {+ const scan = yield* Effect.forkChild(+ runScan({ claudeHomePath, codexHomePath }).pipe(+ Effect.map(({ candidates }) => candidates.map(({ path }) => path)),+ ),+ );+ yield* Effect.scoped(+ Effect.gen(function* () {+ yield* awaitGateReader(path.join(repo, ".git", "config"));+ yield* TestClock.adjust("2 seconds");+ expect(yield* Fiber.join(scan), `scan ${attempt}`).toEqual([repo]);+ }),+ );+ }+ // Hangs if the scans left libuv pool threads stuck in open().+ yield* fileSystem.readFileString(transcriptPath);+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),+ );++ it.effect("still reads the git identity of repositories next to a blocked one", () =>+ Effect.gen(function* () {+ const path = yield* Path.Path;+ const fileSystem = yield* FileSystem.FileSystem;+ const claudeHomePath = yield* makeTempDir("t3code-claude-home-");+ const codexHomePath = yield* makeTempDir("t3code-codex-home-");+ const repos = [+ yield* makeTempDir("t3code-workspace-before-"),+ yield* makeTempDir("t3code-workspace-blocked-"),+ yield* makeTempDir("t3code-workspace-after-"),+ ] as const;+ for (const [index, repo] of repos.entries()) {+ yield* fileSystem.makeDirectory(path.join(repo, ".git"));+ const configPath = path.join(repo, ".git", "config");+ if (index === 1) yield* makeOpenGate(configPath);+ else+ yield* fileSystem.writeFileString(+ configPath,+ `[remote "origin"]\n\turl = [email protected]:pingdotgg/repo-${index}.git\n`,+ );+ yield* writeTranscript({+ filePath: path.join(claudeHomePath, "projects", `-slug-${index}`, "a.jsonl"),+ contents: claudeSessionLine(repo),+ mtimeMs: Date.parse(`2026-01-0${index + 1}T00:00:00.000Z`),+ });+ }++ for (let attempt = 1; attempt <= 2; attempt++) {+ const scan = yield* Effect.forkChild(runScan({ claudeHomePath, codexHomePath }));+ const result = yield* Effect.scoped(+ Effect.gen(function* () {+ yield* awaitGateReader(path.join(repos[1], ".git", "config"));+ yield* TestClock.adjust("2 seconds");+ return yield* Fiber.join(scan);+ }),+ );+ expect(+ result.candidates.map((candidate) => ({ path: candidate.path, git: candidate.git })),+ `scan ${attempt}`,+ ).toEqual([+ {+ path: repos[2],+ git: { remoteKey: "github.com/pingdotgg/repo-2", repository: "pingdotgg/repo-2" },+ },+ { path: repos[1], git: { remoteKey: null, repository: null } },+ {+ path: repos[0],+ git: { remoteKey: "github.com/pingdotgg/repo-0", repository: "pingdotgg/repo-0" },+ },+ ]);+ }+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),+ );++ it.effect("reads every blocked git config of a scan under one deadline", () =>+ Effect.gen(function* () {+ const path = yield* Path.Path;+ const fileSystem = yield* FileSystem.FileSystem;+ const claudeHomePath = yield* makeTempDir("t3code-claude-home-");+ const codexHomePath = yield* makeTempDir("t3code-codex-home-");+ const root = yield* makeTempDir("t3code-workspace-blocked-configs-");+ const repos = [path.join(root, "repo-a"), path.join(root, "repo-b")];+ for (const repo of repos) {+ yield* fileSystem.makeDirectory(path.join(repo, ".git"), { recursive: true });+ yield* makeOpenGate(path.join(repo, ".git", "config"));+ }+ // Two linked worktrees of one bare repository share its blocked config.+ const bareGitDir = path.join(root, "bare.git");+ yield* fileSystem.makeDirectory(bareGitDir);+ yield* makeOpenGate(path.join(bareGitDir, "config"));+ const worktrees = [path.join(root, "wt-1"), path.join(root, "wt-2")];+ for (const worktree of worktrees) {+ const gitDir = path.join(bareGitDir, "worktrees", path.basename(worktree));+ yield* fileSystem.makeDirectory(gitDir, { recursive: true });+ yield* fileSystem.writeFileString(path.join(gitDir, "commondir"), "../..\n");+ yield* fileSystem.makeDirectory(worktree);+ yield* fileSystem.writeFileString(path.join(worktree, ".git"), `gitdir: ${gitDir}\n`);+ }+ for (const [index, cwd] of [...repos, ...worktrees].entries()) {+ yield* writeTranscript({+ filePath: path.join(claudeHomePath, "projects", `-slug-${index}`, "a.jsonl"),+ contents: claudeSessionLine(cwd),+ mtimeMs: Date.parse(`2026-01-0${index + 1}T00:00:00.000Z`),+ });+ }++ const scan = yield* Effect.forkChild(+ runScan({ claudeHomePath, codexHomePath }).pipe(+ Effect.map(({ candidates }) => candidates.map(({ path }) => path).toSorted()),+ ),+ );+ // Every blocked config is open before any deadline passes; reading them+ // one after another would leave the later ones unopened.+ yield* Effect.forEach(+ [...repos.map((repo) => path.join(repo, ".git")), bareGitDir],+ (gitDir) => awaitGateReader(path.join(gitDir, "config")),+ { concurrency: "unbounded" },+ );+ yield* TestClock.adjust("2 seconds");+ expect(yield* Fiber.join(scan)).toEqual(repos);+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),+ );++ it.effect("completes every scan when a .git pointer file or commondir never opens", () =>+ Effect.gen(function* () {+ const path = yield* Path.Path;+ const fileSystem = yield* FileSystem.FileSystem;+ const claudeHomePath = yield* makeTempDir("t3code-claude-home-");+ const codexHomePath = yield* makeTempDir("t3code-codex-home-");+ const root = yield* makeTempDir("t3code-workspace-blocked-pointers-");+ const pointerCheckout = path.join(root, "pointer");+ yield* fileSystem.makeDirectory(pointerCheckout);+ yield* makeOpenGate(path.join(pointerCheckout, ".git"));+ const worktree = path.join(root, "worktree");+ const worktreeGitDir = path.join(root, "main", ".git", "worktrees", "worktree");+ yield* fileSystem.makeDirectory(worktreeGitDir, { recursive: true });+ yield* makeOpenGate(path.join(worktreeGitDir, "commondir"));+ yield* fileSystem.makeDirectory(worktree);+ yield* fileSystem.writeFileString(+ path.join(worktree, ".git"),+ `gitdir: ${worktreeGitDir}\n`,+ );+ for (const [index, cwd] of [pointerCheckout, worktree].entries()) {+ yield* writeTranscript({+ filePath: path.join(claudeHomePath, "projects", `-slug-${index}`, "a.jsonl"),+ contents: claudeSessionLine(cwd),+ mtimeMs: Date.parse(`2026-01-0${index + 1}T00:00:00.000Z`),+ });+ }++ // One scanner across scans: later scans skip the files that blocked.+ yield* Effect.gen(function* () {+ const scanner = yield* AgentSessionScanner.AgentSessionScanner;+ const scanPaths = scanner.scan.pipe(+ Effect.map(({ candidates }) => candidates.map(({ path }) => path)),+ );+ const first = yield* Effect.forkChild(scanPaths);+ // Pointer files are read first, then the commondir files they lead to.+ for (const gatePath of [+ path.join(pointerCheckout, ".git"),+ path.join(worktreeGitDir, "commondir"),+ ]) {+ yield* Effect.scoped(+ Effect.gen(function* () {+ yield* awaitGateReader(gatePath);+ yield* TestClock.adjust("2 seconds");+ }),+ );+ }+ expect(yield* Fiber.join(first)).toEqual([pointerCheckout]);+ for (let attempt = 2; attempt <= LIBUV_POOL_SIZE + 1; attempt++) {+ expect(yield* scanPaths, `scan ${attempt}`).toEqual([pointerCheckout]);+ }+ }).pipe(Effect.provide(layerScannerTest({ claudeHomePath, codexHomePath })));+ // Hangs if the scans left libuv pool threads stuck in open().+ yield* fileSystem.readFileString(path.join(worktree, ".git"));+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),+ );++ it.effect("reads a once-blocked git config again after the retry interval", () =>+ Effect.gen(function* () {+ const path = yield* Path.Path;+ const fileSystem = yield* FileSystem.FileSystem;+ const claudeHomePath = yield* makeTempDir("t3code-claude-home-");+ const codexHomePath = yield* makeTempDir("t3code-codex-home-");+ const repo = yield* makeTempDir("t3code-workspace-unblocked-config-");+ yield* fileSystem.makeDirectory(path.join(repo, ".git"));+ const configPath = path.join(repo, ".git", "config");+ yield* makeOpenGate(configPath);+ yield* writeTranscript({+ filePath: path.join(claudeHomePath, "projects", "-unblocked", "a.jsonl"),+ contents: claudeSessionLine(repo),+ mtimeMs: Date.parse("2026-05-03T00:00:00.000Z"),+ });+ const gitOfScan = (scan: AgentSessionScanner.AgentSessionScanner["Service"]["scan"]) =>+ scan.pipe(Effect.map(({ candidates }) => candidates.map(({ git }) => git)));++ yield* Effect.gen(function* () {+ const scanner = yield* AgentSessionScanner.AgentSessionScanner;+ const blockedScan = yield* Effect.forkChild(gitOfScan(scanner.scan));+ yield* Effect.scoped(+ Effect.gen(function* () {+ yield* awaitGateReader(configPath);+ yield* TestClock.adjust("2 seconds");+ expect(yield* Fiber.join(blockedScan)).toEqual([+ { remoteKey: null, repository: null },+ ]);+ }),+ );++ yield* fileSystem.remove(configPath);+ yield* fileSystem.writeFileString(+ configPath,+ `[remote "origin"]\n\turl = [email protected]:pingdotgg/unblocked.git\n`,+ );+ expect(yield* gitOfScan(scanner.scan), "a blocked path is skipped for a while").toEqual([+ { remoteKey: null, repository: null },+ ]);++ yield* TestClock.adjust("10 minutes");+ expect(yield* gitOfScan(scanner.scan)).toEqual([+ { remoteKey: "github.com/pingdotgg/unblocked", repository: "pingdotgg/unblocked" },+ ]);+ }).pipe(Effect.provide(layerScannerTest({ claudeHomePath, codexHomePath })));+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),+ );+ },+);+describe("parseAgentSessionTranscript", () => {it.each([false, true])("handles the exact record limit and an interior blank overflow=%s",diff --git a/apps/server/src/project/AgentSessionScanner.ts b/apps/server/src/project/AgentSessionScanner.tsindex bbd3ba5a631..6b75ca91e3b 100644--- a/apps/server/src/project/AgentSessionScanner.ts+++ b/apps/server/src/project/AgentSessionScanner.ts@@ -13,6 +13,7 @@ import {type AgentSessionScanResult,type ProviderInstanceConfig,} from "@t3tools/contracts";+import * as Clock from "effect/Clock";import * as Context from "effect/Context";import * as DateTime from "effect/DateTime";import * as Effect from "effect/Effect";@@ -30,6 +31,7 @@ import { normalizeProjectPathForComparison } from "@t3tools/shared/path";import { repositoryPathFromRemoteUrl } from "@t3tools/source-control-core/server/SourceControlProvider";import * as ServerConfig from "../config.ts";+import * as ProcessRunner from "../processRunner.ts";import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts";import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";@@ -64,6 +66,21 @@ const MAX_IMPORT_BYTES = 4 * 1024 * 1024 * 1024;const MAX_IMPORT_TRANSCRIPTS = 100;const MAX_IMPORT_RECORDS = 100_000;+/**+ * open() of a file under macOS privacy protection waits on a consent prompt+ * that a headless server never gets, and a FIFO waits for a writer. Either+ * pins a libuv pool thread that interruption cannot free, so git files of+ * arbitrary transcript cwds are read by a `cat` child we can kill instead.+ */+const GIT_FILE_READ_DEADLINE = "2 seconds";+const MAX_GIT_FILE_BYTES = 1024 * 1024;+// Reads run concurrently, so each phase waits one deadline per batch of this+// many blocked files rather than one per blocked file.+const GIT_FILE_READ_CONCURRENCY = 16;+// A blocked path is skipped for a while, then read again in case it was fixed.+const BLOCKED_GIT_FILE_RETRY_MS = 5 * 60 * 1000;+const MAX_BLOCKED_GIT_FILE_PATHS = 1024;+const TranscriptContentBlock = Schema.Struct({type: Schema.optional(Schema.String),text: Schema.optional(Schema.String),@@ -718,6 +735,7 @@ function sameTranscriptIdentity(left: TranscriptIdentity, right: TranscriptIdent/** @public */export const make = Effect.gen(function* () {const fileSystem = yield* FileSystem.FileSystem;+ const processRunner = yield* ProcessRunner.ProcessRunner;// Concurrent client imports must not hold multiple selected-history budgets.const importReadLock = yield* Semaphore.make(1);const path = yield* Path.Path;@@ -726,7 +744,8 @@ export const make = Effect.gen(function* () {const projectStore = yield* ProjectStore.ProjectStoreV2;const baseDir = path.resolve(serverConfig.baseDir);const worktreesDir = path.resolve(serverConfig.worktreesDir);- const foldWorktreeCase = (yield* HostProcess.Platform) === "win32";+ const isWindows = (yield* HostProcess.Platform) === "win32";+ const foldWorktreeCase = isWindows;const hostEnvironment = yield* HostProcess.Environment;const homeDir = yield* HostProcess.HomeDirectory;// `/private/tmp` is what macOS reports for sessions started in `/tmp`.@@ -773,48 +792,122 @@ export const make = Effect.gen(function* () {return `path:${normalizeProjectPathForComparison(realPath)}`;});- const readGitIdentity = Effect.fn("AgentSessionScanner.readGitIdentity")(function* (- directory: string,- ): Effect.fn.Return<- | { readonly _tag: "Repository"; readonly git: AgentSessionProjectGit | null }- | { readonly _tag: "Worktree" }- | { readonly _tag: "NotGit" }- > {- const gitPath = path.join(directory, ".git");- const gitStats = yield* statOption(gitPath);- if (Option.isNone(gitStats)) return { _tag: "NotGit" } as const;- let gitDir = gitPath;- if (gitStats.value.type !== "Directory") {- const pointer = yield* fileSystem- .readFileString(gitPath)- .pipe(Effect.orElseSucceed(() => ""));- const target = /^gitdir:\s*(.+)$/m.exec(pointer)?.[1]?.trim();- if (target === undefined || target.length === 0) return { _tag: "NotGit" } as const;- gitDir = path.resolve(directory, target);+ // Paths whose own read outlived the deadline, mapped to when they may be read+ // again. Without this every later scan would wait out the deadline again for+ // each phase that touches them.+ const blockedGitFilePaths = new Map<string, number>();++ /** Reads small files without the libuv pool; "" when missing, unreadable or blocked. */+ const readGitFiles = Effect.fn("AgentSessionScanner.readGitFiles")(function* (+ filePaths: ReadonlyArray<string>,+ ) {+ const unique = Array.from(new Set(filePaths));+ const now = yield* Clock.currentTimeMillis;+ const contents = yield* Effect.forEach(+ unique,+ (filePath) => {+ // No privacy prompts or FIFOs to block open() here.+ if (isWindows) {+ return fileSystem.readFileString(filePath).pipe(Effect.orElseSucceed(() => ""));+ }+ if ((blockedGitFilePaths.get(filePath) ?? 0) > now) return Effect.succeed("");+ blockedGitFilePaths.delete(filePath);+ return processRunner+ .run({+ command: "cat",+ args: ["--", filePath],+ timeout: GIT_FILE_READ_DEADLINE,+ timeoutBehavior: "timedOutResult",+ maxOutputBytes: MAX_GIT_FILE_BYTES,+ outputMode: "truncate",+ })+ .pipe(+ Effect.map((result) => {+ if (result.timedOut) {+ if (blockedGitFilePaths.size >= MAX_BLOCKED_GIT_FILE_PATHS) {+ blockedGitFilePaths.delete(blockedGitFilePaths.keys().next().value!);+ }+ blockedGitFilePaths.set(filePath, now + BLOCKED_GIT_FILE_RETRY_MS);+ }+ return result.code === 0 ? result.stdout : "";+ }),+ Effect.orElseSucceed(() => ""),+ );+ },+ { concurrency: isWindows ? 1 : GIT_FILE_READ_CONCURRENCY },+ );+ return new Map(unique.map((filePath, index) => [filePath, contents[index]!]));+ });++ /** Reads every directory's git identity in three phases of concurrent reads. */+ const readGitIdentities = Effect.fn("AgentSessionScanner.readGitIdentities")(function* (+ directories: ReadonlyArray<string>,+ ) {+ type GitIdentity =+ | { readonly _tag: "Repository"; readonly git: AgentSessionProjectGit | null }+ | { readonly _tag: "Worktree" }+ | { readonly _tag: "NotGit" };+ const identities = new Map<string, GitIdentity>();+ const repositories: Array<{ directory: string; gitDir: string; linkedWorktree: boolean }> = [];+ const pointers: Array<{ directory: string; gitPath: string }> = [];+ for (const directory of directories) {+ const gitPath = path.join(directory, ".git");+ const gitStats = yield* statOption(gitPath);+ if (Option.isNone(gitStats)) identities.set(directory, { _tag: "NotGit" });+ else if (gitStats.value.type === "Directory") {+ repositories.push({ directory, gitDir: gitPath, linkedWorktree: false });+ } else pointers.push({ directory, gitPath });}- const linkedWorktree =- gitStats.value.type !== "Directory" && /[\\/]worktrees[\\/][^\\/]+[\\/]?$/.test(gitDir);- if (linkedWorktree) {- const commonDir = yield* fileSystem- .readFileString(path.join(gitDir, "commondir"))- .pipe(Effect.orElseSucceed(() => ""));- if (commonDir.trim().length === 0) return { _tag: "Worktree" } as const;- gitDir = path.resolve(gitDir, commonDir.trim());++ const pointerTexts = yield* readGitFiles(pointers.map(({ gitPath }) => gitPath));+ const linkedWorktrees: Array<{ directory: string; gitDir: string }> = [];+ for (const { directory, gitPath } of pointers) {+ const target = /^gitdir:\s*(.+)$/m.exec(pointerTexts.get(gitPath) ?? "")?.[1]?.trim();+ if (target === undefined || target.length === 0) {+ identities.set(directory, { _tag: "NotGit" });+ continue;+ }+ const gitDir = path.resolve(directory, target);+ if (/[\\/]worktrees[\\/][^\\/]+[\\/]?$/.test(gitDir)) {+ linkedWorktrees.push({ directory, gitDir });+ } else repositories.push({ directory, gitDir, linkedWorktree: false });}- const configText = yield* fileSystem- .readFileString(path.join(gitDir, "config"))- .pipe(Effect.orElseSucceed(() => ""));- // Bare repositories have no main checkout, so offer their linked worktrees independently.- if (linkedWorktree && !isBareGitConfig(configText)) return { _tag: "Worktree" } as const;- const originUrl = parseOriginUrlFromGitConfig(configText);- return {- _tag: "Repository",- git: {- remoteKey:- originUrl === null ? null : sourceControlDefinitions.repositoryKeyFromRemote(originUrl),- repository: repositoryPathFromRemoteUrl(originUrl),- },- } as const;++ const commonDirTexts = yield* readGitFiles(+ linkedWorktrees.map(({ gitDir }) => path.join(gitDir, "commondir")),+ );+ for (const { directory, gitDir } of linkedWorktrees) {+ const commonDir = (commonDirTexts.get(path.join(gitDir, "commondir")) ?? "").trim();+ if (commonDir.length === 0) identities.set(directory, { _tag: "Worktree" });+ else+ repositories.push({+ directory,+ gitDir: path.resolve(gitDir, commonDir),+ linkedWorktree: true,+ });+ }++ const configTexts = yield* readGitFiles(+ repositories.map(({ gitDir }) => path.join(gitDir, "config")),+ );+ for (const { directory, gitDir, linkedWorktree } of repositories) {+ const configText = configTexts.get(path.join(gitDir, "config")) ?? "";+ // Bare repositories have no main checkout, so offer their linked worktrees independently.+ if (linkedWorktree && !isBareGitConfig(configText)) {+ identities.set(directory, { _tag: "Worktree" });+ continue;+ }+ const originUrl = parseOriginUrlFromGitConfig(configText);+ identities.set(directory, {+ _tag: "Repository",+ git: {+ remoteKey:+ originUrl === null ? null : sourceControlDefinitions.repositoryKeyFromRemote(originUrl),+ repository: repositoryPathFromRemoteUrl(originUrl),+ },+ });+ }+ return identities;});const readCwd = Effect.fn("AgentSessionScanner.readCwd")(function* (@@ -1404,6 +1497,30 @@ export const make = Effect.gen(function* () {git: AgentSessionProjectGit | null;}>();+ // Resolve every candidate directory first so one batch reads all git identities.+ const directories = new Map<string, Option.Option<FileSystem.File.Info>>();+ for (const candidate of raw) {+ const expanded = expandHomePath(candidate.cwd.trim(), homeDir);+ if (!path.isAbsolute(expanded)) continue;+ const resolved = path.resolve(expanded);+ if (directories.has(resolved) || isExcludedProjectPath(resolved)) continue;+ const stats = yield* statOption(resolved);+ if (Option.isNone(stats) || stats.value.type !== "Directory") {+ directories.set(resolved, Option.none());+ continue;+ }+ const realPath = yield* fileSystem+ .realPath(resolved)+ .pipe(Effect.orElseSucceed(() => resolved));+ // Symlinks can disguise excluded worktree paths; re-check their targets.+ directories.set(resolved, isExcludedProjectPath(realPath) ? Option.none() : stats);+ }+ const directoryGitIdentities = yield* readGitIdentities(+ Array.from(directories).flatMap(([directory, stats]) =>+ Option.isSome(stats) ? [directory] : [],+ ),+ );+const directoryKeys = new Map<string, string>();const gitIdentities = new Map<string, AgentSessionProjectGit | null>();@@ -1411,28 +1528,16 @@ export const make = Effect.gen(function* () {const expanded = expandHomePath(candidate.cwd.trim(), homeDir);if (!path.isAbsolute(expanded)) continue;const resolved = path.resolve(expanded);- if (isExcludedProjectPath(resolved)) continue;+ const stats = directories.get(resolved);+ if (stats === undefined || Option.isNone(stats)) continue;let key = directoryKeys.get(resolved);if (key === undefined) {- const stats = yield* statOption(resolved);- if (Option.isNone(stats) || stats.value.type !== "Directory") {- directoryKeys.set(resolved, "");- continue;- }- const realPath = yield* fileSystem- .realPath(resolved)- .pipe(Effect.orElseSucceed(() => resolved));- // Symlinks can disguise excluded worktree paths; re-check their targets.- if (isExcludedProjectPath(realPath)) {+ const gitIdentity = directoryGitIdentities.get(resolved);+ if (gitIdentity === undefined || gitIdentity._tag === "Worktree") {key = "";} else {- const gitIdentity = yield* readGitIdentity(resolved);- if (gitIdentity._tag === "Worktree") {- key = "";- } else {- key = yield* directoryIdentity(resolved, stats.value);- gitIdentities.set(key, gitIdentity._tag === "Repository" ? gitIdentity.git : null);- }+ key = yield* directoryIdentity(resolved, stats.value);+ gitIdentities.set(key, gitIdentity._tag === "Repository" ? gitIdentity.git : null);}directoryKeys.set(resolved, key);}@@ -1680,4 +1785,6 @@ export const make = Effect.gen(function* () {return AgentSessionScanner.of({ scan, recentThreads });});-export const layer = Layer.effect(AgentSessionScanner, make);+export const layer = Layer.effect(AgentSessionScanner, make).pipe(+ Layer.provide(ProcessRunner.layer),+);