fix(server): keep Git observation and worktree IO off the event loop

Resolve subscription path identities before callbacks and serialize async worktree metadata mutations by canonical ownership. Git command tracing must not probe the working directory before spawning.
This commit is contained in:
Mohamed Boudra
2026-10-26 18:05:32 +01:00
parent 4f9d9d6de2
commit 32356db309
18 changed files with 805 additions and 301 deletions
@@ -0,0 +1,89 @@
import { realpath } from "node:fs";
import { promisify } from "node:util";
import pLimit from "p-limit";
import { sep } from "node:path";
import { looksLikeDefiniteWindowsPath, normalizePathPreservingCase } from "../utils/path.js";
const nativeRealpath = promisify(realpath.native);
const jsRealpath = promisify(realpath);
const identityIo = pLimit(2);
/** A subscription owns its lexical namespace, including the OS's real-root alias. */
export class GitObservationPaths {
private constructor(
private readonly root: string,
private readonly aliases: string[],
private readonly windows: boolean,
) {}
static async create(root: string): Promise<GitObservationPaths> {
const windows = looksLikeDefiniteWindowsPath(root);
const normalizePath = (value: string) =>
windows
? normalizePathPreservingCase(value, true).replaceAll("\\", "/").toLowerCase()
: normalizePathPreservingCase(value, false);
const aliases = new Set([normalizePath(root)]);
// Sequential: foreign paths must not fan out into the shared libuv pool.
for (const resolve of [nativeRealpath, jsRealpath]) {
try {
aliases.add(normalizePath(await identityIo(() => resolve(root))));
} catch {
/* Missing roots retain lexical identity. */
}
}
return new GitObservationPaths(root, [...aliases], windows);
}
relative(candidate: string): string | null {
const normalized = this.normalizeEventPath(candidate);
const comparable = this.windows ? normalized.toLowerCase() : normalized;
for (const alias of this.aliases) {
if (comparable === alias) return "";
const prefix = alias.endsWith("/") ? alias : `${alias}/`;
if (comparable.startsWith(prefix)) {
// Slice the original spelling, preserving case in ref names on Windows.
return normalized.slice(prefix.length);
}
}
return null;
}
// Compile excluded subtrees in every established root namespace. The event callback
// only compares strings; neither an ignored root nor an event needs another realpath.
createEventFilter(excludedRoots: Iterable<string>): (candidate: string) => boolean {
const excluded: string[] = [];
for (const root of excludedRoots) {
const relative = this.relative(root);
if (relative === null) continue;
for (const alias of this.aliases) {
const subtree = relative ? `${alias}/${relative}` : alias;
excluded.push(this.windows ? subtree.toLowerCase() : subtree);
}
}
const prefixes = excluded.map((root) => `${root}/`);
return (candidate) => {
const normalized = this.normalizeEventPath(candidate);
const comparable = this.windows ? normalized.toLowerCase() : normalized;
if (this.aliases.includes(comparable)) return false;
for (let i = 0; i < excluded.length; i++) {
if (comparable === excluded[i] || comparable.startsWith(prefixes[i])) return false;
}
return true;
};
}
private normalizeEventPath(candidate: string): string {
if (this.windows) return normalizePathPreservingCase(candidate, true).replaceAll("\\", "/");
if (candidate.includes("/.") || candidate.includes("//") || candidate.endsWith("/"))
return normalizePathPreservingCase(candidate, false);
return candidate;
}
matches = (candidate: string): boolean => this.relative(candidate) === "";
toWatchPath(candidate: string): string {
const relative = this.relative(candidate);
if (relative === null) return candidate;
return relative ? `${this.root}${sep}${relative}` : this.root;
}
}
@@ -548,7 +548,7 @@ test("renames an eligible unnamed branch-off worktree once on first agent contex
);
expect(created.worktree.branchName).toBe("dazzling-yak");
expect(readPaseoWorktreeMetadata(created.worktree.worktreePath)).toMatchObject({
expect(await readPaseoWorktreeMetadata(created.worktree.worktreePath)).toMatchObject({
version: 2,
firstAgentBranchAutoName: {
status: "pending",
@@ -575,7 +575,7 @@ test("renames an eligible unnamed branch-off worktree once on first agent contex
branchName: "renamed-from-agent-context",
});
expect(branchAfterFirst).toBe("renamed-from-agent-context");
expect(readPaseoWorktreeMetadata(created.worktree.worktreePath)).toMatchObject({
expect(await readPaseoWorktreeMetadata(created.worktree.worktreePath)).toMatchObject({
version: 2,
firstAgentBranchAutoName: {
status: "attempted",
@@ -762,7 +762,7 @@ test("leaves the branch alone when generated branch text is invalid", async () =
.toString()
.trim(),
).toBe("dazzling-yak");
expect(readPaseoWorktreeMetadata(created.worktree.worktreePath)).toMatchObject({
expect(await readPaseoWorktreeMetadata(created.worktree.worktreePath)).toMatchObject({
version: 2,
firstAgentBranchAutoName: {
status: "attempted",
@@ -794,7 +794,7 @@ test("does not mark checkout branch worktrees as eligible for first-agent rename
// baseRefName must be the repo's default branch, not the checked-out branch
// itself — otherwise the diff panel compares the branch against itself and
// always shows no changes.
expect(readPaseoWorktreeMetadata(created.worktree.worktreePath)).toMatchObject({
expect(await readPaseoWorktreeMetadata(created.worktree.worktreePath)).toMatchObject({
version: 1,
baseRefName: "main",
});
@@ -831,7 +831,7 @@ test("does not mark GitHub PR checkout worktrees as eligible for first-agent ren
createDeps(),
);
expect(readPaseoWorktreeMetadata(created.worktree.worktreePath)).toMatchObject({
expect(await readPaseoWorktreeMetadata(created.worktree.worktreePath)).toMatchObject({
version: 1,
baseRefName: "main",
});
@@ -77,7 +77,7 @@ async function createPaseoWorktreeWithPriority(
const workspaceCwdPlan = await planWorkspaceCwdForWorktree(input.cwd, deps.workspaceGitService);
const createdWorktree = await createWorktreeCore(input, deps);
try {
maybeMarkFirstAgentBranchAutoNameEligible({ createdWorktree });
await maybeMarkFirstAgentBranchAutoNameEligible({ createdWorktree });
const workspaceCwd = mapWorkspaceRelativeCwdToWorktree({
relativeWorkspaceCwd: workspaceCwdPlan.relativeWorkspaceCwd,
targetWorktreePath: createdWorktree.worktree.worktreePath,
@@ -182,9 +182,9 @@ export async function attemptFirstAgentBranchAutoName(options: {
return { attempted: false, renamed: false, branchName: null };
}
let metadata: ReturnType<typeof readPaseoWorktreeMetadata>;
let metadata: Awaited<ReturnType<typeof readPaseoWorktreeMetadata>>;
try {
metadata = readPaseoWorktreeMetadata(options.cwd);
metadata = await readPaseoWorktreeMetadata(options.cwd);
} catch {
return { attempted: false, renamed: false, branchName: null };
}
@@ -199,11 +199,11 @@ export async function attemptFirstAgentBranchAutoName(options: {
const getCurrentBranchImpl = options.getCurrentBranch ?? getCurrentBranch;
const placeholderBranchName = metadata.firstAgentBranchAutoName.placeholderBranchName;
if ((await getCurrentBranchImpl(options.cwd)) !== placeholderBranchName) {
markPaseoWorktreeFirstAgentBranchAutoNameAttempted(options.cwd);
await markPaseoWorktreeFirstAgentBranchAutoNameAttempted(options.cwd);
return { attempted: true, renamed: false, branchName: null };
}
markPaseoWorktreeFirstAgentBranchAutoNameAttempted(options.cwd);
await markPaseoWorktreeFirstAgentBranchAutoNameAttempted(options.cwd);
const branchName = await options.generateBranchNameFromContext({
cwd: options.cwd,
@@ -264,15 +264,15 @@ async function findAvailableBranchName(options: {
return null;
}
function maybeMarkFirstAgentBranchAutoNameEligible(options: {
async function maybeMarkFirstAgentBranchAutoNameEligible(options: {
createdWorktree: Awaited<ReturnType<typeof createWorktreeCore>>;
}): void {
}): Promise<void> {
const { createdWorktree } = options;
if (!createdWorktree.created || createdWorktree.intent.kind !== "branch-off") {
return;
}
writePaseoWorktreeFirstAgentBranchAutoNameMetadata(createdWorktree.worktree.worktreePath, {
await writePaseoWorktreeFirstAgentBranchAutoNameMetadata(createdWorktree.worktree.worktreePath, {
placeholderBranchName: createdWorktree.worktree.branchName,
});
}
@@ -9228,8 +9228,8 @@ test("workspace auto-name uses the backing root for a nested worktree", async ()
execFileSync("git", ["add", "README.md"], { cwd: repoDir, stdio: "pipe" });
execFileSync("git", ["commit", "-m", "initial"], { cwd: repoDir, stdio: "pipe" });
execFileSync("git", ["branch", "-M", "placeholder-branch"], { cwd: repoDir, stdio: "pipe" });
writePaseoWorktreeMetadata(repoDir, { baseRefName: "main" });
writePaseoWorktreeFirstAgentBranchAutoNameMetadata(repoDir, {
await writePaseoWorktreeMetadata(repoDir, { baseRefName: "main" });
await writePaseoWorktreeFirstAgentBranchAutoNameMetadata(repoDir, {
placeholderBranchName: "placeholder-branch",
});
const workspaceCwd = path.join(repoDir, "packages", "app");
@@ -9288,6 +9288,7 @@ test("workspace auto-name uses the backing root for a nested worktree", async ()
firstAgentContext: { prompt: "Fix checkout title" },
});
await vi.runAllTimersAsync();
await vi.waitFor(() => expect(emittedCwds).toEqual([workspaceCwd]));
expect(generateCalls).toBe(1);
expect(stored.get(workspace.workspaceId)).toMatchObject({
@@ -9299,7 +9300,7 @@ test("workspace auto-name uses the backing root for a nested worktree", async ()
.toString()
.trim(),
).toBe("placeholder-branch");
expect(readPaseoWorktreeMetadata(repoDir)).toMatchObject({
expect(await readPaseoWorktreeMetadata(repoDir)).toMatchObject({
version: 2,
firstAgentBranchAutoName: {
status: "attempted",
@@ -347,7 +347,7 @@ async function createBaseRecoveryFixture(baseBranch: string | null) {
test("preserves ordinary checkout behavior when no separate base was recorded", async () => {
const fixture = await createBaseRecoveryFixture(null);
writePaseoWorktreeMetadata(fixture.workspace.cwd, { baseRefName: "feature" });
await writePaseoWorktreeMetadata(fixture.workspace.cwd, { baseRefName: "feature" });
await fixture.archiveAndRemove();
await fixture.service.restore(fixture.workspace.workspaceId);
expect((await fixture.registry.get(fixture.workspace.workspaceId))?.baseBranch).toBeNull();
@@ -430,7 +430,7 @@ test("restores the branch HEAD with a base name when the exact base is missing",
});
expect(existsSync(fixture.workspace.cwd)).toBe(true);
expect((await fixture.registry.get(fixture.workspace.workspaceId))?.archivedAt).toBeNull();
const metadata = readPaseoWorktreeMetadata(fixture.workspace.cwd);
const metadata = await readPaseoWorktreeMetadata(fixture.workspace.cwd);
expect(metadata).toMatchObject({ baseRefName: "main" });
expect(metadata?.baseRef).toBeUndefined();
expect(
@@ -450,7 +450,7 @@ test("restore fetches a deleted local branch from origin and retains its base",
await fixture.archiveAndRemove();
execFileSync("git", ["branch", "-D", "feature"], { cwd: fixture.repoDir });
await fixture.service.restore(fixture.workspace.workspaceId);
expect(readPaseoWorktreeMetadata(fixture.workspace.cwd)?.baseRef).toBe("refs/heads/main");
expect((await readPaseoWorktreeMetadata(fixture.workspace.cwd))?.baseRef).toBe("refs/heads/main");
expect(
await getCheckoutStatus(fixture.workspace.cwd, { paseoHome: fixture.paseoHome }),
).toMatchObject({
@@ -526,3 +526,146 @@ test("a late Git-ignored tree is pruned while tracked changes still notify consu
rmSync(tempDir, { recursive: true, force: true });
}
}, 15_000);
test("Git refresh, command tracing and 10,000 ignored alias events do no synchronous IO", async () => {
const { execFile } = await import("node:child_process");
const { promisify } = await import("node:util");
const source = `
import assert from 'node:assert/strict';
import { mkdtemp, mkdir, writeFile, symlink, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { setImmediate as tick } from 'node:timers/promises';
import { createHook } from 'node:async_hooks';
import pino from 'pino';
import { WorkspaceGitServiceImpl } from './packages/server/src/server/workspace-git-service.ts';
import { runGitCommand } from './packages/server/src/utils/run-git-command.ts';
import { writePaseoWorktreeMetadata } from './packages/server/src/utils/worktree-metadata.ts';
const root = await mkdtemp(join(tmpdir(), 'git-async-contract-'));
const home = join(root, 'home');
const repo = join(root, 'repo');
const worktree = join(home, 'worktrees', 'project', 'topic');
const alias = join(root, 'alias');
const logger = pino({ level: 'trace' }, { write() {} });
let callback;
let notifications = 0;
const service = new WorkspaceGitServiceImpl({ logger, paseoHome: home, deps: {
subscribe: async (_root, onChange) => {
callback = onChange;
return { updateIgnore: async () => {}, unsubscribe: async () => {} };
}
} });
try {
await mkdir(repo);
await runGitCommand(['init', '-b', 'main'], { cwd: repo });
await runGitCommand(['-c', 'user.name=Test', '-c', 'user.email=test@example.com', 'commit', '--allow-empty', '-m', 'base'], { cwd: repo });
await mkdir(join(home, 'worktrees', 'project'), { recursive: true });
await runGitCommand(['worktree', 'add', '-b', 'topic', worktree], { cwd: repo });
await writePaseoWorktreeMetadata(worktree, { baseRefName: 'main' });
await writeFile(join(worktree, '.gitignore'), 'ignored/\\n');
await mkdir(join(worktree, 'ignored'));
await writeFile(join(worktree, 'ignored', 'noise'), 'noise');
await symlink(worktree, alias, process.platform === 'win32' ? 'junction' : 'dir');
const subscription = await service.requestWorkingTreeWatch(alias, () => { notifications++; });
const events = Array.from({ length: process.env.GIT_IO_TRACE ? 2 : 10000 }, (_, i) => ({ type: 'update', path: join(i % 2 ? alias : worktree, 'ignored', 'noise') }));
await tick();
let fsCalls = 0;
const hook = createHook({ init(_id, type) { if (type.startsWith('FSREQ')) fsCalls++; } });
hook.enable();
process.stderr.write('FILTER_START\\n');
const started = performance.now();
const pulse = new Promise((resolve) => setTimeout(() => resolve(performance.now() - started), 0));
callback(null, events);
const filterMs = performance.now() - started;
process.stderr.write('FILTER_END\\n');
hook.disable();
const loopGapMs = await pulse;
assert.equal(fsCalls, 0, "filesystem calls");
assert.equal(notifications, 0, "ignored event notification");
console.log(JSON.stringify({ filterMs, loopGapMs, fsCalls }));
assert.ok(process.env.GIT_IO_TRACE || filterMs < 20, 'filter took ' + filterMs + 'ms');
assert.ok(process.env.GIT_IO_TRACE || loopGapMs < 20, 'event loop stalled for ' + loopGapMs + 'ms');
// Alias identity remains useful after deletion: no per-event realpath can recover this file.
callback(null, [{ type: 'delete', path: join(worktree, 'tracked.txt') }]);
assert.equal(notifications, 1);
process.stderr.write('REFRESH_START\\n');
const snapshot = await service.getSnapshot(worktree);
assert.equal(snapshot.git.isGit, true);
assert.equal(snapshot.git.isPaseoOwnedWorktree, true);
await runGitCommand(['status', '--porcelain'], { cwd: alias, logger });
process.stderr.write('REFRESH_END\\n');
subscription.unsubscribe();
} finally {
await service.dispose();
await rm(root, { recursive: true, force: true });
}
`;
for (const tracing of [false, true]) {
const { stdout, stderr } = await promisify(execFile)(
process.execPath,
[
"--import",
"tsx",
...(tracing ? ["--trace-sync-io"] : []),
"--input-type=module",
"--eval",
source,
],
{
cwd: process.cwd(),
env: { ...process.env, GIT_IO_TRACE: tracing ? "1" : "" },
timeout: 30_000,
maxBuffer: 4 * 1024 * 1024,
},
).catch((error) => {
throw new Error(String(error.stderr).replaceAll(/at .*/g, "[child stack omitted]"));
});
for (const phase of ["FILTER", "REFRESH"]) {
const output = stderr.split(`${phase}_START\n`)[1]?.split(`${phase}_END\n`)[0];
expect(output, `${phase}: synchronous filesystem IO`).toBe("");
}
expect(JSON.parse(stdout.trim().split("\n")[0])).toMatchObject({ fsCalls: 0 });
}
}, 60_000);
test("Git event identity preserves Windows namespace, case and subtree boundaries", async () => {
const { GitObservationPaths } = await import("./git-observation-paths.js");
const paths = await GitObservationPaths.create("C:\\paseo-observation-contract");
const accept = paths.createEventFilter(["C:\\paseo-observation-contract\\Build"]);
expect(paths.relative("\\\\?\\C:\\PASEO-OBSERVATION-CONTRACT\\refs\\heads\\MixedCase")).toBe(
"refs/heads/MixedCase",
);
expect(accept("\\\\?\\C:\\paseo-observation-contract\\build\\noise")).toBe(false);
expect(accept("C:\\paseo-observation-contract\\BuildSibling\\file")).toBe(true);
});
test("concurrent alias requests establish one working-tree subscription", async () => {
const { symlink } = await import("node:fs/promises");
const root = realpathSync(mkdtempSync(path.join(tmpdir(), "git-observation-concurrent-")));
const repo = path.join(root, "repo");
const alias = path.join(root, "alias");
execFileSync("git", ["init", "-b", "main", repo], { stdio: "pipe" });
await symlink(repo, alias, process.platform === "win32" ? "junction" : "dir");
let subscriptions = 0;
const service = new WorkspaceGitServiceImpl({
logger: pino({ enabled: false }),
paseoHome: path.join(root, "home"),
deps: {
subscribe: async () => {
subscriptions++;
return { updateIgnore: async () => {}, unsubscribe: async () => {} };
},
},
});
try {
const watches = await Promise.all([
service.requestWorkingTreeWatch(repo, () => {}),
service.requestWorkingTreeWatch(alias, () => {}),
]);
expect(subscriptions).toBe(1);
for (const watch of watches) watch.unsubscribe();
} finally {
await service.dispose();
rmSync(root, { recursive: true, force: true });
}
});
@@ -42,18 +42,13 @@ import {
type ForgeResolver,
} from "../services/forge-resolver.js";
import { parseGitRevParsePath } from "../utils/git-rev-parse-path.js";
import {
createRealpathAwarePathMatcher,
getRealpathAwareRelativePath,
isPathInsideRoot,
isRealpathInsideRoot,
looksLikeDefiniteWindowsPath,
} from "../utils/path.js";
import { isPathInsideRoot, looksLikeDefiniteWindowsPath } from "../utils/path.js";
import {
createRunGitCommand,
runGitCommand,
type RunGitCommand,
} from "../utils/run-git-command.js";
import { GitObservationPaths } from "./git-observation-paths.js";
import { branchNameFromRef } from "../utils/worktree-metadata.js";
import { listPaseoWorktrees, type PaseoWorktreeInfo } from "../utils/worktree.js";
import { READ_ONLY_GIT_ENV } from "./checkout-git-utils.js";
@@ -417,6 +412,7 @@ class WorkspaceGitWatcherSubscriptionTimeoutError extends Error {
}
interface WorkspaceGitTarget {
gitDirPaths: GitObservationPaths | null;
cwd: string;
listeners: Set<WorkspaceGitListener>;
workingTreeWatchTarget: WorkingTreeWatchTarget | null;
@@ -443,6 +439,7 @@ interface WorkspaceGitTarget {
}
interface RepoGitTarget {
paths: GitObservationPaths;
repoGitRoot: string;
cwd: string;
workspaceKeys: Set<string>;
@@ -470,6 +467,8 @@ interface RepoMetadataWorkspaceRefresh {
}
interface WorkingTreeWatchTarget {
paths: GitObservationPaths;
acceptsEvent: (candidate: string) => boolean;
cwd: string;
watchPath: string;
repoRoot: string | null;
@@ -1165,6 +1164,8 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
private async resolveWorkingTreeWatchTarget(cwd: string): Promise<WorkingTreeWatchTarget> {
const repoRoot = await this.resolveCheckoutWatchRoot(cwd);
const cwdPaths = repoRoot ? await GitObservationPaths.create(cwd) : null;
this.assertNotDisposed();
const targetCwd = repoRoot ?? cwd;
const existingTarget = this.workingTreeWatchTargets.get(targetCwd);
if (existingTarget) {
@@ -1179,7 +1180,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
return target;
}
const watchPath = repoRoot && createRealpathAwarePathMatcher(repoRoot)(cwd) ? cwd : targetCwd;
const watchPath = repoRoot && cwdPaths?.matches(repoRoot) ? cwd : targetCwd;
const setup = this.createWorkingTreeWatchTarget(targetCwd, watchPath, repoRoot).finally(() => {
if (this.workingTreeWatchSetups.get(targetCwd) === setup) {
this.workingTreeWatchSetups.delete(targetCwd);
@@ -1198,6 +1199,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
private createWorkspaceTarget(cwd: string): WorkspaceGitTarget {
const target: WorkspaceGitTarget = {
gitDirPaths: null,
cwd,
listeners: new Set(),
workingTreeWatchTarget: null,
@@ -1330,8 +1332,15 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
const promise = this.deps
.getCheckoutSnapshotFacts(target.cwd, context)
.then((facts) => {
target.latestFacts = facts;
.then(async (facts) => {
const paths =
facts.isGit && facts.absoluteGitDir
? await GitObservationPaths.create(facts.absoluteGitDir)
: null;
if (!target.closed) {
target.gitDirPaths = paths;
target.latestFacts = facts;
}
return facts;
})
.finally(() => {
@@ -1359,7 +1368,11 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
const ignoredDirectories = repoRoot
? (await this.loadIgnoredDirs(watchPath)).ignored
: new Set<string>();
const paths = await GitObservationPaths.create(watchPath);
this.assertNotDisposed();
const target: WorkingTreeWatchTarget = {
paths,
acceptsEvent: paths.createEventFilter([join(watchPath, ".git"), ...ignoredDirectories]),
cwd,
watchPath,
repoRoot,
@@ -1523,15 +1536,14 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
if (watcherErrored) {
return;
}
events = this.relevantWorkingTreeEvents(target, events);
if (events.length === 0) return;
const discovered = this.noteWorkingTreeDirectories(target, events);
if (events.some((event) => basename(event.path) === ".gitignore")) {
void this.refreshWorkingTreeIgnoredDirectories(target);
} else if (discovered) {
this.scheduleWorkingTreeIgnoreRefresh(target);
}
if (!this.hasRelevantWorkingTreeEvent(target, events)) {
return;
}
this.notifyWorkingTreeChanged(target, "working-tree-watch");
},
{ ignore },
@@ -1763,20 +1775,15 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
}
this.removeDeletedKnownDirectories(target, events);
const gitDir = join(target.watchPath, ".git");
// `matchesWatchPath` is realpath-aware because it compares an event-reported
// directory against `target.watchPath` itself — a config-time root that can
// legitimately differ from the watcher's reported form (e.g. a symlinked
// temp dir). It is now gated behind the plain Set lookup below, so it only
// runs for a directory this target has never seen before, not on every
// event.
const matchesWatchPath = createRealpathAwarePathMatcher(target.watchPath);
// Event paths have already been mapped into this subscription's established namespace.
const matchesWatchPath = target.paths.matches;
// One new directory is enough: the scheduled Git query inventories every
// ignored directory that exists by then. Stop before a large event batch
// multiplies containment checks across all its new directories.
for (const event of events) {
const directory = dirname(event.path);
// Cheap Set lookup first — the steady-state case where the directory is
// already known must never reach the realpath-aware matcher below.
// already known do not need another root comparison.
if (target.knownDirectories.has(directory) || matchesWatchPath(directory)) {
continue;
}
@@ -1955,28 +1962,22 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
target.pendingKnownDirectories.clear();
}
private hasRelevantWorkingTreeEvent(
private relevantWorkingTreeEvents(
target: WorkingTreeWatchTarget,
events: FileChange[],
): boolean {
const gitDir = join(target.watchPath, ".git");
const matchesWatchPath = createRealpathAwarePathMatcher(target.watchPath);
return events.some((event) => {
// Directory metadata changes at the watch root do not change Git state.
// FSEvents may emit these when every changed descendant was ignored.
if (matchesWatchPath(event.path)) {
return false;
): FileChange[] {
const relevant: FileChange[] = [];
// Watch backends may report the same path more than once in a batch.
const acceptedPaths = new Map<string, boolean>();
for (const event of events) {
let accepted = acceptedPaths.get(event.path);
if (accepted === undefined) {
accepted = target.acceptsEvent(event.path);
acceptedPaths.set(event.path, accepted);
}
if (isRealpathInsideRoot(gitDir, event.path)) {
return false;
}
for (const ignoredDirectory of target.ignoredDirectories) {
if (isRealpathInsideRoot(ignoredDirectory, event.path)) {
return false;
}
}
return true;
});
if (accepted) relevant.push({ ...event, path: target.paths.toWatchPath(event.path) });
}
return relevant;
}
private refreshWorkingTreeIgnoredDirectories(target: WorkingTreeWatchTarget): Promise<void> {
@@ -2031,6 +2032,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
}
if (!this.haveSamePaths(target.ignoredDirectories, ignoredDirectories)) {
target.ignoredDirectories = ignoredDirectories;
target.acceptsEvent = target.paths.createEventFilter(this.workingTreeIgnoreList(target));
this.pruneKnownDirectories(target);
}
if (target.fallbackPolling) {
@@ -2152,7 +2154,15 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
return;
}
const paths = await GitObservationPaths.create(repoGitRoot);
if (!this.isActiveObservedWorkspaceTarget(workspaceTarget)) return;
const establishedTarget = this.repoTargets.get(repoGitRoot);
if (establishedTarget) {
establishedTarget.workspaceKeys.add(workspaceTarget.cwd);
return;
}
const repoTarget: RepoGitTarget = {
paths,
repoGitRoot,
cwd: workspaceTarget.cwd,
workspaceKeys: new Set([workspaceTarget.cwd]),
@@ -2205,10 +2215,11 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
target: RepoGitTarget,
options?: { replaceFallback?: boolean },
): Promise<boolean> {
const paths = target.paths;
const ignore = getPrunedGitMetadataPaths("common").map((path) =>
join(target.repoGitRoot, path),
);
const matchesRepoGitRoot = createRealpathAwarePathMatcher(target.repoGitRoot);
const matchesRepoGitRoot = paths.matches;
const canary = this.deps.createWatcherLivenessCanary(target.repoGitRoot);
let openedSubscription: FileObserverSubscription | null = null;
let watcherErrored = false;
@@ -2223,7 +2234,9 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
const subscription = await this.subscribeWithDeadline(
target.repoGitRoot,
(error, events) => {
const liveEvents = canary.filterEvents(events);
const liveEvents = canary.filterEvents(
events.map((event) => ({ ...event, path: paths.toWatchPath(event.path) })),
);
if (error) {
if (watcherErrored) {
return;
@@ -2249,7 +2262,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
const relevantEvents = liveEvents.filter(
(event) =>
!matchesRepoGitRoot(event.path) &&
ignore.every((ignoredPath) => !isRealpathInsideRoot(ignoredPath, event.path)),
ignore.every((ignoredPath) => !isPathInsideRoot(ignoredPath, event.path)),
);
if (relevantEvents.length > 0) {
const immediateEvents = target.fetchInFlight
@@ -2362,7 +2375,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
events: FileChange[],
): Map<string, RepoMetadataWorkspaceRefresh> | null {
const refreshes = new Map<string, RepoMetadataWorkspaceRefresh>();
const matchesRepoGitRoot = createRealpathAwarePathMatcher(target.repoGitRoot);
const matchesRepoGitRoot = target.paths.matches;
for (const event of events) {
if (!this.routeRepoMetadataEvent(target, event, matchesRepoGitRoot, refreshes)) return null;
@@ -2377,10 +2390,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
): void {
const workspaceKeys = new Set<string>();
for (const event of events) {
const commonRelativePath = getRealpathAwareRelativePath(
target.repoGitRoot,
event.path,
)?.replaceAll("\\", "/");
const commonRelativePath = target.paths.relative(event.path)?.replaceAll("\\", "/");
if (commonRelativePath === "config" || commonRelativePath === "info/exclude") {
for (const workspaceKey of target.workspaceKeys) workspaceKeys.add(workspaceKey);
continue;
@@ -2390,8 +2400,10 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
if (
facts?.isGit &&
facts.absoluteGitDir &&
getRealpathAwareRelativePath(facts.absoluteGitDir, event.path)?.replaceAll("\\", "/") ===
"config.worktree"
this.workspaceTargets
.get(workspaceKey)
?.gitDirPaths?.relative(event.path)
?.replaceAll("\\", "/") === "config.worktree"
) {
workspaceKeys.add(workspaceKey);
}
@@ -2407,7 +2419,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
}
private isFetchRemoteMetadataEvent(target: RepoGitTarget, event: FileChange): boolean {
const relativePath = getRealpathAwareRelativePath(target.repoGitRoot, event.path);
const relativePath = target.paths.relative(event.path);
const effect = classifyGitMetadataPath("common", relativePath ?? "");
return (
(effect.kind === "ref" && effect.namespace === "remote") ||
@@ -2419,12 +2431,12 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
private routeRepoMetadataEvent(
target: RepoGitTarget,
event: FileChange,
matchesRepoGitRoot: ReturnType<typeof createRealpathAwarePathMatcher>,
matchesRepoGitRoot: (candidate: string) => boolean,
refreshes: Map<string, RepoMetadataWorkspaceRefresh>,
): boolean {
if (this.routePrivateGitDirEvent(target, event, matchesRepoGitRoot, refreshes)) return true;
const commonRelativePath = getRealpathAwareRelativePath(target.repoGitRoot, event.path);
const commonRelativePath = target.paths.relative(event.path);
const effect = classifyGitMetadataPath("common", commonRelativePath ?? "");
switch (effect.kind) {
case "ignore":
@@ -2476,7 +2488,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
private routePrivateGitDirEvent(
target: RepoGitTarget,
event: FileChange,
matchesRepoGitRoot: ReturnType<typeof createRealpathAwarePathMatcher>,
matchesRepoGitRoot: (candidate: string) => boolean,
refreshes: Map<string, RepoMetadataWorkspaceRefresh>,
): boolean {
let matched = false;
@@ -2485,8 +2497,10 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
if (!facts?.isGit || !facts.absoluteGitDir || matchesRepoGitRoot(facts.absoluteGitDir)) {
continue;
}
const relativePath = getRealpathAwareRelativePath(facts.absoluteGitDir, event.path);
if (relativePath === null) continue;
const relativePath = this.workspaceTargets
.get(workspaceKey)
?.gitDirPaths?.relative(event.path);
if (relativePath == null) continue;
matched = true;
const effect = classifyGitMetadataPath("worktree", relativePath);
if (effect.kind === "owner") {
@@ -2500,7 +2514,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
private routeMainCheckoutMetadata(
target: RepoGitTarget,
matchesRepoGitRoot: ReturnType<typeof createRealpathAwarePathMatcher>,
matchesRepoGitRoot: (candidate: string) => boolean,
refreshBase: boolean,
refreshes: Map<string, RepoMetadataWorkspaceRefresh>,
): void {
@@ -74,7 +74,7 @@ export async function bootstrapWorkspaceRegistries(options: {
continue;
}
try {
pinPaseoWorktreeBranchIdentityIfMissing(workspace.worktreeRoot, workspace.branch);
await pinPaseoWorktreeBranchIdentityIfMissing(workspace.worktreeRoot, workspace.branch);
} catch (error) {
options.logger.warn(
{ err: error, workspaceId: workspace.workspaceId },
@@ -343,8 +343,8 @@ describe("generateBranchNameFromFirstAgentContext", () => {
const repoRoot = createTempDir("paseo-branch-config-");
const worktreeRoot = createTempDir("paseo-branch-worktree-");
mkdirSync(path.join(worktreeRoot, ".git"));
writePaseoWorktreeMetadata(worktreeRoot, { baseRefName: "main" });
writePaseoWorktreeFirstAgentBranchAutoNameMetadata(worktreeRoot, {
await writePaseoWorktreeMetadata(worktreeRoot, { baseRefName: "main" });
await writePaseoWorktreeFirstAgentBranchAutoNameMetadata(worktreeRoot, {
placeholderBranchName: "dazzling-yak",
});
writeConfig(repoRoot, {
@@ -854,7 +854,7 @@ describe.skipIf(isPlatform("win32"))("worktree-core POSIX-only", () => {
second.worktree.worktreePath,
"remote.paseo-pr-14.url",
);
const metadata = readPaseoWorktreeMetadata(second.worktree.worktreePath);
const metadata = await readPaseoWorktreeMetadata(second.worktree.worktreePath);
const facts = await getCheckoutSnapshotFacts(second.worktree.worktreePath, { paseoHome });
expect(second.worktree.branchName).toBe("feature/gitlab-mr-1");
@@ -1113,7 +1113,7 @@ describe.skipIf(isPlatform("win32"))("worktree-core POSIX-only", () => {
createCoreDeps({ github }),
);
writeFileSync(
getPaseoWorktreeMetadataPath(second.worktree.worktreePath),
await getPaseoWorktreeMetadataPath(second.worktree.worktreePath),
`${JSON.stringify({ version: 1, baseRefName: "main" }, null, 2)}\n`,
"utf8",
);
@@ -172,7 +172,7 @@ describe("listCheckoutCommits", () => {
mkdirSync(join(worktreesRoot, "repo-hash"), { recursive: true });
git(["worktree", "add", "-b", "feature", worktreeDir], repoDir);
commitFile(worktreeDir, "feature.txt", "feature\n", "Feature work");
writePaseoWorktreeMetadata(worktreeDir, { baseRefName: "deleted-base" });
await writePaseoWorktreeMetadata(worktreeDir, { baseRefName: "deleted-base" });
const { baseRef, commits } = await listCheckoutCommits({
cwd: worktreeDir,
+14 -12
View File
@@ -2859,7 +2859,7 @@ const x = 1;
execFileSync("git", ["worktree", "add", workspaceDir, "contributor/old-change"], {
cwd: repoDir,
});
writePaseoWorktreeMetadata(workspaceDir, {
await writePaseoWorktreeMetadata(workspaceDir, {
baseRefName: "main",
changeRequestLookupTarget: {
headRef: "old-change",
@@ -2899,7 +2899,7 @@ const x = 1;
const workspaceDir = join(paseoHome, "worktrees", "repo", "renamed-by-agent");
mkdirSync(join(paseoHome, "worktrees", "repo"), { recursive: true });
execFileSync("git", ["worktree", "add", workspaceDir, "placeholder"], { cwd: repoDir });
writePaseoWorktreeMetadata(workspaceDir, {
await writePaseoWorktreeMetadata(workspaceDir, {
baseRefName: "main",
changeRequestLookupTarget: {
headRef: "placeholder",
@@ -2936,7 +2936,7 @@ const x = 1;
const workspaceDir = join(paseoHome, "worktrees", "repo", "pinned-worktree");
mkdirSync(join(paseoHome, "worktrees", "repo"), { recursive: true });
execFileSync("git", ["worktree", "add", workspaceDir, "feature/pinned"], { cwd: repoDir });
writePaseoWorktreeMetadata(workspaceDir, {
await writePaseoWorktreeMetadata(workspaceDir, {
baseRefName: "main",
changeRequestLookupTarget: {
headRef: "feature/pinned",
@@ -2975,7 +2975,7 @@ const x = 1;
execFileSync("git", ["worktree", "add", workspaceDir, "contributor/old-change-1"], {
cwd: repoDir,
});
writePaseoWorktreeMetadata(workspaceDir, {
await writePaseoWorktreeMetadata(workspaceDir, {
baseRefName: "main",
changeRequestLookupTarget: {
headRef: "old-change",
@@ -2997,7 +2997,7 @@ const x = 1;
execFileSync("git", ["worktree", "add", workspaceDir, "contributor/old-change"], {
cwd: repoDir,
});
writePaseoWorktreeMetadata(workspaceDir, {
await writePaseoWorktreeMetadata(workspaceDir, {
baseRefName: "main",
changeRequestLookupTarget: {
headRef: "old-change",
@@ -3062,7 +3062,7 @@ const x = 1;
execFileSync("git", ["worktree", "add", workspaceDir, "mixedowner/old-change"], {
cwd: repoDir,
});
writePaseoWorktreeMetadata(workspaceDir, {
await writePaseoWorktreeMetadata(workspaceDir, {
baseRefName: "main",
changeRequestLookupTarget: {
headRef: "old-change",
@@ -3114,7 +3114,7 @@ const x = 1;
execFileSync("git", ["worktree", "add", workspaceDir, "feature/gitlab-mr"], {
cwd: repoDir,
});
writePaseoWorktreeMetadata(workspaceDir, {
await writePaseoWorktreeMetadata(workspaceDir, {
baseRefName: "main",
changeRequestLookupTarget: {
headRef: "feature/gitlab-mr",
@@ -3128,7 +3128,9 @@ const x = 1;
const forge = createGitHubServiceRecordingPullRequestTargets({ requestedTargets });
await renameCurrentBranch(workspaceCwd, "feature/renamed");
expect(readPaseoWorktreeMetadata(workspaceDir)?.changeRequestLookupTarget).toMatchObject({
expect(
(await readPaseoWorktreeMetadata(workspaceDir))?.changeRequestLookupTarget,
).toMatchObject({
localBranchName: "feature/renamed",
});
const renamedFacts = await getCheckoutSnapshotFacts(workspaceDir, { paseoHome });
@@ -3164,7 +3166,7 @@ const x = 1;
execFileSync("git", ["worktree", "add", workspaceDir, "feature/placeholder"], {
cwd: repoDir,
});
writePaseoWorktreeMetadata(workspaceDir, {
await writePaseoWorktreeMetadata(workspaceDir, {
baseRefName: "main",
changeRequestLookupTarget: {
headRef: "feature/placeholder",
@@ -3174,7 +3176,7 @@ const x = 1;
await renameCurrentBranch(workspaceDir, "feature/generated");
expect(readPaseoWorktreeMetadata(workspaceDir)?.changeRequestLookupTarget).toEqual({
expect((await readPaseoWorktreeMetadata(workspaceDir))?.changeRequestLookupTarget).toEqual({
headRef: "feature/generated",
localBranchName: "feature/generated",
});
@@ -3951,7 +3953,7 @@ const x = 1;
cwd: worktree.worktreePath,
});
const metadataPath = getPaseoWorktreeMetadataPath(worktree.worktreePath);
const metadataPath = await getPaseoWorktreeMetadataPath(worktree.worktreePath);
rmSync(metadataPath, { force: true });
const baseDiff = await getCheckoutDiff(worktree.worktreePath, { mode: "base" }, { paseoHome });
@@ -3970,7 +3972,7 @@ const x = 1;
paseoHome,
});
const metadataPath = getPaseoWorktreeMetadataPath(worktree.worktreePath);
const metadataPath = await getPaseoWorktreeMetadataPath(worktree.worktreePath);
rmSync(metadataPath, { force: true });
const status = await getCheckoutStatus(worktree.worktreePath, { paseoHome });
+31 -9
View File
@@ -1,7 +1,15 @@
import { MAX_RELAY_WEBSOCKET_MESSAGE_BYTES } from "@getpaseo/protocol/websocket-message-limit";
import { resolve, dirname, basename } from "path";
import { existsSync, realpathSync } from "fs";
import { open as openFile, readFile, stat as statFile, mkdtemp, copyFile, rm } from "fs/promises";
import {
open as openFile,
readFile,
stat as statFile,
mkdtemp,
copyFile,
realpath,
access,
rm,
} from "fs/promises";
import { tmpdir } from "node:os";
import { setImmediate } from "node:timers/promises";
import { TTLCache } from "@isaacs/ttlcache";
@@ -1104,7 +1112,7 @@ async function getMainRepoRootFromCommonDir(
if (!commonDir) {
throw new Error("Not in a git repository");
}
const normalized = realpathSync(commonDir);
const normalized = await realpath(commonDir);
if (basename(normalized) === ".git") {
return dirname(normalized);
@@ -1229,7 +1237,7 @@ export async function renameCurrentBranch(
const currentBranch = await getCurrentBranch(cwd);
if (currentBranch) {
rebindPaseoWorktreeChangeRequestHint(worktreeRoot, previousBranch, currentBranch);
await rebindPaseoWorktreeChangeRequestHint(worktreeRoot, previousBranch, currentBranch);
}
return { previousBranch, currentBranch };
}
@@ -1274,8 +1282,8 @@ function storedBaseRefFromMetadata(metadata: PaseoWorktreeMetadata | null): stri
return metadata?.baseRef ?? metadata?.baseRefName ?? null;
}
function readPaseoWorktreeBaseRef(worktreeRoot: string): string | null {
return storedBaseRefFromMetadata(readPaseoWorktreeMetadata(worktreeRoot));
async function readPaseoWorktreeBaseRef(worktreeRoot: string): Promise<string | null> {
return storedBaseRefFromMetadata(await readPaseoWorktreeMetadata(worktreeRoot));
}
async function getStoredBaseRefForCwd(
@@ -1549,7 +1557,12 @@ async function abortGitPullConflictState(cwd: string): Promise<void> {
const rebaseMergePath = resolve(gitDir, "rebase-merge");
const rebaseApplyPath = resolve(gitDir, "rebase-apply");
if (existsSync(mergeHeadPath)) {
if (
await access(mergeHeadPath).then(
() => true,
() => false,
)
) {
try {
await runGitCommand(["merge", "--abort"], { cwd, timeout: 120_000 });
} catch {
@@ -1557,7 +1570,16 @@ async function abortGitPullConflictState(cwd: string): Promise<void> {
}
}
if (existsSync(rebaseMergePath) || existsSync(rebaseApplyPath)) {
if (
(await access(rebaseMergePath).then(
() => true,
() => false,
)) ||
(await access(rebaseApplyPath).then(
() => true,
() => false,
))
) {
try {
await runGitCommand(["rebase", "--abort"], { cwd, timeout: 120_000 });
} catch {
@@ -2078,7 +2100,7 @@ export async function getCheckoutSnapshotFacts(
}
const paseoWorktreeMetadata = inspected.paseoWorktree.isPaseoOwnedWorktree
? readPaseoWorktreeMetadata(inspected.paseoWorktree.worktreeRoot)
? await readPaseoWorktreeMetadata(inspected.paseoWorktree.worktreeRoot)
: null;
const storedBaseRef = storedBaseRefFromMetadata(paseoWorktreeMetadata);
const resolvedBaseRef = storedBaseRef ?? (await resolveBaseRef(cwd, context));
+2 -2
View File
@@ -107,7 +107,7 @@ export function isRealpathInsideRoot(root: string, candidate: string): boolean {
return getRealpathAwareRelativePath(root, candidate) !== null;
}
function getRelativePathInsideRoot(root: string, candidate: string): string | null {
export function getRelativePathInsideRoot(root: string, candidate: string): string | null {
const compareAsWindows = shouldCompareAsWindows(root, candidate);
const platformPath = compareAsWindows ? nodePath.win32 : nodePath.posix;
const normalizedRoot = normalizePathForComparison(root, compareAsWindows);
@@ -175,7 +175,7 @@ function normalizePathForComparison(value: string, compareAsWindows: boolean): s
return compareAsWindows ? normalized.toLowerCase() : normalized;
}
function normalizePathPreservingCase(value: string, compareAsWindows: boolean): string {
export function normalizePathPreservingCase(value: string, compareAsWindows: boolean): string {
const platformPath = compareAsWindows ? nodePath.win32 : nodePath.posix;
const comparableValue = compareAsWindows ? stripWindowsNamespacePrefix(value) : value;
const platformNormalized = platformPath.normalize(comparableValue);
@@ -1,5 +1,4 @@
import { AsyncLocalStorage } from "node:async_hooks";
import { existsSync } from "node:fs";
import type { Logger } from "pino";
import type { ProcessEnvRecord } from "../server/paseo-env.js";
import {
@@ -311,7 +310,6 @@ function executeGitCommand<Output>(
command: "git",
args,
cwd: options.cwd,
cwdExists: existsSync(options.cwd),
timeout,
maxOutputBytes,
acceptExitCodes,
+251 -149
View File
@@ -1,7 +1,12 @@
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "fs";
import { mkdir, open, realpath, rename, stat, writeFile } from "node:fs/promises";
import { randomUUID } from "node:crypto";
import { constants } from "node:fs";
import pLimit from "p-limit";
import { isAbsolute, join, resolve } from "path";
import { z } from "zod";
const MAX_WORKTREE_METADATA_BYTES = 64 * 1024;
const ChangeRequestLookupTargetSchema = z.object({
headRef: z.string().min(1),
headRepositoryOwner: z.string().min(1).optional(),
@@ -90,75 +95,78 @@ function normalizeLegacyGitHubOwnerForBranch(owner: string): string | null {
return /^[a-z0-9-]+$/.test(normalized) ? normalized : null;
}
export function rebindPaseoWorktreeChangeRequestHint(
export async function rebindPaseoWorktreeChangeRequestHint(
worktreeRoot: string,
previousBranch: string,
currentBranch: string,
): boolean {
const metadata = readPaseoWorktreeMetadata(worktreeRoot);
const target = getPaseoWorktreeChangeRequestHintForBranch(metadata, previousBranch);
if (!metadata || !target) {
return false;
}
): Promise<boolean> {
return mutateMetadata(worktreeRoot, async (root) => {
const metadata = await readMetadataFile(root);
const target = getPaseoWorktreeChangeRequestHintForBranch(metadata, previousBranch);
if (!metadata || !target) {
return false;
}
writePaseoWorktreeMetadataFile(worktreeRoot, {
...metadata,
changeRequestLookupTarget: {
...target,
...(target.headRef === previousBranch &&
!target.headRepositoryOwner &&
target.changeRequestNumber === undefined
? { headRef: currentBranch }
: {}),
localBranchName: currentBranch,
},
await writePaseoWorktreeMetadataFile(root, {
...metadata,
changeRequestLookupTarget: {
...target,
...(target.headRef === previousBranch &&
!target.headRepositoryOwner &&
target.changeRequestNumber === undefined
? { headRef: currentBranch }
: {}),
localBranchName: currentBranch,
},
});
return true;
});
return true;
}
export function pinPaseoWorktreeBranchIdentityIfMissing(
export async function pinPaseoWorktreeBranchIdentityIfMissing(
worktreeRoot: string,
branch: string,
): boolean {
const metadata = readPaseoWorktreeMetadata(worktreeRoot);
if (!metadata || metadata.changeRequestLookupTarget) {
return false;
}
const target = createPaseoWorktreeChangeRequestHint({
headRef: branch,
localBranchName: branch,
): Promise<boolean> {
return mutateMetadata(worktreeRoot, async (root) => {
const metadata = await readMetadataFile(root);
if (!metadata || metadata.changeRequestLookupTarget) {
return false;
}
const target = createPaseoWorktreeChangeRequestHint({
headRef: branch,
localBranchName: branch,
});
await writePaseoWorktreeMetadataFile(root, {
...metadata,
changeRequestLookupTarget: target,
});
return true;
});
writePaseoWorktreeMetadataFile(worktreeRoot, {
...metadata,
changeRequestLookupTarget: target,
});
return true;
}
function getGitDirForWorktreeRoot(worktreeRoot: string): string {
async function getGitDirForWorktreeRoot(worktreeRoot: string): Promise<string> {
const gitPath = join(worktreeRoot, ".git");
if (!existsSync(gitPath)) {
throw new Error(`Not a git repository: ${worktreeRoot}`);
}
// In a worktree checkout, `.git` is a file containing `gitdir: <path>`.
// In a normal checkout, `.git` is a directory.
let info;
try {
const gitFileContent = readFileSync(gitPath, "utf8");
const match = gitFileContent.match(/gitdir:\s*(.+)/);
if (match?.[1]) {
const raw = match[1].trim();
return isAbsolute(raw) ? raw : resolve(worktreeRoot, raw);
}
} catch {
// If `.git` is a directory, readFileSync will throw; fall through.
info = await stat(gitPath);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT")
throw new Error(`Not a git repository: ${worktreeRoot}`, { cause: error });
throw error;
}
if (info.isDirectory()) return gitPath;
const gitFileContent = await readBoundedFile(gitPath);
const match = gitFileContent.match(/gitdir:\s*(.+)/);
if (match?.[1]) {
const raw = match[1].trim();
return isAbsolute(raw) ? raw : resolve(worktreeRoot, raw);
}
return gitPath;
}
export function getPaseoWorktreeMetadataPath(worktreeRoot: string): string {
const gitDir = getGitDirForWorktreeRoot(worktreeRoot);
export async function getPaseoWorktreeMetadataPath(worktreeRoot: string): Promise<string> {
const gitDir = await getGitDirForWorktreeRoot(worktreeRoot);
return join(gitDir, "paseo", "worktree.json");
}
@@ -213,120 +221,166 @@ function assertValidBaseRef(value: string): void {
}
}
export function writePaseoWorktreeMetadata(
export async function writePaseoWorktreeMetadata(
worktreeRoot: string,
options: {
baseRefName: string;
baseRef?: string;
changeRequestLookupTarget?: PaseoWorktreeChangeRequestHint;
},
): void {
const baseRefName = normalizeBaseRefName(options.baseRefName);
assertValidBaseRef(baseRefName);
const baseRef = options.baseRef?.trim();
if (baseRef) {
assertValidBaseRef(baseRef);
}
): Promise<void> {
return mutateMetadata(worktreeRoot, async (root) => {
const baseRefName = normalizeBaseRefName(options.baseRefName);
assertValidBaseRef(baseRefName);
const baseRef = options.baseRef?.trim();
if (baseRef) {
assertValidBaseRef(baseRef);
}
const metadata: PaseoWorktreeMetadata = {
version: 1,
baseRefName,
...(baseRef ? { baseRef } : {}),
...(options.changeRequestLookupTarget
? { changeRequestLookupTarget: options.changeRequestLookupTarget }
: {}),
};
writePaseoWorktreeMetadataFile(worktreeRoot, metadata);
}
export function writePaseoWorktreeRuntimeMetadata(
worktreeRoot: string,
options: { worktreePort: number },
): void {
if (!Number.isInteger(options.worktreePort) || options.worktreePort <= 0) {
throw new Error(`Invalid worktree runtime port: ${options.worktreePort}`);
}
const current = readPaseoWorktreeMetadata(worktreeRoot);
if (!current) {
throw new Error("Cannot persist worktree runtime metadata: missing base metadata");
}
const next: PaseoWorktreeMetadata = {
...current,
version: 2,
runtime: {
worktreePort: options.worktreePort,
},
};
writePaseoWorktreeMetadataFile(worktreeRoot, next);
}
export function writePaseoWorktreeFirstAgentBranchAutoNameMetadata(
worktreeRoot: string,
options: { placeholderBranchName: string },
): void {
const placeholderBranchName = options.placeholderBranchName.trim();
if (!placeholderBranchName) {
throw new Error("Placeholder branch name is required");
}
const current = readPaseoWorktreeMetadata(worktreeRoot);
if (!current) {
throw new Error("Cannot persist first-agent branch auto-name metadata: missing base metadata");
}
writePaseoWorktreeMetadataFile(worktreeRoot, {
...current,
version: 2,
firstAgentBranchAutoName: {
status: "pending",
placeholderBranchName,
},
const metadata: PaseoWorktreeMetadata = {
version: 1,
baseRefName,
...(baseRef ? { baseRef } : {}),
...(options.changeRequestLookupTarget
? { changeRequestLookupTarget: options.changeRequestLookupTarget }
: {}),
};
await writePaseoWorktreeMetadataFile(root, metadata);
});
}
export function markPaseoWorktreeFirstAgentBranchAutoNameAttempted(
export async function writePaseoWorktreeRuntimeMetadata(
worktreeRoot: string,
options: { worktreePort: number },
): Promise<void> {
return mutateMetadata(worktreeRoot, async (root) => {
if (!Number.isInteger(options.worktreePort) || options.worktreePort <= 0) {
throw new Error(`Invalid worktree runtime port: ${options.worktreePort}`);
}
const current = await readMetadataFile(root);
if (!current) {
throw new Error("Cannot persist worktree runtime metadata: missing base metadata");
}
const next: PaseoWorktreeMetadata = {
...current,
version: 2,
runtime: {
worktreePort: options.worktreePort,
},
};
await writePaseoWorktreeMetadataFile(root, next);
});
}
export async function writePaseoWorktreeFirstAgentBranchAutoNameMetadata(
worktreeRoot: string,
options: { placeholderBranchName: string },
): Promise<void> {
return mutateMetadata(worktreeRoot, async (root) => {
const placeholderBranchName = options.placeholderBranchName.trim();
if (!placeholderBranchName) {
throw new Error("Placeholder branch name is required");
}
const current = await readMetadataFile(root);
if (!current) {
throw new Error(
"Cannot persist first-agent branch auto-name metadata: missing base metadata",
);
}
await writePaseoWorktreeMetadataFile(root, {
...current,
version: 2,
firstAgentBranchAutoName: {
status: "pending",
placeholderBranchName,
},
});
});
}
export async function markPaseoWorktreeFirstAgentBranchAutoNameAttempted(
worktreeRoot: string,
options: { attemptedAt?: string } = {},
): PaseoWorktreeMetadata | null {
const current = readPaseoWorktreeMetadata(worktreeRoot);
if (!current || current.version !== 2 || current.firstAgentBranchAutoName?.status !== "pending") {
return current;
}
): Promise<PaseoWorktreeMetadata | null> {
return mutateMetadata(worktreeRoot, async (root) => {
const current = await readMetadataFile(root);
if (
!current ||
current.version !== 2 ||
current.firstAgentBranchAutoName?.status !== "pending"
) {
return current;
}
const next: PaseoWorktreeMetadata = {
...current,
firstAgentBranchAutoName: {
status: "attempted",
placeholderBranchName: current.firstAgentBranchAutoName.placeholderBranchName,
attemptedAt: options.attemptedAt ?? new Date().toISOString(),
},
};
writePaseoWorktreeMetadataFile(worktreeRoot, next);
return next;
const next: PaseoWorktreeMetadata = {
...current,
firstAgentBranchAutoName: {
status: "attempted",
placeholderBranchName: current.firstAgentBranchAutoName.placeholderBranchName,
attemptedAt: options.attemptedAt ?? new Date().toISOString(),
},
};
await writePaseoWorktreeMetadataFile(root, next);
return next;
});
}
export function readPaseoWorktreeMetadata(worktreeRoot: string): PaseoWorktreeMetadata | null {
const metadataPath = getPaseoWorktreeMetadataPath(worktreeRoot);
if (!existsSync(metadataPath)) {
return null;
}
const parsed = JSON.parse(readFileSync(metadataPath, "utf8"));
return PaseoWorktreeMetadataSchema.parse(parsed);
export async function readPaseoWorktreeMetadata(
worktreeRoot: string,
): Promise<PaseoWorktreeMetadata | null> {
const key = await resolveMetadataIdentity(worktreeRoot);
await metadataMutations.get(key)?.catch(() => {});
return metadataIo(() => readMetadataFile(key));
}
export function requirePaseoWorktreeBaseRefName(worktreeRoot: string): string {
const metadataPath = getPaseoWorktreeMetadataPath(worktreeRoot);
const metadata = readPaseoWorktreeMetadata(worktreeRoot);
async function readMetadataFile(worktreeRoot: string): Promise<PaseoWorktreeMetadata | null> {
const metadataPath = await getPaseoWorktreeMetadataPath(worktreeRoot);
try {
return PaseoWorktreeMetadataSchema.parse(JSON.parse(await readBoundedFile(metadataPath)));
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
throw error;
}
}
// O_NONBLOCK lets us reject FIFOs by kind without hanging in open(). A fixed read also
// caps a regular file that grows between stat and read; readFile's whole-file loop does not.
async function readBoundedFile(path: string): Promise<string> {
const file = await open(path, constants.O_RDONLY | constants.O_NONBLOCK);
try {
const info = await file.stat();
const limit = MAX_WORKTREE_METADATA_BYTES;
if (!info.isFile() || info.size > limit)
throw new Error(`Invalid Paseo worktree metadata file: ${path}`);
const buffer = Buffer.alloc(limit + 1);
let length = 0;
while (length < buffer.length) {
const { bytesRead } = await file.read(buffer, length, buffer.length - length);
if (bytesRead === 0) break;
length += bytesRead;
}
if (length > limit) throw new Error(`Invalid Paseo worktree metadata file: ${path}`);
return buffer.toString("utf8", 0, length);
} finally {
await file.close();
}
}
export async function requirePaseoWorktreeBaseRefName(worktreeRoot: string): Promise<string> {
const metadataPath = await getPaseoWorktreeMetadataPath(worktreeRoot);
const metadata = await readPaseoWorktreeMetadata(worktreeRoot);
if (!metadata) {
throw new Error(`Missing Paseo worktree base metadata: ${metadataPath}`);
}
return metadata.baseRefName;
}
export function readPaseoWorktreeRuntimePort(worktreeRoot: string): number | null {
const metadata = readPaseoWorktreeMetadata(worktreeRoot);
export async function readPaseoWorktreeRuntimePort(worktreeRoot: string): Promise<number | null> {
const metadata = await readPaseoWorktreeMetadata(worktreeRoot);
if (!metadata) {
return null;
}
@@ -336,13 +390,61 @@ export function readPaseoWorktreeRuntimePort(worktreeRoot: string): number | nul
return null;
}
function writePaseoWorktreeMetadataFile(
async function writePaseoWorktreeMetadataFile(
worktreeRoot: string,
metadata: PaseoWorktreeMetadata,
): void {
const metadataPath = getPaseoWorktreeMetadataPath(worktreeRoot);
mkdirSync(join(getGitDirForWorktreeRoot(worktreeRoot), "paseo"), { recursive: true });
const tempPath = `${metadataPath}.${process.pid}.${Date.now()}.tmp`;
writeFileSync(tempPath, `${JSON.stringify(metadata, null, 2)}\n`, "utf8");
renameSync(tempPath, metadataPath);
): Promise<void> {
const metadataPath = await getPaseoWorktreeMetadataPath(worktreeRoot);
const contents = `${JSON.stringify(metadata, null, 2)}\n`;
if (Buffer.byteLength(contents) > MAX_WORKTREE_METADATA_BYTES) {
throw new Error(`Invalid Paseo worktree metadata file: ${metadataPath}`);
}
// Never recreate an archived Git directory while a queued mutation is pending.
try {
await mkdir(join(await getGitDirForWorktreeRoot(worktreeRoot), "paseo"));
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
}
const tempPath = `${metadataPath}.${randomUUID()}.tmp`;
await writeFile(tempPath, contents, "utf8");
await rename(tempPath, metadataPath);
}
const metadataIo = pLimit(2);
const metadataMutations = new Map<string, Promise<unknown>>();
// Only share in-flight identity resolution: a replaced symlink must not retain an old owner.
const metadataIdentities = new Map<string, Promise<string>>();
function resolveMetadataIdentity(worktreeRoot: string): Promise<string> {
const path = resolve(worktreeRoot);
const existing = metadataIdentities.get(path);
if (existing) return existing;
const identity = metadataIo(async () => {
try {
return await realpath(path);
} catch {
return path;
}
}).finally(() => {
if (metadataIdentities.get(path) === identity) metadataIdentities.delete(path);
});
metadataIdentities.set(path, identity);
return identity;
}
async function mutateMetadata<T>(
worktreeRoot: string,
mutation: (root: string) => Promise<T>,
): Promise<T> {
const key = await resolveMetadataIdentity(worktreeRoot);
const previous = metadataMutations.get(key) ?? Promise.resolve();
const pending = previous.catch(() => {}).then(() => metadataIo(() => mutation(key)));
metadataMutations.set(key, pending);
void pending
.finally(() => {
if (metadataMutations.get(key) === pending) metadataMutations.delete(key);
})
.catch(() => {});
return pending;
}
+121 -10
View File
@@ -21,7 +21,13 @@ import {
type WorktreeConfig,
} from "./worktree";
import type { PaseoConfig } from "@getpaseo/protocol/paseo-config-schema";
import { getPaseoWorktreeMetadataPath, readPaseoWorktreeMetadata } from "./worktree-metadata.js";
import {
getPaseoWorktreeMetadataPath,
readPaseoWorktreeMetadata,
writePaseoWorktreeMetadata,
writePaseoWorktreeRuntimeMetadata,
writePaseoWorktreeFirstAgentBranchAutoNameMetadata,
} from "./worktree-metadata.js";
import {
getCheckoutDiff,
getCheckoutStatus,
@@ -125,7 +131,7 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => {
expect(result.worktreePath).toBe(join(paseoHome, "worktrees", projectHash, "hello-world"));
expect(existsSync(result.worktreePath)).toBe(true);
expect(existsSync(join(result.worktreePath, "file.txt"))).toBe(true);
const metadataPath = getPaseoWorktreeMetadataPath(result.worktreePath);
const metadataPath = await getPaseoWorktreeMetadataPath(result.worktreePath);
expect(existsSync(metadataPath)).toBe(true);
const metadata = JSON.parse(readFileSync(metadataPath, "utf8"));
expect(metadata).toMatchObject({
@@ -256,7 +262,7 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => {
cwd: result.worktreePath,
});
const metadataPath = getPaseoWorktreeMetadataPath(result.worktreePath);
const metadataPath = await getPaseoWorktreeMetadataPath(result.worktreePath);
const metadata = JSON.parse(readFileSync(metadataPath, "utf8"));
expect(metadata).toMatchObject({
version: 1,
@@ -319,7 +325,7 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => {
// baseRefName must be the repo's default branch, not the checked-out branch
// itself — otherwise the diff panel compares the branch against itself and
// always shows no changes.
const metadataPath = getPaseoWorktreeMetadataPath(result.worktreePath);
const metadataPath = await getPaseoWorktreeMetadataPath(result.worktreePath);
const metadata = JSON.parse(readFileSync(metadataPath, "utf8"));
expect(metadata).toMatchObject({
version: 1,
@@ -370,7 +376,7 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => {
});
expect(existsSync(result.worktreePath)).toBe(true);
const metadataPath = getPaseoWorktreeMetadataPath(result.worktreePath);
const metadataPath = await getPaseoWorktreeMetadataPath(result.worktreePath);
const metadata = JSON.parse(readFileSync(metadataPath, "utf8"));
expect(metadata).toMatchObject({ version: 1, baseRefName: "develop" });
});
@@ -406,7 +412,9 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => {
expect(result.branchName).toBe("main-1");
expect(existsSync(result.worktreePath)).toBe(true);
expect(readPaseoWorktreeMetadata(result.worktreePath)?.changeRequestLookupTarget).toEqual({
expect(
(await readPaseoWorktreeMetadata(result.worktreePath))?.changeRequestLookupTarget,
).toEqual({
headRef: "main-1",
localBranchName: "main-1",
});
@@ -459,7 +467,7 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => {
.trim();
expect(currentBranch).toBe("user/feature");
const metadataPath = getPaseoWorktreeMetadataPath(result.worktreePath);
const metadataPath = await getPaseoWorktreeMetadataPath(result.worktreePath);
const metadata = JSON.parse(readFileSync(metadataPath, "utf8"));
expect(metadata).toMatchObject({ baseRefName: "main" });
});
@@ -566,7 +574,9 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => {
"from-origin\n",
);
expect(
JSON.parse(readFileSync(getPaseoWorktreeMetadataPath(originResult.worktreePath), "utf8")),
JSON.parse(
readFileSync(await getPaseoWorktreeMetadataPath(originResult.worktreePath), "utf8"),
),
).toMatchObject({ baseRefName: "main" });
});
@@ -607,7 +617,7 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => {
// to the commit the worktree was cut from: "main" resolves local-first, which here is
// a different commit than the fork's upstream.
expect(
JSON.parse(readFileSync(getPaseoWorktreeMetadataPath(result.worktreePath), "utf8")),
JSON.parse(readFileSync(await getPaseoWorktreeMetadataPath(result.worktreePath), "utf8")),
).toMatchObject({ baseRefName: "main", baseRef: "refs/remotes/upstream/main" });
// An untouched child must report no work of its own. Comparing against the wrong base
@@ -694,7 +704,7 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => {
});
expect(
JSON.parse(readFileSync(getPaseoWorktreeMetadataPath(result.worktreePath), "utf8")),
JSON.parse(readFileSync(await getPaseoWorktreeMetadataPath(result.worktreePath), "utf8")),
).toMatchObject({
baseRefName: "release+hotfix",
baseRef: "refs/remotes/upstream/release+hotfix",
@@ -1617,3 +1627,104 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => {
});
});
});
describe.skipIf(isPlatform("win32"))("async worktree metadata", () => {
it("serializes metadata mutations per worktree while another worktree progresses", async () => {
const root = mkdtempSync(join(tmpdir(), "worktree-metadata-order-"));
const first = join(root, "first");
const second = join(root, "second");
mkdirSync(join(first, ".git"), { recursive: true });
mkdirSync(join(second, ".git"), { recursive: true });
try {
await writePaseoWorktreeMetadata(first, { baseRefName: "main" });
await writePaseoWorktreeMetadata(second, { baseRefName: "release" });
const order: string[] = [];
const runtime = writePaseoWorktreeRuntimeMetadata(first, { worktreePort: 4101 }).then(() =>
order.push("first-runtime"),
);
const unrelated = writePaseoWorktreeRuntimeMetadata(second, { worktreePort: 4102 }).then(() =>
order.push("second-runtime"),
);
const naming = writePaseoWorktreeFirstAgentBranchAutoNameMetadata(first, {
placeholderBranchName: "topic",
}).then(() => order.push("first-naming"));
// A read issued while writes are pending observes their completed snapshot.
const snapshot = readPaseoWorktreeMetadata(first);
await Promise.all([runtime, unrelated, naming]);
expect(order.indexOf("first-runtime")).toBeLessThan(order.indexOf("first-naming"));
expect(await snapshot).toMatchObject({
baseRefName: "main",
runtime: { worktreePort: 4101 },
firstAgentBranchAutoName: { status: "pending", placeholderBranchName: "topic" },
});
expect(await readPaseoWorktreeMetadata(second)).toMatchObject({
baseRefName: "release",
runtime: { worktreePort: 4102 },
});
const alias = join(root, "first-alias");
symlinkSync(first, alias, "dir");
await Promise.all([
writePaseoWorktreeRuntimeMetadata(first, { worktreePort: 4103 }),
writePaseoWorktreeFirstAgentBranchAutoNameMetadata(alias, {
placeholderBranchName: "renamed",
}),
]);
expect(await readPaseoWorktreeMetadata(first)).toMatchObject({
runtime: { worktreePort: 4103 },
firstAgentBranchAutoName: { placeholderBranchName: "renamed" },
});
} finally {
rmSync(root, { recursive: true, force: true });
}
});
it("a queued metadata mutation cannot recreate an archived Git directory", async () => {
const root = mkdtempSync(join(tmpdir(), "worktree-metadata-archive-"));
mkdirSync(join(root, ".git"));
try {
await writePaseoWorktreeMetadata(root, { baseRefName: "main" });
const pending = writePaseoWorktreeRuntimeMetadata(root, { worktreePort: 4101 });
// The mutation is queued in a microtask, so archive wins this ordering.
rmSync(join(root, ".git"), { recursive: true });
await expect(pending).rejects.toThrow("Not a git repository");
expect(existsSync(join(root, ".git"))).toBe(false);
} finally {
rmSync(root, { recursive: true, force: true });
}
});
it("recognizes a removed worktree under a symlinked ownership root", async () => {
const root = mkdtempSync(join(tmpdir(), "worktree-ownership-alias-"));
const actual = join(root, "actual");
const alias = join(root, "worktrees");
mkdirSync(actual);
symlinkSync(actual, alias, "dir");
try {
const cwd = join(alias, "project", "removed");
expect(
await isPaseoOwnedWorktreeCwd(cwd, { worktreesRoot: alias, knownGitCommonDir: null }),
).toMatchObject({ allowed: true, worktreePath: cwd });
} finally {
rmSync(root, { recursive: true, force: true });
}
});
it("rejects oversized metadata and named pipes without reading them whole", async () => {
const root = mkdtempSync(join(tmpdir(), "worktree-metadata-admission-"));
mkdirSync(join(root, ".git", "paseo"), { recursive: true });
try {
const path = await getPaseoWorktreeMetadataPath(root);
writeFileSync(path, JSON.stringify({ version: 1, baseRefName: "x".repeat(64 * 1024) }));
await expect(readPaseoWorktreeMetadata(root)).rejects.toThrow(
"Invalid Paseo worktree metadata file",
);
rmSync(path);
execFileSync("mkfifo", [path]);
await expect(readPaseoWorktreeMetadata(root)).rejects.toThrow(
"Invalid Paseo worktree metadata file",
);
} finally {
rmSync(root, { recursive: true, force: true });
}
});
});
+57 -35
View File
@@ -1,7 +1,7 @@
import { execFile } from "child_process";
import { promisify } from "util";
import { constants as fsConstants, existsSync, mkdirSync, realpathSync, statSync } from "fs";
import { copyFile, rm, stat } from "fs/promises";
import { constants as fsConstants } from "fs";
import { copyFile, mkdir, realpath, rm, stat } from "fs/promises";
import { join, basename, dirname, isAbsolute, resolve, sep } from "path";
import net from "node:net";
import { createHash } from "node:crypto";
@@ -37,7 +37,12 @@ import { spawnProcess } from "./spawn.js";
import { resolvePaseoHome } from "../server/paseo-home.js";
import { createExternalProcessEnv } from "../server/paseo-env.js";
import { parseGitRevParsePath, resolveGitRevParsePath } from "./git-rev-parse-path.js";
import { expandTilde, getRealpathAwareRelativePath, isPathInsideRoot } from "./path.js";
import {
expandTilde,
getRealpathAwareRelativePath,
getRelativePathInsideRoot,
isPathInsideRoot,
} from "./path.js";
import { terminateWithTreeKill } from "./tree-kill.js";
export { slugify, validateBranchSlug } from "@getpaseo/protocol/branch-slug";
@@ -607,7 +612,7 @@ async function assertPortAvailable(port: number): Promise<void> {
async function inferRepoRootPathFromWorktreePath(worktreePath: string): Promise<string> {
try {
const commonDir = await getGitCommonDir(worktreePath);
const normalizedCommonDir = normalizePathForOwnership(commonDir);
const normalizedCommonDir = await normalizePathForOwnership(commonDir);
// Normal repo/worktree: common dir is <repoRoot>/.git
if (basename(normalizedCommonDir) === ".git") {
return dirname(normalizedCommonDir);
@@ -623,12 +628,12 @@ async function inferRepoRootPathFromWorktreePath(worktreePath: string): Promise<
});
const topLevel = parseGitRevParsePath(stdout);
if (topLevel) {
return normalizePathForOwnership(topLevel);
return await normalizePathForOwnership(topLevel);
}
} catch {
// ignore
}
return normalizePathForOwnership(worktreePath);
return await normalizePathForOwnership(worktreePath);
}
}
@@ -711,12 +716,12 @@ export async function resolveWorktreeRuntimeEnv(options: {
const branchName =
options.branchName ?? (await resolveBranchNameForWorktreePath(options.worktreePath));
let worktreePort = readPaseoWorktreeRuntimePort(options.worktreePath);
let worktreePort = await readPaseoWorktreeRuntimePort(options.worktreePath);
if (worktreePort === null) {
worktreePort = await getAvailablePort();
const metadata = readPaseoWorktreeMetadata(options.worktreePath);
const metadata = await readPaseoWorktreeMetadata(options.worktreePath);
if (metadata) {
writePaseoWorktreeRuntimeMetadata(options.worktreePath, { worktreePort });
await writePaseoWorktreeRuntimeMetadata(options.worktreePath, { worktreePort });
}
} else {
await assertPortAvailable(worktreePort);
@@ -742,7 +747,7 @@ export async function runWorktreeTeardownCommands(options: {
repoRootPath?: string;
}): Promise<WorktreeTeardownCommandResult[]> {
const teardownCwd = options.teardownCwd ?? options.worktreePath;
if (getRealpathAwareRelativePath(options.worktreePath, teardownCwd) === null) {
if ((await getOwnershipRelativePath(options.worktreePath, teardownCwd)) === null) {
throw new Error(`Worktree teardown cwd is outside the worktree: ${teardownCwd}`);
}
const teardownCommands = getWorktreeTeardownCommands(teardownCwd);
@@ -754,7 +759,7 @@ export async function runWorktreeTeardownCommands(options: {
options.repoRootPath ?? (await inferRepoRootPathFromWorktreePath(options.worktreePath));
const branchName =
options.branchName ?? (await resolveBranchNameForWorktreePath(options.worktreePath));
const worktreePort = readPaseoWorktreeRuntimePort(options.worktreePath);
const worktreePort = await readPaseoWorktreeRuntimePort(options.worktreePath);
const teardownEnv: NodeJS.ProcessEnv = createStringCommandShellEnv(
createExternalProcessEnv(process.env, {
@@ -831,12 +836,12 @@ function deriveShortAlphanumericHash(value: string): string {
export async function deriveWorktreeProjectHash(cwd: string): Promise<string> {
try {
const commonDir = await getGitCommonDir(cwd);
const normalizedCommonDir = normalizePathForOwnership(commonDir);
const normalizedCommonDir = await normalizePathForOwnership(commonDir);
const repoRoot =
basename(normalizedCommonDir) === ".git" ? dirname(normalizedCommonDir) : normalizedCommonDir;
return deriveShortAlphanumericHash(repoRoot);
} catch {
return deriveShortAlphanumericHash(normalizePathForOwnership(cwd));
return deriveShortAlphanumericHash(await normalizePathForOwnership(cwd));
}
}
@@ -904,16 +909,30 @@ export function mapWorkspaceRelativeCwdToWorktree(input: {
return mappedCwd;
}
function normalizePathForOwnership(input: string): string {
async function normalizePathForOwnership(input: string): Promise<string> {
try {
return realpathSync(input);
return await realpath(input);
} catch {
return resolve(input);
}
}
function resolveRepoRootFromGitCommonDir(commonDir: string): string {
const normalizedCommonDir = normalizePathForOwnership(commonDir);
// 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<string | null> {
const roots = [root, await normalizePathForOwnership(root)];
const candidates = [candidate, await normalizePathForOwnership(candidate)];
for (const rootPath of roots) {
for (const candidatePath of candidates) {
const relative = getRelativePathInsideRoot(rootPath, candidatePath);
if (relative !== null) return relative;
}
}
return null;
}
async function resolveRepoRootFromGitCommonDir(commonDir: string): Promise<string> {
const normalizedCommonDir = await normalizePathForOwnership(commonDir);
return basename(normalizedCommonDir) === ".git"
? dirname(normalizedCommonDir)
: normalizedCommonDir;
@@ -923,25 +942,25 @@ export async function isPaseoOwnedWorktreeCwd(
cwd: string,
options?: PaseoWorktreeOwnershipOptions,
): Promise<PaseoWorktreeOwnership> {
const resolvedCwd = normalizePathForOwnership(cwd);
const resolvedCwd = await normalizePathForOwnership(cwd);
// repoRoot is best-effort: git may be unreachable from the worktree (e.g. a
// previous archive attempt removed the admin dir before the working tree
// could be fully cleaned up). We still want to allow archiving in that case.
let repoRoot: string | undefined;
if (options?.knownGitCommonDir) {
repoRoot = resolveRepoRootFromGitCommonDir(options.knownGitCommonDir);
repoRoot = await resolveRepoRootFromGitCommonDir(options.knownGitCommonDir);
} else if (options?.knownGitCommonDir === undefined) {
try {
const gitCommonDir = await getGitCommonDir(cwd);
repoRoot = resolveRepoRootFromGitCommonDir(gitCommonDir);
repoRoot = await resolveRepoRootFromGitCommonDir(gitCommonDir);
} catch {
// ignore
}
}
const worktreesBaseRoot = resolvePaseoWorktreesBaseRoot(options);
const relativePath = getRealpathAwareRelativePath(worktreesBaseRoot, resolvedCwd);
const relativePath = await getOwnershipRelativePath(worktreesBaseRoot, resolvedCwd);
// Ownership is defined by the path living under <worktrees-root>/<hash>/<slug>[/...].
// The <hash>/<slug> prefix is Paseo-private — nothing else writes there — so the
@@ -1012,9 +1031,9 @@ function parseWorktreeList(output: string): ParsedPaseoWorktreeInfo[] {
return entries;
}
function resolveWorktreeCreatedAtIso(worktreePath: string): string {
async function resolveWorktreeCreatedAtIso(worktreePath: string): Promise<string> {
try {
const stats = statSync(worktreePath);
const stats = await stat(worktreePath);
const birthtimeMs = stats.birthtimeMs;
const createdAtMs =
Number.isFinite(birthtimeMs) && birthtimeMs > 0 ? birthtimeMs : stats.ctimeMs;
@@ -1039,12 +1058,15 @@ export async function listPaseoWorktrees({
envOverlay: READ_ONLY_GIT_ENV,
});
return parseWorktreeList(stdout)
.map((entry) => Object.assign({}, entry, { path: normalizePathForOwnership(entry.path) }))
.filter((entry) => getRealpathAwareRelativePath(projectWorktreesRoot, entry.path) !== null)
.map((entry) =>
Object.assign({}, entry, { createdAt: resolveWorktreeCreatedAtIso(entry.path) }),
);
const root = projectWorktreesRoot;
const worktrees: PaseoWorktreeInfo[] = [];
// Inspect foreign paths sequentially; a large worktree list must not consume the FS pool.
for (const entry of parseWorktreeList(stdout)) {
const path = await normalizePathForOwnership(entry.path);
if ((await getOwnershipRelativePath(root, path)) === null) continue;
worktrees.push({ ...entry, path, createdAt: await resolveWorktreeCreatedAtIso(path) });
}
return worktrees;
}
export interface DeletePaseoWorktreeOptions {
@@ -1083,7 +1105,7 @@ export async function deletePaseoWorktree({
}
const requestedPath = worktreePath ?? join(resolvedWorktreesRoot, worktreeSlug!);
const resolvedRequested = normalizePathForOwnership(requestedPath);
const resolvedRequested = await normalizePathForOwnership(requestedPath);
const ownership = await isPaseoOwnedWorktreeCwd(requestedPath, {
paseoHome,
worktreesRoot: worktreesBaseRoot,
@@ -1091,7 +1113,7 @@ export async function deletePaseoWorktree({
const resolvedWorktree =
ownership.allowed && ownership.worktreePath ? ownership.worktreePath : resolvedRequested;
const relativeWorktreePath = getRealpathAwareRelativePath(
const relativeWorktreePath = await getOwnershipRelativePath(
resolvedWorktreesRoot,
resolvedWorktree,
);
@@ -1207,12 +1229,12 @@ export const createWorktree = async ({
}: CreateWorktreeOptions): Promise<CreatedWorktree> => {
const sourcePlan = await resolveWorktreeSourcePlan({ cwd, source, desiredSlug: worktreeSlug });
let worktreePath = join(await getPaseoWorktreesRoot(cwd, paseoHome, worktreesRoot), worktreeSlug);
mkdirSync(dirname(worktreePath), { recursive: true });
await mkdir(dirname(worktreePath), { recursive: true });
// Also handle worktree path collision
let finalWorktreePath = worktreePath;
let pathSuffix = 1;
while (existsSync(finalWorktreePath)) {
while (await pathExists(finalWorktreePath)) {
finalWorktreePath = `${worktreePath}-${pathSuffix}`;
pathSuffix++;
}
@@ -1222,7 +1244,7 @@ export const createWorktree = async ({
cwd,
timeout: 120_000,
});
worktreePath = normalizePathForOwnership(finalWorktreePath);
worktreePath = await normalizePathForOwnership(finalWorktreePath);
if (sourcePlan.pushRemote) {
await configureWorktreePushRemote({
@@ -1239,7 +1261,7 @@ export const createWorktree = async ({
});
}
writePaseoWorktreeMetadata(worktreePath, {
await writePaseoWorktreeMetadata(worktreePath, {
baseRefName: sourcePlan.metadataBaseRefName,
...(sourcePlan.metadataBaseRef ? { baseRef: sourcePlan.metadataBaseRef } : {}),
...(sourcePlan.changeRequestLookupTarget