The best way to control Claude Code, Codex and more from any computer or phone
fix(server): agent session scans no longer hang the server on an unreadable .git/config (#23690)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Nov 2, 2026 at 18:31 UTC
71a7bf9516e3c96358b231c4ef30ba42b2dd6ff0
2 files changed
+458
-60
apps/server/src/project/AgentSessionScanner.test.ts
+291
@@ -1,4 +1,8 @@
1
+// @effect-diagnostics nodeBuiltinImport:off - FIFO gates must be released with a synchronous
2
+// open on the main thread, because the Effect FileSystem queues behind the pinned libuv pool.
3
import * as NodeServices from "@effect/platform-node/NodeServices";
4
+import * as NodeChildProcess from "node:child_process";
5
+import * as NodeFS from "node:fs";
6
import * as NodeOS from "node:os";
7
import { describe, expect, it } from "@effect/vitest";
8
import {
@@ -9,9 +13,11 @@ import {
13
ProviderInstanceId,
14
type ServerSettings as ContractServerSettings,
15
} from "@t3tools/contracts";
16
+import * as HostProcess from "@t3tools/shared/HostProcess";
17
import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
18
import * as DateTime from "effect/DateTime";
19
import * as Effect from "effect/Effect";
20
+import * as Fiber from "effect/Fiber";
21
import * as FileSystem from "effect/FileSystem";
22
import * as Layer from "effect/Layer";
23
import * as Option from "effect/Option";
@@ -248,6 +254,42 @@ const makeFileIdentityFixture = Effect.fn("AgentSessionScanner.test.makeFileIden
254
},
255
);
256
257
+const LIBUV_POOL_SIZE = Number(process.env.UV_THREADPOOL_SIZE ?? 4);
258
+
259
+/**
260
+ * Opening a FIFO for reading waits in `open()` until a writer appears, like a
261
+ * TCC-protected file in a headless macOS daemon, and pins one libuv pool thread
262
+ * that fiber interruption cannot free. The finalizer opens it for writing on the
263
+ * main thread, which releases every waiting reader even with the pool exhausted.
264
+ */
265
+const makeOpenGate = Effect.fn("AgentSessionScanner.test.makeOpenGate")(function* (
266
+ gatePath: string,
267
+) {
268
+ NodeChildProcess.execFileSync("mkfifo", [gatePath]);
269
+ yield* Effect.addFinalizer(() =>
270
+ Effect.sync(() => {
271
+ try {
272
+ NodeFS.closeSync(
273
+ NodeFS.openSync(gatePath, NodeFS.constants.O_WRONLY | NodeFS.constants.O_NONBLOCK),
274
+ );
275
+ } catch {
276
+ // ENXIO: no reader is waiting.
277
+ }
278
+ }),
279
+ );
280
+});
281
+
282
+/**
283
+ * Resolves once a reader has opened the FIFO, so its read deadline is already
284
+ * scheduled on the TestClock. The writer stays open until the scope closes, so
285
+ * the reader sees no EOF and has to wait out that deadline.
286
+ */
287
+const awaitGateReader = (gatePath: string) =>
288
+ Effect.acquireRelease(
289
+ Effect.promise(() => NodeFS.promises.open(gatePath, NodeFS.constants.O_WRONLY)),
290
+ (handle) => Effect.promise(() => handle.close()),
291
+ );
292
+
293
it.layer(NodeServices.layer)("AgentSessionScanner", (it) => {
294
describe("scan", () => {
295
it.effect("reads Claude project cwds from transcripts, newest first", () =>
@@ -1807,6 +1849,255 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => {
1849
});
1850
});
1851
1852
+describe.skipIf(HostProcess.Platform.defaultValue() === "win32")(
1853
+ "AgentSessionScanner scan with a git config open() that never returns",
1854
+ () => {
1855
+ it.effect(
1856
+ "completes every scan and leaves the libuv pool free when .git/config is a FIFO",
1857
+ () =>
1858
+ Effect.gen(function* () {
1859
+ const path = yield* Path.Path;
1860
+ const fileSystem = yield* FileSystem.FileSystem;
1861
+ const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
1862
+ const codexHomePath = yield* makeTempDir("t3code-codex-home-");
1863
+ const repo = yield* makeTempDir("t3code-workspace-fifo-config-");
1864
+ yield* fileSystem.makeDirectory(path.join(repo, ".git"));
1865
+ yield* makeOpenGate(path.join(repo, ".git", "config"));
1866
+ const transcriptPath = path.join(claudeHomePath, "projects", "-fifo", "a.jsonl");
1867
+ yield* writeTranscript({
1868
+ filePath: transcriptPath,
1869
+ contents: claudeSessionLine(repo),
1870
+ mtimeMs: Date.parse("2026-05-03T00:00:00.000Z"),
1871
+ });
1872
+
1873
+ for (let attempt = 1; attempt <= LIBUV_POOL_SIZE + 1; attempt++) {
1874
+ const scan = yield* Effect.forkChild(
1875
+ runScan({ claudeHomePath, codexHomePath }).pipe(
1876
+ Effect.map(({ candidates }) => candidates.map(({ path }) => path)),
1877
+ ),
1878
+ );
1879
+ yield* Effect.scoped(
1880
+ Effect.gen(function* () {
1881
+ yield* awaitGateReader(path.join(repo, ".git", "config"));
1882
+ yield* TestClock.adjust("2 seconds");
1883
+ expect(yield* Fiber.join(scan), `scan ${attempt}`).toEqual([repo]);
1884
+ }),
1885
+ );
1886
+ }
1887
+ // Hangs if the scans left libuv pool threads stuck in open().
1888
+ yield* fileSystem.readFileString(transcriptPath);
1889
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1890
+ );
1891
+
1892
+ it.effect("still reads the git identity of repositories next to a blocked one", () =>
1893
+ Effect.gen(function* () {
1894
+ const path = yield* Path.Path;
1895
+ const fileSystem = yield* FileSystem.FileSystem;
1896
+ const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
1897
+ const codexHomePath = yield* makeTempDir("t3code-codex-home-");
1898
+ const repos = [
1899
+ yield* makeTempDir("t3code-workspace-before-"),
1900
+ yield* makeTempDir("t3code-workspace-blocked-"),
1901
+ yield* makeTempDir("t3code-workspace-after-"),
1902
+ ] as const;
1903
+ for (const [index, repo] of repos.entries()) {
1904
+ yield* fileSystem.makeDirectory(path.join(repo, ".git"));
1905
+ const configPath = path.join(repo, ".git", "config");
1906
+ if (index === 1) yield* makeOpenGate(configPath);
1907
+ else
1908
+ yield* fileSystem.writeFileString(
1909
+ configPath,
1910
+ `[remote "origin"]\n\turl = git@github.com:pingdotgg/repo-${index}.git\n`,
1911
+ );
1912
+ yield* writeTranscript({
1913
+ filePath: path.join(claudeHomePath, "projects", `-slug-${index}`, "a.jsonl"),
1914
+ contents: claudeSessionLine(repo),
1915
+ mtimeMs: Date.parse(`2026-01-0${index + 1}T00:00:00.000Z`),
1916
+ });
1917
+ }
1918
+
1919
+ for (let attempt = 1; attempt <= 2; attempt++) {
1920
+ const scan = yield* Effect.forkChild(runScan({ claudeHomePath, codexHomePath }));
1921
+ const result = yield* Effect.scoped(
1922
+ Effect.gen(function* () {
1923
+ yield* awaitGateReader(path.join(repos[1], ".git", "config"));
1924
+ yield* TestClock.adjust("2 seconds");
1925
+ return yield* Fiber.join(scan);
1926
+ }),
1927
+ );
1928
+ expect(
1929
+ result.candidates.map((candidate) => ({ path: candidate.path, git: candidate.git })),
1930
+ `scan ${attempt}`,
1931
+ ).toEqual([
1932
+ {
1933
+ path: repos[2],
1934
+ git: { remoteKey: "github.com/pingdotgg/repo-2", repository: "pingdotgg/repo-2" },
1935
+ },
1936
+ { path: repos[1], git: { remoteKey: null, repository: null } },
1937
+ {
1938
+ path: repos[0],
1939
+ git: { remoteKey: "github.com/pingdotgg/repo-0", repository: "pingdotgg/repo-0" },
1940
+ },
1941
+ ]);
1942
+ }
1943
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1944
+ );
1945
+
1946
+ it.effect("reads every blocked git config of a scan under one deadline", () =>
1947
+ Effect.gen(function* () {
1948
+ const path = yield* Path.Path;
1949
+ const fileSystem = yield* FileSystem.FileSystem;
1950
+ const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
1951
+ const codexHomePath = yield* makeTempDir("t3code-codex-home-");
1952
+ const root = yield* makeTempDir("t3code-workspace-blocked-configs-");
1953
+ const repos = [path.join(root, "repo-a"), path.join(root, "repo-b")];
1954
+ for (const repo of repos) {
1955
+ yield* fileSystem.makeDirectory(path.join(repo, ".git"), { recursive: true });
1956
+ yield* makeOpenGate(path.join(repo, ".git", "config"));
1957
+ }
1958
+ // Two linked worktrees of one bare repository share its blocked config.
1959
+ const bareGitDir = path.join(root, "bare.git");
1960
+ yield* fileSystem.makeDirectory(bareGitDir);
1961
+ yield* makeOpenGate(path.join(bareGitDir, "config"));
1962
+ const worktrees = [path.join(root, "wt-1"), path.join(root, "wt-2")];
1963
+ for (const worktree of worktrees) {
1964
+ const gitDir = path.join(bareGitDir, "worktrees", path.basename(worktree));
1965
+ yield* fileSystem.makeDirectory(gitDir, { recursive: true });
1966
+ yield* fileSystem.writeFileString(path.join(gitDir, "commondir"), "../..\n");
1967
+ yield* fileSystem.makeDirectory(worktree);
1968
+ yield* fileSystem.writeFileString(path.join(worktree, ".git"), `gitdir: ${gitDir}\n`);
1969
+ }
1970
+ for (const [index, cwd] of [...repos, ...worktrees].entries()) {
1971
+ yield* writeTranscript({
1972
+ filePath: path.join(claudeHomePath, "projects", `-slug-${index}`, "a.jsonl"),
1973
+ contents: claudeSessionLine(cwd),
1974
+ mtimeMs: Date.parse(`2026-01-0${index + 1}T00:00:00.000Z`),
1975
+ });
1976
+ }
1977
+
1978
+ const scan = yield* Effect.forkChild(
1979
+ runScan({ claudeHomePath, codexHomePath }).pipe(
1980
+ Effect.map(({ candidates }) => candidates.map(({ path }) => path).toSorted()),
1981
+ ),
1982
+ );
1983
+ // Every blocked config is open before any deadline passes; reading them
1984
+ // one after another would leave the later ones unopened.
1985
+ yield* Effect.forEach(
1986
+ [...repos.map((repo) => path.join(repo, ".git")), bareGitDir],
1987
+ (gitDir) => awaitGateReader(path.join(gitDir, "config")),
1988
+ { concurrency: "unbounded" },
1989
+ );
1990
+ yield* TestClock.adjust("2 seconds");
1991
+ expect(yield* Fiber.join(scan)).toEqual(repos);
1992
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1993
+ );
1994
+
1995
+ it.effect("completes every scan when a .git pointer file or commondir never opens", () =>
1996
+ Effect.gen(function* () {
1997
+ const path = yield* Path.Path;
1998
+ const fileSystem = yield* FileSystem.FileSystem;
1999
+ const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
2000
+ const codexHomePath = yield* makeTempDir("t3code-codex-home-");
2001
+ const root = yield* makeTempDir("t3code-workspace-blocked-pointers-");
2002
+ const pointerCheckout = path.join(root, "pointer");
2003
+ yield* fileSystem.makeDirectory(pointerCheckout);
2004
+ yield* makeOpenGate(path.join(pointerCheckout, ".git"));
2005
+ const worktree = path.join(root, "worktree");
2006
+ const worktreeGitDir = path.join(root, "main", ".git", "worktrees", "worktree");
2007
+ yield* fileSystem.makeDirectory(worktreeGitDir, { recursive: true });
2008
+ yield* makeOpenGate(path.join(worktreeGitDir, "commondir"));
2009
+ yield* fileSystem.makeDirectory(worktree);
2010
+ yield* fileSystem.writeFileString(
2011
+ path.join(worktree, ".git"),
2012
+ `gitdir: ${worktreeGitDir}\n`,
2013
+ );
2014
+ for (const [index, cwd] of [pointerCheckout, worktree].entries()) {
2015
+ yield* writeTranscript({
2016
+ filePath: path.join(claudeHomePath, "projects", `-slug-${index}`, "a.jsonl"),
2017
+ contents: claudeSessionLine(cwd),
2018
+ mtimeMs: Date.parse(`2026-01-0${index + 1}T00:00:00.000Z`),
2019
+ });
2020
+ }
2021
+
2022
+ // One scanner across scans: later scans skip the files that blocked.
2023
+ yield* Effect.gen(function* () {
2024
+ const scanner = yield* AgentSessionScanner.AgentSessionScanner;
2025
+ const scanPaths = scanner.scan.pipe(
2026
+ Effect.map(({ candidates }) => candidates.map(({ path }) => path)),
2027
+ );
2028
+ const first = yield* Effect.forkChild(scanPaths);
2029
+ // Pointer files are read first, then the commondir files they lead to.
2030
+ for (const gatePath of [
2031
+ path.join(pointerCheckout, ".git"),
2032
+ path.join(worktreeGitDir, "commondir"),
2033
+ ]) {
2034
+ yield* Effect.scoped(
2035
+ Effect.gen(function* () {
2036
+ yield* awaitGateReader(gatePath);
2037
+ yield* TestClock.adjust("2 seconds");
2038
+ }),
2039
+ );
2040
+ }
2041
+ expect(yield* Fiber.join(first)).toEqual([pointerCheckout]);
2042
+ for (let attempt = 2; attempt <= LIBUV_POOL_SIZE + 1; attempt++) {
2043
+ expect(yield* scanPaths, `scan ${attempt}`).toEqual([pointerCheckout]);
2044
+ }
2045
+ }).pipe(Effect.provide(layerScannerTest({ claudeHomePath, codexHomePath })));
2046
+ // Hangs if the scans left libuv pool threads stuck in open().
2047
+ yield* fileSystem.readFileString(path.join(worktree, ".git"));
2048
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
2049
+ );
2050
+
2051
+ it.effect("reads a once-blocked git config again after the retry interval", () =>
2052
+ Effect.gen(function* () {
2053
+ const path = yield* Path.Path;
2054
+ const fileSystem = yield* FileSystem.FileSystem;
2055
+ const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
2056
+ const codexHomePath = yield* makeTempDir("t3code-codex-home-");
2057
+ const repo = yield* makeTempDir("t3code-workspace-unblocked-config-");
2058
+ yield* fileSystem.makeDirectory(path.join(repo, ".git"));
2059
+ const configPath = path.join(repo, ".git", "config");
2060
+ yield* makeOpenGate(configPath);
2061
+ yield* writeTranscript({
2062
+ filePath: path.join(claudeHomePath, "projects", "-unblocked", "a.jsonl"),
2063
+ contents: claudeSessionLine(repo),
2064
+ mtimeMs: Date.parse("2026-05-03T00:00:00.000Z"),
2065
+ });
2066
+ const gitOfScan = (scan: AgentSessionScanner.AgentSessionScanner["Service"]["scan"]) =>
2067
+ scan.pipe(Effect.map(({ candidates }) => candidates.map(({ git }) => git)));
2068
+
2069
+ yield* Effect.gen(function* () {
2070
+ const scanner = yield* AgentSessionScanner.AgentSessionScanner;
2071
+ const blockedScan = yield* Effect.forkChild(gitOfScan(scanner.scan));
2072
+ yield* Effect.scoped(
2073
+ Effect.gen(function* () {
2074
+ yield* awaitGateReader(configPath);
2075
+ yield* TestClock.adjust("2 seconds");
2076
+ expect(yield* Fiber.join(blockedScan)).toEqual([
2077
+ { remoteKey: null, repository: null },
2078
+ ]);
2079
+ }),
2080
+ );
2081
+
2082
+ yield* fileSystem.remove(configPath);
2083
+ yield* fileSystem.writeFileString(
2084
+ configPath,
2085
+ `[remote "origin"]\n\turl = git@github.com:pingdotgg/unblocked.git\n`,
2086
+ );
2087
+ expect(yield* gitOfScan(scanner.scan), "a blocked path is skipped for a while").toEqual([
2088
+ { remoteKey: null, repository: null },
2089
+ ]);
2090
+
2091
+ yield* TestClock.adjust("10 minutes");
2092
+ expect(yield* gitOfScan(scanner.scan)).toEqual([
2093
+ { remoteKey: "github.com/pingdotgg/unblocked", repository: "pingdotgg/unblocked" },
2094
+ ]);
2095
+ }).pipe(Effect.provide(layerScannerTest({ claudeHomePath, codexHomePath })));
2096
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
2097
+ );
2098
+ },
2099
+);
2100
+
2101
describe("parseAgentSessionTranscript", () => {
2102
it.each([false, true])(
2103
"handles the exact record limit and an interior blank overflow=%s",
apps/server/src/project/AgentSessionScanner.ts
+167
-60
@@ -13,6 +13,7 @@ import {
13
type AgentSessionScanResult,
14
type ProviderInstanceConfig,
15
} from "@t3tools/contracts";
16
+import * as Clock from "effect/Clock";
17
import * as Context from "effect/Context";
18
import * as DateTime from "effect/DateTime";
19
import * as Effect from "effect/Effect";
@@ -30,6 +31,7 @@ import { normalizeProjectPathForComparison } from "@t3tools/shared/path";
31
import { repositoryPathFromRemoteUrl } from "@t3tools/source-control-core/server/SourceControlProvider";
32
33
import * as ServerConfig from "../config.ts";
34
+import * as ProcessRunner from "../processRunner.ts";
35
import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";
36
import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts";
37
import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
@@ -64,6 +66,21 @@ const MAX_IMPORT_BYTES = 4 * 1024 * 1024 * 1024;
66
const MAX_IMPORT_TRANSCRIPTS = 100;
67
const MAX_IMPORT_RECORDS = 100_000;
68
69
+/**
70
+ * open() of a file under macOS privacy protection waits on a consent prompt
71
+ * that a headless server never gets, and a FIFO waits for a writer. Either
72
+ * pins a libuv pool thread that interruption cannot free, so git files of
73
+ * arbitrary transcript cwds are read by a `cat` child we can kill instead.
74
+ */
75
+const GIT_FILE_READ_DEADLINE = "2 seconds";
76
+const MAX_GIT_FILE_BYTES = 1024 * 1024;
77
+// Reads run concurrently, so each phase waits one deadline per batch of this
78
+// many blocked files rather than one per blocked file.
79
+const GIT_FILE_READ_CONCURRENCY = 16;
80
+// A blocked path is skipped for a while, then read again in case it was fixed.
81
+const BLOCKED_GIT_FILE_RETRY_MS = 5 * 60 * 1000;
82
+const MAX_BLOCKED_GIT_FILE_PATHS = 1024;
83
+
84
const TranscriptContentBlock = Schema.Struct({
85
type: Schema.optional(Schema.String),
86
text: Schema.optional(Schema.String),
@@ -718,6 +735,7 @@ function sameTranscriptIdentity(left: TranscriptIdentity, right: TranscriptIdent
735
/** @public */
736
export const make = Effect.gen(function* () {
737
const fileSystem = yield* FileSystem.FileSystem;
738
+ const processRunner = yield* ProcessRunner.ProcessRunner;
739
// Concurrent client imports must not hold multiple selected-history budgets.
740
const importReadLock = yield* Semaphore.make(1);
741
const path = yield* Path.Path;
@@ -726,7 +744,8 @@ export const make = Effect.gen(function* () {
744
const projectStore = yield* ProjectStore.ProjectStoreV2;
745
const baseDir = path.resolve(serverConfig.baseDir);
746
const worktreesDir = path.resolve(serverConfig.worktreesDir);
729
- const foldWorktreeCase = (yield* HostProcess.Platform) === "win32";
747
+ const isWindows = (yield* HostProcess.Platform) === "win32";
748
+ const foldWorktreeCase = isWindows;
749
const hostEnvironment = yield* HostProcess.Environment;
750
const homeDir = yield* HostProcess.HomeDirectory;
751
// `/private/tmp` is what macOS reports for sessions started in `/tmp`.
@@ -773,48 +792,122 @@ export const make = Effect.gen(function* () {
792
return `path:${normalizeProjectPathForComparison(realPath)}`;
793
});
794
776
- const readGitIdentity = Effect.fn("AgentSessionScanner.readGitIdentity")(function* (
777
- directory: string,
778
- ): Effect.fn.Return<
779
- | { readonly _tag: "Repository"; readonly git: AgentSessionProjectGit | null }
780
- | { readonly _tag: "Worktree" }
781
- | { readonly _tag: "NotGit" }
782
- > {
783
- const gitPath = path.join(directory, ".git");
784
- const gitStats = yield* statOption(gitPath);
785
- if (Option.isNone(gitStats)) return { _tag: "NotGit" } as const;
786
- let gitDir = gitPath;
787
- if (gitStats.value.type !== "Directory") {
788
- const pointer = yield* fileSystem
789
- .readFileString(gitPath)
790
- .pipe(Effect.orElseSucceed(() => ""));
791
- const target = /^gitdir:\s*(.+)$/m.exec(pointer)?.[1]?.trim();
792
- if (target === undefined || target.length === 0) return { _tag: "NotGit" } as const;
793
- gitDir = path.resolve(directory, target);
795
+ // Paths whose own read outlived the deadline, mapped to when they may be read
796
+ // again. Without this every later scan would wait out the deadline again for
797
+ // each phase that touches them.
798
+ const blockedGitFilePaths = new Map<string, number>();
799
+
800
+ /** Reads small files without the libuv pool; "" when missing, unreadable or blocked. */
801
+ const readGitFiles = Effect.fn("AgentSessionScanner.readGitFiles")(function* (
802
+ filePaths: ReadonlyArray<string>,
803
+ ) {
804
+ const unique = Array.from(new Set(filePaths));
805
+ const now = yield* Clock.currentTimeMillis;
806
+ const contents = yield* Effect.forEach(
807
+ unique,
808
+ (filePath) => {
809
+ // No privacy prompts or FIFOs to block open() here.
810
+ if (isWindows) {
811
+ return fileSystem.readFileString(filePath).pipe(Effect.orElseSucceed(() => ""));
812
+ }
813
+ if ((blockedGitFilePaths.get(filePath) ?? 0) > now) return Effect.succeed("");
814
+ blockedGitFilePaths.delete(filePath);
815
+ return processRunner
816
+ .run({
817
+ command: "cat",
818
+ args: ["--", filePath],
819
+ timeout: GIT_FILE_READ_DEADLINE,
820
+ timeoutBehavior: "timedOutResult",
821
+ maxOutputBytes: MAX_GIT_FILE_BYTES,
822
+ outputMode: "truncate",
823
+ })
824
+ .pipe(
825
+ Effect.map((result) => {
826
+ if (result.timedOut) {
827
+ if (blockedGitFilePaths.size >= MAX_BLOCKED_GIT_FILE_PATHS) {
828
+ blockedGitFilePaths.delete(blockedGitFilePaths.keys().next().value!);
829
+ }
830
+ blockedGitFilePaths.set(filePath, now + BLOCKED_GIT_FILE_RETRY_MS);
831
+ }
832
+ return result.code === 0 ? result.stdout : "";
833
+ }),
834
+ Effect.orElseSucceed(() => ""),
835
+ );
836
+ },
837
+ { concurrency: isWindows ? 1 : GIT_FILE_READ_CONCURRENCY },
838
+ );
839
+ return new Map(unique.map((filePath, index) => [filePath, contents[index]!]));
840
+ });
841
+
842
+ /** Reads every directory's git identity in three phases of concurrent reads. */
843
+ const readGitIdentities = Effect.fn("AgentSessionScanner.readGitIdentities")(function* (
844
+ directories: ReadonlyArray<string>,
845
+ ) {
846
+ type GitIdentity =
847
+ | { readonly _tag: "Repository"; readonly git: AgentSessionProjectGit | null }
848
+ | { readonly _tag: "Worktree" }
849
+ | { readonly _tag: "NotGit" };
850
+ const identities = new Map<string, GitIdentity>();
851
+ const repositories: Array<{ directory: string; gitDir: string; linkedWorktree: boolean }> = [];
852
+ const pointers: Array<{ directory: string; gitPath: string }> = [];
853
+ for (const directory of directories) {
854
+ const gitPath = path.join(directory, ".git");
855
+ const gitStats = yield* statOption(gitPath);
856
+ if (Option.isNone(gitStats)) identities.set(directory, { _tag: "NotGit" });
857
+ else if (gitStats.value.type === "Directory") {
858
+ repositories.push({ directory, gitDir: gitPath, linkedWorktree: false });
859
+ } else pointers.push({ directory, gitPath });
860
}
795
- const linkedWorktree =
796
- gitStats.value.type !== "Directory" && /[\\/]worktrees[\\/][^\\/]+[\\/]?$/.test(gitDir);
797
- if (linkedWorktree) {
798
- const commonDir = yield* fileSystem
799
- .readFileString(path.join(gitDir, "commondir"))
800
- .pipe(Effect.orElseSucceed(() => ""));
801
- if (commonDir.trim().length === 0) return { _tag: "Worktree" } as const;
802
- gitDir = path.resolve(gitDir, commonDir.trim());
861
+
862
+ const pointerTexts = yield* readGitFiles(pointers.map(({ gitPath }) => gitPath));
863
+ const linkedWorktrees: Array<{ directory: string; gitDir: string }> = [];
864
+ for (const { directory, gitPath } of pointers) {
865
+ const target = /^gitdir:\s*(.+)$/m.exec(pointerTexts.get(gitPath) ?? "")?.[1]?.trim();
866
+ if (target === undefined || target.length === 0) {
867
+ identities.set(directory, { _tag: "NotGit" });
868
+ continue;
869
+ }
870
+ const gitDir = path.resolve(directory, target);
871
+ if (/[\\/]worktrees[\\/][^\\/]+[\\/]?$/.test(gitDir)) {
872
+ linkedWorktrees.push({ directory, gitDir });
873
+ } else repositories.push({ directory, gitDir, linkedWorktree: false });
874
}
804
- const configText = yield* fileSystem
805
- .readFileString(path.join(gitDir, "config"))
806
- .pipe(Effect.orElseSucceed(() => ""));
807
- // Bare repositories have no main checkout, so offer their linked worktrees independently.
808
- if (linkedWorktree && !isBareGitConfig(configText)) return { _tag: "Worktree" } as const;
809
- const originUrl = parseOriginUrlFromGitConfig(configText);
810
- return {
811
- _tag: "Repository",
812
- git: {
813
- remoteKey:
814
- originUrl === null ? null : sourceControlDefinitions.repositoryKeyFromRemote(originUrl),
815
- repository: repositoryPathFromRemoteUrl(originUrl),
816
- },
817
- } as const;
875
+
876
+ const commonDirTexts = yield* readGitFiles(
877
+ linkedWorktrees.map(({ gitDir }) => path.join(gitDir, "commondir")),
878
+ );
879
+ for (const { directory, gitDir } of linkedWorktrees) {
880
+ const commonDir = (commonDirTexts.get(path.join(gitDir, "commondir")) ?? "").trim();
881
+ if (commonDir.length === 0) identities.set(directory, { _tag: "Worktree" });
882
+ else
883
+ repositories.push({
884
+ directory,
885
+ gitDir: path.resolve(gitDir, commonDir),
886
+ linkedWorktree: true,
887
+ });
888
+ }
889
+
890
+ const configTexts = yield* readGitFiles(
891
+ repositories.map(({ gitDir }) => path.join(gitDir, "config")),
892
+ );
893
+ for (const { directory, gitDir, linkedWorktree } of repositories) {
894
+ const configText = configTexts.get(path.join(gitDir, "config")) ?? "";
895
+ // Bare repositories have no main checkout, so offer their linked worktrees independently.
896
+ if (linkedWorktree && !isBareGitConfig(configText)) {
897
+ identities.set(directory, { _tag: "Worktree" });
898
+ continue;
899
+ }
900
+ const originUrl = parseOriginUrlFromGitConfig(configText);
901
+ identities.set(directory, {
902
+ _tag: "Repository",
903
+ git: {
904
+ remoteKey:
905
+ originUrl === null ? null : sourceControlDefinitions.repositoryKeyFromRemote(originUrl),
906
+ repository: repositoryPathFromRemoteUrl(originUrl),
907
+ },
908
+ });
909
+ }
910
+ return identities;
911
});
912
913
const readCwd = Effect.fn("AgentSessionScanner.readCwd")(function* (
@@ -1404,6 +1497,30 @@ export const make = Effect.gen(function* () {
1497
git: AgentSessionProjectGit | null;
1498
}
1499
>();
1500
+ // Resolve every candidate directory first so one batch reads all git identities.
1501
+ const directories = new Map<string, Option.Option<FileSystem.File.Info>>();
1502
+ for (const candidate of raw) {
1503
+ const expanded = expandHomePath(candidate.cwd.trim(), homeDir);
1504
+ if (!path.isAbsolute(expanded)) continue;
1505
+ const resolved = path.resolve(expanded);
1506
+ if (directories.has(resolved) || isExcludedProjectPath(resolved)) continue;
1507
+ const stats = yield* statOption(resolved);
1508
+ if (Option.isNone(stats) || stats.value.type !== "Directory") {
1509
+ directories.set(resolved, Option.none());
1510
+ continue;
1511
+ }
1512
+ const realPath = yield* fileSystem
1513
+ .realPath(resolved)
1514
+ .pipe(Effect.orElseSucceed(() => resolved));
1515
+ // Symlinks can disguise excluded worktree paths; re-check their targets.
1516
+ directories.set(resolved, isExcludedProjectPath(realPath) ? Option.none() : stats);
1517
+ }
1518
+ const directoryGitIdentities = yield* readGitIdentities(
1519
+ Array.from(directories).flatMap(([directory, stats]) =>
1520
+ Option.isSome(stats) ? [directory] : [],
1521
+ ),
1522
+ );
1523
+
1524
const directoryKeys = new Map<string, string>();
1525
const gitIdentities = new Map<string, AgentSessionProjectGit | null>();
1526
@@ -1411,28 +1528,16 @@ export const make = Effect.gen(function* () {
1528
const expanded = expandHomePath(candidate.cwd.trim(), homeDir);
1529
if (!path.isAbsolute(expanded)) continue;
1530
const resolved = path.resolve(expanded);
1414
- if (isExcludedProjectPath(resolved)) continue;
1531
+ const stats = directories.get(resolved);
1532
+ if (stats === undefined || Option.isNone(stats)) continue;
1533
let key = directoryKeys.get(resolved);
1534
if (key === undefined) {
1417
- const stats = yield* statOption(resolved);
1418
- if (Option.isNone(stats) || stats.value.type !== "Directory") {
1419
- directoryKeys.set(resolved, "");
1420
- continue;
1421
- }
1422
- const realPath = yield* fileSystem
1423
- .realPath(resolved)
1424
- .pipe(Effect.orElseSucceed(() => resolved));
1425
- // Symlinks can disguise excluded worktree paths; re-check their targets.
1426
- if (isExcludedProjectPath(realPath)) {
1535
+ const gitIdentity = directoryGitIdentities.get(resolved);
1536
+ if (gitIdentity === undefined || gitIdentity._tag === "Worktree") {
1537
key = "";
1538
} else {
1429
- const gitIdentity = yield* readGitIdentity(resolved);
1430
- if (gitIdentity._tag === "Worktree") {
1431
- key = "";
1432
- } else {
1433
- key = yield* directoryIdentity(resolved, stats.value);
1434
- gitIdentities.set(key, gitIdentity._tag === "Repository" ? gitIdentity.git : null);
1435
- }
1539
+ key = yield* directoryIdentity(resolved, stats.value);
1540
+ gitIdentities.set(key, gitIdentity._tag === "Repository" ? gitIdentity.git : null);
1541
}
1542
directoryKeys.set(resolved, key);
1543
}
@@ -1680,4 +1785,6 @@ export const make = Effect.gen(function* () {
1785
return AgentSessionScanner.of({ scan, recentThreads });
1786
});
1787
1683
-export const layer = Layer.effect(AgentSessionScanner, make);
1788
+export const layer = Layer.effect(AgentSessionScanner, make).pipe(
1789
+ Layer.provide(ProcessRunner.layer),
1790
+);