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