Open History to see the last commit
1/**
2 * KnownWorkspaces - the folders a client-named cwd may act in: a T3-managed
3 * worktree folder, a registered project, or a thread's worktree. Clients send
4 * the thread's worktree, else the project root. A client also sets a thread's
5 * worktree path, so one counts only under a managed folder or when git lists
6 * it as a worktree of the thread's project.
7 *
8 * @module KnownWorkspaces
9 */
10import * as HostProcess from "@t3tools/shared/HostProcess";
11import * as Context from "effect/Context";
12import * as Effect from "effect/Effect";
13import * as FileSystem from "effect/FileSystem";
14import * as Layer from "effect/Layer";
15import * as Path from "effect/Path";
16import * as Schema from "effect/Schema";
17import * as SqlClient from "effect/sql/SqlClient";
18
19import * as ServerConfig from "../config.ts";
20import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";
21import * as ServerSettings from "../serverSettings.ts";
22import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
23import { isFilesystemRoot, managedWorktreesDirectories } from "../worktreesDirectory.ts";
24
25export class UnknownWorkspaceError extends Schema.TaggedError<UnknownWorkspaceError>()(
26 "UnknownWorkspaceError",
27 {
28 cwd: Schema.String,
29 cause: Schema.optional(Schema.Defect()),
30 },
31) {
32 override get message(): string {
33 return `'${this.cwd}' is not a registered project, a managed worktree, or a thread's worktree.`;
34 }
35}
36
37/** Whether `candidate` is `root` or inside it. Resolve both the same way first. */
38export const isWithinRoot = (path: Path.Path, candidate: string, root: string) => {
39 const relative = path.relative(root, candidate);
40 return (
41 relative === "" ||
42 (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
43 );
44};
45
46export class KnownWorkspaces extends Context.Service<
47 KnownWorkspaces,
48 {
49 /** Whether a symlink-resolved path is inside a known workspace. */
50 readonly contains: (realPath: string) => Effect.Effect<boolean>;
51 /** Fails unless `cwd` exists and resolves inside a known workspace. */
52 readonly assertContains: (cwd: string) => Effect.Effect<void, UnknownWorkspaceError>;
53 }
54>()("t3/workspace/KnownWorkspaces") {}
55
56/** @public Service construction is part of the canonical Effect module API. */
57export const make = Effect.gen(function* () {
58 const config = yield* ServerConfig.ServerConfig;
59 const fileSystem = yield* FileSystem.FileSystem;
60 const path = yield* Path.Path;
61 const settings = yield* ServerSettings.ServerSettingsService;
62 const projectStore = yield* ProjectStore.ProjectStoreV2;
63 const sql = yield* SqlClient.SqlClient;
64 const git = yield* GitVcsDriver.GitVcsDriver;
65
66 // A root that does not exist yet keeps its lexical path. One that cannot be
67 // resolved for another reason, or resolves to a filesystem root, grants nothing.
68 const resolveRoot = (value: string) => {
69 const resolvedPath = path.resolve(value);
70 return fileSystem.realPath(resolvedPath).pipe(
71 Effect.catchTags({
72 PlatformError: (cause) =>
73 Effect.succeed(cause.reason._tag === "NotFound" ? resolvedPath : null),
74 }),
75 Effect.map((root) => (root === null || isFilesystemRoot(root, path) ? null : root)),
76 );
77 };
78
79 const contains: KnownWorkspaces["Service"]["contains"] = Effect.fn("KnownWorkspaces.contains")(
80 function* (realPath) {
81 const within = (root: string | null) => root !== null && isWithinRoot(path, realPath, root);
82 const worktreeSettings = yield* settings.getSettings.pipe(
83 Effect.orElseSucceed(() => ({ worktreesDirectory: "", previousWorktreesDirectories: [] })),
84 );
85 const home = yield* HostProcess.HomeDirectory;
86 const managedDirectories = managedWorktreesDirectories(
87 worktreeSettings,
88 config.worktreesDir,
89 path,
90 home,
91 );
92 const managed = (yield* Effect.forEach(managedDirectories, resolveRoot)).filter(
93 (root) => root !== null,
94 );
95 if (managed.some(within)) return true;
96
97 const projects = yield* projectStore.listShells().pipe(Effect.orElseSucceed(() => []));
98 for (const project of projects) {
99 if (within(yield* resolveRoot(project.workspaceRoot))) return true;
100 }
101
102 const threads = yield* sql<{ readonly worktreePath: string; readonly projectId: string }>`
103 SELECT DISTINCT
104 json_extract(payload_json, '$.worktreePath') AS "worktreePath",
105 project_id AS "projectId"
106 FROM orchestration_v2_projection_threads
107 WHERE deleted_at IS NULL AND json_extract(payload_json, '$.worktreePath') IS NOT NULL
108 `.pipe(Effect.orElseSucceed(() => []));
109 const projectWorktrees = new Map<string, ReadonlyArray<string>>();
110 const isProjectWorktree = Effect.fnUntraced(function* (
111 projectId: string,
112 worktreePath: string,
113 ) {
114 const project = projects.find((candidate) => candidate.id === projectId);
115 if (project === undefined) return false;
116 let listed = projectWorktrees.get(projectId);
117 if (listed === undefined) {
118 listed = yield* git.listWorktreePaths(project.workspaceRoot).pipe(
119 Effect.flatMap((paths) => Effect.forEach(paths, resolveRoot)),
120 Effect.map((paths) => paths.filter((listedPath) => listedPath !== null)),
121 Effect.orElseSucceed((): ReadonlyArray<string> => []),
122 );
123 projectWorktrees.set(projectId, listed);
124 }
125 const real = yield* resolveRoot(worktreePath);
126 return real !== null && listed.includes(real);
127 });
128 for (const { worktreePath, projectId } of threads) {
129 // A relative path would resolve against the server's own cwd. One under a
130 // managed folder is still resolved: it can be a symlink to a checkout elsewhere.
131 if (!path.isAbsolute(worktreePath)) continue;
132 if (!within(yield* resolveRoot(worktreePath))) continue;
133 const lexical = path.resolve(worktreePath);
134 if (managedDirectories.some((directory) => isWithinRoot(path, lexical, directory))) {
135 return true;
136 }
137 if (yield* isProjectWorktree(projectId, worktreePath)) return true;
138 }
139 return false;
140 },
141 );
142
143 const assertContains: KnownWorkspaces["Service"]["assertContains"] = Effect.fn(
144 "KnownWorkspaces.assertContains",
145 )(function* (cwd) {
146 // `..` collapses on the path as named before symlinks resolve, as the write does.
147 const realCwd = yield* fileSystem
148 .realPath(path.resolve(cwd))
149 .pipe(Effect.mapError((cause) => new UnknownWorkspaceError({ cwd, cause })));
150 if (!(yield* contains(realCwd))) return yield* new UnknownWorkspaceError({ cwd });
151 });
152
153 return KnownWorkspaces.of({ contains, assertContains });
154});
155
156export const layer = Layer.effect(KnownWorkspaces, make);