From 72b9e7da38e19628de93b187b7e338d35eae0c78 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Thu, 26 Nov 2026 02:15:06 +0100 Subject: [PATCH] fix(server): limit Git rescans to checkouts affected by the change Root watcher events used to read full Git status for every registered checkout. Select affected checkout directories through resolved ancestry and shared Git metadata, and reuse the repository's worktree registration when reading checkout identity. Co-authored-by: Victor Dozal --- .github/workflows/ci.yml | 2 + ...it-service.observation.integration.test.ts | 30 ++ .../workspace-git-service.primitive.test.ts | 2 +- .../src/server/workspace-git-service.ts | 23 +- ...rkspace-reconciliation-observation.test.ts | 277 +++++++++++++++++- .../workspace-reconciliation-service.ts | 232 ++++++++++++--- .../src/utils/checkout-git-identity.test.ts | 119 ++++++++ packages/server/src/utils/checkout-git.ts | 75 ++++- .../server/src/utils/worktree-metadata.ts | 16 + packages/server/src/utils/worktree.ts | 64 +++- 10 files changed, 775 insertions(+), 65 deletions(-) create mode 100644 packages/server/src/utils/checkout-git-identity.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 265f3e65c5..5115e72783 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -342,6 +342,8 @@ jobs: run: | npm run test:unit --workspace=@getpaseo/server -- \ src/server/file-observer \ + src/server/workspace-reconciliation-observation.test.ts \ + src/utils/checkout-git-identity.test.ts \ src/server/workspace-git-service.observation.test.ts \ src/server/workspace-git-service.observation.integration.test.ts \ --bail=1 diff --git a/packages/server/src/server/workspace-git-service.observation.integration.test.ts b/packages/server/src/server/workspace-git-service.observation.integration.test.ts index a943fcf482..2e3cfa941b 100644 --- a/packages/server/src/server/workspace-git-service.observation.integration.test.ts +++ b/packages/server/src/server/workspace-git-service.observation.integration.test.ts @@ -137,6 +137,36 @@ test("a fresh checkout read makes a newly initialized repository available to ca expect(realpathSync.native(repoRoot)).toBe(realpathSync.native(repo)); }, 30_000); +test("a checkout read for reconciliation never scans the working tree", async () => { + const root = realpathSync(mkdtempSync(path.join(tmpdir(), "paseo-checkout-read-"))); + const repo = path.join(root, "repo"); + mkdirSync(repo); + const git = (...args: string[]) => + execFileSync("git", ["-c", "commit.gpgsign=false", ...args], { cwd: repo, stdio: "pipe" }); + git("init", "-b", "main"); + git("config", "user.email", "test@example.com"); + git("config", "user.name", "Test"); + writeFileSync(path.join(repo, "README.md"), "base\n"); + git("add", "."); + git("commit", "-m", "base"); + const service = new WorkspaceGitServiceImpl({ + logger: pino({ enabled: false }), + paseoHome: path.join(root, "home"), + }); + cleanup.push(async () => { + await service.dispose(); + rmSync(root, { recursive: true, force: true }); + }); + + startGitCommandMetrics(); + const checkout = await service.getCheckout(repo, { priority: "background" }); + const verbs = stopGitCommandMetrics().commands.map((command) => command.args[0]); + + expect(checkout).toMatchObject({ isGit: true, currentBranch: "main" }); + expect(verbs.length).toBeGreaterThan(0); + expect(verbs.filter((verb) => ["status", "ls-files", "rev-list"].includes(verb))).toEqual([]); +}, 30_000); + test("recursive observation updates tracked state and prunes ignored storms", async () => { const tempDir = realpathSync(mkdtempSync(path.join(tmpdir(), "paseo-git-observation-"))); const repoDir = path.join(tempDir, "repo"); diff --git a/packages/server/src/server/workspace-git-service.primitive.test.ts b/packages/server/src/server/workspace-git-service.primitive.test.ts index c1fc132381..fdf115d279 100644 --- a/packages/server/src/server/workspace-git-service.primitive.test.ts +++ b/packages/server/src/server/workspace-git-service.primitive.test.ts @@ -429,7 +429,7 @@ describe("WorkspaceGitServiceImpl primitive refresh entrypoint", () => { test("getCheckout surfaces an unexpected Git read failure", async () => { const service = createService({ - getCheckoutStatus: vi.fn(async () => { + getCheckoutIdentity: vi.fn(async () => { throw new Error("Git read failed"); }), }); diff --git a/packages/server/src/server/workspace-git-service.ts b/packages/server/src/server/workspace-git-service.ts index 59cacbeefe..bb6b1a1671 100644 --- a/packages/server/src/server/workspace-git-service.ts +++ b/packages/server/src/server/workspace-git-service.ts @@ -7,7 +7,7 @@ import pLimit from "p-limit"; import type pino from "pino"; import type { ForgeWeb, ProjectCheckoutLitePayload } from "@getpaseo/protocol/messages"; import { parseGitRemoteLocation } from "@getpaseo/protocol/git-remote"; -import type { CheckoutContext, UpstreamState } from "../utils/checkout-git.js"; +import type { CheckoutContext, CheckoutReadSession, UpstreamState } from "../utils/checkout-git.js"; import { type BranchCheckoutResolution, type BranchSuggestion, @@ -19,6 +19,7 @@ import { getCheckoutRefDerivedState, getCheckoutSnapshotFacts, getCheckoutShortstat, + getCheckoutIdentity, getCheckoutStatus, getCheckoutWorktreeState, getPullRequestStatus, @@ -367,6 +368,7 @@ export type WorkspaceGitSnapshotOptions = type WorkspaceGitRefreshOrigin = "demand" | "observation"; export interface WorkspaceGitCheckoutReadOptions { + readSession?: CheckoutReadSession; /** Git lane for the fresh checkout read; defaults to the caller's ambient lane. */ priority?: GitProcessPriority; } @@ -417,6 +419,7 @@ interface WorkspaceGitServiceDependencies { subscribe: SubscribeToFileChanges; getCheckoutSnapshotFacts: typeof getCheckoutSnapshotFacts; getCheckoutRefDerivedState: typeof getCheckoutRefDerivedState; + getCheckoutIdentity: typeof getCheckoutIdentity; getCheckoutStatus: typeof getCheckoutStatus; getCheckoutShortstat: typeof getCheckoutShortstat; getCheckoutWorktreeState: typeof getCheckoutWorktreeState; @@ -637,6 +640,7 @@ function buildDefaultWorkspaceGitServiceDeps( subscribe, getCheckoutSnapshotFacts, getCheckoutRefDerivedState, + getCheckoutIdentity, getCheckoutStatus, getCheckoutShortstat, getCheckoutWorktreeState, @@ -875,16 +879,17 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { ): Promise { this.assertNotDisposed(); const normalizedCwd = resolve(cwd); - const status = await this.deps.getCheckoutStatus(normalizedCwd, { + const identity = await this.deps.getCheckoutIdentity(normalizedCwd, { paseoHome: this.paseoHome, worktreesRoot: this.worktreesRoot, logger: this.logger, + readSession: options?.readSession, ...(options?.priority ? { runGitCommand: createRunGitCommand("checkout-read", { priority: options.priority }) } : {}), }); const cached = this.getCachedSnapshot(normalizedCwd); - if (cached && cached.git.isGit !== status.isGit) { + if (cached && cached.git.isGit !== identity.isGit) { // A fresh checkout read discovered a repository transition. Keep the // shared snapshot current before exposing the new project capability. await this.getSnapshot(normalizedCwd, { @@ -893,7 +898,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { reason: "checkout-classification-changed", }); } - if (!status.isGit) { + if (!identity.isGit) { return checkoutLiteFromGitSnapshot(normalizedCwd, { isGit: false, currentBranch: null, @@ -905,11 +910,11 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { } return checkoutLiteFromGitSnapshot(normalizedCwd, { isGit: true, - currentBranch: status.currentBranch, - remoteUrl: status.remoteUrl, - repoRoot: status.repoRoot, - isPaseoOwnedWorktree: status.isPaseoOwnedWorktree, - mainRepoRoot: status.mainRepoRoot, + currentBranch: identity.currentBranch, + remoteUrl: identity.remoteUrl, + repoRoot: identity.repoRoot, + isPaseoOwnedWorktree: identity.isPaseoOwnedWorktree, + mainRepoRoot: identity.mainRepoRoot, }); } diff --git a/packages/server/src/server/workspace-reconciliation-observation.test.ts b/packages/server/src/server/workspace-reconciliation-observation.test.ts index f8cd5f106a..891b8ded58 100644 --- a/packages/server/src/server/workspace-reconciliation-observation.test.ts +++ b/packages/server/src/server/workspace-reconciliation-observation.test.ts @@ -1,4 +1,5 @@ -import { mkdirSync, mkdtempSync, rmSync } from "node:fs"; +import { execFileSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, renameSync, rmSync, symlinkSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import type { ProjectCheckoutLitePayload } from "@getpaseo/protocol/messages"; @@ -6,6 +7,10 @@ import { afterEach, describe, expect, test } from "vitest"; import { createTestLogger } from "../test-utils/test-logger.js"; import { areEquivalentPaths } from "../utils/path.js"; +import { + WorkspaceGitServiceImpl, + type WorkspaceGitCheckoutReadOptions, +} from "./workspace-git-service.js"; import { deriveProjectKey } from "./project-key.js"; import { createPersistedProjectRecord, @@ -175,10 +180,19 @@ class ObservedPlacements { private readonly service: WorkspaceReconciliationService; private started = false; private checkoutReadCount = 0; + private readonly checkoutReadCwds: string[] = []; - constructor(private readonly specs: ProjectSpec[]) { + private readonly gitService: WorkspaceGitServiceImpl | null; + + constructor( + private readonly specs: ProjectSpec[], + realGit = false, + ) { cleanupPaths.push(this.home); const logger = createTestLogger(); + this.gitService = realGit + ? new WorkspaceGitServiceImpl({ logger, paseoHome: this.absolute("paseo-home") }) + : null; this.projects = new ObservedProjectRegistry(path.join(this.home, "projects.json"), logger); this.workspaces = new ObservedWorkspaceRegistry( path.join(this.home, "workspaces.json"), @@ -194,7 +208,7 @@ class ObservedPlacements { this.service = new WorkspaceReconciliationService({ projectRegistry: this.projects, workspaceRegistry: this.workspaces, - workspaceGitService: { getCheckout: async (cwd) => this.readCheckout(cwd) }, + workspaceGitService: { getCheckout: async (cwd, options) => this.readCheckout(cwd, options) }, logger, watchProjectRoot, clock: this.clock, @@ -248,6 +262,31 @@ class ObservedPlacements { this.activeWatch(root)?.onChange("rename", filename); } + git(root: string, ...args: string[]): void { + execFileSync("git", args, { cwd: this.absolute(root), stdio: "pipe" }); + } + + rename(from: string, to: string): void { + renameSync(this.absolute(from), this.absolute(to)); + } + + link(alias: string, target: string): void { + symlinkSync( + this.absolute(target), + this.absolute(alias), + process.platform === "win32" ? "junction" : "dir", + ); + } + + async project(projectId: string) { + return this.projects.get(projectId); + } + + async disposeGit(): Promise { + this.dispose(); + await this.gitService?.dispose(); + } + makeProjectGit(projectId: string, branch = "main"): void { const rootPath = this.rootByProjectId.get(projectId); if (!rootPath) throw new Error(`Unknown project: ${projectId}`); @@ -324,6 +363,11 @@ class ObservedPlacements { return this.checkoutReadCount; } + /** Home-relative directories read since the last call, with portable separators. */ + takeCheckoutReads(): string[] { + return this.checkoutReadCwds.splice(0).sort(); + } + get pendingTimers(): number { return this.clock.pendingCount; } @@ -368,8 +412,13 @@ class ObservedPlacements { } } - private async readCheckout(cwd: string): Promise { + private async readCheckout( + cwd: string, + options?: WorkspaceGitCheckoutReadOptions, + ): Promise { this.checkoutReadCount += 1; + this.checkoutReadCwds.push(path.relative(this.home, cwd).split(path.sep).join("/")); + if (this.gitService) return this.gitService.getCheckout(cwd, options); const configured = [...this.checkoutByCwd.entries()].find(([root]) => areEquivalentPaths(root, cwd), )?.[1]; @@ -398,6 +447,18 @@ class ObservedPlacements { } } +/** Projects `a`, `b` and `c`, each rooted at `repo-` with its own worktrees. */ +function threeProjects(worktreeCount: number): ProjectSpec[] { + return ["a", "b", "c"].map((name) => ({ + id: `project-${name}`, + root: `repo-${name}`, + workspaces: Array.from({ length: worktreeCount }, (_, index) => ({ + id: `${name}${index + 1}`, + cwd: `repo-${name}/worktree-${index + 1}`, + })), + })); +} + describe("observed workspace placement", () => { test("installs and publishes a new project before add resolves without Git feedback", async () => { const observed = new ObservedPlacements([]); @@ -462,6 +523,214 @@ describe("observed workspace placement", () => { observed.dispose(); }); + test("reads only the workspaces of the project whose Git directory changed", async () => { + const observed = new ObservedPlacements(threeProjects(3)); + await observed.start(); + + observed.change("repo-b", ".git"); + await observed.advanceBy(DEBOUNCE_MS); + + expect(observed.takeCheckoutReads()).toEqual([ + "repo-b", + "repo-b/worktree-1", + "repo-b/worktree-2", + "repo-b/worktree-3", + ]); + observed.dispose(); + }); + + test("updates nested projects and workspaces when a parent directory becomes a Git repository", async () => { + const observed = new ObservedPlacements([ + { id: "parent", root: "repo", workspaces: [{ id: "parent-ws", cwd: "repo" }] }, + { id: "nested", root: "repo/sub", workspaces: [{ id: "nested-ws", cwd: "repo/sub" }] }, + { id: "outside", root: "outside", workspaces: [{ id: "attached-ws", cwd: "repo/sub" }] }, + { id: "unrelated", root: "repo-other" }, + ]); + await observed.start(); + try { + observed.makeProjectGit("parent"); + observed.makeProjectGit("nested"); + + observed.change("repo", ".git"); + await observed.advanceBy(DEBOUNCE_MS); + + expect(observed.projectUpdates).toContainEqual({ + kind: "upsert", + project: expect.objectContaining({ projectId: "nested", kind: "git" }), + }); + expect(await observed.placement("nested-ws")).toMatchObject({ kind: "local_checkout" }); + expect(await observed.placement("attached-ws")).toMatchObject({ kind: "local_checkout" }); + expect(observed.workspaceBatches.map((batch) => batch.sort())).toEqual([ + ["attached-ws", "nested-ws", "parent-ws"], + ]); + expect(observed.takeCheckoutReads()).toEqual(["outside", "repo", "repo/sub"]); + } finally { + observed.dispose(); + } + }); + + test("updates a separately registered directory alias when its parent becomes a Git repo", async () => { + const observed = new ObservedPlacements([{ id: "repo", root: "repo" }], true); + try { + await observed.start(); + await observed.add({ id: "sub", root: "repo/sub" }); + observed.link("alias", "repo/sub"); + await observed.add({ + id: "alias", + root: "alias", + workspaces: [{ id: "alias-ws", cwd: "alias" }], + }); + const savedProject = await observed.project("alias"); + const savedWorkspace = await observed.placement("alias-ws"); + observed.git("repo", "init", "-b", "main"); + observed.change("repo", ".git"); + await observed.advanceBy(DEBOUNCE_MS); + + expect(await observed.project("alias")).toMatchObject({ + kind: "git", + rootPath: savedProject?.rootPath, + }); + expect(await observed.placement("alias-ws")).toMatchObject({ + kind: "local_checkout", + cwd: savedWorkspace?.cwd, + }); + expect(observed.workspaceBatches.flat()).toContain("alias-ws"); + } finally { + await observed.disposeGit(); + } + }); + + test("reads a separately registered linked worktree alongside its main checkout and skips unrelated Git repos", async () => { + const observed = new ObservedPlacements( + [ + { id: "repo", root: "repo", workspaces: [{ id: "main-ws", cwd: "repo" }] }, + { + id: "unrelated", + root: "repo-other", + workspaces: [{ id: "other-ws", cwd: "repo-other" }], + }, + ], + true, + ); + try { + await observed.start(); + observed.git("repo", "init", "-b", "main"); + observed.git( + "repo", + "-c", + "user.name=Test", + "-c", + "user.email=test@example.com", + "commit", + "--allow-empty", + "-m", + "initial", + ); + observed.git("repo", "remote", "add", "origin", "https://github.com/acme/old.git"); + observed.git("repo", "worktree", "add", "-b", "feature", "../linked"); + await observed.add({ + id: "linked", + root: "linked", + workspaces: [{ id: "linked-ws", cwd: "linked" }], + }); + observed.git("repo-other", "init", "-b", "main"); + observed.change("linked", ".git"); + await observed.advanceBy(DEBOUNCE_MS); + expect(await observed.placement("linked-ws")).toMatchObject({ branch: "feature" }); + const oldKey = (await observed.project("linked"))?.projectKey; + observed.takeCheckoutReads(); + + observed.git("repo", "remote", "set-url", "origin", "https://github.com/acme/new.git"); + observed.git("repo", "branch", "-m", "feature", "renamed"); + observed.change("repo", ".git"); + await observed.advanceBy(DEBOUNCE_MS); + + expect(await observed.placement("linked-ws")).toMatchObject({ branch: "renamed" }); + const linkedProject = await observed.project("linked"); + expect(linkedProject?.projectKey).toEqual((await observed.project("repo"))?.projectKey); + expect(linkedProject?.projectKey).not.toEqual(oldKey); + expect(observed.takeCheckoutReads()).toEqual(["linked", "repo"]); + expect(await observed.project("unrelated")).toMatchObject({ kind: "non_git" }); + expect(await observed.placement("other-ws")).toMatchObject({ kind: "directory" }); + + observed.rename("repo/.git", "repo/.git-backup"); + observed.change("repo", ".git"); + await observed.advanceBy(DEBOUNCE_MS); + + expect(await observed.project("linked")).toMatchObject({ kind: "non_git" }); + expect(await observed.placement("linked-ws")).toMatchObject({ kind: "directory" }); + expect(observed.takeCheckoutReads()).toEqual(["linked", "repo"]); + } finally { + await observed.disposeGit(); + } + }); + + test("turns Git changes under several roots into one read per changed root", async () => { + const observed = new ObservedPlacements(threeProjects(1)); + await observed.start(); + + for (const root of ["repo-a", "repo-c", "repo-a", "repo-c", "repo-a"]) { + observed.change(root, ".git"); + } + await observed.advanceBy(DEBOUNCE_MS); + + expect(observed.takeCheckoutReads()).toEqual([ + "repo-a", + "repo-a/worktree-1", + "repo-c", + "repo-c/worktree-1", + ]); + observed.dispose(); + }); + + test("a change that lands during a pass queues a pass for only that root", async () => { + const observed = new ObservedPlacements(threeProjects(1)); + await observed.start(); + observed.makeProjectGit("project-a"); + observed.makeProjectGit("project-b"); + const firstPassRead = observed.holdNextReconciliation(); + const firstBatch = observed.waitForWorkspaceBatch(); + const secondBatch = firstBatch.then(() => observed.waitForWorkspaceBatch()); + + observed.change("repo-a", ".git"); + const firstPass = observed.advanceBy(DEBOUNCE_MS); + await firstPassRead.started; + observed.change("repo-b", ".git"); + observed.change("repo-b", ".git"); + await observed.advanceBy(DEBOUNCE_MS); + firstPassRead.release(); + await firstPass; + await secondBatch; + + expect(observed.workspaceBatches).toEqual([["a1"], ["b1"]]); + expect(observed.takeCheckoutReads()).toEqual([ + "repo-a", + "repo-a/worktree-1", + "repo-b", + "repo-b/worktree-1", + ]); + observed.dispose(); + }); + + test("keeps the changed roots of a failed pass for the next one", async () => { + const observed = new ObservedPlacements([ + { id: "project-a", root: "repo-a", workspaces: [{ id: "a1", cwd: "repo-a" }] }, + { id: "project-b", root: "repo-b", workspaces: [{ id: "b1", cwd: "repo-b" }] }, + ]); + await observed.start(); + observed.makeProjectGit("project-a"); + observed.failNextReconciliation(new Error("registry unavailable")); + + observed.change("repo-a", ".git"); + await observed.advanceBy(DEBOUNCE_MS); + observed.change("repo-b", ".git"); + await observed.advanceBy(DEBOUNCE_MS); + + expect(observed.takeCheckoutReads()).toEqual(["repo-a", "repo-b"]); + expect((await observed.placement("a1"))?.kind).toBe("local_checkout"); + observed.dispose(); + }); + test("recovers errored and temporarily unavailable watchers on the periodic pass", async () => { const observed = new ObservedPlacements([ { id: "project-errored", root: "errored" }, diff --git a/packages/server/src/server/workspace-reconciliation-service.ts b/packages/server/src/server/workspace-reconciliation-service.ts index 84a0221a7f..d21a32d451 100644 --- a/packages/server/src/server/workspace-reconciliation-service.ts +++ b/packages/server/src/server/workspace-reconciliation-service.ts @@ -1,5 +1,7 @@ -import { watch as watchPath } from "node:fs"; +import { realpath, watch as watchPath } from "node:fs"; +import { dirname, join } from "node:path"; import { stat } from "node:fs/promises"; +import { promisify } from "node:util"; import { setImmediate as yieldToLoop } from "node:timers/promises"; import pLimit from "p-limit"; import type { ProjectCheckoutLitePayload } from "@getpaseo/protocol/messages"; @@ -11,15 +13,20 @@ import type { PersistedWorkspaceRecord, } from "./workspace-registry.js"; import type { WorkspaceGitService } from "./workspace-git-service.js"; -import { areEquivalentPaths } from "../utils/path.js"; +import { areEquivalentPaths, createPathContainmentMatcher } from "../utils/path.js"; import { deriveProjectKind, reconcileWorkspacePlacement, type MutableWorkspacePlacement, } from "./workspace-registry-model.js"; import { workspaceIdsForProjects } from "./workspace-directory.js"; +import { createCheckoutReadSession, type CheckoutReadSession } from "../utils/checkout-git.js"; +import { getGitCommonDirForWorktreeRoot } from "../utils/worktree-metadata.js"; import { deriveProjectKey } from "./project-key.js"; +const resolveRealpath = promisify(realpath); +const resolveNativeRealpath = promisify(realpath.native); + const DEFAULT_RESCAN_INTERVAL_MS = 5 * 60_000; const DEFAULT_DEBOUNCE_MS = 100; const INSPECTION_CONCURRENCY = 2; @@ -120,15 +127,22 @@ interface CachedCheckoutRead { checkout: Promise; } +interface CheckoutDirectory { + path: string; + commonDir: string | null; +} + +type DirectoryInspection = DirectoryState | CheckoutDirectory; + export type DirectoryState = "directory" | "missing" | "unreadable"; export class WorkspaceReconciliationService { // Timed-out fs operations retain their slot until the OS returns. Never use // the deadline to admit more work into libuv's shared threadpool. - private readonly timedOutPaths = new Set(); + private readonly timedOutPaths = new Map(); private inspectionSaturated = false; private readonly inspectionWaiters = new Set<() => void>(); - private readonly pendingInspections = new Map>(); + private readonly pendingInspections = new Map>(); private readonly directoryInspection: (targetPath: string) => Promise; private readonly inspectionTimeoutMs: number; private readonly serverId: string | undefined; @@ -151,6 +165,9 @@ export class WorkspaceReconciliationService { private disposed = false; private started = false; private reconciling = false; + // Project roots whose `.git` changed since the last observed pass. A metadata + // pass reads only these; the periodic full pass covers everything else. + private readonly changedRoots = new Set(); private reconcileQueuedMode: "metadata" | "full" | null = null; constructor(options: WorkspaceReconciliationServiceOptions) { @@ -211,17 +228,42 @@ export class WorkspaceReconciliationService { this.watchers.length = 0; } - /** Reconciles mutable Git facts only; never archives missing records. */ - async reconcileGitMetadata(): Promise { + /** + * Reconciles mutable Git facts only; never archives missing records. With + * `rootPaths`, read projects and workspaces whose checkouts can change under those paths. + */ + async reconcileGitMetadata(options?: { rootPaths?: string[] }): Promise { const start = Date.now(); const changes: ReconciliationChange[] = []; - const [projects, workspaces] = await Promise.all([ + const [allProjects, workspaces] = await Promise.all([ this.projectRegistry.list(), this.workspaceRegistry.listActive(), ]); + const projects = allProjects.filter((project) => !project.archivedAt); + const activeWorkspaces = workspaces.filter((workspace) => !workspace.archivedAt); + const affectedDirectories = options?.rootPaths + ? await findAffectedCheckoutDirectories( + options.rootPaths, + [ + ...projects.map((project) => project.rootPath), + ...activeWorkspaces.map((workspace) => workspace.cwd), + ], + (path, read) => this.inspectPath(path, "scope", read), + ) + : null; + const isAffectedDirectory = (cwd: string) => affectedDirectories?.has(cwd) ?? true; + const affectedProjectIds = new Set( + projects + .filter((project) => isAffectedDirectory(project.rootPath)) + .map((project) => project.projectId), + ); + // An explicitly chosen project can own a workspace outside its root. const workspacesByProject = new Map(); const workspaceStates = await mapBounded( - workspaces.filter((w) => !w.archivedAt), + activeWorkspaces.filter( + (workspace) => + affectedProjectIds.has(workspace.projectId) || isAffectedDirectory(workspace.cwd), + ), async (workspace) => ({ workspace, state: await this.inspectDirectory(workspace.cwd) }), ); for (const { workspace, state } of workspaceStates) { @@ -232,7 +274,10 @@ export class WorkspaceReconciliationService { workspacesByProject.set(workspace.projectId, siblings); } const projectStates = await mapBounded( - projects.filter((p) => !p.archivedAt), + projects.filter( + (project) => + affectedProjectIds.has(project.projectId) || workspacesByProject.has(project.projectId), + ), async (project) => ({ project, state: await this.inspectDirectory(project.rootPath) }), ); await this.reconcileGitMetadataForProjects( @@ -351,10 +396,11 @@ export class WorkspaceReconciliationService { ): Promise { const checkoutReads: CachedCheckoutRead[] = []; const checkoutReadLimit = pLimit(CHECKOUT_READ_CONCURRENCY); + const readSession = createCheckoutReadSession(); const readCheckout = (cwd: string): Promise => { const existing = checkoutReads.find((read) => areEquivalentPaths(read.cwd, cwd)); if (existing) return existing.checkout; - const checkout = checkoutReadLimit(() => this.readCheckout(cwd)); + const checkout = checkoutReadLimit(() => this.readCheckout(cwd, readSession)); checkoutReads.push({ cwd, checkout }); return checkout; }; @@ -496,6 +542,7 @@ export class WorkspaceReconciliationService { { recursive: false }, (_event, filename) => { if (filename === null || filename.toString() === ".git") { + this.changedRoots.add(project.rootPath); this.scheduleObservedReconciliation(); } }, @@ -539,28 +586,20 @@ export class WorkspaceReconciliationService { } return; } + // Take the roots that changed so far. Events arriving during this pass + // land in a fresh set and queue one more pass for just those roots. + const rootPaths = [...this.changedRoots]; + this.changedRoots.clear(); + if (mode === "metadata" && rootPaths.length === 0) return; this.reconciling = true; try { await this.syncProjectRootWatches(); - const result = mode === "full" ? await this.runOnce() : await this.reconcileGitMetadata(); - const workspaceIds = new Set(); - const projectIds = new Set(); - for (const change of result.changesApplied) { - if (change.kind === "workspace_updated" || change.kind === "workspace_archived") { - workspaceIds.add(change.workspaceId); - } - if (change.kind === "project_updated") projectIds.add(change.projectId); - } - if (projectIds.size > 0) { - const workspaces = await this.workspaceRegistry.listActive(); - for (const workspaceId of workspaceIdsForProjects(workspaces, projectIds)) { - workspaceIds.add(workspaceId); - } - } - if (!this.disposed && workspaceIds.size > 0) { - await this.onWorkspacesChanged?.(Array.from(workspaceIds)); - } + const result = + mode === "full" ? await this.runOnce() : await this.reconcileGitMetadata({ rootPaths }); + await this.publishChangedWorkspaces(result); } catch (error) { + // A failed pass keeps its roots pending for the next pass. + for (const rootPath of rootPaths) this.changedRoots.add(rootPath); if (!this.disposed) { this.logger.warn({ err: error }, "Workspace reconciliation failed"); } @@ -574,7 +613,30 @@ export class WorkspaceReconciliationService { } } - private async readCheckout(cwd: string): Promise { + private async publishChangedWorkspaces(result: ReconciliationResult): Promise { + const workspaceIds = new Set(); + const projectIds = new Set(); + for (const change of result.changesApplied) { + if (change.kind === "workspace_updated" || change.kind === "workspace_archived") { + workspaceIds.add(change.workspaceId); + } + if (change.kind === "project_updated") projectIds.add(change.projectId); + } + if (projectIds.size > 0) { + const workspaces = await this.workspaceRegistry.listActive(); + for (const workspaceId of workspaceIdsForProjects(workspaces, projectIds)) { + workspaceIds.add(workspaceId); + } + } + if (!this.disposed && workspaceIds.size > 0) { + await this.onWorkspacesChanged?.(Array.from(workspaceIds)); + } + } + + private async readCheckout( + cwd: string, + readSession: CheckoutReadSession, + ): Promise { if (!this.workspaceGitService) { return { cwd, @@ -588,7 +650,7 @@ export class WorkspaceReconciliationService { } // Reconciliation converges in the background; it must not queue ahead of // Git work a user is waiting for. - return this.workspaceGitService.getCheckout(cwd, { priority: "background" }); + return this.workspaceGitService.getCheckout(cwd, { priority: "background", readSession }); } private wakeInspectionWaiters(): void { @@ -597,21 +659,33 @@ export class WorkspaceReconciliationService { } private async inspectDirectory(targetPath: string): Promise { + const result = await this.inspectPath(targetPath, "directory", () => + this.directoryInspection(targetPath), + ); + return typeof result === "string" ? result : "directory"; + } + + private async inspectPath( + targetPath: string, + purpose: "directory" | "scope", + read: () => Promise, + ): Promise { + const key = `${purpose}:${targetPath}`; // A healthy in-flight inspection owns capacity temporarily. Wait for it; // only unresolved operations that have all timed out justify skipping paths. while ( !this.disposed && - !this.pendingInspections.has(targetPath) && + !this.pendingInspections.has(key) && this.pendingInspections.size >= INSPECTION_CONCURRENCY ) { if (this.timedOutPaths.size === INSPECTION_CONCURRENCY) return "unreadable"; await new Promise((resolve) => this.inspectionWaiters.add(resolve)); } if (this.disposed) return "unreadable"; - let pending = this.pendingInspections.get(targetPath); + let pending = this.pendingInspections.get(key); if (!pending) { pending = Promise.resolve() - .then(() => this.directoryInspection(targetPath)) + .then(read) .catch((error) => { if (isMissingPathError(error)) return "missing" as const; this.logger.warn( @@ -621,8 +695,8 @@ export class WorkspaceReconciliationService { return "unreadable" as const; }) .finally(() => { - this.pendingInspections.delete(targetPath); - this.timedOutPaths.delete(targetPath); + this.pendingInspections.delete(key); + this.timedOutPaths.delete(key); this.wakeInspectionWaiters(); if (this.inspectionSaturated && this.timedOutPaths.size === 0) { this.inspectionSaturated = false; @@ -632,20 +706,20 @@ export class WorkspaceReconciliationService { ); } }); - this.pendingInspections.set(targetPath, pending); + this.pendingInspections.set(key, pending); } let timer: ReturnType | undefined; try { return await Promise.race([ pending, - new Promise((resolve) => { + new Promise((resolve) => { timer = setTimeout(() => { - this.timedOutPaths.add(targetPath); + this.timedOutPaths.set(key, targetPath); this.wakeInspectionWaiters(); if (!this.inspectionSaturated && this.timedOutPaths.size === INSPECTION_CONCURRENCY) { this.inspectionSaturated = true; this.logger.warn( - { paths: [...this.timedOutPaths] }, + { paths: [...this.timedOutPaths.values()] }, "Workspace directory inspection saturated; preserving uninspected workspaces", ); } @@ -663,6 +737,86 @@ export class WorkspaceReconciliationService { } } +/** + * Resolve saved directories for selection only. The registries keep their original paths. + * Looking up the nearest .git entry and commondir uses bounded filesystem reads, so a + * watcher event does not start Git processes in repositories it is about to exclude. + */ +async function findAffectedCheckoutDirectories( + changedRoots: string[], + candidates: string[], + inspect: (path: string, read: () => Promise) => Promise, +): Promise> { + const resolved = new Map>(); + const resolvePath = (path: string) => { + let result = resolved.get(path); + if (!result) { + result = resolveRealpath(path) + .catch(() => resolveNativeRealpath(path)) + .catch(() => path); + resolved.set(path, result); + } + return result; + }; + const gitDirectories = new Map>(); + const findCommonDir = async (cwd: string): Promise => { + for (let current = cwd; ; current = dirname(current)) { + let result = gitDirectories.get(current); + if (!result) { + result = getGitCommonDirForWorktreeRoot(current); + gitDirectories.set(current, result); + } + const gitDir = await result; + if (gitDir) return resolvePath(gitDir); + if (dirname(current) === current) return null; + } + }; + + const dirty = await mapBounded(changedRoots, (root) => + inspect(root, async () => { + const path = await resolvePath(root); + return { path, commonDir: await findCommonDir(path) }; + }), + ); + const roots = dirty.map((entry, index) => + typeof entry === "string" ? changedRoots[index]! : entry.path, + ); + const tree = createPathContainmentMatcher({ + roots, + compareAsWindows: process.platform === "win32", + }); + const commonDirs = dirty.flatMap((entry) => + typeof entry !== "string" && entry.commonDir ? [entry.commonDir] : [], + ); + // If a main checkout loses .git, surviving linked checkouts still point at + // their missing admin directories inside it. + const gitEntries = createPathContainmentMatcher({ + roots: roots.map((root) => join(root, ".git")), + compareAsWindows: process.platform === "win32", + }); + const repositories = createPathContainmentMatcher({ + roots: commonDirs, + compareAsWindows: process.platform === "win32", + }); + const affected = new Set(); + await mapBounded([...new Set(candidates)], async (candidate) => { + const entry = await inspect(candidate, async () => { + const path = await resolvePath(candidate); + const commonDir = !tree.matches(path) ? await findCommonDir(path) : null; + return { path, commonDir }; + }); + const path = typeof entry === "string" ? candidate : entry.path; + if ( + tree.matches(path) || + (typeof entry !== "string" && + entry.commonDir && + (repositories.matchesExact(entry.commonDir) || gitEntries.matches(entry.commonDir))) + ) + affected.add(candidate); + }); + return affected; +} + function isMissingPathError(error: unknown): boolean { if (typeof error !== "object" || error === null || !("code" in error)) return false; return error.code === "ENOENT" || error.code === "ENOTDIR"; diff --git a/packages/server/src/utils/checkout-git-identity.test.ts b/packages/server/src/utils/checkout-git-identity.test.ts new file mode 100644 index 0000000000..036f8188a6 --- /dev/null +++ b/packages/server/src/utils/checkout-git-identity.test.ts @@ -0,0 +1,119 @@ +import { execFileSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { realpath } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { + createCheckoutReadSession, + getCheckoutIdentity, + getCheckoutStatus, +} from "./checkout-git.js"; +import { writePaseoWorktreeMetadata } from "./worktree-metadata.js"; +import { createWorktree } from "./worktree.js"; +import { startGitCommandMetrics, stopGitCommandMetrics } from "./run-git-command.js"; + +function git(cwd: string, ...args: string[]): void { + execFileSync("git", ["-c", "commit.gpgsign=false", ...args], { cwd, stdio: "ignore" }); +} + +describe("getCheckoutIdentity", () => { + let tempDir: string; + let paseoHome: string; + let repoDir: string; + let linkedDir: string; + let plainDir: string; + + beforeEach(() => { + tempDir = realpathSync(mkdtempSync(join(tmpdir(), "checkout-identity-"))); + paseoHome = join(tempDir, "paseo-home"); + repoDir = join(tempDir, "repo"); + linkedDir = join(tempDir, "linked"); + plainDir = join(tempDir, "plain"); + mkdirSync(paseoHome); + mkdirSync(repoDir); + mkdirSync(plainDir); + git(repoDir, "init", "-b", "main"); + git(repoDir, "config", "user.email", "test@test.com"); + git(repoDir, "config", "user.name", "Test"); + writeFileSync(join(repoDir, "tracked.txt"), "tracked\n"); + git(repoDir, "add", "."); + git(repoDir, "commit", "-m", "initial"); + git(repoDir, "remote", "add", "origin", "https://github.com/acme/widgets.git"); + git(repoDir, "worktree", "add", "-b", "feature", linkedDir); + }); + + afterEach(() => { + rmSync(tempDir, { recursive: true, force: true }); + }); + + it("reports the same identity as the full status for a checkout, linked and Paseo worktrees and a plain folder", async () => { + const paseoWorktree = await createWorktree({ + cwd: repoDir, + worktreeSlug: "alpha", + source: { kind: "branch-off", baseBranch: "main", branchName: "alpha" }, + paseoHome, + }); + for (const cwd of [repoDir, linkedDir, paseoWorktree.worktreePath]) { + const status = await getCheckoutStatus(cwd, { paseoHome }); + const identity = await getCheckoutIdentity(cwd, { paseoHome }); + if (!status.isGit) throw new Error(`${cwd} should be a git checkout`); + expect(identity).toEqual({ + isGit: true, + repoRoot: status.repoRoot, + mainRepoRoot: status.mainRepoRoot, + currentBranch: status.currentBranch, + remoteUrl: status.remoteUrl, + isPaseoOwnedWorktree: status.isPaseoOwnedWorktree, + }); + } + const mainRepoRoot = await realpath(repoDir); + expect(await getCheckoutIdentity(linkedDir, { paseoHome })).toMatchObject({ + currentBranch: "feature", + mainRepoRoot, + }); + expect(await getCheckoutIdentity(paseoWorktree.worktreePath, { paseoHome })).toMatchObject({ + isPaseoOwnedWorktree: true, + mainRepoRoot, + }); + expect(await getCheckoutIdentity(plainDir, { paseoHome })).toEqual({ isGit: false }); + }); + + it("reads Git worktree registration once for all marked worktrees in a batch", async () => { + const second = join(tempDir, "second"); + git(repoDir, "worktree", "add", "-b", "second", second); + await writePaseoWorktreeMetadata(linkedDir, { baseRefName: "main" }); + await writePaseoWorktreeMetadata(second, { baseRefName: "main" }); + + const readSession = createCheckoutReadSession(); + startGitCommandMetrics(); + try { + const checkouts = await Promise.all([ + getCheckoutIdentity(linkedDir, { paseoHome, readSession }), + getCheckoutIdentity(second, { paseoHome, readSession }), + ]); + expect(checkouts).toMatchObject([ + { isGit: true, currentBranch: "feature", isPaseoOwnedWorktree: true }, + { isGit: true, currentBranch: "second", isPaseoOwnedWorktree: true }, + ]); + const worktreeLists = stopGitCommandMetrics().commands.filter( + (command) => command.args[0] === "worktree" && command.args[1] === "list", + ); + expect(worktreeLists).toHaveLength(1); + } finally { + stopGitCommandMetrics(); + } + }); + + it("never scans the working tree or compares commits", async () => { + startGitCommandMetrics(); + await getCheckoutIdentity(repoDir, { paseoHome }); + await getCheckoutIdentity(linkedDir, { paseoHome }); + const verbs = stopGitCommandMetrics().commands.map((command) => command.args[0]); + + expect(verbs.length).toBeGreaterThan(0); + expect( + verbs.filter((verb) => ["status", "ls-files", "rev-list", "diff"].includes(verb)), + ).toEqual([]); + }); +}); diff --git a/packages/server/src/utils/checkout-git.ts b/packages/server/src/utils/checkout-git.ts index 253e042a7c..45f2131145 100644 --- a/packages/server/src/utils/checkout-git.ts +++ b/packages/server/src/utils/checkout-git.ts @@ -43,7 +43,11 @@ import { parseGitRevParsePath, resolveGitRevParsePath } from "./git-rev-parse-pa import { runGitCommand, type RunGitCommand } from "./run-git-command.js"; import { readGitFileContents, readGitFileContentAtRef } from "./git-file-contents.js"; import { unquoteGitPath } from "./git-quoted-path.js"; -import { isPaseoOwnedWorktreeCwd, resolvePaseoWorktreesBaseRoot } from "./worktree.js"; +import { + createRegisteredWorktreeLookup, + isPaseoOwnedWorktreeCwd, + resolvePaseoWorktreesBaseRoot, +} from "./worktree.js"; import { branchNameFromRef, findPaseoWorktreeRootForCwd, @@ -970,11 +974,18 @@ export interface MergeFromBaseOptions { requireCleanTarget?: boolean; } +export function createCheckoutReadSession() { + return { isRegisteredWorktree: createRegisteredWorktreeLookup() }; +} + +export type CheckoutReadSession = ReturnType; + export interface CheckoutContext { paseoHome?: string; worktreesRoot?: string; logger?: Pick; facts?: CheckoutSnapshotFacts | null; + readSession?: CheckoutReadSession; runGitCommand?: RunGitCommand; // `git config --get` results shared by the lookups of one snapshot, keyed by config key. // Several lookups read the same keys; this keeps each to one process. @@ -1312,6 +1323,7 @@ async function getPaseoWorktreeForCwd( paseoHome: options.context?.paseoHome, worktreesRoot: options.context?.worktreesRoot, knownGitCommonDir: options.knownGitCommonDir, + isRegisteredWorktree: options.context?.readSession?.isRegisteredWorktree, }); if (!ownership.allowed) { return { isPaseoOwnedWorktree: false }; @@ -2061,7 +2073,8 @@ interface CheckoutInspectionContext { async function inspectCheckoutContext( cwd: string, - context?: CheckoutContext, + context: CheckoutContext | undefined, + options: { includeAbsoluteGitDir: boolean }, ): Promise { const root = await getWorktreeRoot(cwd, context); if (!root) { @@ -2071,7 +2084,7 @@ async function inspectCheckoutContext( const [currentBranch, remoteUrl, absoluteGitDir, gitCommonDir] = await Promise.all([ getCurrentBranch(cwd, context), getOriginRemoteUrl(cwd, context), - resolveAbsoluteGitDir(cwd, context), + options.includeAbsoluteGitDir ? resolveAbsoluteGitDir(cwd, context) : null, resolveGitCommonDir(cwd, context), ]); const paseoWorktree = await getPaseoWorktreeForCwd(cwd, { @@ -2316,7 +2329,7 @@ async function collectCheckoutSnapshotFacts( cwd: string, context: CheckoutContext, ): Promise { - const inspected = await inspectCheckoutContext(cwd, context); + const inspected = await inspectCheckoutContext(cwd, context, { includeAbsoluteGitDir: true }); if (!inspected) { return { isGit: false }; } @@ -2551,6 +2564,60 @@ async function getUntrackedDiffText( }; } +export type CheckoutIdentity = + | { isGit: false } + | { + isGit: true; + repoRoot: string; + mainRepoRoot: string | null; + currentBranch: string | null; + remoteUrl: string | null; + isPaseoOwnedWorktree: boolean; + }; + +/** + * What a checkout is, without the state of its files. Reports the same identity fields as + * `getCheckoutStatus` but never scans the working tree (`status`), compares against a base, or + * counts commits, so reading many checkouts in the background stays cheap. + */ +export async function getCheckoutIdentity( + cwd: string, + context?: CheckoutContext, +): Promise { + const inspected = await inspectCheckoutContext(cwd, context, { includeAbsoluteGitDir: false }); + if (!inspected) { + return { isGit: false }; + } + const { worktreeRoot, currentBranch, remoteUrl, paseoWorktree } = inspected; + const mainRepoRoot = await getMainRepoRootFromCommonDir( + cwd, + inspected.gitCommonDir, + context, + ).catch(() => null); + // `getCheckoutStatus` reports a worktree as Paseo-owned only when it also resolves a base. + const isPaseoOwnedWorktree = + paseoWorktree.isPaseoOwnedWorktree && + Boolean( + storedBaseRefFromMetadata(await readPaseoWorktreeMetadata(worktreeRoot)) ?? + (await resolveBaseRef(cwd, context)), + ); + const isLinkedCheckout = mainRepoRoot !== null && resolve(mainRepoRoot) !== resolve(worktreeRoot); + let reportedMainRepoRoot: string | null = null; + if (isPaseoOwnedWorktree) { + reportedMainRepoRoot = mainRepoRoot ?? worktreeRoot; + } else if (isLinkedCheckout) { + reportedMainRepoRoot = mainRepoRoot; + } + return { + isGit: true, + repoRoot: worktreeRoot, + mainRepoRoot: reportedMainRepoRoot, + currentBranch, + remoteUrl, + isPaseoOwnedWorktree, + }; +} + export async function getCheckoutStatus( cwd: string, context?: CheckoutContext, diff --git a/packages/server/src/utils/worktree-metadata.ts b/packages/server/src/utils/worktree-metadata.ts index 912d5fd94e..6a306b5517 100644 --- a/packages/server/src/utils/worktree-metadata.ts +++ b/packages/server/src/utils/worktree-metadata.ts @@ -177,6 +177,22 @@ async function getGitDirForWorktreeRoot(worktreeRoot: string): Promise { return gitPath; } +/** Locate the admin directory used for shared refs and configuration. */ +export async function getGitCommonDirForWorktreeRoot(worktreeRoot: string): Promise { + let gitDir: string; + try { + gitDir = await getGitDirForWorktreeRoot(worktreeRoot); + } catch { + return null; + } + try { + const commonDir = (await readBoundedFile(join(gitDir, "commondir"))).trim(); + return commonDir ? resolve(gitDir, commonDir) : gitDir; + } catch { + return gitDir; + } +} + export async function getPaseoWorktreeMetadataPath(worktreeRoot: string): Promise { const gitDir = await getGitDirForWorktreeRoot(worktreeRoot); return join(gitDir, "paseo", "worktree.json"); diff --git a/packages/server/src/utils/worktree.ts b/packages/server/src/utils/worktree.ts index d7b5d42270..e2261ceca2 100644 --- a/packages/server/src/utils/worktree.ts +++ b/packages/server/src/utils/worktree.ts @@ -244,6 +244,7 @@ export interface PaseoWorktreeOwnership { export interface PaseoWorktreeOwnershipOptions extends WorktreeRootOptions { knownGitCommonDir?: string | null; + isRegisteredWorktree?: RegisteredWorktreeLookup; } export interface WorktreeRootOptions { @@ -1123,7 +1124,7 @@ export async function isPaseoOwnedWorktreeCwd( // is not proof — it lives in a git admin dir a user can copy into a // hand-made directory that git does not know about. if (options?.knownGitCommonDir !== null) { - const metadataProof = await resolveMetadataOwnedWorktree(cwd, repoRoot); + const metadataProof = await resolveMetadataOwnedWorktree(cwd, repoRoot, options); if (metadataProof) { return { allowed: true, @@ -1164,6 +1165,7 @@ export async function isPaseoOwnedWorktreeCwd( async function resolveMetadataOwnedWorktree( cwd: string, repoRoot: string | undefined, + options?: PaseoWorktreeOwnershipOptions, ): Promise<{ worktreePath: string; worktreeRoot: string } | null> { try { const root = await findPaseoWorktreeRootForCwd(cwd); @@ -1171,18 +1173,64 @@ async function resolveMetadataOwnedWorktree( const candidate = await normalizePathForOwnership(root); if (repoRoot !== undefined && candidate === (await normalizePathForOwnership(repoRoot))) return null; - const { entries } = await readGitWorktreeEntries(candidate); - for (const entry of entries) { - if ((await normalizePathForOwnership(entry.path)) === candidate) { - return { worktreePath: candidate, worktreeRoot: dirname(candidate) }; - } - } - return null; + const isRegistered = options?.isRegisteredWorktree ?? isRegisteredGitWorktree; + return (await isRegistered(candidate, options?.knownGitCommonDir)) + ? { worktreePath: candidate, worktreeRoot: dirname(candidate) } + : null; } catch { return null; } } +type RegisteredWorktreeLookup = ( + canonicalCheckoutPath: string, + gitCommonDir?: string | null, +) => Promise; + +async function isRegisteredGitWorktree(candidate: string): Promise { + const { entries } = await readGitWorktreeEntries(candidate); + for (const entry of entries) { + if ((await normalizePathForOwnership(entry.path)) === candidate) return true; + } + return false; +} + +/** Share Git's worktree registration proof for one batch of checkout reads. */ +export function createRegisteredWorktreeLookup(): RegisteredWorktreeLookup { + const reads = new Map>(); + return async (candidate, gitCommonDir) => { + if (!gitCommonDir) return isRegisteredGitWorktree(candidate); + const repository = await normalizePathForOwnership(gitCommonDir); + let membership = reads.get(repository); + if (!membership) { + membership = readRegisteredWorktreeLookup(candidate).catch((error) => { + reads.delete(repository); + throw error; + }); + reads.set(repository, membership); + } + return (await membership)(candidate); + }; +} + +async function readRegisteredWorktreeLookup(cwd: string): Promise { + const { entries } = await readGitWorktreeEntries(cwd); + const registeredPaths = new Set(entries.map((entry) => resolve(entry.path))); + const resolvedPaths = new Map>(); + return async (candidate) => { + if (registeredPaths.has(candidate)) return true; + for (const path of registeredPaths) { + let canonical = resolvedPaths.get(path); + if (!canonical) { + canonical = normalizePathForOwnership(path); + resolvedPaths.set(path, canonical); + } + if ((await canonical) === candidate) return true; + } + return false; + }; +} + type ParsedPaseoWorktreeInfo = Omit; interface ParsedWorktreeEntry extends ParsedPaseoWorktreeInfo {