Compare commits

...
Author SHA1 Message Date
Mohamed Boudra 0466204ff4 fix(server): keep git from adopting bare-repository-shaped directories
Git discovery treats any directory holding `HEAD`, `config`, `objects/` and
`refs/` as a bare repository, at the working directory or in a parent. Daemon
git commands then ran with that directory's config. They now pass
`-c safe.bareRepository=explicit`. The flag is left off only when the working
directory is a bare repository that a linked worktree's `.git` file points back
to, so the bare + linked-worktree layout keeps working.

The diff reader ran `git status` inside every submodule path. An uninitialized
submodule has no `.git`, so git walked up to whatever repository sat above it.
The reader now skips submodules without `.git` and pins `GIT_DIR=.git` for
initialized ones.

The worktree-include plugin spawns git directly and gets the same flags.
2026-11-23 09:41:58 +01:00
Mohamed Boudra 3389138eb7 fix(hub): validate agents against the workspace catalog (#10582)
Trigger save validation used the host-wide provider catalog, so it rejected models offered by the workspace catalog. Pass the optional working directory through to provider discovery.
2026-11-23 15:11:09 +07:00
14 changed files with 340 additions and 31 deletions
@@ -94,6 +94,19 @@ describe("Hub session protocol", () => {
expect(SessionOutboundMessageSchema.parse(response)).toEqual(response);
});
test("round-trips the working directory on named-agent validation", () => {
const request = {
type: "hub.execution.agent.validate.request",
requestId: "validate-workspace",
provider: "opencode",
model: "workspace-model",
cwd: "/workspace",
};
expect(SessionInboundMessageSchema.parse(request)).toEqual(request);
expect(SessionInboundMessageSchema.safeParse({ ...request, cwd: 123 }).success).toBe(false);
});
test("accepts the Hub execution create request", () => {
const message = {
type: "hub.execution.agent.create.request",
+1
View File
@@ -3465,6 +3465,7 @@ export const HubExecutionAgentValidateRequestSchema = z.object({
type: z.literal("hub.execution.agent.validate.request"),
requestId: z.string(),
provider: z.string(),
cwd: z.string().optional(),
model: z.string().optional(),
modeId: z.string().optional(),
thinkingOptionId: z.string().optional(),
@@ -6,6 +6,7 @@ import { filterSelectableAgentModels } from "./agent-sdk-types.js";
export interface AgentConfigurationValidationInput {
provider: string;
cwd?: string;
model?: string;
modeId?: string;
thinkingOptionId?: string;
@@ -321,6 +321,40 @@ describe("ProviderSnapshotManager public surface", () => {
}
});
test("validates workspace-only models against the requested working directory", async () => {
const cwd = resolveSnapshotCwd("/tmp/workspace-models");
const model = { provider: "opencode", id: "workspace-model", label: "Workspace model" };
const manager = new ProviderSnapshotManager({
logger: createTestLogger(),
extraClients: {
opencode: createExtraClient("opencode", {
isAvailable: async () => true,
fetchCatalog: async (options) => ({
models: options.scope === "workspace" && options.cwd === cwd ? [model] : [],
modes: [],
}),
}),
},
});
const input = { provider: model.provider, model: model.id };
const unavailable = [
{
path: ["model"],
message: "Model 'workspace-model' is not available for provider 'opencode'",
},
];
try {
await expect(manager.validateAgentConfiguration(input)).resolves.toEqual(unavailable);
await expect(manager.validateAgentConfiguration({ ...input, cwd })).resolves.toEqual([]);
await expect(
manager.validateAgentConfiguration({ ...input, cwd: "/tmp/missing-workspace" }),
).resolves.toEqual(unavailable);
} finally {
manager.destroy();
}
});
test("accepts a legacy Ultra Code choice on a model with an independent effort catalog", async () => {
const manager = new ProviderSnapshotManager({
logger: createTestLogger(),
@@ -650,6 +650,7 @@ export class ProviderSnapshotManager {
const provider = await this.getProvider({
provider: input.provider,
cwd: input.cwd,
wait: true,
});
if (!provider.enabled) {
@@ -778,3 +778,40 @@ test.each([
}
},
);
test("an uninitialized submodule below a bare repository layout does not fail the comparison", async () => {
const cwd = await mkdtemp(join(tmpdir(), "diff-uninitialized-submodule-"));
const git = (...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim();
const { mkdir } = await import("node:fs/promises");
try {
git("init", "-b", "main");
git("config", "user.name", "Test");
git("config", "user.email", "test@example.com");
await writeFile(join(cwd, "README.md"), "base\n");
git("add", ".");
git("-c", "commit.gpgsign=false", "commit", "-m", "base");
const base = git("rev-parse", "HEAD");
git("update-index", "--add", "--cacheinfo", `160000,${base},vendor/sub`);
git("-c", "commit.gpgsign=false", "commit", "-m", "record submodule");
// `vendor/` holds files shaped like a bare repository; git discovery from the
// uninitialized `vendor/sub` would stop there before reaching the superproject.
git("init", "--bare", "-q", "vendor");
await mkdir(join(cwd, "vendor", "sub"));
const comparison = await listComparison({
cwd,
base: { kind: "rev", rev: base },
head: { kind: "worktree" },
highlight: false,
});
try {
expect(comparison.files.map((file) => [file.entry.path, file.entry.change])).toContainEqual([
"vendor/sub",
"added",
]);
} finally {
await comparison.close();
}
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
+19 -6
View File
@@ -12,7 +12,7 @@ import {
type CheckoutDiffCompare,
} from "../../utils/checkout-git.js";
import { lstat, readFile, readlink } from "node:fs/promises";
import { resolve } from "node:path";
import { join, resolve } from "node:path";
import type { DiffEndpoint, DiffSubscribeRequest } from "@getpaseo/protocol/messages";
import type { DiffEntry, DiffBody } from "@getpaseo/protocol/binary-frames/index";
import { runGitCommand, type GitCommandOptions } from "../../utils/run-git-command.js";
@@ -444,15 +444,28 @@ async function readWorktreeContent({
if (value.isSymbolicLink())
return { hashed: false, literal: `symlink:${await readlink(absolutePath)}` };
if (value.isDirectory() && (header[0] === ":160000" || header[1] === "160000")) {
const submodule = await runGitCommand(
["status", "--porcelain=v2", "--branch", "--untracked-files=normal"],
{ cwd: absolutePath, envOverlay: { GIT_OPTIONAL_LOCKS: "0" } },
);
return { hashed: false, literal: `submodule:${submodule.stdout}` };
return { hashed: false, literal: `submodule:${await readSubmoduleStatus(absolutePath)}` };
}
return { hashed: value.isFile() && text, literal: null };
}
// An uninitialized submodule has no `.git`; running git there would discover
// whichever repository sits above it. Pinning GIT_DIR keeps an initialized
// submodule's status on its own `.git`.
async function readSubmoduleStatus(submodulePath: string): Promise<string> {
try {
await lstat(join(submodulePath, ".git"));
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") return "";
throw error;
}
const status = await runGitCommand(
["status", "--porcelain=v2", "--branch", "--untracked-files=normal"],
{ cwd: submodulePath, envOverlay: { GIT_DIR: ".git", GIT_OPTIONAL_LOCKS: "0" } },
);
return status.stdout;
}
function diffArguments(compare: Compare, baseSha: string, headSha: string): string[] {
const revisions: string[] = [];
if (compare.base.kind !== "index") revisions.push(baseSha);
@@ -86,23 +86,29 @@ class RejectingHubExecutionAgents implements HubExecutionAgents {
}
describe("HubExecutionController", () => {
test("validates a named agent through the daemon provider registry", async () => {
test.each([
{ cwd: "/workspace", valid: true },
{ cwd: undefined, valid: false },
{ cwd: "/missing-workspace", valid: false },
])("validates a named agent with cwd $cwd", async ({ cwd, valid }) => {
const messages: SessionOutboundMessage[] = [];
const unavailable = { path: ["model"], message: "Model is unavailable" };
const validateAgentConfiguration = async (
message: Omit<HubExecutionAgentValidateRequest, "type" | "requestId">,
) =>
message.model === "missing" ? [{ path: ["model"], message: "Model is unavailable" }] : [];
input: Omit<HubExecutionAgentValidateRequest, "type" | "requestId">,
) => (input.model === "workspace-model" && input.cwd === "/workspace" ? [] : [unavailable]);
const controller = new HubExecutionController({
agents: new ControlledHubExecutionAgents(),
validateAgentConfiguration,
send: (message) => messages.push(message),
});
const scope = cwd === undefined ? {} : { cwd };
await controller.validateAgent({
type: "hub.execution.agent.validate.request",
requestId: "validate-agent",
provider: "codex",
model: "missing",
provider: "opencode",
model: "workspace-model",
...scope,
});
expect(messages).toEqual([
@@ -110,8 +116,8 @@ describe("HubExecutionController", () => {
type: "hub.execution.agent.validate.response",
payload: {
requestId: "validate-agent",
valid: false,
issues: [{ path: ["model"], message: "Model is unavailable" }],
valid,
issues: valid ? [] : [unavailable],
error: null,
},
},
@@ -87,6 +87,7 @@ export class HubExecutionController {
try {
issues = await this.validateAgentConfiguration({
provider: message.provider,
cwd: message.cwd,
model: message.model,
modeId: message.modeId,
thinkingOptionId: message.thinkingOptionId,
@@ -0,0 +1,46 @@
import type { Dirent } from "node:fs";
import { lstat, readdir, readFile, realpath } from "node:fs/promises";
import { basename, dirname, join, resolve } from "node:path";
const GITFILE_PREFIX = "gitdir:";
/**
* True when `cwd` is a bare repository that a linked worktree checkout points
* back to: some `<cwd>/worktrees/<name>/gitdir` names a real `.git` file whose
* `gitdir:` line resolves to that same `worktrees/<name>` directory. A clone
* cannot contain `.git` files, so a directory layout that only looks like a bare
* repository never passes. Symlinked entries and unreadable files count as not
* linked.
*/
export async function isLinkedBareRepository(cwd: string): Promise<boolean> {
try {
if (!(await lstat(join(cwd, "HEAD"))).isFile()) return false;
const worktreesDir = join(await realpath(cwd), "worktrees");
if (!(await lstat(worktreesDir)).isDirectory()) return false;
const entries = await readdir(worktreesDir, { withFileTypes: true });
for (const entry of entries) {
if (await isLinkedWorktreeAdminDir(worktreesDir, entry)) return true;
}
return false;
} catch {
return false;
}
}
async function isLinkedWorktreeAdminDir(worktreesDir: string, entry: Dirent): Promise<boolean> {
if (!entry.isDirectory()) return false;
const adminDir = join(worktreesDir, entry.name);
try {
const gitdirFile = join(adminDir, "gitdir");
if (!(await lstat(gitdirFile)).isFile()) return false;
const dotGitPath = resolve(adminDir, (await readFile(gitdirFile, "utf8")).trim());
if (basename(dotGitPath) !== ".git") return false;
if (!(await lstat(dotGitPath)).isFile()) return false;
const firstLine = (await readFile(dotGitPath, "utf8")).split(/\r?\n/, 1)[0] ?? "";
if (!firstLine.startsWith(GITFILE_PREFIX)) return false;
const target = resolve(dirname(dotGitPath), firstLine.slice(GITFILE_PREFIX.length).trim());
return (await realpath(target)) === adminDir;
} catch {
return false;
}
}
@@ -1,4 +1,14 @@
import { chmodSync, existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { execFileSync } from "node:child_process";
import {
chmodSync,
existsSync,
mkdirSync,
mkdtempSync,
realpathSync,
rmSync,
symlinkSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
@@ -49,3 +59,116 @@ describe("runGitCommand fsmonitor isolation", () => {
expect(result.stdout.trim()).toBe("false");
});
});
function git(args: string[], cwd?: string): string {
return execFileSync("git", args, { cwd, encoding: "utf8", stdio: "pipe" }).trim();
}
function makeTempDir(): string {
const dir = realpathSync(mkdtempSync(path.join(tmpdir(), "paseo-git-discovery-")));
tempDirs.push(dir);
return dir;
}
// Files shaped like a bare repository (`HEAD`, `config`, `objects/`, `refs/`) that
// git would adopt implicitly, with a clean filter that leaves a marker when run.
function createBareRepositoryLayout(root: string, name: string): { dir: string; marker: string } {
const dir = path.join(root, name);
git(["init", "--bare", "-q", dir]);
const marker = path.join(root, `${name}.marker`);
writeFileSync(path.join(dir, "info", "attributes"), "* filter=probe\n");
git(["config", "-f", path.join(dir, "config"), "filter.probe.clean", `touch '${marker}'; cat`]);
return { dir, marker };
}
function createBareRepositoryWithLinkedWorktree(root: string): {
bareRepo: string;
worktree: string;
} {
const source = path.join(root, "source");
git(["init", "-q", "-b", "main", source]);
git(
[
"-c",
"user.name=Test",
"-c",
"user.email=test@example.com",
"commit",
"-q",
"--allow-empty",
"-m",
"base",
],
source,
);
const bareRepo = path.join(root, "repo.git");
git(["clone", "-q", "--bare", source, bareRepo]);
const worktree = path.join(root, "main");
git(["worktree", "add", "-q", worktree, "main"], bareRepo);
return { bareRepo, worktree };
}
describe("runGitCommand repository discovery", () => {
it("does not adopt a bare repository layout at the working directory", async () => {
const root = makeTempDir();
const layout = createBareRepositoryLayout(root, "layout");
writeFileSync(path.join(layout.dir, "f.txt"), "contents\n");
await runGitCommand(["hash-object", "--path=f.txt", "f.txt"], { cwd: layout.dir });
expect(existsSync(layout.marker)).toBe(false);
await expect(
runGitCommand(["rev-parse", "--absolute-git-dir"], { cwd: layout.dir }),
).rejects.toThrow(/cannot use bare repository/);
});
it("does not adopt a bare repository layout in a parent directory", async () => {
const root = makeTempDir();
const layout = createBareRepositoryLayout(root, "layout");
const nested = path.join(layout.dir, "nested");
mkdirSync(nested);
writeFileSync(path.join(nested, "f.txt"), "contents\n");
await runGitCommand(["hash-object", "--path=f.txt", "f.txt"], { cwd: nested });
expect(existsSync(layout.marker)).toBe(false);
await expect(
runGitCommand(["rev-parse", "--absolute-git-dir"], { cwd: nested }),
).rejects.toThrow(/cannot use bare repository/);
});
it("does not adopt a bare repository layout whose worktrees directory is a symlink", async () => {
const root = makeTempDir();
const { bareRepo } = createBareRepositoryWithLinkedWorktree(root);
const layout = createBareRepositoryLayout(root, "layout");
symlinkSync(path.join(bareRepo, "worktrees"), path.join(layout.dir, "worktrees"));
await expect(
runGitCommand(["rev-parse", "--absolute-git-dir"], { cwd: layout.dir }),
).rejects.toThrow(/cannot use bare repository/);
});
it("does not adopt a bare repository layout whose worktree entry belongs to another repository", async () => {
const root = makeTempDir();
const { worktree } = createBareRepositoryWithLinkedWorktree(root);
const layout = createBareRepositoryLayout(root, "layout");
const adminDir = path.join(layout.dir, "worktrees", "main");
mkdirSync(adminDir, { recursive: true });
writeFileSync(path.join(adminDir, "gitdir"), `${path.join(worktree, ".git")}\n`);
await expect(
runGitCommand(["rev-parse", "--absolute-git-dir"], { cwd: layout.dir }),
).rejects.toThrow(/cannot use bare repository/);
});
it("runs in a bare repository that a linked worktree points back to", async () => {
const root = makeTempDir();
const { bareRepo, worktree } = createBareRepositoryWithLinkedWorktree(root);
const fromBare = await runGitCommand(["worktree", "list", "--porcelain"], { cwd: bareRepo });
const fromWorktree = await runGitCommand(["rev-parse", "--git-common-dir"], { cwd: worktree });
expect(fromBare.stdout).toContain(`worktree ${worktree}\n`);
expect(path.resolve(worktree, fromWorktree.stdout.trim())).toBe(bareRepo);
});
});
+29 -14
View File
@@ -11,6 +11,7 @@ import {
startGitCommandTrace,
submitGitCommandTrace,
} from "./git-command-trace.js";
import { isLinkedBareRepository } from "./linked-bare-repository.js";
import { spawnProcess } from "./spawn.js";
import {
GitProcessScheduler,
@@ -302,7 +303,7 @@ function executeGitCommand<Output>(
pending: gitProcessScheduler.pendingCount,
});
const runtimeMetric = gitRuntimeMetrics.submit(getGitOperation(args), submission.provenance);
const startCommand = () => {
const spawnCommand = (configArgs: string[]) => {
let releaseProcessSlot!: () => void;
const exited = new Promise<void>((resolve) => {
releaseProcessSlot = resolve;
@@ -407,19 +408,12 @@ function executeGitCommand<Output>(
let child: ReturnType<typeof spawnProcess>;
try {
// `core.quotepath=false` makes git emit raw UTF-8 paths instead of
// octal-escaping non-ASCII bytes (e.g. `测试文件.txt` vs `"\346\265\213..."`).
// `core.fsmonitor=false` prevents repository config from launching a command.
child = spawnProcess(
"git",
["-c", "core.quotepath=false", "-c", "core.fsmonitor=false", ...args],
{
cwd: options.cwd,
envOverlay,
shell: false,
stdio: [options.input === undefined ? "ignore" : "pipe", "pipe", "pipe"],
},
);
child = spawnProcess("git", [...configArgs, ...args], {
cwd: options.cwd,
envOverlay,
shell: false,
stdio: [options.input === undefined ? "ignore" : "pipe", "pipe", "pipe"],
});
spawnGitCommandTrace(commandTrace, child.pid);
} catch (error) {
rejectSpawnFailure(error);
@@ -574,6 +568,15 @@ function executeGitCommand<Output>(
});
return { result: resultPromise, exited };
};
// The process slot stays held through the config lookup because `exited`
// settles only after the spawned process exits. `resolveGitConfigArgs` never rejects.
const startCommand = () => {
const spawned = resolveGitConfigArgs(options.cwd).then(spawnCommand);
return {
result: spawned.then((scheduled) => scheduled.result),
exited: spawned.then((scheduled) => scheduled.exited),
};
};
const promise = gitProcessScheduler.run(startCommand, { priority });
gitRuntimeMetrics.observeLimiter(
gitProcessScheduler.activeCount,
@@ -582,6 +585,18 @@ function executeGitCommand<Output>(
return promise;
}
// `core.quotepath=false` makes git emit raw UTF-8 paths instead of
// octal-escaping non-ASCII bytes (e.g. `测试文件.txt` vs `"\346\265\213..."`).
// `core.fsmonitor=false` prevents repository config from launching a command.
// `safe.bareRepository=explicit` stops git from adopting a directory that only
// looks like a bare repository, at `cwd` or above it. A bare repository with
// linked worktrees still works when `cwd` is that repository.
async function resolveGitConfigArgs(cwd: string): Promise<string[]> {
const args = ["-c", "core.quotepath=false", "-c", "core.fsmonitor=false"];
if (await isLinkedBareRepository(cwd)) return args;
return [...args, "-c", "safe.bareRepository=explicit"];
}
export const runGitCommand: RunGitCommand = (args, options) =>
executeGitCommand(args, options, decodeUtf8, {});
+14 -1
View File
@@ -1,6 +1,6 @@
import { execFileSync } from "node:child_process";
import { existsSync } from "node:fs";
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
@@ -54,6 +54,19 @@ afterEach(async () => {
});
describe("copyWorktreeIncludes", () => {
it("does not run a command the source repository configures as its fsmonitor", async () => {
const marker = join(root, "fsmonitor.marker");
const hook = join(root, "fsmonitor-hook.sh");
await writeFile(hook, `#!/bin/sh\n: > '${marker}'\nprintf '1\\n'\n`);
await chmod(hook, 0o755);
await writeSource({ ".gitignore": ".env\n", ".worktreeinclude": ".env\n", ".env": "A=1" });
execFileSync("git", ["add", ".gitignore", ".worktreeinclude"], { cwd: source });
execFileSync("git", ["config", "core.fsmonitor", hook], { cwd: source });
expect(await copied()).toEqual([".env"]);
expect(existsSync(marker)).toBe(false);
});
it("does not search inside an ignored directory that no pattern names", async () => {
await writeSource({
".gitignore": "node_modules/\n.env\n",
+6 -1
View File
@@ -14,8 +14,13 @@ export type CopyResult =
| { kind: "no-include-file" }
| { kind: "copied"; copied: string[]; skipped: string[] };
// `core.fsmonitor=false` prevents repository config from launching a command.
// `safe.bareRepository=explicit` stops git from adopting a directory that only
// looks like a bare repository.
const GIT_CONFIG_ARGS = ["-c", "core.fsmonitor=false", "-c", "safe.bareRepository=explicit"];
async function git(cwd: string, args: string[], input?: string): Promise<string> {
const child = exec("git", args, { cwd, maxBuffer: 64 * 1024 * 1024 });
const child = exec("git", [...GIT_CONFIG_ARGS, ...args], { cwd, maxBuffer: 64 * 1024 * 1024 });
if (input !== undefined) {
child.child.stdin?.end(input);
}