From 972a6876b8e5c59de7d17dc25f592dd7148fb1c6 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 30 Apr 2026 23:05:37 -0700 Subject: [PATCH] Introduce pluggable VCS driver for git operations - Replace direct GitCore dependencies with VcsDriver and VcsProcess - Move checkpointing, workspace, and orchestration flows onto the new VCS abstraction - Drop workspace-specific git helpers from GitCore --- .../OrchestrationEngineHarness.integration.ts | 18 +- apps/server/src/checkpointing/Errors.ts | 7 +- .../Layers/CheckpointStore.test.ts | 40 +-- .../checkpointing/Layers/CheckpointStore.ts | 60 ++--- apps/server/src/git/Layers/GitCore.test.ts | 88 ------ apps/server/src/git/Layers/GitCore.ts | 146 ---------- apps/server/src/git/Layers/GitManager.test.ts | 52 ++-- apps/server/src/git/Layers/GitManager.ts | 4 +- apps/server/src/git/Services/GitCore.ts | 25 -- .../Layers/CheckpointReactor.test.ts | 14 +- .../Layers/ProviderCommandReactor.test.ts | 4 +- .../Layers/ProviderCommandReactor.ts | 4 +- apps/server/src/server.test.ts | 61 +++-- apps/server/src/server.ts | 12 +- .../src/vcs/Layers/GitVcsDriver.test.ts | 125 +++++++++ apps/server/src/vcs/Layers/GitVcsDriver.ts | 252 ++++++++++++++++++ apps/server/src/vcs/Layers/VcsProcess.ts | 194 ++++++++++++++ apps/server/src/vcs/Services/VcsDriver.ts | 30 +++ apps/server/src/vcs/Services/VcsProcess.ts | 32 +++ .../workspace/Layers/WorkspaceEntries.test.ts | 16 +- .../src/workspace/Layers/WorkspaceEntries.ts | 38 +-- .../Layers/WorkspaceFileSystem.test.ts | 5 +- apps/server/src/ws.ts | 4 +- packages/contracts/src/index.ts | 1 + packages/contracts/src/vcs.ts | 139 ++++++++++ 25 files changed, 960 insertions(+), 411 deletions(-) create mode 100644 apps/server/src/vcs/Layers/GitVcsDriver.test.ts create mode 100644 apps/server/src/vcs/Layers/GitVcsDriver.ts create mode 100644 apps/server/src/vcs/Layers/VcsProcess.ts create mode 100644 apps/server/src/vcs/Services/VcsDriver.ts create mode 100644 apps/server/src/vcs/Services/VcsProcess.ts create mode 100644 packages/contracts/src/vcs.ts diff --git a/apps/server/integration/OrchestrationEngineHarness.integration.ts b/apps/server/integration/OrchestrationEngineHarness.integration.ts index d650f62308..27c55bbffb 100644 --- a/apps/server/integration/OrchestrationEngineHarness.integration.ts +++ b/apps/server/integration/OrchestrationEngineHarness.integration.ts @@ -25,8 +25,6 @@ import { import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts"; import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts"; -import { GitCoreLive } from "../src/git/Layers/GitCore.ts"; -import { GitCore, type GitCoreShape } from "../src/git/Services/GitCore.ts"; import { GitStatusBroadcaster } from "../src/git/Services/GitStatusBroadcaster.ts"; import { TextGeneration, type TextGenerationShape } from "../src/git/Services/TextGeneration.ts"; import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts"; @@ -35,6 +33,7 @@ import { ProjectionCheckpointRepositoryLive } from "../src/persistence/Layers/Pr import { ProjectionPendingApprovalRepositoryLive } from "../src/persistence/Layers/ProjectionPendingApprovals.ts"; import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/ProviderSessionRuntime.ts"; import { makeSqlitePersistenceLive } from "../src/persistence/Layers/Sqlite.ts"; +import { VcsDriver, type VcsDriverShape } from "../src/vcs/Services/VcsDriver.ts"; import { ProjectionCheckpointRepository } from "../src/persistence/Services/ProjectionCheckpoints.ts"; import { ProjectionPendingApprovalRepository } from "../src/persistence/Services/ProjectionPendingApprovals.ts"; import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.ts"; @@ -77,6 +76,8 @@ import { import { deriveServerPaths, ServerConfig } from "../src/config.ts"; import { WorkspaceEntriesLive } from "../src/workspace/Layers/WorkspaceEntries.ts"; import { WorkspacePathsLive } from "../src/workspace/Layers/WorkspacePaths.ts"; +import { GitVcsDriverLive } from "../src/vcs/Layers/GitVcsDriver.ts"; +import { VcsProcessLive } from "../src/vcs/Layers/VcsProcess.ts"; function runGit(cwd: string, args: ReadonlyArray) { return execFileSync("git", args, { @@ -291,7 +292,7 @@ export const makeOrchestrationIntegrationHarness = ( Layer.provide(providerEventLoggersLayer), ); - const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive)); + const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitVcsDriverLive)); const projectionSnapshotQueryLayer = OrchestrationProjectionSnapshotQueryLive; const runtimeServicesLayer = Layer.mergeAll( projectionSnapshotQueryLayer, @@ -307,17 +308,17 @@ export const makeOrchestrationIntegrationHarness = ( Layer.provideMerge(runtimeServicesLayer), Layer.provideMerge(serverSettingsLayer), ); - const gitCoreLayer = Layer.succeed(GitCore, { - renameBranch: (input: Parameters[0]) => + const vcsDriverLayer = Layer.succeed(VcsDriver, { + renameBranch: (input: Parameters[0]) => Effect.succeed({ branch: input.newBranch }), - } as unknown as GitCoreShape); + } as unknown as VcsDriverShape); const textGenerationLayer = Layer.succeed(TextGeneration, { generateBranchName: () => Effect.succeed({ branch: "update" }), generateThreadTitle: () => Effect.succeed({ title: "New thread" }), } as unknown as TextGenerationShape); const providerCommandReactorLayer = ProviderCommandReactorLive.pipe( Layer.provideMerge(runtimeServicesLayer), - Layer.provideMerge(gitCoreLayer), + Layer.provideMerge(vcsDriverLayer), Layer.provideMerge(textGenerationLayer), Layer.provideMerge(serverSettingsLayer), ); @@ -342,11 +343,12 @@ export const makeOrchestrationIntegrationHarness = ( Layer.provideMerge( WorkspaceEntriesLive.pipe( Layer.provide(WorkspacePathsLive), - Layer.provideMerge(gitCoreLayer), + Layer.provideMerge(GitVcsDriverLive), Layer.provide(NodeServices.layer), ), ), Layer.provideMerge(WorkspacePathsLive), + Layer.provideMerge(VcsProcessLive), ); const orchestrationReactorLayer = OrchestrationReactorLive.pipe( Layer.provideMerge(runtimeIngestionLayer), diff --git a/apps/server/src/checkpointing/Errors.ts b/apps/server/src/checkpointing/Errors.ts index cb873559c1..c6875e585c 100644 --- a/apps/server/src/checkpointing/Errors.ts +++ b/apps/server/src/checkpointing/Errors.ts @@ -1,6 +1,6 @@ import { Schema } from "effect"; import type { ProjectionRepositoryError } from "../persistence/Errors.ts"; -import { GitCommandError } from "@t3tools/contracts"; +import type { VcsError } from "@t3tools/contracts"; /** * CheckpointUnavailableError - Expected checkpoint does not exist. @@ -35,9 +35,6 @@ export class CheckpointInvariantError extends Schema.TaggedErrorClass, -): Effect.Effect { +): Effect.Effect { return Effect.gen(function* () { - const gitCore = yield* GitCore; - const result = yield* gitCore.execute({ + const process = yield* VcsProcess; + const result = yield* process.run({ operation: "CheckpointStore.test.git", + command: "git", cwd, args, timeoutMs: 10_000, @@ -64,14 +69,9 @@ function git( function initRepoWithCommit( cwd: string, -): Effect.Effect< - void, - GitCommandError | PlatformError.PlatformError, - GitCore | FileSystem.FileSystem -> { +): Effect.Effect { return Effect.gen(function* () { - const core = yield* GitCore; - yield* core.initRepo({ cwd }); + yield* git(cwd, ["init"]); yield* git(cwd, ["config", "user.email", "test@test.com"]); yield* git(cwd, ["config", "user.name", "Test"]); yield* writeTextFile(path.join(cwd, "README.md"), "# test\n"); diff --git a/apps/server/src/checkpointing/Layers/CheckpointStore.ts b/apps/server/src/checkpointing/Layers/CheckpointStore.ts index 211877e9b1..d7b0b8b34c 100644 --- a/apps/server/src/checkpointing/Layers/CheckpointStore.ts +++ b/apps/server/src/checkpointing/Layers/CheckpointStore.ts @@ -14,8 +14,8 @@ import { randomUUID } from "node:crypto"; import { Effect, Layer, FileSystem, Path } from "effect"; import { CheckpointInvariantError } from "../Errors.ts"; -import { GitCommandError } from "@t3tools/contracts"; -import { GitCore } from "../../git/Services/GitCore.ts"; +import { VcsProcessExitError } from "@t3tools/contracts"; +import { VcsDriver } from "../../vcs/Services/VcsDriver.ts"; import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts"; import { CheckpointRef } from "@t3tools/contracts"; @@ -24,10 +24,10 @@ const CHECKPOINT_DIFF_MAX_OUTPUT_BYTES = 10_000_000; const makeCheckpointStore = Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; - const git = yield* GitCore; + const vcs = yield* VcsDriver; - const resolveHeadCommit = (cwd: string): Effect.Effect => - git + const resolveHeadCommit = (cwd: string) => + vcs .execute({ operation: "CheckpointStore.resolveHeadCommit", cwd, @@ -36,7 +36,7 @@ const makeCheckpointStore = Effect.gen(function* () { }) .pipe( Effect.map((result) => { - if (result.code !== 0) { + if (result.exitCode !== 0) { return null; } const commit = result.stdout.trim(); @@ -44,21 +44,18 @@ const makeCheckpointStore = Effect.gen(function* () { }), ); - const hasHeadCommit = (cwd: string): Effect.Effect => - git + const hasHeadCommit = (cwd: string) => + vcs .execute({ operation: "CheckpointStore.hasHeadCommit", cwd, args: ["rev-parse", "--verify", "HEAD"], allowNonZeroExit: true, }) - .pipe(Effect.map((result) => result.code === 0)); + .pipe(Effect.map((result) => result.exitCode === 0)); - const resolveCheckpointCommit = ( - cwd: string, - checkpointRef: CheckpointRef, - ): Effect.Effect => - git + const resolveCheckpointCommit = (cwd: string, checkpointRef: CheckpointRef) => + vcs .execute({ operation: "CheckpointStore.resolveCheckpointCommit", cwd, @@ -67,7 +64,7 @@ const makeCheckpointStore = Effect.gen(function* () { }) .pipe( Effect.map((result) => { - if (result.code !== 0) { + if (result.exitCode !== 0) { return null; } const commit = result.stdout.trim(); @@ -76,7 +73,7 @@ const makeCheckpointStore = Effect.gen(function* () { ); const isGitRepository: CheckpointStoreShape["isGitRepository"] = (cwd) => - git + vcs .execute({ operation: "CheckpointStore.isGitRepository", cwd, @@ -84,7 +81,7 @@ const makeCheckpointStore = Effect.gen(function* () { allowNonZeroExit: true, }) .pipe( - Effect.map((result) => result.code === 0 && result.stdout.trim() === "true"), + Effect.map((result) => result.exitCode === 0 && result.stdout.trim() === "true"), Effect.catch(() => Effect.succeed(false)), ); @@ -108,7 +105,7 @@ const makeCheckpointStore = Effect.gen(function* () { const headExists = yield* hasHeadCommit(input.cwd); if (headExists) { - yield* git.execute({ + yield* vcs.execute({ operation, cwd: input.cwd, args: ["read-tree", "HEAD"], @@ -116,14 +113,14 @@ const makeCheckpointStore = Effect.gen(function* () { }); } - yield* git.execute({ + yield* vcs.execute({ operation, cwd: input.cwd, args: ["add", "-A", "--", "."], env: commitEnv, }); - const writeTreeResult = yield* git.execute({ + const writeTreeResult = yield* vcs.execute({ operation, cwd: input.cwd, args: ["write-tree"], @@ -131,16 +128,17 @@ const makeCheckpointStore = Effect.gen(function* () { }); const treeOid = writeTreeResult.stdout.trim(); if (treeOid.length === 0) { - return yield* new GitCommandError({ + return yield* new VcsProcessExitError({ operation, command: "git write-tree", cwd: input.cwd, + exitCode: 0, detail: "git write-tree returned an empty tree oid.", }); } const message = `t3 checkpoint ref=${input.checkpointRef}`; - const commitTreeResult = yield* git.execute({ + const commitTreeResult = yield* vcs.execute({ operation, cwd: input.cwd, args: ["commit-tree", treeOid, "-m", message], @@ -148,15 +146,16 @@ const makeCheckpointStore = Effect.gen(function* () { }); const commitOid = commitTreeResult.stdout.trim(); if (commitOid.length === 0) { - return yield* new GitCommandError({ + return yield* new VcsProcessExitError({ operation, command: "git commit-tree", cwd: input.cwd, + exitCode: 0, detail: "git commit-tree returned an empty commit oid.", }); } - yield* git.execute({ + yield* vcs.execute({ operation, cwd: input.cwd, args: ["update-ref", input.checkpointRef, commitOid], @@ -197,12 +196,12 @@ const makeCheckpointStore = Effect.gen(function* () { return false; } - yield* git.execute({ + yield* vcs.execute({ operation, cwd: input.cwd, args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."], }); - yield* git.execute({ + yield* vcs.execute({ operation, cwd: input.cwd, args: ["clean", "-fd", "--", "."], @@ -210,7 +209,7 @@ const makeCheckpointStore = Effect.gen(function* () { const headExists = yield* hasHeadCommit(input.cwd); if (headExists) { - yield* git.execute({ + yield* vcs.execute({ operation, cwd: input.cwd, args: ["reset", "--quiet", "--", "."], @@ -235,15 +234,16 @@ const makeCheckpointStore = Effect.gen(function* () { } if (!fromCommitOid || !toCommitOid) { - return yield* new GitCommandError({ + return yield* new VcsProcessExitError({ operation, command: "git diff", cwd: input.cwd, + exitCode: 1, detail: "Checkpoint ref is unavailable for diff operation.", }); } - const result = yield* git.execute({ + const result = yield* vcs.execute({ operation, cwd: input.cwd, args: ["diff", "--patch", "--minimal", "--no-color", fromCommitOid, toCommitOid], @@ -262,7 +262,7 @@ const makeCheckpointStore = Effect.gen(function* () { yield* Effect.forEach( input.checkpointRefs, (checkpointRef) => - git.execute({ + vcs.execute({ operation, cwd: input.cwd, args: ["update-ref", "-d", checkpointRef], diff --git a/apps/server/src/git/Layers/GitCore.test.ts b/apps/server/src/git/Layers/GitCore.test.ts index 665c4b138f..2f2c8bd130 100644 --- a/apps/server/src/git/Layers/GitCore.test.ts +++ b/apps/server/src/git/Layers/GitCore.test.ts @@ -173,13 +173,6 @@ function buildLargeText(lineCount = 20_000): string { .concat("\n"); } -function splitNullSeparatedPaths(input: string): string[] { - return input - .split("\0") - .map((value) => value.trim()) - .filter((value) => value.length > 0); -} - // ── Tests ── it.layer(TestLayer)("git integration", (it) => { @@ -223,87 +216,6 @@ it.layer(TestLayer)("git integration", (it) => { ); }); - describe("workspace helpers", () => { - it.effect("filterIgnoredPaths chunks large path lists and preserves kept paths", () => - Effect.gen(function* () { - const cwd = "/virtual/repo"; - const relativePaths = Array.from({ length: 340 }, (_, index) => { - const prefix = index % 3 === 0 ? "ignored" : "kept"; - return `${prefix}/segment-${String(index).padStart(4, "0")}/${"x".repeat(900)}.ts`; - }); - const expectedPaths = relativePaths.filter( - (relativePath) => !relativePath.startsWith("ignored/"), - ); - - const seenChunks: string[][] = []; - const core = yield* makeIsolatedGitCore((input) => { - if ( - input.args.join(" ") !== - "-c core.fsmonitor=false -c core.untrackedCache=false check-ignore --no-index -z --stdin" - ) { - return Effect.fail( - new GitCommandError({ - operation: input.operation, - command: `git ${input.args.join(" ")}`, - cwd: input.cwd, - detail: "unexpected git command in chunking test", - }), - ); - } - - const chunkPaths = splitNullSeparatedPaths(input.stdin ?? ""); - seenChunks.push(chunkPaths); - const ignoredPaths = chunkPaths.filter((relativePath) => - relativePath.startsWith("ignored/"), - ); - - return Effect.succeed({ - code: ignoredPaths.length > 0 ? 0 : 1, - stdout: ignoredPaths.length > 0 ? `${ignoredPaths.join("\0")}\0` : "", - stderr: "", - stdoutTruncated: false, - stderrTruncated: false, - }); - }); - - const result = yield* core.filterIgnoredPaths(cwd, relativePaths); - - expect(seenChunks.length).toBeGreaterThan(1); - expect(seenChunks.flat()).toEqual(relativePaths); - expect(result).toEqual(expectedPaths); - }), - ); - - it.effect("listWorkspaceFiles disables fsmonitor and untracked cache helpers", () => - Effect.gen(function* () { - const core = yield* makeIsolatedGitCore((input) => { - expect(input.args).toEqual([ - "-c", - "core.fsmonitor=false", - "-c", - "core.untrackedCache=false", - "ls-files", - "--cached", - "--others", - "--exclude-standard", - "-z", - ]); - return Effect.succeed({ - code: 0, - stdout: "src/index.ts\0README.md\0", - stderr: "", - stdoutTruncated: false, - stderrTruncated: false, - }); - }); - - const result = yield* core.listWorkspaceFiles("/virtual/repo"); - expect(result.paths).toEqual(["src/index.ts", "README.md"]); - expect(result.truncated).toBe(false); - }), - ); - }); - // ── listGitBranches ── describe("listGitBranches", () => { diff --git a/apps/server/src/git/Layers/GitCore.ts b/apps/server/src/git/Layers/GitCore.ts index 3e9df316f1..2fac4b9adf 100644 --- a/apps/server/src/git/Layers/GitCore.ts +++ b/apps/server/src/git/Layers/GitCore.ts @@ -46,14 +46,6 @@ const PREPARED_COMMIT_PATCH_MAX_OUTPUT_BYTES = 49_000; const RANGE_COMMIT_SUMMARY_MAX_OUTPUT_BYTES = 19_000; const RANGE_DIFF_SUMMARY_MAX_OUTPUT_BYTES = 19_000; const RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES = 59_000; -const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024; -const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024; -const WORKSPACE_GIT_HARDENED_CONFIG_ARGS = [ - "-c", - "core.fsmonitor=false", - "-c", - "core.untrackedCache=false", -] as const; const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15); const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5); const STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN = Duration.seconds(5); @@ -126,47 +118,6 @@ function parseNumstatEntries( return entries; } -function splitNullSeparatedPaths(input: string, truncated: boolean): string[] { - const parts = input.split("\0"); - if (parts.length === 0) return []; - - if (truncated && parts[parts.length - 1]?.length) { - parts.pop(); - } - - return parts.filter((value) => value.length > 0); -} - -function chunkPathsForGitCheckIgnore(relativePaths: readonly string[]): string[][] { - const chunks: string[][] = []; - let chunk: string[] = []; - let chunkBytes = 0; - - for (const relativePath of relativePaths) { - const relativePathBytes = Buffer.byteLength(relativePath) + 1; - if (chunk.length > 0 && chunkBytes + relativePathBytes > GIT_CHECK_IGNORE_MAX_STDIN_BYTES) { - chunks.push(chunk); - chunk = []; - chunkBytes = 0; - } - - chunk.push(relativePath); - chunkBytes += relativePathBytes; - - if (chunkBytes >= GIT_CHECK_IGNORE_MAX_STDIN_BYTES) { - chunks.push(chunk); - chunk = []; - chunkBytes = 0; - } - } - - if (chunk.length > 0) { - chunks.push(chunk); - } - - return chunks; -} - function parsePorcelainPath(line: string): string | null { if (line.startsWith("? ") || line.startsWith("! ")) { const simple = line.slice(2).trim(); @@ -1634,100 +1585,6 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)), ); - const isInsideWorkTree: GitCoreShape["isInsideWorkTree"] = (cwd) => - executeGit("GitCore.isInsideWorkTree", cwd, ["rev-parse", "--is-inside-work-tree"], { - allowNonZeroExit: true, - timeoutMs: 5_000, - maxOutputBytes: 4_096, - }).pipe(Effect.map((result) => result.code === 0 && result.stdout.trim() === "true")); - - const listWorkspaceFiles: GitCoreShape["listWorkspaceFiles"] = (cwd) => - executeGit( - "GitCore.listWorkspaceFiles", - cwd, - [ - ...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, - "ls-files", - "--cached", - "--others", - "--exclude-standard", - "-z", - ], - { - allowNonZeroExit: true, - timeoutMs: 20_000, - maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES, - truncateOutputAtMaxBytes: true, - }, - ).pipe( - Effect.flatMap((result) => - result.code === 0 - ? Effect.succeed({ - paths: splitNullSeparatedPaths(result.stdout, result.stdoutTruncated), - truncated: result.stdoutTruncated, - }) - : Effect.fail( - createGitCommandError( - "GitCore.listWorkspaceFiles", - cwd, - [ - ...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, - "ls-files", - "--cached", - "--others", - "--exclude-standard", - "-z", - ], - result.stderr.trim().length > 0 ? result.stderr.trim() : "git ls-files failed", - ), - ), - ), - ); - - const filterIgnoredPaths: GitCoreShape["filterIgnoredPaths"] = (cwd, relativePaths) => - Effect.gen(function* () { - if (relativePaths.length === 0) { - return relativePaths; - } - - const ignoredPaths = new Set(); - const chunks = chunkPathsForGitCheckIgnore(relativePaths); - - for (const chunk of chunks) { - const result = yield* executeGit( - "GitCore.filterIgnoredPaths", - cwd, - [...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, "check-ignore", "--no-index", "-z", "--stdin"], - { - stdin: `${chunk.join("\0")}\0`, - allowNonZeroExit: true, - timeoutMs: 20_000, - maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES, - truncateOutputAtMaxBytes: true, - }, - ); - - if (result.code !== 0 && result.code !== 1) { - return yield* createGitCommandError( - "GitCore.filterIgnoredPaths", - cwd, - [...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, "check-ignore", "--no-index", "-z", "--stdin"], - result.stderr.trim().length > 0 ? result.stderr.trim() : "git check-ignore failed", - ); - } - - for (const ignoredPath of splitNullSeparatedPaths(result.stdout, result.stdoutTruncated)) { - ignoredPaths.add(ignoredPath); - } - } - - if (ignoredPaths.size === 0) { - return relativePaths; - } - - return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath)); - }); - const listBranches: GitCoreShape["listBranches"] = Effect.fn("listBranches")(function* (input) { const branchRecencyPromise = readBranchRecency(input.cwd).pipe( Effect.catch(() => Effect.succeed(new Map())), @@ -2185,9 +2042,6 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { pullCurrentBranch, readRangeContext, readConfigValue, - isInsideWorkTree, - listWorkspaceFiles, - filterIgnoredPaths, listBranches, createWorktree, fetchPullRequestBranch, diff --git a/apps/server/src/git/Layers/GitManager.test.ts b/apps/server/src/git/Layers/GitManager.test.ts index b8eeb54189..b94a771dfb 100644 --- a/apps/server/src/git/Layers/GitManager.test.ts +++ b/apps/server/src/git/Layers/GitManager.test.ts @@ -21,8 +21,9 @@ import { GitHubCli, } from "../Services/GitHubCli.ts"; import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts"; -import { GitCoreLive } from "./GitCore.ts"; -import { GitCore } from "../Services/GitCore.ts"; +import { GitVcsDriverLive } from "../../vcs/Layers/GitVcsDriver.ts"; +import { VcsProcessLive } from "../../vcs/Layers/VcsProcess.ts"; +import { VcsDriver } from "../../vcs/Services/VcsDriver.ts"; import { makeGitManager } from "./GitManager.ts"; import { ServerConfig } from "../../config.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; @@ -211,16 +212,33 @@ function runGit( ): Effect.Effect< { readonly code: number; readonly stdout: string; readonly stderr: string }, GitCommandError, - GitCore + VcsDriver > { return Effect.gen(function* () { - const gitCore = yield* GitCore; - return yield* gitCore.execute({ - operation: "GitManager.test.runGit", - cwd, - args, - allowNonZeroExit, - }); + const vcs = yield* VcsDriver; + const result = yield* vcs + .execute({ + operation: "GitManager.test.runGit", + cwd, + args, + allowNonZeroExit, + }) + .pipe( + Effect.mapError( + (error) => + new GitCommandError({ + operation: "GitManager.test.runGit", + command: `git ${args.join(" ")}`, + cwd, + detail: error.message, + }), + ), + ); + return { + code: result.exitCode, + stdout: result.stdout, + stderr: result.stderr, + }; }); } @@ -229,7 +247,7 @@ function initRepo( ): Effect.Effect< void, PlatformError.PlatformError | GitCommandError, - FileSystem.FileSystem | Scope.Scope | GitCore + FileSystem.FileSystem | Scope.Scope | VcsDriver > { return Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -245,7 +263,7 @@ function initRepo( function createBareRemote(): Effect.Effect< string, PlatformError.PlatformError | GitCommandError, - FileSystem.FileSystem | Scope.Scope | GitCore + FileSystem.FileSystem | Scope.Scope | VcsDriver > { return Effect.gen(function* () { const remoteDir = yield* makeTempDir("t3code-git-remote-"); @@ -259,7 +277,7 @@ function configureRemote( remoteName: string, remotePath: string, fetchNamespace: string, -): Effect.Effect { +): Effect.Effect { return Effect.gen(function* () { yield* runGit(cwd, ["config", `remote.${remoteName}.url`, remotePath]); yield* runGit(cwd, [ @@ -639,7 +657,8 @@ function makeManager(input?: { const serverSettingsLayer = ServerSettingsService.layerTest(); - const gitCoreLayer = GitCoreLive.pipe( + const vcsDriverLayer = GitVcsDriverLive.pipe( + Layer.provideMerge(VcsProcessLive), Layer.provideMerge(NodeServices.layer), Layer.provideMerge(ServerConfigLayer), ); @@ -653,7 +672,7 @@ function makeManager(input?: { runForThread: () => Effect.succeed({ status: "no-script" as const }), }, ), - gitCoreLayer, + vcsDriverLayer, serverSettingsLayer, ).pipe(Layer.provideMerge(NodeServices.layer)); @@ -665,8 +684,9 @@ function makeManager(input?: { const asThreadId = (threadId: string) => threadId as ThreadId; -const GitManagerTestLayer = GitCoreLive.pipe( +const GitManagerTestLayer = GitVcsDriverLive.pipe( Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-git-manager-test-" })), + Layer.provideMerge(VcsProcessLive), Layer.provideMerge(NodeServices.layer), ); diff --git a/apps/server/src/git/Layers/GitManager.ts b/apps/server/src/git/Layers/GitManager.ts index 21f3411d1e..349a19a59e 100644 --- a/apps/server/src/git/Layers/GitManager.ts +++ b/apps/server/src/git/Layers/GitManager.ts @@ -38,7 +38,6 @@ import { type GitManagerShape, type GitRunStackedActionOptions, } from "../Services/GitManager.ts"; -import { GitCore } from "../Services/GitCore.ts"; import type { GitStatusDetails } from "../Services/GitCore.ts"; import { GitHubCli, type GitHubPullRequestSummary } from "../Services/GitHubCli.ts"; import { TextGeneration } from "../Services/TextGeneration.ts"; @@ -50,6 +49,7 @@ import { decodeGitHubPullRequestListJson, formatGitHubJsonDecodeError, } from "../githubPullRequests.ts"; +import { VcsDriver } from "../../vcs/Services/VcsDriver.ts"; const COMMIT_TIMEOUT_MS = 10 * 60_000; const MAX_PROGRESS_TEXT_LENGTH = 500; @@ -491,7 +491,7 @@ function toPullRequestHeadRemoteInfo(pr: { } export const makeGitManager = Effect.fn("makeGitManager")(function* () { - const gitCore = yield* GitCore; + const gitCore = yield* VcsDriver; const gitHubCli = yield* GitHubCli; const textGeneration = yield* TextGeneration; const projectSetupScriptRunner = yield* ProjectSetupScriptRunner; diff --git a/apps/server/src/git/Services/GitCore.ts b/apps/server/src/git/Services/GitCore.ts index 9f3bc0b9b9..232cbe29d7 100644 --- a/apps/server/src/git/Services/GitCore.ts +++ b/apps/server/src/git/Services/GitCore.ts @@ -98,11 +98,6 @@ export interface GitRangeContext { diffPatch: string; } -export interface GitListWorkspaceFilesResult { - readonly paths: ReadonlyArray; - readonly truncated: boolean; -} - export interface GitRenameBranchInput { cwd: string; oldBranch: string; @@ -205,26 +200,6 @@ export interface GitCoreShape { key: string, ) => Effect.Effect; - /** - * Determine whether the provided cwd is inside a git work tree. - */ - readonly isInsideWorkTree: (cwd: string) => Effect.Effect; - - /** - * List tracked and untracked workspace file paths relative to cwd. - */ - readonly listWorkspaceFiles: ( - cwd: string, - ) => Effect.Effect; - - /** - * Remove gitignored paths from a relative path list. - */ - readonly filterIgnoredPaths: ( - cwd: string, - relativePaths: ReadonlyArray, - ) => Effect.Effect, GitCommandError>; - /** * List local + remote branches and branch metadata. */ diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts index 5603ce6325..bc19e8c902 100644 --- a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts +++ b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts @@ -24,8 +24,9 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { CheckpointStoreLive } from "../../checkpointing/Layers/CheckpointStore.ts"; import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts"; -import { GitCoreLive } from "../../git/Layers/GitCore.ts"; import { GitStatusBroadcaster } from "../../git/Services/GitStatusBroadcaster.ts"; +import { GitVcsDriverLive } from "../../vcs/Layers/GitVcsDriver.ts"; +import { VcsProcessLive } from "../../vcs/Layers/VcsProcess.ts"; import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts"; import { CheckpointReactorLive } from "./CheckpointReactor.ts"; import { OrchestrationEngineLive } from "./OrchestrationEngine.ts"; @@ -306,10 +307,15 @@ describe("CheckpointReactor", () => { Layer.provideMerge(RuntimeReceiptBusLive), Layer.provideMerge(Layer.succeed(ProviderService, provider.service)), Layer.provideMerge(gitStatusBroadcasterLayer), - Layer.provideMerge(CheckpointStoreLive), - Layer.provideMerge(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))), + Layer.provideMerge(CheckpointStoreLive.pipe(Layer.provide(GitVcsDriverLive))), + Layer.provideMerge( + WorkspaceEntriesLive.pipe( + Layer.provide(WorkspacePathsLive), + Layer.provideMerge(GitVcsDriverLive), + ), + ), Layer.provideMerge(WorkspacePathsLive), - Layer.provideMerge(GitCoreLive), + Layer.provideMerge(VcsProcessLive), Layer.provideMerge(ServerConfigLayer), Layer.provideMerge(NodeServices.layer), ); diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index c44f291504..0d16d3ebdd 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -33,7 +33,6 @@ import { ProviderService, type ProviderServiceShape, } from "../../provider/Services/ProviderService.ts"; -import { GitCore, type GitCoreShape } from "../../git/Services/GitCore.ts"; import { GitStatusBroadcaster, type GitStatusBroadcasterShape, @@ -52,6 +51,7 @@ import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts"; import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { ServerSettingsService } from "../../serverSettings.ts"; +import { VcsDriver, type VcsDriverShape } from "../../vcs/Services/VcsDriver.ts"; const asProjectId = (value: string): ProjectId => ProjectId.make(value); const asApprovalRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.make(value); @@ -324,7 +324,7 @@ describe("ProviderCommandReactor", () => { const layer = ProviderCommandReactorLive.pipe( Layer.provideMerge(orchestrationLayer), Layer.provideMerge(Layer.succeed(ProviderService, service)), - Layer.provideMerge(Layer.succeed(GitCore, { renameBranch } as unknown as GitCoreShape)), + Layer.provideMerge(Layer.succeed(VcsDriver, { renameBranch } as unknown as VcsDriverShape)), Layer.provideMerge( Layer.succeed(GitStatusBroadcaster, { getStatus: () => Effect.die("getStatus should not be called in this test"), diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index 9a9f3d71b0..ea955553ed 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -16,7 +16,6 @@ import { Cache, Cause, Duration, Effect, Equal, Layer, Option, Schema, Stream } import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker"; import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts"; -import { GitCore } from "../../git/Services/GitCore.ts"; import { GitStatusBroadcaster } from "../../git/Services/GitStatusBroadcaster.ts"; import { increment, orchestrationEventsProcessedTotal } from "../../observability/Metrics.ts"; import { ProviderAdapterRequestError } from "../../provider/Errors.ts"; @@ -29,6 +28,7 @@ import { type ProviderCommandReactorShape, } from "../Services/ProviderCommandReactor.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; +import { VcsDriver } from "../../vcs/Services/VcsDriver.ts"; type ProviderIntentEvent = Extract< OrchestrationEvent, @@ -168,7 +168,7 @@ function buildGeneratedWorktreeBranchName(raw: string): string { const make = Effect.gen(function* () { const orchestrationEngine = yield* OrchestrationEngineService; const providerService = yield* ProviderService; - const git = yield* GitCore; + const git = yield* VcsDriver; const gitStatusBroadcaster = yield* GitStatusBroadcaster; const textGeneration = yield* TextGeneration; const serverSettingsService = yield* ServerSettingsService; diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts index e699ad8339..7d0066d4c6 100644 --- a/apps/server/src/server.test.ts +++ b/apps/server/src/server.test.ts @@ -58,7 +58,6 @@ import { CheckpointDiffQuery, type CheckpointDiffQueryShape, } from "./checkpointing/Services/CheckpointDiffQuery.ts"; -import { GitCore, type GitCoreShape } from "./git/Services/GitCore.ts"; import { GitManager, type GitManagerShape } from "./git/Services/GitManager.ts"; import { GitStatusBroadcasterLive } from "./git/Layers/GitStatusBroadcaster.ts"; import { @@ -105,6 +104,7 @@ import { import { WorkspaceEntriesLive } from "./workspace/Layers/WorkspaceEntries.ts"; import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem.ts"; import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts"; +import { VcsDriver, type VcsDriverShape } from "./vcs/Services/VcsDriver.ts"; import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts"; import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts"; @@ -195,16 +195,6 @@ const makeDefaultOrchestrationThreadShell = ( }; }; -const workspaceAndProjectServicesLayer = Layer.mergeAll( - WorkspacePathsLive, - WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive)), - WorkspaceFileSystemLive.pipe( - Layer.provide(WorkspacePathsLive), - Layer.provide(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))), - ), - ProjectFaviconResolverLive, -); - const browserOtlpTracingLayer = Layer.mergeAll( FetchHttpClient.layer, OtlpSerialization.layerJson, @@ -324,7 +314,7 @@ const buildAppUnderTest = (options?: { providerRegistry?: Partial; serverSettings?: Partial; open?: Partial; - gitCore?: Partial; + vcsDriver?: Partial; gitManager?: Partial; gitStatusBroadcaster?: Partial; projectSetupScriptRunner?: Partial; @@ -372,22 +362,34 @@ const buildAppUnderTest = (options?: { ...options?.config, }; const layerConfig = Layer.succeed(ServerConfig, config); - const gitCoreLayer = Layer.mock(GitCore)({ + const vcsDriverLayer = Layer.mock(VcsDriver)({ + capabilities: { + kind: "git", + supportsWorktrees: true, + supportsBookmarks: false, + supportsAtomicSnapshot: false, + supportsPushDefaultRemote: true, + }, + detectRepository: () => Effect.succeed(null), isInsideWorkTree: () => Effect.succeed(false), listWorkspaceFiles: () => Effect.succeed({ paths: [], truncated: false, + freshness: { + source: "live-local", + observedAt: new Date(0).toISOString(), + }, }), filterIgnoredPaths: (_cwd, relativePaths) => Effect.succeed(relativePaths), - ...options?.layers?.gitCore, + ...options?.layers?.vcsDriver, }); const gitManagerLayer = Layer.mock(GitManager)({ ...options?.layers?.gitManager, }); const workspaceEntriesLayer = WorkspaceEntriesLive.pipe( Layer.provide(WorkspacePathsLive), - Layer.provideMerge(gitCoreLayer), + Layer.provideMerge(vcsDriverLayer), ); const workspaceAndProjectServicesLayer = Layer.mergeAll( WorkspacePathsLive, @@ -441,7 +443,6 @@ const buildAppUnderTest = (options?: { ...options?.layers?.open, }), ), - Layer.provide(gitCoreLayer), Layer.provide(gitManagerLayer), Layer.provideMerge(gitStatusBroadcasterLayer), Layer.provide( @@ -2068,12 +2069,16 @@ it.layer(NodeServices.layer)("server router seam", (it) => { yield* buildAppUnderTest({ layers: { - gitCore: { + vcsDriver: { isInsideWorkTree: () => Effect.succeed(true), listWorkspaceFiles: () => Effect.succeed({ paths: ["src/tracked.ts"], truncated: false, + freshness: { + source: "live-local", + observedAt: new Date(0).toISOString(), + }, }), filterIgnoredPaths: (_cwd, relativePaths) => Effect.succeed( @@ -2372,7 +2377,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { worktreePath: null, }), }, - gitCore: { + vcsDriver: { pullCurrentBranch: () => Effect.succeed({ status: "pulled", @@ -2526,7 +2531,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { let statusCalls = 0; yield* buildAppUnderTest({ layers: { - gitCore: { + vcsDriver: { pullCurrentBranch: () => Effect.fail(gitError), }, gitManager: { @@ -2680,7 +2685,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { Effect.gen(function* () { yield* buildAppUnderTest({ layers: { - gitCore: { + vcsDriver: { pullCurrentBranch: () => Effect.succeed({ status: "pulled" as const, @@ -3494,7 +3499,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { pr: null, }), ); - const createWorktree = vi.fn((_: Parameters[0]) => + const createWorktree = vi.fn((_: Parameters[0]) => Effect.succeed({ worktree: { branch: "t3code/bootstrap-branch", @@ -3515,7 +3520,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { yield* buildAppUnderTest({ layers: { - gitCore: { + vcsDriver: { createWorktree, }, gitStatusBroadcaster: { @@ -3619,7 +3624,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { it.effect("records setup-script failures without aborting bootstrap turn start", () => Effect.gen(function* () { const dispatchedCommands: Array = []; - const createWorktree = vi.fn((_: Parameters[0]) => + const createWorktree = vi.fn((_: Parameters[0]) => Effect.succeed({ worktree: { branch: "t3code/bootstrap-branch", @@ -3634,7 +3639,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { yield* buildAppUnderTest({ layers: { - gitCore: { + vcsDriver: { createWorktree, }, orchestrationEngine: { @@ -3712,7 +3717,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { it.effect("does not misattribute setup activity dispatch failures as setup launch failures", () => Effect.gen(function* () { const dispatchedCommands: Array = []; - const createWorktree = vi.fn((_: Parameters[0]) => + const createWorktree = vi.fn((_: Parameters[0]) => Effect.succeed({ worktree: { branch: "t3code/bootstrap-branch", @@ -3734,7 +3739,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { yield* buildAppUnderTest({ layers: { - gitCore: { + vcsDriver: { createWorktree, }, orchestrationEngine: { @@ -3830,13 +3835,13 @@ it.layer(NodeServices.layer)("server router seam", (it) => { it.effect("cleans up created bootstrap threads when worktree creation defects", () => Effect.gen(function* () { const dispatchedCommands: Array = []; - const createWorktree = vi.fn((_: Parameters[0]) => + const createWorktree = vi.fn((_: Parameters[0]) => Effect.die(new Error("worktree exploded")), ); yield* buildAppUnderTest({ layers: { - gitCore: { + vcsDriver: { createWorktree, }, orchestrationEngine: { diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 85f2d84ad2..66bbd68acc 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -25,7 +25,6 @@ import { ProviderSessionReaperLive } from "./provider/Layers/ProviderSessionReap import { OpenCodeRuntimeLive } from "./provider/opencodeRuntime.ts"; import { CheckpointDiffQueryLive } from "./checkpointing/Layers/CheckpointDiffQuery.ts"; import { CheckpointStoreLive } from "./checkpointing/Layers/CheckpointStore.ts"; -import { GitCoreLive } from "./git/Layers/GitCore.ts"; import { GitHubCliLive } from "./git/Layers/GitHubCli.ts"; import { GitStatusBroadcasterLive } from "./git/Layers/GitStatusBroadcaster.ts"; import { TextGenerationLive } from "./git/Layers/TextGenerationLive.ts"; @@ -47,6 +46,8 @@ import { RepositoryIdentityResolverLive } from "./project/Layers/RepositoryIdent import { WorkspaceEntriesLive } from "./workspace/Layers/WorkspaceEntries.ts"; import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem.ts"; import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts"; +import { GitVcsDriverLive } from "./vcs/Layers/GitVcsDriver.ts"; +import { VcsProcessLive } from "./vcs/Layers/VcsProcess.ts"; import { ProjectSetupScriptRunnerLive } from "./project/Layers/ProjectSetupScriptRunner.ts"; import { ObservabilityLive } from "./observability/Layers/Observability.ts"; import { ServerEnvironmentLive } from "./environment/Layers/ServerEnvironment.ts"; @@ -135,7 +136,7 @@ const ReactorLayerLive = Layer.empty.pipe( const CheckpointingLayerLive = Layer.empty.pipe( Layer.provideMerge(CheckpointDiffQueryLive), - Layer.provideMerge(CheckpointStoreLive), + Layer.provideMerge(CheckpointStoreLive.pipe(Layer.provide(GitVcsDriverLive))), ); const ProviderSessionDirectoryLayerLive = ProviderSessionDirectoryLive.pipe( @@ -157,7 +158,7 @@ const PersistenceLayerLive = Layer.empty.pipe(Layer.provideMerge(SqlitePersisten const GitManagerLayerLive = GitManagerLive.pipe( Layer.provideMerge(ProjectSetupScriptRunnerLive), - Layer.provideMerge(GitCoreLive), + Layer.provideMerge(GitVcsDriverLive), Layer.provideMerge(GitHubCliLive), Layer.provideMerge(TextGenerationLive), ); @@ -165,14 +166,14 @@ const GitManagerLayerLive = GitManagerLive.pipe( const GitLayerLive = Layer.empty.pipe( Layer.provideMerge(GitManagerLayerLive), Layer.provideMerge(GitStatusBroadcasterLive.pipe(Layer.provide(GitManagerLayerLive))), - Layer.provideMerge(GitCoreLive), + Layer.provideMerge(GitVcsDriverLive), ); const TerminalLayerLive = TerminalManagerLive.pipe(Layer.provide(PtyAdapterLive)); const WorkspaceEntriesLayerLive = WorkspaceEntriesLive.pipe( Layer.provide(WorkspacePathsLive), - Layer.provideMerge(GitCoreLive), + Layer.provideMerge(GitVcsDriverLive), ); const WorkspaceFileSystemLayerLive = WorkspaceFileSystemLive.pipe( @@ -310,6 +311,7 @@ export const makeServerLayer = Layer.unwrap( Layer.provideMerge(HttpServerLive), Layer.provide(ObservabilityLive), Layer.provideMerge(FetchHttpClient.layer), + Layer.provideMerge(VcsProcessLive), Layer.provideMerge(PlatformServicesLive), ); }), diff --git a/apps/server/src/vcs/Layers/GitVcsDriver.test.ts b/apps/server/src/vcs/Layers/GitVcsDriver.test.ts new file mode 100644 index 0000000000..454ba6bd0a --- /dev/null +++ b/apps/server/src/vcs/Layers/GitVcsDriver.test.ts @@ -0,0 +1,125 @@ +import { it } from "@effect/vitest"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { Effect, Layer } from "effect"; +import { describe, expect } from "vitest"; + +import { ServerConfig } from "../../config.ts"; +import { VcsProcess } from "../Services/VcsProcess.ts"; +import { VcsDriver } from "../Services/VcsDriver.ts"; +import { GitVcsDriverLive } from "./GitVcsDriver.ts"; + +const splitNullSeparatedPaths = (input: string): string[] => + input + .split("\0") + .map((value) => value.trim()) + .filter((value) => value.length > 0); + +const GitVcsDriverTestDependencies = ServerConfig.layerTest(process.cwd(), { + prefix: "t3-git-vcs-driver-test-", +}).pipe(Layer.provide(NodeServices.layer)); + +it.layer(Layer.empty)("GitVcsDriverLive", (it) => { + describe("workspace helpers", () => { + it.effect("filterIgnoredPaths chunks large path lists and preserves kept paths", () => + Effect.gen(function* () { + const cwd = "/virtual/repo"; + const relativePaths = Array.from({ length: 340 }, (_, index) => { + const prefix = index % 3 === 0 ? "ignored" : "kept"; + return `${prefix}/segment-${String(index).padStart(4, "0")}/${"x".repeat(900)}.ts`; + }); + const expectedPaths = relativePaths.filter( + (relativePath) => !relativePath.startsWith("ignored/"), + ); + + const seenChunks: string[][] = []; + const layer = GitVcsDriverLive.pipe( + Layer.provideMerge(GitVcsDriverTestDependencies), + Layer.provideMerge(NodeServices.layer), + Layer.provide( + Layer.succeed(VcsProcess, { + run: (input) => { + expect(input.command).toBe("git"); + expect(input.args).toEqual([ + "-c", + "core.fsmonitor=false", + "-c", + "core.untrackedCache=false", + "check-ignore", + "--no-index", + "-z", + "--stdin", + ]); + + const chunkPaths = splitNullSeparatedPaths(input.stdin ?? ""); + seenChunks.push(chunkPaths); + const ignoredPaths = chunkPaths.filter((relativePath) => + relativePath.startsWith("ignored/"), + ); + + return Effect.succeed({ + exitCode: ignoredPaths.length > 0 ? 0 : 1, + stdout: ignoredPaths.length > 0 ? `${ignoredPaths.join("\0")}\0` : "", + stderr: "", + stdoutTruncated: false, + stderrTruncated: false, + }); + }, + }), + ), + ); + + const result = yield* Effect.gen(function* () { + const vcs = yield* VcsDriver; + return yield* vcs.filterIgnoredPaths(cwd, relativePaths); + }).pipe(Effect.provide(layer)); + + expect(seenChunks.length).toBeGreaterThan(1); + expect(seenChunks.flat()).toEqual(relativePaths); + expect(result).toEqual(expectedPaths); + }), + ); + + it.effect("listWorkspaceFiles disables fsmonitor and untracked cache helpers", () => + Effect.gen(function* () { + const layer = GitVcsDriverLive.pipe( + Layer.provideMerge(GitVcsDriverTestDependencies), + Layer.provideMerge(NodeServices.layer), + Layer.provide( + Layer.succeed(VcsProcess, { + run: (input) => { + expect(input.command).toBe("git"); + expect(input.args).toEqual([ + "-c", + "core.fsmonitor=false", + "-c", + "core.untrackedCache=false", + "ls-files", + "--cached", + "--others", + "--exclude-standard", + "-z", + ]); + return Effect.succeed({ + exitCode: 0, + stdout: "src/index.ts\0README.md\0", + stderr: "", + stdoutTruncated: false, + stderrTruncated: false, + }); + }, + }), + ), + ); + + const result = yield* Effect.gen(function* () { + const vcs = yield* VcsDriver; + return yield* vcs.listWorkspaceFiles("/virtual/repo"); + }).pipe(Effect.provide(layer)); + + expect(result.paths).toEqual(["src/index.ts", "README.md"]); + expect(result.truncated).toBe(false); + expect(result.freshness.source).toBe("live-local"); + }), + ); + }); +}); diff --git a/apps/server/src/vcs/Layers/GitVcsDriver.ts b/apps/server/src/vcs/Layers/GitVcsDriver.ts new file mode 100644 index 0000000000..be547a4c45 --- /dev/null +++ b/apps/server/src/vcs/Layers/GitVcsDriver.ts @@ -0,0 +1,252 @@ +import { Effect, Layer } from "effect"; + +import { VcsProcessExitError } from "@t3tools/contracts"; +import { makeGitCore } from "../../git/Layers/GitCore.ts"; +import { VcsDriver, type VcsDriverShape } from "../Services/VcsDriver.ts"; +import { VcsProcess, type VcsProcessShape } from "../Services/VcsProcess.ts"; + +const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024; +const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024; +const WORKSPACE_GIT_HARDENED_CONFIG_ARGS = [ + "-c", + "core.fsmonitor=false", + "-c", + "core.untrackedCache=false", +] as const; + +function nowFreshness() { + return { + source: "live-local" as const, + observedAt: new Date().toISOString(), + }; +} + +function splitNullSeparatedPaths(input: string, truncated: boolean): string[] { + const parts = input.split("\0"); + if (parts.length === 0) return []; + + if (truncated && parts[parts.length - 1]?.length) { + parts.pop(); + } + + return parts.filter((value) => value.length > 0); +} + +function chunkPathsForGitCheckIgnore(relativePaths: ReadonlyArray): string[][] { + const chunks: string[][] = []; + let chunk: string[] = []; + let chunkBytes = 0; + + for (const relativePath of relativePaths) { + const relativePathBytes = Buffer.byteLength(relativePath) + 1; + if (chunk.length > 0 && chunkBytes + relativePathBytes > GIT_CHECK_IGNORE_MAX_STDIN_BYTES) { + chunks.push(chunk); + chunk = []; + chunkBytes = 0; + } + + chunk.push(relativePath); + chunkBytes += relativePathBytes; + + if (chunkBytes >= GIT_CHECK_IGNORE_MAX_STDIN_BYTES) { + chunks.push(chunk); + chunk = []; + chunkBytes = 0; + } + } + + if (chunk.length > 0) { + chunks.push(chunk); + } + + return chunks; +} + +const gitCommand = ( + process: VcsProcessShape, + operation: string, + cwd: string, + args: ReadonlyArray, + options?: { + readonly stdin?: string; + readonly allowNonZeroExit?: boolean; + readonly timeoutMs?: number; + readonly maxOutputBytes?: number; + readonly truncateOutputAtMaxBytes?: boolean; + }, +) => + process.run({ + operation, + command: "git", + args, + cwd, + ...(options?.stdin !== undefined ? { stdin: options.stdin } : {}), + ...(options?.allowNonZeroExit !== undefined + ? { allowNonZeroExit: options.allowNonZeroExit } + : {}), + ...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}), + ...(options?.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}), + ...(options?.truncateOutputAtMaxBytes !== undefined + ? { truncateOutputAtMaxBytes: options.truncateOutputAtMaxBytes } + : {}), + }); + +export const makeGitVcsDriver = Effect.fn("makeGitVcsDriver")(function* () { + const process = yield* VcsProcess; + const legacyGit = yield* makeGitCore(); + const capabilities = { + kind: "git" as const, + supportsWorktrees: true, + supportsBookmarks: false, + supportsAtomicSnapshot: false, + supportsPushDefaultRemote: true, + }; + + const isInsideWorkTree: VcsDriverShape["isInsideWorkTree"] = (cwd) => + gitCommand( + process, + "GitVcsDriver.isInsideWorkTree", + cwd, + ["rev-parse", "--is-inside-work-tree"], + { + allowNonZeroExit: true, + timeoutMs: 5_000, + maxOutputBytes: 4_096, + }, + ).pipe(Effect.map((result) => result.exitCode === 0 && result.stdout.trim() === "true")); + + const execute: VcsDriverShape["execute"] = (input) => + gitCommand(process, input.operation, input.cwd, input.args, { + ...(input.stdin !== undefined ? { stdin: input.stdin } : {}), + ...(input.allowNonZeroExit !== undefined ? { allowNonZeroExit: input.allowNonZeroExit } : {}), + ...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}), + ...(input.maxOutputBytes !== undefined ? { maxOutputBytes: input.maxOutputBytes } : {}), + ...(input.truncateOutputAtMaxBytes !== undefined + ? { truncateOutputAtMaxBytes: input.truncateOutputAtMaxBytes } + : {}), + }); + + const detectRepository: VcsDriverShape["detectRepository"] = Effect.fn("detectRepository")( + function* (cwd) { + if (!(yield* isInsideWorkTree(cwd))) { + return null; + } + + const root = yield* gitCommand(process, "GitVcsDriver.detectRepository.root", cwd, [ + "rev-parse", + "--show-toplevel", + ]); + const gitCommonDir = yield* gitCommand( + process, + "GitVcsDriver.detectRepository.commonDir", + cwd, + ["rev-parse", "--git-common-dir"], + ).pipe(Effect.catch(() => Effect.succeed(null))); + + return { + kind: "git" as const, + rootPath: root.stdout.trim(), + metadataPath: gitCommonDir?.stdout.trim() || null, + freshness: nowFreshness(), + }; + }, + ); + + const listWorkspaceFiles: VcsDriverShape["listWorkspaceFiles"] = (cwd) => + gitCommand( + process, + "GitVcsDriver.listWorkspaceFiles", + cwd, + [ + ...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, + "ls-files", + "--cached", + "--others", + "--exclude-standard", + "-z", + ], + { + allowNonZeroExit: true, + timeoutMs: 20_000, + maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES, + truncateOutputAtMaxBytes: true, + }, + ).pipe( + Effect.flatMap((result) => + result.exitCode === 0 + ? Effect.succeed({ + paths: splitNullSeparatedPaths(result.stdout, result.stdoutTruncated), + truncated: result.stdoutTruncated, + freshness: nowFreshness(), + }) + : Effect.fail( + new VcsProcessExitError({ + operation: "GitVcsDriver.listWorkspaceFiles", + command: "git ls-files", + cwd, + exitCode: result.exitCode, + detail: result.stderr.trim() || "git ls-files failed", + }), + ), + ), + ); + + const filterIgnoredPaths: VcsDriverShape["filterIgnoredPaths"] = Effect.fn("filterIgnoredPaths")( + function* (cwd, relativePaths) { + if (relativePaths.length === 0) { + return relativePaths; + } + + const ignoredPaths = new Set(); + const chunks = chunkPathsForGitCheckIgnore(relativePaths); + + for (const chunk of chunks) { + const result = yield* gitCommand( + process, + "GitVcsDriver.filterIgnoredPaths", + cwd, + [...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, "check-ignore", "--no-index", "-z", "--stdin"], + { + stdin: `${chunk.join("\0")}\0`, + allowNonZeroExit: true, + timeoutMs: 20_000, + maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES, + truncateOutputAtMaxBytes: true, + }, + ); + + if (result.exitCode !== 0 && result.exitCode !== 1) { + return yield* new VcsProcessExitError({ + operation: "GitVcsDriver.filterIgnoredPaths", + command: "git check-ignore", + cwd, + exitCode: result.exitCode, + detail: result.stderr.trim() || "git check-ignore failed", + }); + } + + for (const ignoredPath of splitNullSeparatedPaths(result.stdout, result.stdoutTruncated)) { + ignoredPaths.add(ignoredPath); + } + } + + if (ignoredPaths.size === 0) { + return relativePaths; + } + + return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath)); + }, + ); + + return VcsDriver.of({ + ...legacyGit, + capabilities, + execute, + detectRepository, + isInsideWorkTree, + listWorkspaceFiles, + filterIgnoredPaths, + }); +}); + +export const GitVcsDriverLive = Layer.effect(VcsDriver, makeGitVcsDriver()); diff --git a/apps/server/src/vcs/Layers/VcsProcess.ts b/apps/server/src/vcs/Layers/VcsProcess.ts new file mode 100644 index 0000000000..c406f0bdca --- /dev/null +++ b/apps/server/src/vcs/Layers/VcsProcess.ts @@ -0,0 +1,194 @@ +import { Duration, Effect, Layer, Option, PlatformError, Stream } from "effect"; +import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; + +import { + VcsOutputDecodeError, + VcsProcessExitError, + VcsProcessSpawnError, + VcsProcessTimeoutError, +} from "@t3tools/contracts"; +import { VcsProcess, type VcsProcessInput, type VcsProcessOutput } from "../Services/VcsProcess.ts"; + +const DEFAULT_TIMEOUT_MS = 30_000; +const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000; +const OUTPUT_TRUNCATED_MARKER = "\n\n[truncated]"; + +function commandLabel(command: string, args: ReadonlyArray): string { + return [command, ...args].join(" "); +} + +const collectOutput = Effect.fn("VcsProcess.collectOutput")(function* ( + input: VcsProcessInput, + stream: Stream.Stream, + maxOutputBytes: number, + truncateOutputAtMaxBytes: boolean, +) { + const decoder = new TextDecoder(); + let text = ""; + let bytes = 0; + let truncated = false; + + yield* Stream.runForEach(stream, (chunk) => + Effect.sync(() => { + if (truncated) return; + + const remainingBytes = maxOutputBytes - bytes; + if (remainingBytes <= 0) { + truncated = true; + if (truncateOutputAtMaxBytes) { + text += OUTPUT_TRUNCATED_MARKER; + return; + } + return; + } + + const nextChunk = chunk.byteLength > remainingBytes ? chunk.slice(0, remainingBytes) : chunk; + text += decoder.decode(nextChunk, { stream: true }); + bytes += nextChunk.byteLength; + + if (chunk.byteLength > remainingBytes) { + truncated = true; + if (truncateOutputAtMaxBytes) { + text += OUTPUT_TRUNCATED_MARKER; + } + } + }), + ).pipe( + Effect.mapError( + (cause) => + new VcsOutputDecodeError({ + operation: input.operation, + command: commandLabel(input.command, input.args), + cwd: input.cwd, + detail: "failed to collect process output", + cause, + }), + ), + ); + + if (!truncated) { + text += decoder.decode(); + } + + return { text, truncated }; +}); + +export const makeVcsProcess = Effect.fn("makeVcsProcess")(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + + const run = Effect.fn("VcsProcess.run")(function* (input: VcsProcessInput) { + const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS; + const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES; + const label = commandLabel(input.command, input.args); + + const runProcess = Effect.gen(function* () { + const child = yield* spawner + .spawn( + ChildProcess.make(input.command, [...input.args], { + cwd: input.cwd, + env: { + ...process.env, + ...input.env, + }, + }), + ) + .pipe( + Effect.mapError( + (cause) => + new VcsProcessSpawnError({ + operation: input.operation, + command: label, + cwd: input.cwd, + cause, + }), + ), + ); + + const [stdout, stderr, exitCode] = yield* Effect.all( + [ + collectOutput( + input, + child.stdout, + maxOutputBytes, + input.truncateOutputAtMaxBytes ?? false, + ), + collectOutput( + input, + child.stderr, + maxOutputBytes, + input.truncateOutputAtMaxBytes ?? false, + ), + child.exitCode.pipe( + Effect.map((value) => Number(value)), + Effect.mapError( + (cause) => + new VcsOutputDecodeError({ + operation: input.operation, + command: label, + cwd: input.cwd, + detail: "failed to read process exit code", + cause, + }), + ), + ), + input.stdin === undefined + ? Effect.void + : Stream.run(Stream.encodeText(Stream.make(input.stdin)), child.stdin).pipe( + Effect.mapError( + (cause) => + new VcsOutputDecodeError({ + operation: input.operation, + command: label, + cwd: input.cwd, + detail: "failed to write process stdin", + cause, + }), + ), + ), + ], + { concurrency: "unbounded" }, + ).pipe(Effect.map(([stdout, stderr, exitCode]) => [stdout, stderr, exitCode] as const)); + + if (!input.allowNonZeroExit && exitCode !== 0) { + return yield* new VcsProcessExitError({ + operation: input.operation, + command: label, + cwd: input.cwd, + exitCode, + detail: stderr.text.trim() || `${label} exited with code ${exitCode}.`, + }); + } + + return { + exitCode, + stdout: stdout.text, + stderr: stderr.text, + stdoutTruncated: stdout.truncated, + stderrTruncated: stderr.truncated, + } satisfies VcsProcessOutput; + }); + + return yield* runProcess.pipe( + Effect.scoped, + Effect.timeoutOption(Duration.millis(timeoutMs)), + Effect.flatMap((result) => + Option.match(result, { + onSome: Effect.succeed, + onNone: () => + Effect.fail( + new VcsProcessTimeoutError({ + operation: input.operation, + command: label, + cwd: input.cwd, + timeoutMs, + }), + ), + }), + ), + ); + }); + + return VcsProcess.of({ run }); +}); + +export const VcsProcessLive = Layer.effect(VcsProcess, makeVcsProcess()); diff --git a/apps/server/src/vcs/Services/VcsDriver.ts b/apps/server/src/vcs/Services/VcsDriver.ts new file mode 100644 index 0000000000..1cc7c3f804 --- /dev/null +++ b/apps/server/src/vcs/Services/VcsDriver.ts @@ -0,0 +1,30 @@ +import { Context, type Effect } from "effect"; + +import type { + VcsDriverCapabilities, + VcsError, + VcsListWorkspaceFilesResult, + VcsRepositoryIdentity, +} from "@t3tools/contracts"; +import type { GitCoreShape } from "../../git/Services/GitCore.ts"; +import type { VcsProcessInput, VcsProcessOutput } from "./VcsProcess.ts"; + +export interface VcsDriverShape extends Omit { + readonly capabilities: VcsDriverCapabilities; + readonly execute: ( + input: Omit, + ) => Effect.Effect; + readonly detectRepository: (cwd: string) => Effect.Effect; + readonly isInsideWorkTree: (cwd: string) => Effect.Effect; + readonly listWorkspaceFiles: ( + cwd: string, + ) => Effect.Effect; + readonly filterIgnoredPaths: ( + cwd: string, + relativePaths: ReadonlyArray, + ) => Effect.Effect, VcsError>; +} + +export class VcsDriver extends Context.Service()( + "t3/vcs/Services/VcsDriver", +) {} diff --git a/apps/server/src/vcs/Services/VcsProcess.ts b/apps/server/src/vcs/Services/VcsProcess.ts new file mode 100644 index 0000000000..ff29f19784 --- /dev/null +++ b/apps/server/src/vcs/Services/VcsProcess.ts @@ -0,0 +1,32 @@ +import { Context, type Effect } from "effect"; + +import type { VcsError } from "@t3tools/contracts"; + +export interface VcsProcessInput { + readonly operation: string; + readonly command: string; + readonly args: ReadonlyArray; + readonly cwd: string; + readonly stdin?: string; + readonly env?: NodeJS.ProcessEnv; + readonly allowNonZeroExit?: boolean; + readonly timeoutMs?: number; + readonly maxOutputBytes?: number; + readonly truncateOutputAtMaxBytes?: boolean; +} + +export interface VcsProcessOutput { + readonly exitCode: number; + readonly stdout: string; + readonly stderr: string; + readonly stdoutTruncated: boolean; + readonly stderrTruncated: boolean; +} + +export interface VcsProcessShape { + readonly run: (input: VcsProcessInput) => Effect.Effect; +} + +export class VcsProcess extends Context.Service()( + "t3/vcs/Services/VcsProcess", +) {} diff --git a/apps/server/src/workspace/Layers/WorkspaceEntries.test.ts b/apps/server/src/workspace/Layers/WorkspaceEntries.test.ts index 85b43ab37f..61f2b9240c 100644 --- a/apps/server/src/workspace/Layers/WorkspaceEntries.test.ts +++ b/apps/server/src/workspace/Layers/WorkspaceEntries.test.ts @@ -5,8 +5,9 @@ import { it, afterEach, describe, expect, vi } from "@effect/vitest"; import { Effect, FileSystem, Layer, Path, PlatformError } from "effect"; import { ServerConfig } from "../../config.ts"; -import { GitCoreLive } from "../../git/Layers/GitCore.ts"; -import { GitCore } from "../../git/Services/GitCore.ts"; +import { GitVcsDriverLive } from "../../vcs/Layers/GitVcsDriver.ts"; +import { VcsProcessLive } from "../../vcs/Layers/VcsProcess.ts"; +import { VcsProcess } from "../../vcs/Services/VcsProcess.ts"; import { WorkspaceEntries } from "../Services/WorkspaceEntries.ts"; import { WorkspaceEntriesLive } from "./WorkspaceEntries.ts"; import { WorkspacePathsLive } from "./WorkspacePaths.ts"; @@ -14,7 +15,8 @@ import { WorkspacePathsLive } from "./WorkspacePaths.ts"; const TestLayer = Layer.empty.pipe( Layer.provideMerge(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))), Layer.provideMerge(WorkspacePathsLive), - Layer.provideMerge(GitCoreLive), + Layer.provideMerge(VcsProcessLive), + Layer.provideMerge(GitVcsDriverLive.pipe(Layer.provide(VcsProcessLive))), Layer.provide( ServerConfig.layerTest(process.cwd(), { prefix: "t3-workspace-entries-test-", @@ -25,12 +27,11 @@ const TestLayer = Layer.empty.pipe( const makeTempDir = Effect.fn(function* (opts?: { prefix?: string; git?: boolean }) { const fileSystem = yield* FileSystem.FileSystem; - const gitCore = yield* GitCore; const dir = yield* fileSystem.makeTempDirectoryScoped({ prefix: opts?.prefix ?? "t3code-workspace-entries-", }); if (opts?.git) { - yield* gitCore.initRepo({ cwd: dir }); + yield* git(dir, ["init"]); } return dir; }); @@ -51,9 +52,10 @@ function writeTextFile( const git = (cwd: string, args: ReadonlyArray, env?: NodeJS.ProcessEnv) => Effect.gen(function* () { - const gitCore = yield* GitCore; - const result = yield* gitCore.execute({ + const process = yield* VcsProcess; + const result = yield* process.run({ operation: "WorkspaceEntries.test.git", + command: "git", cwd, args, ...(env ? { env } : {}), diff --git a/apps/server/src/workspace/Layers/WorkspaceEntries.ts b/apps/server/src/workspace/Layers/WorkspaceEntries.ts index 7cb16b652b..7bb143347f 100644 --- a/apps/server/src/workspace/Layers/WorkspaceEntries.ts +++ b/apps/server/src/workspace/Layers/WorkspaceEntries.ts @@ -13,7 +13,7 @@ import { type RankedSearchResult, } from "@t3tools/shared/searchRanking"; -import { GitCore } from "../../git/Services/GitCore.ts"; +import { VcsDriver } from "../../vcs/Services/VcsDriver.ts"; import { WorkspaceEntries, WorkspaceEntriesBrowseError, @@ -174,38 +174,38 @@ const resolveBrowseTarget = ( export const makeWorkspaceEntries = Effect.gen(function* () { const path = yield* Path.Path; - const gitOption = yield* Effect.serviceOption(GitCore); + const vcsOption = yield* Effect.serviceOption(VcsDriver); const workspacePaths = yield* WorkspacePaths; - const isInsideGitWorkTree = (cwd: string): Effect.Effect => - Option.match(gitOption, { - onSome: (git) => git.isInsideWorkTree(cwd).pipe(Effect.catch(() => Effect.succeed(false))), + const isInsideVcsWorkTree = (cwd: string): Effect.Effect => + Option.match(vcsOption, { + onSome: (vcs) => vcs.isInsideWorkTree(cwd).pipe(Effect.catch(() => Effect.succeed(false))), onNone: () => Effect.succeed(false), }); - const filterGitIgnoredPaths = ( + const filterVcsIgnoredPaths = ( cwd: string, relativePaths: string[], ): Effect.Effect => - Option.match(gitOption, { - onSome: (git) => - git.filterIgnoredPaths(cwd, relativePaths).pipe( + Option.match(vcsOption, { + onSome: (vcs) => + vcs.filterIgnoredPaths(cwd, relativePaths).pipe( Effect.map((paths) => [...paths]), Effect.catch(() => Effect.succeed(relativePaths)), ), onNone: () => Effect.succeed(relativePaths), }); - const buildWorkspaceIndexFromGit = Effect.fn("WorkspaceEntries.buildWorkspaceIndexFromGit")( + const buildWorkspaceIndexFromVcs = Effect.fn("WorkspaceEntries.buildWorkspaceIndexFromVcs")( function* (cwd: string) { - if (Option.isNone(gitOption)) { + if (Option.isNone(vcsOption)) { return null; } - if (!(yield* isInsideGitWorkTree(cwd))) { + if (!(yield* isInsideVcsWorkTree(cwd))) { return null; } - const listedFiles = yield* gitOption.value + const listedFiles = yield* vcsOption.value .listWorkspaceFiles(cwd) .pipe(Effect.catch(() => Effect.succeed(null))); @@ -216,7 +216,7 @@ export const makeWorkspaceEntries = Effect.gen(function* () { const listedPaths = [...listedFiles.paths] .map((entry) => toPosixPath(entry)) .filter((entry) => entry.length > 0 && !isPathInIgnoredDirectory(entry)); - const filePaths = yield* filterGitIgnoredPaths(cwd, listedPaths); + const filePaths = yield* filterVcsIgnoredPaths(cwd, listedPaths); const directorySet = new Set(); for (const filePath of filePaths) { @@ -288,7 +288,7 @@ export const makeWorkspaceEntries = Effect.gen(function* () { const buildWorkspaceIndexFromFilesystem = Effect.fn( "WorkspaceEntries.buildWorkspaceIndexFromFilesystem", )(function* (cwd: string): Effect.fn.Return { - const shouldFilterWithGitIgnore = yield* isInsideGitWorkTree(cwd); + const shouldFilterWithGitIgnore = yield* isInsideVcsWorkTree(cwd); let pendingDirectories: string[] = [""]; const entries: SearchableWorkspaceEntry[] = []; @@ -336,7 +336,7 @@ export const makeWorkspaceEntries = Effect.gen(function* () { candidateEntries.map((entry) => entry.relativePath), ); const allowedPathSet = shouldFilterWithGitIgnore - ? new Set(yield* filterGitIgnoredPaths(cwd, candidatePaths)) + ? new Set(yield* filterVcsIgnoredPaths(cwd, candidatePaths)) : null; for (const candidateEntries of candidateEntriesByDirectory) { @@ -378,9 +378,9 @@ export const makeWorkspaceEntries = Effect.gen(function* () { const buildWorkspaceIndex = Effect.fn("WorkspaceEntries.buildWorkspaceIndex")(function* ( cwd: string, ): Effect.fn.Return { - const gitIndexed = yield* buildWorkspaceIndexFromGit(cwd); - if (gitIndexed) { - return gitIndexed; + const vcsIndexed = yield* buildWorkspaceIndexFromVcs(cwd); + if (vcsIndexed) { + return vcsIndexed; } return yield* buildWorkspaceIndexFromFilesystem(cwd); }); diff --git a/apps/server/src/workspace/Layers/WorkspaceFileSystem.test.ts b/apps/server/src/workspace/Layers/WorkspaceFileSystem.test.ts index fcfd13c912..71829708c9 100644 --- a/apps/server/src/workspace/Layers/WorkspaceFileSystem.test.ts +++ b/apps/server/src/workspace/Layers/WorkspaceFileSystem.test.ts @@ -3,7 +3,8 @@ import { it, describe, expect } from "@effect/vitest"; import { Effect, FileSystem, Layer, Path } from "effect"; import { ServerConfig } from "../../config.ts"; -import { GitCoreLive } from "../../git/Layers/GitCore.ts"; +import { GitVcsDriverLive } from "../../vcs/Layers/GitVcsDriver.ts"; +import { VcsProcessLive } from "../../vcs/Layers/VcsProcess.ts"; import { WorkspaceEntries } from "../Services/WorkspaceEntries.ts"; import { WorkspaceFileSystem } from "../Services/WorkspaceFileSystem.ts"; import { WorkspaceEntriesLive } from "./WorkspaceEntries.ts"; @@ -19,7 +20,7 @@ const TestLayer = Layer.empty.pipe( Layer.provideMerge(ProjectLayer), Layer.provideMerge(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))), Layer.provideMerge(WorkspacePathsLive), - Layer.provideMerge(GitCoreLive), + Layer.provideMerge(GitVcsDriverLive.pipe(Layer.provide(VcsProcessLive))), Layer.provide( ServerConfig.layerTest(process.cwd(), { prefix: "t3-workspace-files-test-", diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index fd256b32df..da0bfad598 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -29,7 +29,6 @@ import { RpcSerialization, RpcServer } from "effect/unstable/rpc"; import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery.ts"; import { ServerConfig } from "./config.ts"; -import { GitCore } from "./git/Services/GitCore.ts"; import { GitManager } from "./git/Services/GitManager.ts"; import { GitStatusBroadcaster } from "./git/Services/GitStatusBroadcaster.ts"; import { Keybindings } from "./keybindings.ts"; @@ -50,6 +49,7 @@ import { TerminalManager } from "./terminal/Services/Manager.ts"; import { WorkspaceEntries } from "./workspace/Services/WorkspaceEntries.ts"; import { WorkspaceFileSystem } from "./workspace/Services/WorkspaceFileSystem.ts"; import { WorkspacePathOutsideRootError } from "./workspace/Services/WorkspacePaths.ts"; +import { VcsDriver } from "./vcs/Services/VcsDriver.ts"; import { ProjectSetupScriptRunner } from "./project/Services/ProjectSetupScriptRunner.ts"; import { RepositoryIdentityResolver } from "./project/Services/RepositoryIdentityResolver.ts"; import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts"; @@ -137,7 +137,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) => const keybindings = yield* Keybindings; const open = yield* Open; const gitManager = yield* GitManager; - const git = yield* GitCore; + const git = yield* VcsDriver; const gitStatusBroadcaster = yield* GitStatusBroadcaster; const terminalManager = yield* TerminalManager; const providerRegistry = yield* ProviderRegistry; diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index ad90571740..6e7f6b7e62 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -11,6 +11,7 @@ export * from "./keybindings.ts"; export * from "./server.ts"; export * from "./settings.ts"; export * from "./git.ts"; +export * from "./vcs.ts"; export * from "./orchestration.ts"; export * from "./editor.ts"; export * from "./project.ts"; diff --git a/packages/contracts/src/vcs.ts b/packages/contracts/src/vcs.ts new file mode 100644 index 0000000000..3bef29a479 --- /dev/null +++ b/packages/contracts/src/vcs.ts @@ -0,0 +1,139 @@ +import { Schema } from "effect"; +import { TrimmedNonEmptyString } from "./baseSchemas.ts"; + +export const VcsDriverKind = Schema.Literals(["git", "jj", "sapling", "unknown"]); +export type VcsDriverKind = typeof VcsDriverKind.Type; + +export const VcsFreshnessSource = Schema.Literals([ + "live-local", + "cached-local", + "cached-remote", + "explicit-remote", +]); +export type VcsFreshnessSource = typeof VcsFreshnessSource.Type; + +export const VcsFreshness = Schema.Struct({ + source: VcsFreshnessSource, + observedAt: TrimmedNonEmptyString, + expiresAt: Schema.optional(TrimmedNonEmptyString), +}); +export type VcsFreshness = typeof VcsFreshness.Type; + +export const VcsDriverCapabilities = Schema.Struct({ + kind: VcsDriverKind, + supportsWorktrees: Schema.Boolean, + supportsBookmarks: Schema.Boolean, + supportsAtomicSnapshot: Schema.Boolean, + supportsPushDefaultRemote: Schema.Boolean, +}); +export type VcsDriverCapabilities = typeof VcsDriverCapabilities.Type; + +export const VcsRepositoryIdentity = Schema.Struct({ + kind: VcsDriverKind, + rootPath: TrimmedNonEmptyString, + metadataPath: Schema.NullOr(TrimmedNonEmptyString), + freshness: VcsFreshness, +}); +export type VcsRepositoryIdentity = typeof VcsRepositoryIdentity.Type; + +export const VcsListWorkspaceFilesResult = Schema.Struct({ + paths: Schema.Array(TrimmedNonEmptyString), + truncated: Schema.Boolean, + freshness: VcsFreshness, +}); +export type VcsListWorkspaceFilesResult = typeof VcsListWorkspaceFilesResult.Type; + +export class VcsProcessSpawnError extends Schema.TaggedErrorClass()( + "VcsProcessSpawnError", + { + operation: Schema.String, + command: Schema.String, + cwd: Schema.String, + cause: Schema.Defect, + }, +) { + override get message(): string { + return `VCS process failed to spawn in ${this.operation}: ${this.command} (${this.cwd})`; + } +} + +export class VcsProcessExitError extends Schema.TaggedErrorClass()( + "VcsProcessExitError", + { + operation: Schema.String, + command: Schema.String, + cwd: Schema.String, + exitCode: Schema.Number, + detail: Schema.String, + }, +) { + override get message(): string { + return `VCS process failed in ${this.operation}: ${this.command} (${this.cwd}) exited with ${this.exitCode} - ${this.detail}`; + } +} + +export class VcsProcessTimeoutError extends Schema.TaggedErrorClass()( + "VcsProcessTimeoutError", + { + operation: Schema.String, + command: Schema.String, + cwd: Schema.String, + timeoutMs: Schema.Number, + }, +) { + override get message(): string { + return `VCS process timed out in ${this.operation}: ${this.command} (${this.cwd}) after ${this.timeoutMs}ms`; + } +} + +export class VcsOutputDecodeError extends Schema.TaggedErrorClass()( + "VcsOutputDecodeError", + { + operation: Schema.String, + command: Schema.String, + cwd: Schema.String, + detail: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) { + override get message(): string { + return `VCS output decode failed in ${this.operation}: ${this.command} (${this.cwd}) - ${this.detail}`; + } +} + +export class VcsRepositoryDetectionError extends Schema.TaggedErrorClass()( + "VcsRepositoryDetectionError", + { + operation: Schema.String, + cwd: Schema.String, + detail: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) { + override get message(): string { + return `VCS repository detection failed in ${this.operation}: ${this.cwd} - ${this.detail}`; + } +} + +export class VcsUnsupportedOperationError extends Schema.TaggedErrorClass()( + "VcsUnsupportedOperationError", + { + operation: Schema.String, + kind: VcsDriverKind, + detail: Schema.String, + }, +) { + override get message(): string { + return `VCS operation is unsupported for ${this.kind} in ${this.operation}: ${this.detail}`; + } +} + +export const VcsError = Schema.Union([ + VcsProcessSpawnError, + VcsProcessExitError, + VcsProcessTimeoutError, + VcsOutputDecodeError, + VcsRepositoryDetectionError, + VcsUnsupportedOperationError, +]); +export type VcsError = typeof VcsError.Type;