import { assert, it } from "@effect/vitest"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { CommandId, GitCommandError, ProjectId, ThreadId, VcsProcessSpawnError, VcsProcessTimeoutError, } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Cause from "effect/Cause"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Logger from "effect/Logger"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as PlatformError from "effect/PlatformError"; import { ChildProcessSpawner } from "effect/process"; import * as Scope from "effect/Scope"; import * as TestClock from "effect/testing/TestClock"; import * as ServerConfig from "../config.ts"; import * as GitManager from "../git/GitManager.ts"; import * as GitWorkflow from "../git/GitWorkflowService.ts"; import * as RuntimeLayer from "../orchestration-v2/runtimeLayer.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as ProcessRunner from "../processRunner.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; import * as VcsProcess from "../vcs/VcsProcess.ts"; import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; import * as ProjectEnrichmentService from "./ProjectEnrichmentService.ts"; import * as ProjectFaviconResolver from "./ProjectFaviconResolver.ts"; import * as ProjectService from "./ProjectService.ts"; import * as RepositoryIdentityResolver from "./RepositoryIdentityResolver.ts"; import * as ManagedProjectFolders from "./ManagedProjectFolders.ts"; const layerGitWorkflow = (vcsProcess?: Layer.Layer) => GitWorkflow.layer.pipe( Layer.provide(VcsDriverRegistry.layer.pipe(Layer.provide(vcsProcess ?? VcsProcess.layer))), Layer.provide(Layer.mock(GitManager.GitManager)({})), ); const layerEnrichment = ProjectEnrichmentService.layer.pipe( Layer.provide( Layer.mergeAll( Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, { resolve: () => Effect.succeed(null), }), Layer.succeed(ProjectFaviconResolver.ProjectFaviconResolver, { invalidate: () => Effect.void, resolvePath: () => Effect.succeed(null), }), ), ), ); const layerRealGit = GitVcsDriver.layer.pipe(Layer.provide(VcsProcess.layer)); interface HarnessOptions { readonly fileSystem?: (real: FileSystem.FileSystem) => FileSystem.FileSystem; readonly vcsProcess?: Layer.Layer; readonly git?: typeof layerRealGit; readonly projects?: ( real: ProjectService.ProjectService["Service"], ) => ProjectService.ProjectService["Service"]; } const layer = (baseDir: string, options?: HarnessOptions) => ManagedProjectFolders.layer.pipe( Layer.provide( options?.fileSystem === undefined ? Layer.empty : Layer.effect( FileSystem.FileSystem, FileSystem.FileSystem.pipe(Effect.map(options.fileSystem)), ), ), Layer.provide( options?.projects === undefined ? Layer.empty : Layer.effect( ProjectService.ProjectService, ProjectService.ProjectService.pipe(Effect.map(options.projects)), ), ), Layer.provideMerge(RuntimeLayer.layerProjectService), Layer.provideMerge(layerEnrichment), Layer.provideMerge(WorkspacePaths.layer), Layer.provideMerge(layerGitWorkflow(options?.vcsProcess)), Layer.provideMerge(options?.git ?? layerRealGit), Layer.provideMerge(SqlitePersistence.layerMemory), Layer.provideMerge(ServerSettings.layerTest()), Layer.provideMerge(ServerConfig.layerTest(baseDir, baseDir)), Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), ); const withScratch = ( body: (input: { readonly baseDir: string; }) => Effect.Effect< A, E, | ManagedProjectFolders.ManagedProjectFolders | ProjectService.ProjectService | NodeServices.NodeServices | Scope.Scope >, options?: HarnessOptions, ) => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const baseDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-managed-folders-" }); return yield* body({ baseDir }).pipe(Effect.provide(layer(baseDir, options))); }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))); const git = (cwd: string, args: ReadonlyArray) => ProcessRunner.ProcessRunner.pipe( Effect.flatMap((runner) => runner.run({ command: "git", args: ["-C", cwd, ...args] })), Effect.provide(ProcessRunner.layer), ); const requireRoot = Effect.gen(function* () { const scratch = yield* ManagedProjectFolders.ManagedProjectFolders; return Option.getOrThrow(yield* scratch.scratchRoot); }); it.effect("offers nothing, and says why once, when the data dir sits inside a Git checkout", () => { const warnings: string[] = []; const logger = Logger.make(({ logLevel, message }) => { if (logLevel === "Warn") warnings.push(String(message)); }); return Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const checkout = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-scratch-repo-" }); yield* git(checkout, ["init", "--quiet"]); const baseDir = path.join(checkout, ".t3"); yield* fileSystem.makeDirectory(baseDir); const repositoryRoot = (yield* git(baseDir, ["rev-parse", "--show-toplevel"])).stdout.trim(); yield* Effect.gen(function* () { const scratch = yield* ManagedProjectFolders.ManagedProjectFolders; assert.isTrue(Option.isNone(yield* scratch.scratchRoot)); assert.isFalse(yield* scratch.isScratchProject(ProjectId.make("project:any"))); const failure = yield* Effect.flip(scratch.ensureScratchProject); assert.equal(failure._tag, "ScratchUnavailableError"); assert.include(failure.message, baseDir); // The root prefixes the data dir, so it must appear on its own. assert.include(failure.message.replaceAll(baseDir, ""), repositoryRoot); yield* Effect.flip(scratch.ensureScratchProject); }).pipe( Effect.provide( Layer.mergeAll(layer(baseDir), Logger.layer([logger], { mergeWithExisting: false })), ), ); assert.equal(warnings.length, 1); assert.include(warnings[0], baseDir); }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))); }); it.effect("offers a Scratch folder when Git is not installed", () => withScratch( ({ baseDir }) => Effect.gen(function* () { const path = yield* Path.Path; assert.equal(yield* requireRoot, path.resolve(baseDir, "scratch")); }), { vcsProcess: Layer.succeed(VcsProcess.VcsProcess, { run: (input) => Effect.fail( new VcsProcessSpawnError({ operation: input.operation, command: input.command, cwd: input.cwd, cause: PlatformError.systemError({ _tag: "NotFound", module: "ChildProcess", method: "spawn", syscall: `spawn ${input.command}`, }), }), ), }), }, ), ); it.effect("offers the Scratch folder once a Git check that timed out is asked again", () => withScratch( ({ baseDir }) => Effect.gen(function* () { const path = yield* Path.Path; const scratch = yield* ManagedProjectFolders.ManagedProjectFolders; assert.isTrue(Option.isNone(yield* scratch.scratchRoot)); assert.equal(yield* requireRoot, path.resolve(baseDir, "scratch")); }), { vcsProcess: Layer.effect( VcsProcess.VcsProcess, Effect.map(VcsProcess.make, (real) => { let timedOut = false; return VcsProcess.VcsProcess.of({ run: (input) => Effect.suspend(() => { if (timedOut) return real.run(input); timedOut = true; return Effect.fail( new VcsProcessTimeoutError({ operation: input.operation, command: input.command, cwd: input.cwd, timeoutMs: 5_000, }), ); }), }); }), ).pipe( Layer.provide(ProcessRunner.layer), Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), ), }, ), ); it.effect("creates one Scratch project, even for concurrent first requests", () => withScratch(() => Effect.gen(function* () { const scratch = yield* ManagedProjectFolders.ManagedProjectFolders; const projects = yield* ProjectService.ProjectService; const racers = yield* Effect.all( Array.from({ length: 8 }, () => scratch.ensureScratchProject), { concurrency: "unbounded" }, ); const again = yield* scratch.ensureScratchProject; assert.deepEqual( new Set(racers.map((result) => result.projectId)), new Set([again.projectId]), ); const snapshot = yield* projects.snapshot; const root = yield* requireRoot; const scratchProjects = snapshot.projects.filter((project) => project.workspaceRoot === root); assert.lengthOf(scratchProjects, 1); assert.equal(scratchProjects[0]?.title, "No project"); assert.deepEqual(scratchProjects[0]?.projectIcon, { kind: "lucide", name: "message-square-dashed", color: "gray", }); }), ), ); it.effect("recreates the Scratch folder after it is deleted", () => withScratch(() => Effect.gen(function* () { const scratch = yield* ManagedProjectFolders.ManagedProjectFolders; const fileSystem = yield* FileSystem.FileSystem; const { projectId } = yield* scratch.ensureScratchProject; const root = yield* requireRoot; yield* fileSystem.remove(root, { recursive: true }); assert.equal((yield* scratch.ensureScratchProject).projectId, projectId); assert.isTrue(yield* fileSystem.exists(root)); yield* fileSystem.remove(root, { recursive: true }); const folder = yield* scratch.folderForThread({ projectId, threadId: ThreadId.make("thread-after-delete"), text: "Still works", }); assert.isTrue(yield* fileSystem.exists(Option.getOrThrow(folder))); }), ), ); it.effect("gives each Scratch thread its own folder, named from its message", () => withScratch(() => Effect.gen(function* () { const scratch = yield* ManagedProjectFolders.ManagedProjectFolders; const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const { projectId } = yield* scratch.ensureScratchProject; const root = yield* requireRoot; const text = "Convert these PNGs to WebP, please!"; const first = Option.getOrThrow( yield* scratch.folderForThread({ projectId, threadId: ThreadId.make("thread:a:0123456789abcdef"), text, }), ); const second = Option.getOrThrow( yield* scratch.folderForThread({ projectId, threadId: ThreadId.make("thread:b:0123456789abcdef"), text, }), ); const third = Option.getOrThrow( yield* scratch.folderForThread({ projectId, threadId: ThreadId.make("thread:b0123456789abcdef"), text, }), ); assert.equal(new Set([first, second, third]).size, 3); for (const folder of [first, second, third]) { assert.equal(path.dirname(folder), root); assert.match(path.basename(folder), /^\d{4}-\d{2}-\d{2}-convert-these-pngs-to-webp-/); assert.isTrue(yield* fileSystem.exists(folder)); } const pasted = Option.getOrThrow( yield* scratch.folderForThread({ projectId, threadId: ThreadId.make("thread-pasted"), text: `${"word ".repeat(10_000)}../../etc`, }), ); assert.equal(path.dirname(pasted), root); assert.isAtMost(path.basename(pasted).length, 80); const accented = Option.getOrThrow( yield* scratch.folderForThread({ projectId, threadId: ThreadId.make("thread-diacritics"), text: "tìm kiếm skill", }), ); assert.match(path.basename(accented), /^\d{4}-\d{2}-\d{2}-tim-kiem-skill-/); }), ), ); it.effect("leaves threads in other projects alone", () => withScratch(({ baseDir }) => Effect.gen(function* () { const scratch = yield* ManagedProjectFolders.ManagedProjectFolders; const projects = yield* ProjectService.ProjectService; const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const { projectId: scratchId } = yield* scratch.ensureScratchProject; const other = yield* projects.create({ commandId: CommandId.make("command:other"), projectId: ProjectId.make("project:other"), title: "Other", workspaceRoot: path.join(baseDir, "other"), createWorkspaceRootIfMissing: true, }); const folder = yield* scratch.folderForThread({ projectId: other.id, threadId: ThreadId.make("thread-other"), text: "Hello", }); assert.isTrue(Option.isNone(folder)); assert.deepEqual(yield* fileSystem.readDirectory(yield* requireRoot), []); assert.isTrue(yield* scratch.isScratchProject(scratchId)); assert.isFalse(yield* scratch.isScratchProject(other.id)); }), ), ); it.effect("still knows No project when its folder is the target of a symlinked Scratch", () => withScratch(({ baseDir }) => Effect.gen(function* () { const scratch = yield* ManagedProjectFolders.ManagedProjectFolders; const projects = yield* ProjectService.ProjectService; const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const root = yield* requireRoot; const target = path.join(yield* fileSystem.realPath(baseDir), "visible-chats"); yield* fileSystem.makeDirectory(target); yield* fileSystem.symlink(target, root); const { projectId } = yield* scratch.ensureScratchProject; yield* projects.update({ commandId: CommandId.make("command:point-at-target"), projectId, workspaceRoot: target, }); assert.isTrue(yield* scratch.isScratchProject(projectId)); assert.equal((yield* scratch.ensureScratchProject).projectId, projectId); assert.deepStrictEqual(yield* scratch.scratchRoot, Option.some(target)); }), ), ); const GIT_IDENTITY_KEYS = [ "GIT_AUTHOR_NAME", "GIT_AUTHOR_EMAIL", "GIT_COMMITTER_NAME", "GIT_COMMITTER_EMAIL", "EMAIL", "GIT_CONFIG_GLOBAL", "GIT_CONFIG_NOSYSTEM", ] as const; const withGitEnv = ( env: Partial>, effect: Effect.Effect, ) => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const emptyConfig = yield* fileSystem.makeTempFileScoped({ prefix: "t3-gitconfig-" }); const hostEnv: NodeJS.ProcessEnv = { ...(yield* HostProcess.Environment) }; for (const key of GIT_IDENTITY_KEYS) delete hostEnv[key]; return yield* effect.pipe( Effect.provideService(HostProcess.Environment, { ...hostEnv, GIT_CONFIG_GLOBAL: emptyConfig, GIT_CONFIG_NOSYSTEM: "1", ...env, }), ); }); const TEST_IDENTITY = { GIT_AUTHOR_NAME: "Test", GIT_AUTHOR_EMAIL: "test@test.com", GIT_COMMITTER_NAME: "Test", GIT_COMMITTER_EMAIL: "test@test.com", }; const gitOutput = (cwd: string, args: ReadonlyArray) => git(cwd, args).pipe(Effect.map((result) => result.stdout.trim())); it.effect("starts a named project as a committed repository, and suffixes a taken name", () => withScratch(({ baseDir }) => withGitEnv( TEST_IDENTITY, Effect.gen(function* () { const folders = yield* ManagedProjectFolders.ManagedProjectFolders; const projects = yield* ProjectService.ProjectService; const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const root = path.resolve(baseDir, "projects"); assert.equal(folders.namedProjectsRoot, root); const attributes = path.join(baseDir, "crlf.gitattributes"); const crlfConfig = path.join(baseDir, "crlf.gitconfig"); yield* fileSystem.writeFileString(attributes, "* text=auto eol=crlf\n"); yield* git(baseDir, ["config", "--file", crlfConfig, "core.safecrlf", "true"]); yield* git(baseDir, ["config", "--file", crlfConfig, "core.attributesFile", attributes]); (yield* HostProcess.Environment).GIT_CONFIG_GLOBAL = crlfConfig; const first = yield* folders.createNamedProject({ name: "Pinball Stats" }); const second = yield* folders.createNamedProject({ name: "pinball stats" }); assert.equal(first.workspaceRoot, path.join(root, "pinball-stats")); assert.equal(second.workspaceRoot, path.join(root, "pinball-stats-2")); assert.isUndefined(first.commitError); const project = Option.getOrThrow(yield* projects.getById(first.projectId)); assert.equal(project.title, "Pinball Stats"); assert.equal(project.workspaceRoot, first.workspaceRoot); const readme = yield* fileSystem.readFileString( path.join(first.workspaceRoot, "README.md"), ); assert.include(readme, "# Pinball Stats"); assert.include(readme, `src="assets/icon.svg"`); const icon = yield* fileSystem.readFileString( path.join(first.workspaceRoot, "assets", "icon.svg"), ); assert.include(icon, ">PS"); assert.equal( yield* gitOutput(first.workspaceRoot, ["log", "--format=%s"]), "Initial commit", ); assert.equal( yield* gitOutput(first.workspaceRoot, ["rev-parse", "--abbrev-ref", "HEAD"]), "main", ); assert.equal(yield* gitOutput(first.workspaceRoot, ["status", "--porcelain"]), ""); }), ), ), ); it.effect("scaffolds and registers a named project inside the chosen parent", () => withScratch(({ baseDir }) => withGitEnv( TEST_IDENTITY, Effect.gen(function* () { const folders = yield* ManagedProjectFolders.ManagedProjectFolders; const projects = yield* ProjectService.ProjectService; const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const parent = path.join(baseDir, "Development"); yield* fileSystem.makeDirectory(parent); yield* fileSystem.makeDirectory(path.join(parent, "custom-app")); const result = yield* folders .createNamedProject({ name: "Custom App", parentPath: "~/Development" }) .pipe(Effect.provideService(HostProcess.HomeDirectory, baseDir)); assert.equal( result.workspaceRoot, path.join(yield* fileSystem.realPath(parent), "custom-app-2"), ); assert.equal( Option.getOrThrow(yield* projects.getById(result.projectId)).workspaceRoot, result.workspaceRoot, ); assert.equal( yield* gitOutput(result.workspaceRoot, ["log", "--format=%s"]), "Initial commit", ); assert.isFalse(yield* fileSystem.exists(folders.namedProjectsRoot)); }), ), ), ); it.effect("places a project under the canonical directory behind a parent symlink", () => withScratch(({ baseDir }) => withGitEnv( TEST_IDENTITY, Effect.gen(function* () { if ((yield* HostProcess.Platform) === "win32") return; const folders = yield* ManagedProjectFolders.ManagedProjectFolders; const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const target = path.join(baseDir, "target"); const parentPath = path.join(baseDir, "link"); yield* fileSystem.makeDirectory(target); yield* fileSystem.symlink(target, parentPath); const result = yield* folders.createNamedProject({ name: "Linked App", parentPath }); assert.equal( result.workspaceRoot, path.join(yield* fileSystem.realPath(target), "linked-app"), ); }), ), ), ); it.effect("rejects relative paths for the named project's parent", () => withScratch( () => Effect.gen(function* () { const folders = yield* ManagedProjectFolders.ManagedProjectFolders; for (const parentPath of [".", "./dev", "dev"]) { const error = yield* Effect.flip( folders.createNamedProject({ name: "Relative", parentPath }), ); assert.equal( error._tag === "NamedProjectFolderError" && error.parentFailure, "relative_path", ); } }), { fileSystem: (real) => ({ ...real, makeDirectory: () => Effect.die("A relative parent must be rejected before mkdir"), }), }, ), ); it.effect("rejects a named project parent that resolves to a network path", () => withScratch( ({ baseDir }) => Effect.gen(function* () { const folders = yield* ManagedProjectFolders.ManagedProjectFolders; const error = yield* Effect.flip( folders.createNamedProject({ name: "Via Network", parentPath: baseDir, }), ); assert.equal( error._tag === "NamedProjectFolderError" && error.parentFailure, "network_path", ); }), { fileSystem: (real) => ({ ...real, realPath: () => Effect.succeed("//server/share") }), }, ), ); it.effect("rejects a UNC target behind an ancestor junction before following it", () => withScratch( ({ baseDir }) => Effect.gen(function* () { const folders = yield* ManagedProjectFolders.ManagedProjectFolders; const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const junction = path.join(baseDir, "junction"); yield* fileSystem.makeDirectory(junction); const error = yield* folders .createNamedProject({ name: "Via Network", parentPath: path.join(junction, "child") }) .pipe(Effect.flip); assert.equal( error._tag === "NamedProjectFolderError" && error.parentFailure, "network_path", ); }), { fileSystem: (real) => ({ ...real, lstat: (folder) => real .lstat(folder) .pipe( Effect.map((info) => /[/\\]junction$/.test(folder) ? { ...info, type: "SymbolicLink" } : info, ), ), readLink: () => Effect.succeed(String.raw`\\server\share`), stat: () => Effect.die("A network junction must be rejected before stat"), realPath: () => Effect.die("A network junction must be rejected before realPath"), }), }, ), ); it.effect("rejects missing, non-directory, network, and foreign Windows project parents", () => withScratch(({ baseDir }) => Effect.gen(function* () { const folders = yield* ManagedProjectFolders.ManagedProjectFolders; const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const missing = path.join(baseDir, "missing"); const file = path.join(baseDir, "file"); yield* fileSystem.writeFileString(file, ""); for (const [parentPath, message] of [ [missing, "does not exist"], [file, "is not a directory"], ["//server/share", "Network paths"], ["C:\\Code", "Windows-style paths"], ] as const) { const error = yield* folders .createNamedProject({ name: "Custom App", parentPath }) .pipe(Effect.provideService(HostProcess.Platform, "darwin"), Effect.flip); assert.equal(error._tag, "NamedProjectFolderError"); assert.include(error.message, message); } assert.isFalse(yield* fileSystem.exists(missing)); assert.isFalse(yield* fileSystem.exists(folders.namedProjectsRoot)); }), ), ); it.effect("gives concurrent named projects with the same name distinct folders", () => withScratch(() => withGitEnv( TEST_IDENTITY, Effect.gen(function* () { const folders = yield* ManagedProjectFolders.ManagedProjectFolders; const projects = yield* ProjectService.ProjectService; const created = yield* Effect.all( Array.from({ length: 4 }, () => folders.createNamedProject({ name: "Race" })), { concurrency: "unbounded" }, ); assert.equal(new Set(created.map((result) => result.workspaceRoot)).size, 4); assert.equal(new Set(created.map((result) => result.projectId)).size, 4); const snapshot = yield* projects.snapshot; for (const result of created) { assert.isTrue( snapshot.projects.some((project) => project.workspaceRoot === result.workspaceRoot), ); } }), ), ), ); it.effect("keeps a named project and reports why when Git cannot commit", () => withScratch(({ baseDir }) => withGitEnv( {}, Effect.gen(function* () { const folders = yield* ManagedProjectFolders.ManagedProjectFolders; const projects = yield* ProjectService.ProjectService; const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; yield* fileSystem.writeFileString( path.join(baseDir, "no-identity.gitconfig"), "[user]\n\tuseConfigOnly = true\n", ); (yield* HostProcess.Environment).GIT_CONFIG_GLOBAL = path.join( baseDir, "no-identity.gitconfig", ); const result = yield* folders.createNamedProject({ name: "No Identity" }); assert.include(result.commitError ?? "", "no name or email"); assert.isTrue(Option.isSome(yield* projects.getById(result.projectId))); assert.isTrue(yield* fileSystem.exists(path.join(result.workspaceRoot, "README.md"))); assert.isTrue(yield* fileSystem.exists(path.join(result.workspaceRoot, ".git"))); }), ), ), ); it.effect("says Git is not installed when a named project cannot start Git", () => withScratch( () => Effect.gen(function* () { const folders = yield* ManagedProjectFolders.ManagedProjectFolders; const failure = yield* Effect.flip(folders.createNamedProject({ name: "T3Code Test" })); assert.strictEqual( failure.message, "Git isn't installed on this machine. Install Git to create a project.", ); }), { git: GitVcsDriver.layer.pipe( Layer.provide( Layer.succeed( ChildProcessSpawner.ChildProcessSpawner, ChildProcessSpawner.make(() => Effect.fail( PlatformError.systemError({ _tag: "NotFound", module: "ChildProcess", method: "spawn", syscall: "spawn git", }), ), ), ), ), ), }, ), ); it.effect("keeps a folder that another project owns when the create conflicts", () => withScratch(({ baseDir }) => withGitEnv( TEST_IDENTITY, Effect.gen(function* () { const folders = yield* ManagedProjectFolders.ManagedProjectFolders; const projects = yield* ProjectService.ProjectService; const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const taken = path.join(folders.namedProjectsRoot, "taken"); yield* projects.create({ commandId: CommandId.make("command:owner"), projectId: ProjectId.make("project:owner"), title: "Owner", workspaceRoot: taken, createWorkspaceRootIfMissing: true, }); yield* fileSystem.remove(taken, { recursive: true }); const failure = yield* Effect.flip(folders.createNamedProject({ name: "Taken" })); assert.equal(failure._tag, "NamedProjectCreateError"); assert.equal(failure.message, "Failed to create the project."); assert.isTrue(yield* fileSystem.exists(path.join(taken, "README.md"))); const owner = yield* projects.getByWorkspaceRoot(taken); assert.equal(Option.getOrThrow(owner).id, ProjectId.make("project:owner")); assert.deepEqual(yield* fileSystem.readDirectory(path.resolve(baseDir, "projects")), [ "taken", ]); }), ), ), ); it.effect.each(["ordinary", "symlinked"] as const)( "rolls back a rejected create through the physical key under a %s projects root", (rootKind) => Effect.gen(function* () { if (rootKind === "symlinked" && (yield* HostProcess.Platform) === "win32") return; const lockKeys: string[] = []; const ownerKeys: string[] = []; const removing = yield* Deferred.make(); const finishRemove = yield* Deferred.make(); const removed = yield* Deferred.make(); yield* withScratch( ({ baseDir }) => withGitEnv( TEST_IDENTITY, Effect.gen(function* () { const folders = yield* ManagedProjectFolders.ManagedProjectFolders; const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; if (rootKind === "symlinked") { const physicalParent = path.join(yield* fileSystem.realPath(baseDir), "physical"); yield* fileSystem.makeDirectory(physicalParent); yield* fileSystem.symlink(physicalParent, folders.namedProjectsRoot); } const caller = yield* folders .createNamedProject({ name: "Rejected" }) .pipe(Effect.flip, Effect.forkChild); yield* Deferred.await(removing); yield* TestClock.adjust("5 seconds"); assert.isDefined(caller.pollUnsafe(), "the rejected create still waits for remove"); const failure = yield* Fiber.join(caller); assert.equal(failure._tag, "NamedProjectCreateError"); assert.equal(failure.message, "Failed to create the project."); yield* Deferred.succeed(finishRemove, undefined); yield* Deferred.await(removed); const physicalParent = yield* fileSystem.realPath(folders.namedProjectsRoot); const physicalKey = path.join(physicalParent, "rejected"); const alias = path.join(folders.namedProjectsRoot, "rejected"); const expectedKeys = alias === physicalKey ? [physicalKey] : [physicalKey, alias]; assert.deepEqual(lockKeys, expectedKeys); assert.deepEqual(ownerKeys, expectedKeys); assert.deepEqual(yield* fileSystem.readDirectory(physicalParent), []); }).pipe(Effect.ensuring(Deferred.succeed(finishRemove, undefined))), ), { fileSystem: (real) => ({ ...real, remove: (target, options) => /[/\\]rejected$/.test(target) ? Deferred.succeed(removing, undefined).pipe( Effect.andThen(Deferred.await(finishRemove)), Effect.andThen(real.remove(target, options)), Effect.tap(() => Deferred.succeed(removed, undefined)), ) : real.remove(target, options), }), projects: (real) => ProjectService.ProjectService.of({ ...real, create: (input) => Effect.fail( new ProjectService.ProjectOperationError({ operation: "dispatch-project-command", projectId: input.projectId, cause: "store unavailable", }), ), withWorkspaceLock: (key, operation) => { lockKeys.push(key); return real.withWorkspaceLock(key, operation); }, getByWorkspaceRoot: (key) => { ownerKeys.push(key); return real.getByWorkspaceRoot(key); }, }), }, ); }), ); it.effect.each(["ordinary", "physical", "alias", "different symlink"] as const)( "preserves a folder registered through the %s path while scaffolding fails", (ownerPath) => Effect.gen(function* () { if (ownerPath !== "ordinary" && (yield* HostProcess.Platform) === "win32") return; const scaffolding = yield* Deferred.make(); const failScaffold = yield* Deferred.make(); yield* withScratch( ({ baseDir }) => Effect.gen(function* () { const folders = yield* ManagedProjectFolders.ManagedProjectFolders; const projects = yield* ProjectService.ProjectService; const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const physicalParent = path.join(yield* fileSystem.realPath(baseDir), "physical"); if (ownerPath !== "ordinary") { yield* fileSystem.makeDirectory(physicalParent); yield* fileSystem.symlink(physicalParent, folders.namedProjectsRoot); } const workspaceRoot = path.join(folders.namedProjectsRoot, "claimed"); const file = path.join(workspaceRoot, "keep.txt"); const fiber = yield* folders .createNamedProject({ name: "Claimed" }) .pipe(Effect.flip, Effect.forkChild); yield* Deferred.await(scaffolding); const ownerParent = ownerPath === "physical" ? physicalParent : folders.namedProjectsRoot; const otherAlias = path.join(baseDir, "other-alias"); if (ownerPath === "different symlink") { yield* fileSystem.symlink(physicalParent, otherAlias); } const ownerRoot = path.join( ownerPath === "different symlink" ? otherAlias : ownerParent, "claimed", ); const owner = yield* projects.create({ commandId: CommandId.make("command:scaffold-owner"), projectId: ProjectId.make("project:scaffold-owner"), title: "Owner", workspaceRoot: ownerRoot, }); assert.equal(owner.workspaceRoot, ownerRoot); yield* fileSystem.writeFileString(file, "keep"); yield* Deferred.succeed(failScaffold, undefined); assert.equal((yield* Fiber.join(fiber))._tag, "NamedProjectFolderError"); assert.equal(yield* fileSystem.readFileString(file), "keep"); }), { git: Layer.mock(GitVcsDriver.GitVcsDriver)({ readConfigValue: () => Effect.succeed(null), execute: ({ cwd, operation }) => Deferred.succeed(scaffolding, undefined).pipe( Effect.andThen(Deferred.await(failScaffold)), Effect.andThen( Effect.fail( new GitCommandError({ command: "git", cwd, operation, detail: "init failed" }), ), ), ), }), }, ); }), ); it.effect.each(["stalls", "fails"] as const)( "keeps the folder and returns the error when another project's root probe %s", (probe) => Effect.gen(function* () { const probed = yield* Deferred.make(); yield* withScratch( ({ baseDir }) => Effect.gen(function* () { const folders = yield* ManagedProjectFolders.ManagedProjectFolders; const projects = yield* ProjectService.ProjectService; const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; yield* projects.create({ commandId: CommandId.make("command:hung-owner"), projectId: ProjectId.make("project:hung-owner"), title: "Elsewhere", workspaceRoot: path.join(baseDir, "hung"), createWorkspaceRootIfMissing: true, }); const fiber = yield* folders .createNamedProject({ name: "Kept" }) .pipe(Effect.flip, Effect.forkChild); yield* Deferred.await(probed); yield* TestClock.adjust("2 seconds"); assert.equal((yield* Fiber.join(fiber))._tag, "NamedProjectFolderError"); assert.deepEqual(yield* fileSystem.readDirectory(folders.namedProjectsRoot), ["kept"]); }), { fileSystem: (real) => { const hung = /[/\\]hung$/; const stall = (target: string) => Deferred.succeed(probed, undefined).pipe( Effect.andThen( probe === "stalls" ? Effect.never : Effect.fail( PlatformError.systemError({ _tag: "PermissionDenied", module: "FileSystem", method: "lstat", pathOrDescriptor: target, }), ), ), ); return { ...real, lstat: (target) => (hung.test(target) ? stall(target) : real.lstat(target)), realPath: (target) => (hung.test(target) ? stall(target) : real.realPath(target)), }; }, git: Layer.mock(GitVcsDriver.GitVcsDriver)({ readConfigValue: () => Effect.succeed(null), execute: ({ cwd, operation }) => Effect.fail( new GitCommandError({ command: "git", cwd, operation, detail: "init failed" }), ), }), }, ); }), ); it.effect.each([ { registrationPath: "canonical", createExit: "scaffold failure", removeOutcome: "succeeds" }, { registrationPath: "claim alias", createExit: "scaffold failure", removeOutcome: "fails" }, { registrationPath: "different symlink", createExit: "cancellation", removeOutcome: "succeeds" }, ])( "bounds rollback after $createExit and blocks registration via $registrationPath until remove $removeOutcome", ({ registrationPath, createExit, removeOutcome }) => Effect.gen(function* () { if (registrationPath !== "canonical" && (yield* HostProcess.Platform) === "win32") return; const scaffolding = yield* Deferred.make(); const removing = yield* Deferred.make(); const finishRemove = yield* Deferred.make(); yield* withScratch( ({ baseDir }) => Effect.gen(function* () { const folders = yield* ManagedProjectFolders.ManagedProjectFolders; const projects = yield* ProjectService.ProjectService; const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const physicalParent = path.join(yield* fileSystem.realPath(baseDir), "physical"); yield* fileSystem.makeDirectory(physicalParent); if (registrationPath !== "canonical") { yield* fileSystem.symlink(physicalParent, folders.namedProjectsRoot); } const otherAlias = path.join(baseDir, "other-alias"); if (registrationPath === "different symlink") { yield* fileSystem.symlink(physicalParent, otherAlias); } const registrationParent = registrationPath === "canonical" ? physicalParent : registrationPath === "claim alias" ? folders.namedProjectsRoot : otherAlias; const registrationRoot = path.join(registrationParent, "waiting"); const canonicalRoot = path.join(physicalParent, "waiting"); const creation = yield* folders .createNamedProject({ name: "Waiting", ...(registrationPath === "canonical" ? { parentPath: physicalParent } : {}), }) .pipe(Effect.forkChild); yield* Deferred.await(scaffolding); const caller = yield* Effect.forkChild( createExit === "cancellation" ? Fiber.interrupt(creation).pipe(Effect.andThen(Fiber.await(creation))) : Fiber.await(creation), { startImmediately: true }, ); yield* Deferred.await(removing); yield* TestClock.adjust("4999 millis"); assert.isUndefined(caller.pollUnsafe()); yield* TestClock.adjust("1 millis"); assert.isDefined(caller.pollUnsafe(), "the caller still waits after five seconds"); const originalExit = yield* Fiber.join(caller); if (createExit === "cancellation") { if (!Exit.isFailure(originalExit)) return assert.fail("Expected create to be interrupted"); assert.isTrue(Cause.hasInterruptsOnly(originalExit.cause)); } else { const failure = Option.getOrThrow(Exit.findErrorOption(originalExit)); assert.equal(failure._tag, "NamedProjectFolderError"); assert.equal(failure.message, "Failed to create the project folder."); assert.include(String(failure.cause), "init failed"); } // Taking a free lock finishes at once, so a pending probe means the removal holds it. const lockProbe = yield* projects .withWorkspaceLock(canonicalRoot, Effect.void) .pipe(Effect.forkChild({ startImmediately: true })); assert.isUndefined(lockProbe.pollUnsafe()); const waitingId = ProjectId.make("project:waiting"); const registration = yield* projects .create({ commandId: CommandId.make("command:register-waiting"), projectId: waitingId, title: "Waiting", workspaceRoot: registrationRoot, }) .pipe(Effect.exit, Effect.forkChild({ startImmediately: true })); const elsewhere = yield* projects.create({ commandId: CommandId.make("command:create-elsewhere"), projectId: ProjectId.make("project:elsewhere"), title: "Elsewhere", workspaceRoot: path.join(baseDir, "elsewhere"), createWorkspaceRootIfMissing: true, }); const updated = yield* projects.update({ commandId: CommandId.make("command:update-elsewhere"), projectId: elsewhere.id, title: "Still working", }); assert.equal(updated.title, "Still working"); assert.isUndefined(registration.pollUnsafe()); assert.deepEqual( (yield* projects.snapshot).projects.map((project) => project.id), [elsewhere.id], ); assert.isTrue(yield* fileSystem.exists(canonicalRoot)); yield* Deferred.succeed(finishRemove, undefined); yield* Fiber.join(lockProbe); const registered = yield* Fiber.join(registration); const laterCreate = projects.create({ commandId: CommandId.make("command:retry-registration"), projectId: ProjectId.make("project:retry"), title: "Retry registration", workspaceRoot: registrationRoot, createWorkspaceRootIfMissing: true, }); if (removeOutcome === "fails") { assert.equal((yield* registered).id, waitingId); const owner = yield* projects.getByWorkspaceRoot(registrationRoot); assert.equal(Option.getOrThrow(owner).id, waitingId); assert.isTrue(yield* fileSystem.exists(canonicalRoot)); assert.equal((yield* Effect.flip(laterCreate))._tag, "ProjectConflictError"); } else { const error = Option.getOrThrow(Exit.findErrorOption(registered)); assert.instanceOf(error, ProjectService.ProjectOperationError); assert.propertyVal(error, "operation", "dispatch-project-command"); assert.nestedPropertyVal(error, "cause.cause._tag", "WorkspaceRootNotExistsError"); assert.deepEqual( (yield* projects.snapshot).projects.map((project) => project.id), [elsewhere.id], ); assert.isFalse(yield* fileSystem.exists(canonicalRoot)); assert.equal((yield* laterCreate).workspaceRoot, registrationRoot); } }).pipe(Effect.ensuring(Deferred.succeed(finishRemove, undefined))), { fileSystem: (real) => ({ ...real, remove: (target, options) => /[/\\]waiting$/.test(target) ? Deferred.succeed(removing, undefined).pipe( Effect.andThen(Deferred.await(finishRemove)), Effect.andThen( removeOutcome === "fails" ? Effect.fail( PlatformError.systemError({ _tag: "PermissionDenied", module: "FileSystem", method: "remove", pathOrDescriptor: target, }), ) : real.remove(target, options), ), ) : real.remove(target, options), }), git: Layer.mock(GitVcsDriver.GitVcsDriver)({ readConfigValue: () => Effect.succeed(null), execute: ({ cwd, operation }) => Deferred.succeed(scaffolding, undefined).pipe( Effect.andThen( createExit === "cancellation" ? Effect.never : Effect.fail( new GitCommandError({ command: "git", cwd, operation, detail: "init failed", }), ), ), ), }), }, ); }), ); it.effect.each(["directory", "symlink"] as const)( "preserves a replacement %s when rolling back a cancelled create", (replacement) => Effect.gen(function* () { if (replacement === "symlink" && (yield* HostProcess.Platform) === "win32") return; const scaffolding = yield* Deferred.make(); yield* withScratch( ({ baseDir }) => Effect.gen(function* () { const folders = yield* ManagedProjectFolders.ManagedProjectFolders; const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const workspaceRoot = path.join(folders.namedProjectsRoot, "replaced"); const original = path.join(baseDir, "original"); const fiber = yield* folders .createNamedProject({ name: "Replaced" }) .pipe(Effect.forkChild); yield* Deferred.await(scaffolding); yield* fileSystem.rename(workspaceRoot, original); if (replacement === "symlink") { yield* fileSystem.symlink(original, workspaceRoot); } else { yield* fileSystem.makeDirectory(workspaceRoot); } const valuableFile = path.join(workspaceRoot, "keep.txt"); yield* fileSystem.writeFileString(valuableFile, "keep"); yield* Fiber.interrupt(fiber); assert.equal(yield* fileSystem.readFileString(valuableFile), "keep"); }), { git: Layer.mock(GitVcsDriver.GitVcsDriver)({ readConfigValue: () => Effect.succeed(null), execute: () => Deferred.succeed(scaffolding, undefined).pipe(Effect.andThen(Effect.never)), }), }, ); }), ); it.effect.each(["claiming", "scaffolding", "registering", "registered"] as const)( "rolls back a cancelled named project only if it has no owner (%s)", (stage) => Effect.gen(function* () { const reachedStage = yield* Deferred.make(); const finishClaim = yield* Deferred.make(); const pause = Deferred.succeed(reachedStage, undefined).pipe(Effect.andThen(Effect.never)); yield* withScratch( () => withGitEnv( TEST_IDENTITY, Effect.gen(function* () { const folders = yield* ManagedProjectFolders.ManagedProjectFolders; const projects = yield* ProjectService.ProjectService; const fileSystem = yield* FileSystem.FileSystem; const fiber = yield* folders .createNamedProject({ name: "Cancelled" }) .pipe(Effect.forkChild); yield* Deferred.await(reachedStage); assert.deepEqual(yield* fileSystem.readDirectory(folders.namedProjectsRoot), [ "cancelled", ]); const interruption = yield* Effect.forkChild(Fiber.interrupt(fiber), { startImmediately: true, }); yield* Deferred.succeed(finishClaim, undefined); yield* Fiber.join(interruption); const owned = stage === "registered"; assert.deepEqual( yield* fileSystem.readDirectory(folders.namedProjectsRoot), owned ? ["cancelled"] : [], ); assert.lengthOf((yield* projects.snapshot).projects, owned ? 1 : 0); }), ), stage === "claiming" ? { fileSystem: (real) => ({ ...real, lstat: (target) => /[/\\]cancelled$/.test(target) ? real .lstat(target) .pipe( Effect.tap(() => Deferred.succeed(reachedStage, undefined).pipe( Effect.andThen(Deferred.await(finishClaim)), ), ), ) : real.lstat(target), }), } : stage === "scaffolding" ? { git: Layer.mock(GitVcsDriver.GitVcsDriver)({ readConfigValue: () => Effect.succeed(null), execute: () => pause, }), } : { projects: (real) => ProjectService.ProjectService.of({ ...real, create: (input) => stage === "registering" ? pause : real.create(input).pipe(Effect.andThen(pause)), }), }, ); }), );