From f0bf09efee6e94d5e7769eebe1b70dd09897edd4 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Thu, 26 Nov 2026 10:01:52 +0700 Subject: [PATCH] Limit Git rescans to checkouts affected by the change (#10863) Closes #8771 --- .github/workflows/ci.yml | 2 + .../src/server/file-observer/index.test.ts | 10 +- ...it-service.observation.integration.test.ts | 30 ++ .../workspace-git-service.primitive.test.ts | 2 +- .../src/server/workspace-git-service.ts | 22 +- ...rkspace-reconciliation-observation.test.ts | 392 +++++++++++++++++- .../workspace-reconciliation-service.ts | 324 +++++++++++---- .../src/utils/checkout-git-identity.test.ts | 155 +++++++ packages/server/src/utils/checkout-git.ts | 97 ++++- .../server/src/utils/checkout-read-session.ts | 37 ++ packages/server/src/utils/path.ts | 2 +- .../server/src/utils/worktree-metadata.ts | 16 + packages/server/src/utils/worktree.ts | 117 +++++- 13 files changed, 1097 insertions(+), 109 deletions(-) create mode 100644 packages/server/src/utils/checkout-git-identity.test.ts create mode 100644 packages/server/src/utils/checkout-read-session.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 265f3e65c..5115e7278 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/file-observer/index.test.ts b/packages/server/src/server/file-observer/index.test.ts index 8053a6da2..1b0aacf44 100644 --- a/packages/server/src/server/file-observer/index.test.ts +++ b/packages/server/src/server/file-observer/index.test.ts @@ -217,16 +217,22 @@ test("observes files moved into the tree with their directory", async () => { await mkdir(movedFrom); const movedFile = join(movedFrom, "already-written.txt"); await writeFile(movedFile, "ready"); + const canary = createWatcherLivenessCanary(root); const events: FileChange[] = []; const subscription = await subscribeToFileChanges(root, (error, batch) => { expect(error).toBeNull(); - events.push(...batch); + events.push(...canary.filterEvents(batch)); }); + // macOS starts delivering native events asynchronously after subscription. + await canary.verify(); + events.length = 0; + const movedTo = join(root, "prepared"); await rename(movedFrom, movedTo); + // Native recursive backends discover moved directory contents on their quiet audit. await expect - .poll(() => events.map((event) => event.path)) + .poll(() => events.map((event) => event.path), { timeout: 10_000 }) .toContain(join(movedTo, "already-written.txt")); await subscription.unsubscribe(); }); 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 a943fcf48..2e3cfa941 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 c1fc13238..fdf115d27 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 59cacbeef..97e19b37a 100644 --- a/packages/server/src/server/workspace-git-service.ts +++ b/packages/server/src/server/workspace-git-service.ts @@ -7,6 +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 { CheckoutReadSession } from "../utils/checkout-read-session.js"; import type { CheckoutContext, UpstreamState } from "../utils/checkout-git.js"; import { type BranchCheckoutResolution, @@ -19,6 +20,7 @@ import { getCheckoutRefDerivedState, getCheckoutSnapshotFacts, getCheckoutShortstat, + getCheckoutIdentity, getCheckoutStatus, getCheckoutWorktreeState, getPullRequestStatus, @@ -367,6 +369,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 +420,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 +641,7 @@ function buildDefaultWorkspaceGitServiceDeps( subscribe, getCheckoutSnapshotFacts, getCheckoutRefDerivedState, + getCheckoutIdentity, getCheckoutStatus, getCheckoutShortstat, getCheckoutWorktreeState, @@ -875,16 +880,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 +899,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 +911,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 f8cd5f106..469e0db19 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,329 @@ 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(["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.each(["removal", "replacement"])( + "updates a separately registered linked worktree after updates and metadata %s", + async (change) => { + 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"); + if (change === "replacement") observed.git("repo", "init", "-b", "main"); + 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("skips independent nested repositories and workspaces attached from other repositories", async () => { + const observed = new ObservedPlacements( + [ + { + id: "outer", + root: "outer", + workspaces: [ + { id: "outer-ws", cwd: "outer" }, + { id: "foreign-ws", cwd: "foreign" }, + ], + }, + { + id: "nested", + root: "outer/independent", + workspaces: [ + { id: "nested-ws", cwd: "outer/independent" }, + { id: "nested-linked-ws", cwd: "independent-linked" }, + ], + }, + ], + true, + ); + try { + await observed.start(); + for (const root of ["outer", "outer/independent", "foreign"]) { + observed.git(root, "init", "-b", "main"); + } + observed.git( + "outer/independent", + "-c", + "user.name=Test", + "-c", + "user.email=test@example.com", + "-c", + "commit.gpgsign=false", + "commit", + "--allow-empty", + "-m", + "initial", + ); + observed.git( + "outer/independent", + "worktree", + "add", + "-b", + "feature", + "../../independent-linked", + ); + observed.change("outer", ".git"); + await observed.advanceBy(DEBOUNCE_MS); + + expect(observed.takeCheckoutReads()).toEqual(["outer"]); + expect(await observed.placement("outer-ws")).toMatchObject({ kind: "local_checkout" }); + for (const id of ["foreign-ws", "nested-ws", "nested-linked-ws"]) { + expect(await observed.placement(id)).toMatchObject({ kind: "directory" }); + } + } finally { + await observed.disposeGit(); + } + }); + + test("skips a submodule and its linked checkout when the parent Git directory is intact", async () => { + const observed = new ObservedPlacements( + [{ id: "outer", root: "outer", workspaces: [{ id: "outer-ws", cwd: "outer" }] }], + true, + ); + try { + await observed.start(); + await observed.add({ id: "source", root: "source" }); + observed.git("source", "init", "-b", "main"); + observed.git( + "source", + "-c", + "user.name=Test", + "-c", + "user.email=test@example.com", + "-c", + "commit.gpgsign=false", + "commit", + "--allow-empty", + "-m", + "initial", + ); + observed.git("outer", "init", "-b", "main"); + observed.git( + "outer", + "-c", + "protocol.file.allow=always", + "submodule", + "add", + "../source", + "sub", + ); + observed.git("outer/sub", "worktree", "add", "-b", "feature", "../../sub-linked"); + await observed.add({ id: "sub", root: "outer/sub" }); + await observed.add({ id: "sub-linked", root: "sub-linked" }); + + observed.change("outer", ".git"); + await observed.advanceBy(DEBOUNCE_MS); + + expect(observed.takeCheckoutReads()).toEqual(["outer"]); + observed.rename("outer/.git", "outer/.git-backup"); + observed.change("outer", ".git"); + await observed.advanceBy(DEBOUNCE_MS); + + expect(observed.takeCheckoutReads()).toEqual(["outer", "outer/sub", "sub-linked"]); + } 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 84a0221a7..03cdb2e0f 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 { basename, 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 { CheckoutReadSession } from "../utils/checkout-read-session.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; @@ -110,7 +117,7 @@ export interface WorkspaceReconciliationServiceOptions { interface ProjectReconciliationInput { project: PersistedProjectRecord; siblings: PersistedWorkspaceRecord[]; - currentGit: ProjectCheckoutLitePayload; + currentGit: ProjectCheckoutLitePayload | null; readCheckout: (cwd: string) => Promise; changes: ReconciliationChange[]; } @@ -120,15 +127,27 @@ interface CachedCheckoutRead { checkout: Promise; } +interface ResolvedPath { + path: string; + missing: boolean; +} + +interface CheckoutDirectory { + path: string; + repository: { root: string; commonDir: ResolvedPath } | 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 +170,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 +233,33 @@ 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 workspacesByProject = new Map(); const workspaceStates = await mapBounded( - workspaces.filter((w) => !w.archivedAt), + activeWorkspaces.filter((workspace) => isAffectedDirectory(workspace.cwd)), async (workspace) => ({ workspace, state: await this.inspectDirectory(workspace.cwd) }), ); for (const { workspace, state } of workspaceStates) { @@ -232,13 +270,17 @@ export class WorkspaceReconciliationService { workspacesByProject.set(workspace.projectId, siblings); } const projectStates = await mapBounded( - projects.filter((p) => !p.archivedAt), + projects.filter( + (project) => + isAffectedDirectory(project.rootPath) || workspacesByProject.has(project.projectId), + ), async (project) => ({ project, state: await this.inspectDirectory(project.rootPath) }), ); await this.reconcileGitMetadataForProjects( projectStates.filter(({ state }) => state === "directory").map(({ project }) => project), workspacesByProject, changes, + isAffectedDirectory, ); if (changes.length > 0) this.onChanges?.(changes); return { changesApplied: changes, durationMs: Date.now() - start }; @@ -348,13 +390,15 @@ export class WorkspaceReconciliationService { projectsToReconcile: PersistedProjectRecord[], workspacesByProject: Map, changes: ReconciliationChange[], + isAffectedDirectory: (cwd: string) => boolean = () => true, ): Promise { const checkoutReads: CachedCheckoutRead[] = []; const checkoutReadLimit = pLimit(CHECKOUT_READ_CONCURRENCY); + const readSession = new CheckoutReadSession(); 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; }; @@ -369,7 +413,7 @@ export class WorkspaceReconciliationService { await Promise.all( roots.map(async ({ rootPath, projects }) => { try { - const rootGit = await readCheckout(rootPath); + const rootGit = isAffectedDirectory(rootPath) ? await readCheckout(rootPath) : null; await Promise.all( projects.map((project) => this.reconcileProject({ @@ -402,39 +446,7 @@ export class WorkspaceReconciliationService { ); const project = await this.projectRegistry.get(input.project.projectId); if (!project || project.archivedAt || project.rootPath !== input.project.rootPath) return; - const projectUpdates: Partial> = {}; - const mappedKind = deriveProjectKind(currentGit); - const projectKey = deriveProjectKey({ - rootPath: project.rootPath, - remoteUrl: currentGit.remoteUrl, - worktreeRoot: currentGit.worktreeRoot, - mainRepoRoot: currentGit.mainRepoRoot, - serverId: this.serverId, - }); - - if (project.kind !== mappedKind) { - projectUpdates.kind = mappedKind; - } - if (project.projectKey !== projectKey) { - projectUpdates.projectKey = projectKey; - } - - if (Object.keys(projectUpdates).length > 0) { - const timestamp = new Date().toISOString(); - let applied = false; - await this.projectRegistry.update(project.projectId, (current) => { - if (current.archivedAt || current.rootPath !== project.rootPath) return current; - applied = true; - return { ...current, ...projectUpdates, updatedAt: timestamp }; - }); - if (applied) - changes.push({ - kind: "project_updated", - projectId: project.projectId, - directory: project.rootPath, - fields: projectUpdates, - }); - } + if (currentGit) await this.reconcileProjectMetadata(project, currentGit, changes); await Promise.all( workspaceCheckouts.map(async (entry) => { @@ -468,6 +480,46 @@ export class WorkspaceReconciliationService { ); } + private async reconcileProjectMetadata( + project: PersistedProjectRecord, + currentGit: ProjectCheckoutLitePayload, + changes: ReconciliationChange[], + ): Promise { + const projectUpdates: Partial> = {}; + const mappedKind = deriveProjectKind(currentGit); + const projectKey = deriveProjectKey({ + rootPath: project.rootPath, + remoteUrl: currentGit.remoteUrl, + worktreeRoot: currentGit.worktreeRoot, + mainRepoRoot: currentGit.mainRepoRoot, + serverId: this.serverId, + }); + + if (project.kind !== mappedKind) { + projectUpdates.kind = mappedKind; + } + if (project.projectKey !== projectKey) { + projectUpdates.projectKey = projectKey; + } + + if (Object.keys(projectUpdates).length > 0) { + const timestamp = new Date().toISOString(); + let applied = false; + await this.projectRegistry.update(project.projectId, (current) => { + if (current.archivedAt || current.rootPath !== project.rootPath) return current; + applied = true; + return { ...current, ...projectUpdates, updatedAt: timestamp }; + }); + if (applied) + changes.push({ + kind: "project_updated", + projectId: project.projectId, + directory: project.rootPath, + fields: projectUpdates, + }); + } + } + private async syncProjectRootWatches(): Promise { if (this.disposed) return; const projects = await this.projectRegistry.list(); @@ -496,6 +548,7 @@ export class WorkspaceReconciliationService { { recursive: false }, (_event, filename) => { if (filename === null || filename.toString() === ".git") { + this.changedRoots.add(project.rootPath); this.scheduleObservedReconciliation(); } }, @@ -539,28 +592,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 +619,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 +656,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 +665,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 +701,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 +712,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 +743,102 @@ 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 = (targetPath: string): Promise => { + let result = resolved.get(targetPath); + if (!result) { + // Prefer the native resolver so Windows 8.3 short paths (e.g. RUNNER~1) canonicalize + // to the same long path Git writes into linked worktree `.git` pointers. + result = resolveNativeRealpath(targetPath) + .catch((error) => { + if (isMissingPathError(error)) throw error; + return resolveRealpath(targetPath); + }) + .then( + (resolvedPath) => ({ path: resolvedPath, missing: false }), + async (error) => { + if (!isMissingPathError(error)) return { path: targetPath, missing: false }; + const parent = dirname(targetPath); + if (parent === targetPath) return { path: targetPath, missing: true }; + const resolvedParent = await resolvePath(parent); + return { path: join(resolvedParent.path, basename(targetPath)), missing: true }; + }, + ); + resolved.set(targetPath, result); + } + return result; + }; + const gitDirectories = new Map>(); + const findRepository = 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 { root: current, commonDir: await resolvePath(gitDir) }; + if (dirname(current) === current) return null; + } + }; + + const inspectCheckoutDirectory = (directory: string) => + inspect(directory, async () => { + const { path } = await resolvePath(directory); + return { path, repository: await findRepository(path) }; + }); + const dirty = await mapBounded(changedRoots, inspectCheckoutDirectory); + 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.repository ? [entry.repository.commonDir.path] : [], + ); + 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 inspectCheckoutDirectory(candidate); + const path = typeof entry === "string" ? candidate : entry.path; + const repository = typeof entry === "string" ? null : entry.repository; + const commonDir = repository?.commonDir; + // A broken checkout can still point beneath the changed .git entry after + // removal or replacement. Existing submodule metadata has its own identity. + const sharesMetadata = + commonDir && + (repositories.matchesExact(commonDir.path) || + (commonDir.missing && gitEntries.matches(commonDir.path))); + // A surviving nested repository provides its own metadata even if its + // parent gains or loses a .git entry. + const hasIndependentNestedRepository = + repository && tree.matches(repository.root) && !tree.matchesExact(repository.root); + if (sharesMetadata || (tree.matches(path) && !hasIndependentNestedRepository)) { + 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 000000000..ea4a11a07 --- /dev/null +++ b/packages/server/src/utils/checkout-git-identity.test.ts @@ -0,0 +1,155 @@ +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 { getCheckoutIdentity, getCheckoutStatus } from "./checkout-git.js"; +import { CheckoutReadSession } from "./checkout-read-session.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 = new CheckoutReadSession(); + 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("shares worktree registration and main checkout discovery in a bare repository", async () => { + const bare = join(tempDir, "shared.git"); + const main = join(tempDir, "main"); + const first = join(tempDir, "first"); + const second = join(tempDir, "second"); + git(repoDir, "clone", "--bare", repoDir, bare); + git(bare, "worktree", "add", main, "main"); + git(bare, "worktree", "add", "-b", "first", first); + git(bare, "worktree", "add", "-b", "second", second); + await writePaseoWorktreeMetadata(first, { baseRefName: "main" }); + await writePaseoWorktreeMetadata(second, { baseRefName: "main" }); + + const readSession = new CheckoutReadSession(); + startGitCommandMetrics(); + try { + const checkouts = await Promise.all( + [main, first, second].map((cwd) => getCheckoutIdentity(cwd, { paseoHome, readSession })), + ); + const mainRepoRoot = await realpath(main); + expect(checkouts).toMatchObject([ + { currentBranch: "main", isPaseoOwnedWorktree: false, mainRepoRoot: null }, + { currentBranch: "first", isPaseoOwnedWorktree: true }, + { currentBranch: "second", isPaseoOwnedWorktree: true }, + ]); + for (const checkout of checkouts.slice(1)) { + if (!checkout.isGit || !checkout.mainRepoRoot) { + throw new Error("Expected bare worktree checkout to report mainRepoRoot"); + } + expect(realpathSync.native(checkout.mainRepoRoot)).toBe(mainRepoRoot); + } + 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 253e042a7..c711e0207 100644 --- a/packages/server/src/utils/checkout-git.ts +++ b/packages/server/src/utils/checkout-git.ts @@ -39,11 +39,17 @@ import { ForgeCliMissingError, ForgeCommandError, } from "../services/forge-cli-command.js"; +import type { CheckoutReadSession } from "./checkout-read-session.js"; +import { areEquivalentPaths, normalizePathForComparison } from "./path.js"; import { parseGitRevParsePath, resolveGitRevParsePath } from "./git-rev-parse-path.js"; 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 { + isPaseoOwnedWorktreeCwd, + readWorktreeRegistration, + resolvePaseoWorktreesBaseRoot, +} from "./worktree.js"; import { branchNameFromRef, findPaseoWorktreeRootForCwd, @@ -975,6 +981,7 @@ export interface CheckoutContext { 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. @@ -1157,6 +1164,22 @@ async function getMainRepoRootFromCommonDir( return dirname(normalized); } + const session = context?.readSession; + if (session) { + return session.readMainCheckout( + normalizePathForComparison(normalized, process.platform === "win32"), + async () => { + const { entries } = await readWorktreeRegistration( + cwd, + normalized, + session, + getRunGitCommand(context), + ); + return selectMainCheckout(entries, normalized, context); + }, + ); + } + const { stdout: worktreeOut } = await getRunGitCommand(context)( ["worktree", "list", "--porcelain"], { @@ -1164,7 +1187,14 @@ async function getMainRepoRootFromCommonDir( envOverlay: READ_ONLY_GIT_ENV, }, ); - const worktrees = parseWorktreeList(worktreeOut); + return selectMainCheckout(parseWorktreeList(worktreeOut), normalized, context); +} + +async function selectMainCheckout( + worktrees: readonly Pick[], + normalized: string, + context?: CheckoutContext, +): Promise { const paseoPaths = new Set( ( await Promise.all( @@ -1312,6 +1342,8 @@ async function getPaseoWorktreeForCwd( paseoHome: options.context?.paseoHome, worktreesRoot: options.context?.worktreesRoot, knownGitCommonDir: options.knownGitCommonDir, + readSession: options.context?.readSession, + runGitCommand: options.context?.runGitCommand, }); if (!ownership.allowed) { return { isPaseoOwnedWorktree: false }; @@ -2061,7 +2093,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 +2104,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 +2349,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 +2584,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 && !areEquivalentPaths(mainRepoRoot, 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/checkout-read-session.ts b/packages/server/src/utils/checkout-read-session.ts new file mode 100644 index 000000000..54decd8b5 --- /dev/null +++ b/packages/server/src/utils/checkout-read-session.ts @@ -0,0 +1,37 @@ +export interface WorktreeRegistration { + entries: readonly { path: string; isBare?: boolean }[]; + contains(canonicalCheckoutPath: string): Promise; +} + +/** Shares repository-wide reads for the lifetime of one checkout reconciliation pass. */ +export class CheckoutReadSession { + private readonly worktrees = new Map>(); + private readonly mainCheckouts = new Map>(); + + readWorktrees( + repository: string, + read: () => Promise, + ): Promise { + return readOnce(this.worktrees, repository, read); + } + + readMainCheckout(repository: string, read: () => Promise): Promise { + return readOnce(this.mainCheckouts, repository, read); + } +} + +function readOnce( + reads: Map>, + key: string, + read: () => Promise, +): Promise { + let result = reads.get(key); + if (!result) { + result = read().catch((error) => { + reads.delete(key); + throw error; + }); + reads.set(key, result); + } + return result; +} diff --git a/packages/server/src/utils/path.ts b/packages/server/src/utils/path.ts index b507ac280..1e27fc76c 100644 --- a/packages/server/src/utils/path.ts +++ b/packages/server/src/utils/path.ts @@ -246,7 +246,7 @@ export function looksLikeDefiniteWindowsPath(value: string): boolean { ); } -function normalizePathForComparison(value: string, compareAsWindows: boolean): string { +export function normalizePathForComparison(value: string, compareAsWindows: boolean): string { const normalized = normalizePathPreservingCase(value, compareAsWindows); return compareAsWindows ? normalized.toLowerCase() : normalized; } diff --git a/packages/server/src/utils/worktree-metadata.ts b/packages/server/src/utils/worktree-metadata.ts index 912d5fd94..6a306b551 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 d7b5d4227..360bcaf83 100644 --- a/packages/server/src/utils/worktree.ts +++ b/packages/server/src/utils/worktree.ts @@ -36,19 +36,23 @@ import { writePaseoWorktreeRuntimeMetadata, } from "./worktree-metadata.js"; import { runWithRepositoryRoot } from "./git-repository-discovery.js"; -import { runGitCommand } from "./run-git-command.js"; +import { runGitCommand, type RunGitCommand } from "./run-git-command.js"; import { getCurrentBranch, resolveRepositoryDefaultBranch } from "./checkout-git.js"; import { spawnProcess } from "./spawn.js"; import { applyLaunchWrap } from "./launch-wrap.js"; import { resolvePaseoHome } from "../server/paseo-home.js"; import { createExternalProcessEnv } from "../server/paseo-env.js"; +import type { CheckoutReadSession, WorktreeRegistration } from "./checkout-read-session.js"; import { parseGitRevParsePath, resolveGitRevParsePath } from "./git-rev-parse-path.js"; import { + areEquivalentPaths, + createPathContainmentMatcher, createRealpathAwarePathMatcher, expandTilde, getRealpathAwareRelativePath, getRelativePathInsideRoot, isPathInsideRoot, + normalizePathForComparison, normalizePathForIdentity, } from "./path.js"; import { terminateWithTreeKill } from "./tree-kill.js"; @@ -244,6 +248,8 @@ export interface PaseoWorktreeOwnership { export interface PaseoWorktreeOwnershipOptions extends WorktreeRootOptions { knownGitCommonDir?: string | null; + readSession?: CheckoutReadSession; + runGitCommand?: RunGitCommand; } export interface WorktreeRootOptions { @@ -1074,6 +1080,23 @@ async function ownershipPathVariants(input: string): Promise { return [...variants]; } +async function canonicalizeOwnershipPath(input: string): Promise { + try { + return await ownershipIdentityIo(() => resolveNativeOwnershipPath(input)); + } catch { + return normalizePathForOwnership(input); + } +} + +async function areEquivalentOwnershipPaths(left: string, right: string): Promise { + if (areEquivalentPaths(left, right)) return true; + const [leftVariants, rightVariants] = await Promise.all([ + ownershipPathVariants(left), + ownershipPathVariants(right), + ]); + return leftVariants.some((l) => rightVariants.some((r) => areEquivalentPaths(l, r))); +} + // Keep lexical variants for missing paths: archive must still recognize a removed // worktree below a symlinked worktrees root, whose full realpath no longer exists. async function getOwnershipRelativePath(root: string, candidate: string): Promise { @@ -1123,7 +1146,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,30 +1187,92 @@ 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); if (!root) return null; const candidate = await normalizePathForOwnership(root); - if (repoRoot !== undefined && candidate === (await normalizePathForOwnership(repoRoot))) + if (repoRoot !== undefined && (await areEquivalentOwnershipPaths(candidate, 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; + return (await isRegisteredGitWorktree(candidate, options)) + ? { worktreePath: candidate, worktreeRoot: dirname(candidate) } + : null; } catch { return null; } } +async function isRegisteredGitWorktree( + candidate: string, + options?: PaseoWorktreeOwnershipOptions, +): Promise { + if (options?.readSession && options.knownGitCommonDir) { + const registration = await readWorktreeRegistration( + candidate, + options.knownGitCommonDir, + options.readSession, + options.runGitCommand, + ); + return registration.contains(candidate); + } + const { entries } = await readGitWorktreeEntries(candidate); + const matcher = createPathContainmentMatcher({ + roots: await ownershipPathVariants(candidate), + compareAsWindows: process.platform === "win32", + }); + for (const entry of entries) { + if (matcher.matchesExact(entry.path)) return true; + const entryVariants = await ownershipPathVariants(entry.path); + if (entryVariants.some((variant) => matcher.matchesExact(variant))) return true; + } + return false; +} + +export async function readWorktreeRegistration( + cwd: string, + gitCommonDir: string, + session: CheckoutReadSession, + run: RunGitCommand = runGitCommand, +): Promise { + const repository = normalizePathForComparison( + await canonicalizeOwnershipPath(gitCommonDir), + process.platform === "win32", + ); + return session.readWorktrees(repository, async () => { + const { entries } = await readGitWorktreeEntries(cwd, run); + const registeredPaths = new Set(entries.map((entry) => resolve(entry.path))); + const resolvedPaths = new Map>(); + return { + entries, + async contains(candidate) { + const matcher = createPathContainmentMatcher({ + roots: await ownershipPathVariants(candidate), + compareAsWindows: process.platform === "win32", + }); + for (const registered of registeredPaths) { + if (matcher.matchesExact(registered)) return true; + } + for (const registered of registeredPaths) { + let variants = resolvedPaths.get(registered); + if (!variants) { + variants = ownershipPathVariants(registered); + resolvedPaths.set(registered, variants); + } + if ((await variants).some((variant) => matcher.matchesExact(variant))) return true; + } + return false; + }, + }; + }); +} + type ParsedPaseoWorktreeInfo = Omit; interface ParsedWorktreeEntry extends ParsedPaseoWorktreeInfo { /** A bare repository or a worktree whose directory is gone; nothing can work there. */ unusable?: true; + isBare?: true; } /** @@ -1198,8 +1283,9 @@ interface ParsedWorktreeEntry extends ParsedPaseoWorktreeInfo { */ async function readGitWorktreeEntries( cwd: string, + run: RunGitCommand = runGitCommand, ): Promise<{ entries: ParsedWorktreeEntry[]; exact: boolean }> { - const nulResult = await runGitCommand(["worktree", "list", "--porcelain", "-z"], { + const nulResult = await run(["worktree", "list", "--porcelain", "-z"], { cwd, envOverlay: READ_ONLY_GIT_ENV, acceptExitCodes: [0, 129], @@ -1210,7 +1296,7 @@ async function readGitWorktreeEntries( exact: true, }; } - const { stdout } = await runGitCommand(["worktree", "list", "--porcelain"], { + const { stdout } = await run(["worktree", "list", "--porcelain"], { cwd, envOverlay: READ_ONLY_GIT_ENV, }); @@ -1247,7 +1333,10 @@ function parseWorktreeEntriesTokens( current.branchName = ref.startsWith("refs/heads/") ? ref.slice("refs/heads/".length) : ref; } else if (token.startsWith("HEAD ")) { current.head = token.slice("HEAD ".length).trim(); - } else if (token === "bare" || token.startsWith("prunable")) { + } else if (token === "bare") { + current.isBare = true; + current.unusable = true; + } else if (token.startsWith("prunable")) { current.unusable = true; } else if ((lineDelimited ? token.trim() : token).length === 0) { if (current.path) { @@ -1340,7 +1429,7 @@ async function listPaseoWorktreesAtRepositoryRoot({ const roots = await ownershipPathVariants(projectWorktreesRoot); const worktrees: PaseoWorktreeInfo[] = []; // Inspect foreign paths sequentially; a large worktree list must not consume the FS pool. - for (const { unusable: _unusable, ...entry } of entries) { + for (const { unusable: _unusable, isBare: _isBare, ...entry } of entries) { const path = await normalizePathForOwnership(entry.path); if ( !roots.some((root) => getRelativePathInsideRoot(root, path) !== null) &&