Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions apps/server/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -566,13 +566,15 @@ const layerWorkspaceFileSystem = WorkspaceFileSystem.layer.pipe(
Layer.provide(layerKnownWorkspaces),
);

const layerWorkspaceFolders = WorkspaceFolders.layer.pipe(
Layer.provide(Layer.merge(ProjectStore.layer, TaskFolderStore.layer)),
);

const layerWorkspace = Layer.mergeAll(
WorkspacePaths.layer,
layerWorkspaceEntries,
layerWorkspaceFileSystem,
WorkspaceFolders.layer.pipe(
Layer.provide(Layer.merge(ProjectStore.layer, TaskFolderStore.layer)),
),
layerWorkspaceFolders,
);

const layerProjectFaviconResolver = ProjectFaviconResolver.layer.pipe(
Expand Down Expand Up @@ -873,8 +875,15 @@ const layerRuntimeDependencies = layerRuntimeCoreDependencies.pipe(
Layer.provideMerge(DirectEndpoints.layer.pipe(Layer.provide(layerServerEnvironment))),
Layer.provideMerge(ServerLifecycleEvents.layer),
// GitVcsDriver.layer is memoized and some of its build sites live outside this file, so the
// fetch interval goes in context here, before the first build captures it.
// fetch interval and the nested repositories go in context here, before the first build
// captures them.
Layer.provideMerge(VcsAutomaticFetchInterval.layer.pipe(Layer.provide(layerServerSettings))),
Layer.provideMerge(
WorkspaceFolders.layerVcsNestedRepositories.pipe(
Layer.provide(layerWorkspaceFolders),
Layer.provide(layerPersistence),
),
),
Layer.provide(NetService.layer),
);

Expand Down
49 changes: 49 additions & 0 deletions apps/server/src/vcs/GitVcsDriverCore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ import {
import { autoPullProjects } from "../serverRuntimeStartup.ts";
import * as GitVcsDriver from "./GitVcsDriver.ts";
import { VcsAutomaticFetchInterval } from "./VcsAutomaticFetchInterval.ts";
import { VcsNestedRepositories } from "./VcsNestedRepositories.ts";
import { gitConfigEnv } from "./VcsProcess.ts";

const encodeGitCommandError = Schema.encodeEffect(Schema.fromJsonString(GitCommandError));
Expand Down Expand Up @@ -3961,6 +3962,54 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
}),
);

it.effect("leaves the repositories a project covers out of its checkout's Git views", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
yield* initRepoWithCommit(cwd);
const fileSystem = yield* FileSystem.FileSystem;
const driver = yield* makeGitVcsDriverCore().pipe(
Effect.provideService(VcsNestedRepositories, (input) =>
Effect.succeed(input.worktreeRoot === cwd ? ["api", "web"] : []),
),
);
// `web` is also listed in .gitignore: naming it in git add's pathspec would fail.
for (const nested of ["api", "web"]) {
yield* fileSystem.makeDirectory(`${cwd}/${nested}`);
yield* initRepoWithCommit(`${cwd}/${nested}`);
yield* writeTextFile(cwd, `${nested}/dirty.txt`, "nested change\n");
}
yield* writeTextFile(cwd, ".gitignore", "web/\n");
yield* git(cwd, ["add", ".gitignore"]);
yield* git(cwd, ["commit", "-m", "ignore web"]);
yield* writeTextFile(cwd, "notes.txt", "root change\n");

const status = yield* driver.statusDetailsLocal(cwd, { includeBranchChanges: true });
assert.deepStrictEqual(status.workingTree.files, [
{ path: "notes.txt", insertions: 0, deletions: 0 },
]);
assert.deepStrictEqual(status.branchChanges, {
baseRef: null,
insertions: 1,
deletions: 0,
});
const preview = yield* driver.getReviewDiffPreview({ cwd, ignoreWhitespace: false });
const workingTree = preview.sources.find((source) => source.kind === "working-tree");
assert.deepStrictEqual(
workingTree?.files?.map((file) => file.path),
["notes.txt"],
);
assert.notInclude(workingTree?.diff, "api");

yield* driver.commit(cwd, "Root change", "", { stage: {} });
assert.deepStrictEqual((yield* git(cwd, ["ls-tree", "--name-only", "HEAD"])).split("\n"), [
".gitignore",
"README.md",
"notes.txt",
]);
assert.isFalse((yield* driver.statusDetailsLocal(cwd)).hasWorkingTreeChanges);
}),
);

it.effect("keeps untracked filenames with pathspec magic in the review", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
Expand Down
66 changes: 56 additions & 10 deletions apps/server/src/vcs/GitVcsDriverCore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../observabil
import * as GitVcsDriver from "./GitVcsDriver.ts";
import { removeEmptyDirectory, type RemoveEmptyDirectoryError } from "./removeEmptyDirectory.ts";
import { VcsAutomaticFetchInterval } from "./VcsAutomaticFetchInterval.ts";
import { VcsNestedRepositories } from "./VcsNestedRepositories.ts";
import { gitConfigEnv, serverGitConfigEnv, unsetInheritedRepositoryEnv } from "./VcsProcess.ts";
import { makeWorktreeCheckoutCache } from "./worktreeCheckoutCache.ts";
import { removeLinkedWorktree } from "./worktreeRemoval.ts";
Expand Down Expand Up @@ -1046,6 +1047,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
const hostPlatform = yield* HostProcess.Platform;
const serviceScope = yield* Effect.scope;
const automaticFetchInterval = yield* VcsAutomaticFetchInterval;
const nestedRepositories = yield* VcsNestedRepositories;
type StatusFetchState = {
phase: "queued" | "running" | "claimed";
claimed: Deferred.Deferred<void>;
Expand Down Expand Up @@ -1316,6 +1318,38 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
},
});

// Unexcluded, a repository the project covers inside this checkout shows as an untracked folder
// and `add -A` stages it as a gitlink. git add rejects a pathspec naming an ignored folder, and
// skips that folder anyway.
const nestedRepositoryExclusions = Effect.fn("GitVcsDriver.nestedRepositoryExclusions")(
function* (cwd: string, worktreeRoot: string) {
const nested = yield* nestedRepositories({ cwd, worktreeRoot });
if (nested.length === 0) return [];
const args = ["check-ignore", "--no-index", "-z", "--stdin"];
const checked = yield* executeGit(
"GitVcsDriver.nestedRepositoryExclusions",
worktreeRoot,
args,
{ stdin: `${nested.join("\0")}\0`, allowNonZeroExit: true },
);
if (checked.exitCode !== 0 && checked.exitCode !== 1) {
return yield* new GitCommandError({
...gitCommandContext({
operation: "GitVcsDriver.nestedRepositoryExclusions",
cwd: worktreeRoot,
args,
}),
detail: "Could not check which repositories inside the project Git ignores.",
...(checked.exitCode === null ? {} : { exitCode: checked.exitCode }),
});
}
const ignored = new Set(splitNullSeparatedGitStdoutPaths(checked));
return nested
.filter((relativePath) => !ignored.has(relativePath))
.map((relativePath) => `:(top,exclude,literal)${relativePath}`);
},
);

const runGit = (
operation: string,
cwd: string,
Expand Down Expand Up @@ -2829,10 +2863,13 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
const statusCacheKey = repositoryPaths?.gitCommonDir;
const refsGeneration =
statusCacheKey === undefined ? undefined : currentListRefsGeneration(statusCacheKey);
const exclusions = repositoryPaths?.worktreeRoot
? yield* nestedRepositoryExclusions(cwd, repositoryPaths.worktreeRoot)
: [];
const readStatus = executeGitWithStableDiagnostics(
"GitVcsDriver.statusDetails.status",
cwd,
statusArgs,
exclusions.length === 0 ? statusArgs : [...statusArgs, "--", ...exclusions],
{
allowNonZeroExit: true,
maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES,
Expand All @@ -2848,7 +2885,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
executeGitWithStableDiagnostics(
"GitVcsDriver.statusDetails.numstat",
cwd,
["diff-index", "-M", "--numstat", "-z", ref, "--"],
["diff-index", "-M", "--numstat", "-z", ref, "--", ...exclusions],
{ allowNonZeroExit: true, maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES },
);
// diff-index does not read status output, so both spawn together; a non-repository discards it.
Expand Down Expand Up @@ -3020,6 +3057,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
options?.includeBranchChanges
? readBranchChangeTotals(repositoryPaths?.worktreeRoot ?? cwd, refName, {
untrackedRoots,
exclusions,
headOid,
...(index ? { indexPath: index } : {}),
}).pipe(Effect.orElseSucceed(() => undefined))
Expand Down Expand Up @@ -3346,10 +3384,12 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
});
}
}
const worktreeRoot = (yield* resolveRepositoryPaths(cwd))?.worktreeRoot;
const exclusions = worktreeRoot ? yield* nestedRepositoryExclusions(cwd, worktreeRoot) : [];
yield* runGit(
"GitVcsDriver.commit.addAll",
cwd,
[...config, "add", "-A"],
[...config, "add", "-A", ...(exclusions.length === 0 ? [] : ["--", ...exclusions])],
env ? { env } : {},
);
}
Expand Down Expand Up @@ -4441,6 +4481,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
branch: string | null,
options?: {
readonly untrackedRoots: ReadonlyArray<string>;
readonly exclusions?: ReadonlyArray<string>;
readonly headOid: string | null;
readonly indexPath?: string;
},
Expand All @@ -4467,11 +4508,15 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
});
}
const roots = options?.untrackedRoots ?? [];
const exclusions = options?.exclusions ?? [];
// Bound pathspec matching work and stay below Windows' command-line limit.
const pathspecs =
roots.length <= 128 && roots.reduce((length, root) => length + root.length + 16, 0) < 8_000
const pathspecs = [
...(roots.length <= 128 &&
roots.reduce((length, root) => length + root.length + 16, 0) < 8_000
? roots.map((root) => `:(top,literal)${root}`)
: [];
: []),
...exclusions,
];
// Changed untracked roots skip the backoff and scan again.
const rootsKey = roots.join("\0");
const remembered = untrackedTotalsFailures.get(cwd);
Expand Down Expand Up @@ -4526,7 +4571,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
"GitVcsDriver.readBranchChangeTotals",
cwd,
// Plumbing: porcelain diff refreshes and rewrites the real index, taking index.lock.
["diff-index", "-M", "--numstat", "-z", ref, "--"],
["diff-index", "-M", "--numstat", "-z", ref, "--", ...exclusions],
{
allowNonZeroExit: true,
maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES,
Expand Down Expand Up @@ -4755,7 +4800,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
const getReviewDiffPreview = Effect.fn("getReviewDiffPreview")(function* (
input: ReviewDiffPreviewInput,
) {
const pathArgs = input.file
const filePathArgs = input.file
? [input.file.path, ...(input.file.previousPath ? [input.file.previousPath] : [])].map(
(path) => `:(top,literal)${path}`,
)
Expand Down Expand Up @@ -4829,7 +4874,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
const stat = yield* executeGit(
"GitVcsDriver.getReviewDiffPreview.commitStat",
cwd,
[...diffArgs, "--raw", "--numstat", "-z", commit.parent, commit.sha, "--", ...pathArgs],
[...diffArgs, "--raw", "--numstat", "-z", commit.parent, commit.sha, "--", ...filePathArgs],
{ maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES },
);
const files = parseReviewNumstat(stat.stdout);
Expand All @@ -4839,7 +4884,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
: yield* executeGit(
"GitVcsDriver.getReviewDiffPreview.commitPatch",
cwd,
[...diffArgs, "--patch", commit.parent, commit.sha, "--", ...pathArgs],
[...diffArgs, "--patch", commit.parent, commit.sha, "--", ...filePathArgs],
{ maxOutputBytes: patchLimit, appendTruncationMarker: true },
);
const diffHash = yield* hashDiff(patch.stdout, files);
Expand All @@ -4864,6 +4909,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
};
}

const pathArgs = input.file ? filePathArgs : yield* nestedRepositoryExclusions(input.cwd, cwd);
const dirtyRef = sourceKind === "branch-range" ? null : "HEAD";
const review =
tracked?.review ??
Expand Down
14 changes: 14 additions & 0 deletions apps/server/src/vcs/VcsNestedRepositories.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";

/**
* The repositories a project covers inside a checkout of its folder, relative to `worktreeRoot`
* with `/` separators. Each has its own status, review and commits, so the checkout's own Git views
* leave them out. Empty where no project layer is provided.
*/
export class VcsNestedRepositories extends Context.Reference<
(input: {
readonly cwd: string;
readonly worktreeRoot: string;
}) => Effect.Effect<ReadonlyArray<string>>
>("t3/vcs/VcsNestedRepositories", { defaultValue: () => () => Effect.succeed([]) }) {}
69 changes: 50 additions & 19 deletions apps/server/src/workspace/WorkspaceFolders.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,27 @@ import * as WorkspaceFolders from "./WorkspaceFolders.ts";

const projectId = ProjectId.make("project:workspace-folders");

const rowOf = (project: {
readonly workspaceRoot: string;
readonly trackedFolders: ReadonlyArray<ProjectTrackedFolder>;
}) => ({
projectId,
title: "Project",
hasCustomTitle: false,
defaultModelSelection: null,
defaultThreadEnvMode: null,
autoPull: false,
faviconPath: null,
projectIcon: null,
scripts: [],
pinnedAt: null,
archivedAt: null,
createdAt: "2026-06-21T00:00:00.000Z",
updatedAt: "2026-06-21T00:00:00.000Z",
deletedAt: null,
...project,
});

const layerFor = (project?: {
readonly workspaceRoot: string;
readonly trackedFolders: ReadonlyArray<ProjectTrackedFolder>;
Expand All @@ -21,25 +42,11 @@ const layerFor = (project?: {
Layer.provide(
Layer.mock(ProjectStore.ProjectStoreV2)({
get: () =>
project === undefined
? Effect.succeedNone
: Effect.succeedSome({
projectId,
title: "Project",
hasCustomTitle: false,
defaultModelSelection: null,
defaultThreadEnvMode: null,
autoPull: false,
faviconPath: null,
projectIcon: null,
scripts: [],
pinnedAt: null,
archivedAt: null,
createdAt: "2026-06-21T00:00:00.000Z",
updatedAt: "2026-06-21T00:00:00.000Z",
deletedAt: null,
...project,
}),
project === undefined ? Effect.succeedNone : Effect.succeedSome(rowOf(project)),
findActiveByWorkspaceRoot: (workspaceRoot) =>
project?.workspaceRoot === workspaceRoot
? Effect.succeedSome(rowOf(project))
: Effect.succeedNone,
}),
),
Layer.provideMerge(TaskFolderStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory))),
Expand Down Expand Up @@ -189,6 +196,21 @@ it.layer(NodeServices.layer)("WorkspaceFolders", (it) => {
["web", repository("web")],
["Outside", outside],
]);
// What the project folder's own Git views leave out: the repositories it covers inside.
assert.deepEqual(
yield* workspaceFolders.nestedRepositories({
cwd: workspaceRoot,
worktreeRoot: workspaceRoot,
}),
["docs", "src/web"],
);
assert.deepEqual(
yield* workspaceFolders.nestedRepositories({
cwd: path.join(workspaceRoot, "docs"),
worktreeRoot: path.join(workspaceRoot, "docs"),
}),
[],
);
}).pipe(Effect.provide(layerFor({ workspaceRoot, trackedFolders })));
}),
);
Expand Down Expand Up @@ -459,6 +481,15 @@ it.layer(NodeServices.layer)("WorkspaceFolders", (it) => {
}),
{ folders: [], extraRoots: [] },
);
// The thread's checkout of the project folder leaves out the worktree inside it, which
// Git names by its resolved path.
assert.deepEqual(
yield* workspaceFolders.nestedRepositories({
cwd: path.join(taskRoot, "ctx"),
worktreeRoot: path.join(realWorktrees, "x", "feature-0123", "ctx"),
}),
["vendor/lib"],
);
}).pipe(Effect.provide(layerFor({ workspaceRoot: ctx, trackedFolders })));
}),
);
Expand Down
Loading