Compare commits

...
Author SHA1 Message Date
Mohamed Boudra 065eac9f47 fix(server): avoid shadowed path parameter in workspace reconciliation 2026-11-26 02:46:24 +01:00
Mohamed Boudra 3936137993 fix(server): refresh linked checkouts after Git metadata replacement
A replacement .git directory can exist before reconciliation runs while linked checkouts still point at its missing former worktree entries. Detect missing administrative paths on the dependent checkout so live submodules keep their own scope.
2026-11-26 02:37:19 +01:00
Mohamed Boudra d97d0ba1c0 fix(server): keep submodules out of parent Git rescans
Use Git admin path containment when a watched Git directory is missing. An intact parent and its submodules keep separate common directories even though their administrative files share an ancestor.
2026-11-26 02:32:05 +01:00
Mohamed Boudra f84cfbc362 fix(server): keep Git reconciliation scoped to repository dependencies
An independent repository under the watched root and workspaces attached from other repositories do not share the changed checkout's Git metadata. Select each independently and use membership for publication. Share one worktree listing for both ownership and main-checkout discovery in bare repositories.
2026-11-26 02:26:43 +01:00
Mohamed Boudra c990940288 fix(server): keep checkout read sessions independent of Git execution
The filesystem-only reconciliation probe bundles the reconciliation service on its own. Keep the pass cache lightweight so importing it does not initialize the checkout and relay stack.
2026-11-26 02:17:04 +01:00
Mohamed BoudraandVictor Dozal 72b9e7da38 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 <v.dozal@live.com>
2026-11-26 02:15:06 +01:00
11 changed files with 1031 additions and 105 deletions
+2
View File
@@ -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
@@ -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");
@@ -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");
}),
});
@@ -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<ProjectCheckoutLitePayload> {
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,
});
}
@@ -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<void> {
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<ProjectCheckoutLitePayload> {
private async readCheckout(
cwd: string,
options?: WorkspaceGitCheckoutReadOptions,
): Promise<ProjectCheckoutLitePayload> {
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-<name>` 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" },
@@ -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 { 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<ProjectCheckoutLitePayload>;
changes: ReconciliationChange[];
}
@@ -120,15 +127,27 @@ interface CachedCheckoutRead {
checkout: Promise<ProjectCheckoutLitePayload>;
}
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<string>();
private readonly timedOutPaths = new Map<string, string>();
private inspectionSaturated = false;
private readonly inspectionWaiters = new Set<() => void>();
private readonly pendingInspections = new Map<string, Promise<DirectoryState>>();
private readonly pendingInspections = new Map<string, Promise<DirectoryInspection>>();
private readonly directoryInspection: (targetPath: string) => Promise<DirectoryState>;
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<string>();
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<ReconciliationResult> {
/**
* 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<ReconciliationResult> {
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<string, PersistedWorkspaceRecord[]>();
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<string, PersistedWorkspaceRecord[]>,
changes: ReconciliationChange[],
isAffectedDirectory: (cwd: string) => boolean = () => true,
): Promise<void> {
const checkoutReads: CachedCheckoutRead[] = [];
const checkoutReadLimit = pLimit(CHECKOUT_READ_CONCURRENCY);
const readSession = new CheckoutReadSession();
const readCheckout = (cwd: string): Promise<ProjectCheckoutLitePayload> => {
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<Pick<PersistedProjectRecord, "kind" | "projectKey">> = {};
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<void> {
const projectUpdates: Partial<Pick<PersistedProjectRecord, "kind" | "projectKey">> = {};
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<void> {
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<string>();
const projectIds = new Set<string>();
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<ProjectCheckoutLitePayload> {
private async publishChangedWorkspaces(result: ReconciliationResult): Promise<void> {
const workspaceIds = new Set<string>();
const projectIds = new Set<string>();
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<ProjectCheckoutLitePayload> {
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<DirectoryState> {
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<DirectoryInspection>,
): Promise<DirectoryInspection> {
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<void>((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<typeof setTimeout> | undefined;
try {
return await Promise.race([
pending,
new Promise<DirectoryState>((resolve) => {
new Promise<DirectoryInspection>((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,91 @@ 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<CheckoutDirectory>) => Promise<DirectoryInspection>,
): Promise<Set<string>> {
const resolved = new Map<string, Promise<ResolvedPath>>();
const resolvePath = (path: string) => {
let result = resolved.get(path);
if (!result) {
result = resolveRealpath(path)
.catch(() => resolveNativeRealpath(path))
.then(
(resolvedPath) => ({ path: resolvedPath, missing: false }),
(error) => ({ path, missing: isMissingPathError(error) }),
);
resolved.set(path, result);
}
return result;
};
const gitDirectories = new Map<string, Promise<string | null>>();
const findRepository = async (cwd: string): Promise<CheckoutDirectory["repository"]> => {
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<string>();
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";
@@ -0,0 +1,149 @@
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, mainRepoRoot },
{ currentBranch: "second", isPaseoOwnedWorktree: true, 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([]);
});
});
+88 -5
View File
@@ -39,11 +39,16 @@ import {
ForgeCliMissingError,
ForgeCommandError,
} from "../services/forge-cli-command.js";
import type { CheckoutReadSession } from "./checkout-read-session.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 +980,7 @@ export interface CheckoutContext {
worktreesRoot?: string;
logger?: Pick<Logger, "trace" | "warn">;
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 +1163,19 @@ async function getMainRepoRootFromCommonDir(
return dirname(normalized);
}
const session = context?.readSession;
if (session) {
return session.readMainCheckout(normalized, 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 +1183,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<GitWorktreeEntry, "path" | "isBare">[],
normalized: string,
context?: CheckoutContext,
): Promise<string> {
const paseoPaths = new Set(
(
await Promise.all(
@@ -1312,6 +1338,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 +2089,8 @@ interface CheckoutInspectionContext {
async function inspectCheckoutContext(
cwd: string,
context?: CheckoutContext,
context: CheckoutContext | undefined,
options: { includeAbsoluteGitDir: boolean },
): Promise<CheckoutInspectionContext | null> {
const root = await getWorktreeRoot(cwd, context);
if (!root) {
@@ -2071,7 +2100,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 +2345,7 @@ async function collectCheckoutSnapshotFacts(
cwd: string,
context: CheckoutContext,
): Promise<CheckoutSnapshotFacts> {
const inspected = await inspectCheckoutContext(cwd, context);
const inspected = await inspectCheckoutContext(cwd, context, { includeAbsoluteGitDir: true });
if (!inspected) {
return { isGit: false };
}
@@ -2551,6 +2580,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<CheckoutIdentity> {
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,
@@ -0,0 +1,37 @@
export interface WorktreeRegistration {
entries: readonly { path: string; isBare?: boolean }[];
contains(canonicalCheckoutPath: string): Promise<boolean>;
}
/** Shares repository-wide reads for the lifetime of one checkout reconciliation pass. */
export class CheckoutReadSession {
private readonly worktrees = new Map<string, Promise<WorktreeRegistration>>();
private readonly mainCheckouts = new Map<string, Promise<string>>();
readWorktrees(
repository: string,
read: () => Promise<WorktreeRegistration>,
): Promise<WorktreeRegistration> {
return readOnce(this.worktrees, repository, read);
}
readMainCheckout(repository: string, read: () => Promise<string>): Promise<string> {
return readOnce(this.mainCheckouts, repository, read);
}
}
function readOnce<T>(
reads: Map<string, Promise<T>>,
key: string,
read: () => Promise<T>,
): Promise<T> {
let result = reads.get(key);
if (!result) {
result = read().catch((error) => {
reads.delete(key);
throw error;
});
reads.set(key, result);
}
return result;
}
@@ -177,6 +177,22 @@ async function getGitDirForWorktreeRoot(worktreeRoot: string): Promise<string> {
return gitPath;
}
/** Locate the admin directory used for shared refs and configuration. */
export async function getGitCommonDirForWorktreeRoot(worktreeRoot: string): Promise<string | null> {
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<string> {
const gitDir = await getGitDirForWorktreeRoot(worktreeRoot);
return join(gitDir, "paseo", "worktree.json");
+67 -13
View File
@@ -36,12 +36,13 @@ 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 {
createRealpathAwarePathMatcher,
@@ -244,6 +245,8 @@ export interface PaseoWorktreeOwnership {
export interface PaseoWorktreeOwnershipOptions extends WorktreeRootOptions {
knownGitCommonDir?: string | null;
readSession?: CheckoutReadSession;
runGitCommand?: RunGitCommand;
}
export interface WorktreeRootOptions {
@@ -1123,7 +1126,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 +1167,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,23 +1175,69 @@ 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;
return (await isRegisteredGitWorktree(candidate, options))
? { worktreePath: candidate, worktreeRoot: dirname(candidate) }
: null;
} catch {
return null;
}
}
async function isRegisteredGitWorktree(
candidate: string,
options?: PaseoWorktreeOwnershipOptions,
): Promise<boolean> {
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);
for (const entry of entries) {
if ((await normalizePathForOwnership(entry.path)) === candidate) return true;
}
return false;
}
export async function readWorktreeRegistration(
cwd: string,
gitCommonDir: string,
session: CheckoutReadSession,
run: RunGitCommand = runGitCommand,
): Promise<WorktreeRegistration> {
const repository = await normalizePathForOwnership(gitCommonDir);
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<string, Promise<string>>();
return {
entries,
async contains(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<PaseoWorktreeInfo, "createdAt">;
interface ParsedWorktreeEntry extends ParsedPaseoWorktreeInfo {
/** A bare repository or a worktree whose directory is gone; nothing can work there. */
unusable?: true;
isBare?: true;
}
/**
@@ -1198,8 +1248,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 +1261,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 +1298,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 +1394,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) &&