Open History to see the last commit
1import {
2 PROJECT_TRACKED_FOLDERS_MAX,
3 type ProjectId,
4 type ProjectTrackedFolder,
5 type WorkspaceFolder,
6 WorkspaceFoldersError,
7 type WorkspaceListFoldersInput,
8 type WorkspaceListFoldersResult,
9 type WorkspaceScanFoldersInput,
10 type WorkspaceScanFoldersResult,
11} from "@t3tools/contracts";
12import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
13import * as HostProcess from "@t3tools/shared/HostProcess";
14import { fromLenientJson } from "@t3tools/shared/schemaJson";
15import * as Context from "effect/Context";
16import * as Effect from "effect/Effect";
17import * as FileSystem from "effect/FileSystem";
18import * as Layer from "effect/Layer";
19import * as Option from "effect/Option";
20import * as Path from "effect/Path";
21import * as Schema from "effect/Schema";
22
23import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";
24import { isWithinRoot } from "./KnownWorkspaces.ts";
25
26/** A tracked folder a thread works in, besides its own cwd. */
27export interface ThreadFolder {
28 readonly name: string;
29 readonly path: string;
30 readonly isGitRepository: boolean;
31}
32
33export interface ThreadWorkspace {
34 readonly folders: ReadonlyArray<ThreadFolder>;
35 /** Paths of the folders outside the thread's cwd, which an agent needs granted to reach. */
36 readonly extraRoots: ReadonlyArray<string>;
37}
38
39const EMPTY_WORKSPACE: ThreadWorkspace = { folders: [], extraRoots: [] };
40
41export class WorkspaceFolders extends Context.Service<
42 WorkspaceFolders,
43 {
44 /**
45 * The tracked folders a thread reaches. A thread in its own worktree reaches none: the
46 * project's checkouts are shared, and the worktree is what isolates the thread.
47 */
48 readonly forThread: (input: {
49 readonly projectId: ProjectId;
50 readonly worktreePath: string | null;
51 }) => Effect.Effect<ThreadWorkspace, WorkspaceFoldersError>;
52 readonly list: (
53 input: WorkspaceListFoldersInput,
54 ) => Effect.Effect<WorkspaceListFoldersResult, WorkspaceFoldersError>;
55 readonly scan: (
56 input: WorkspaceScanFoldersInput,
57 ) => Effect.Effect<WorkspaceScanFoldersResult, WorkspaceFoldersError>;
58 }
59>()("t3/workspace/WorkspaceFolders") {}
60
61const DETECTION_CONCURRENCY = 8;
62const CODE_WORKSPACE_EXTENSION = ".code-workspace";
63
64const decodeCodeWorkspace = Schema.decodeUnknownEffect(
65 fromLenientJson(
66 Schema.Struct({
67 folders: Schema.optional(
68 Schema.Array(
69 Schema.Struct({
70 path: Schema.optional(Schema.String),
71 name: Schema.optional(Schema.String),
72 }),
73 ),
74 ),
75 }),
76 ),
77);
78
79/** Submodule paths a `.gitmodules` file declares, relative to its folder with `/` separators. */
80const parseGitmodulesPaths = (text: string): ReadonlyArray<string> =>
81 text.split(/\r?\n/).flatMap((line) => {
82 const value = /^\s*path\s*=\s*(.*?)\s*$/.exec(line)?.[1];
83 if (value === undefined) return [];
84 const normalized = value.replaceAll('"', "").replaceAll("\\", "/").replace(/\/+$/, "");
85 return normalized === "" ? [] : [normalized];
86 });
87
88// Built once per operation: the probes share the caller's file system and path services.
89const folderProbes = Effect.gen(function* () {
90 const fileSystem = yield* FileSystem.FileSystem;
91 const path = yield* Path.Path;
92
93 const exists = (target: string) =>
94 fileSystem.exists(target).pipe(Effect.orElseSucceed(() => false));
95
96 // Sandboxes and containment checks work on what a path resolves to, not on a symlink's name.
97 const realPath = (target: string) =>
98 fileSystem.realPath(target).pipe(Effect.orElseSucceed(() => target));
99
100 // A repository is a folder with its own `.git`; a folder deeper inside one is plain files.
101 // Untraced: it runs once per folder inside the calling operation's span.
102 const classify = Effect.fnUntraced(function* (
103 folder: ProjectTrackedFolder,
104 ): Effect.fn.Return<WorkspaceFolder> {
105 if (yield* exists(path.join(folder.path, ".git"))) return { ...folder, state: "git" };
106 return { ...folder, state: (yield* exists(folder.path)) ? "plain" : "missing" };
107 });
108
109 return { exists, realPath, classify };
110});
111
112const readCodeWorkspaceFolders = Effect.fn("WorkspaceFolders.readCodeWorkspaceFolders")(function* (
113 root: string,
114 fileName: string,
115) {
116 const fileSystem = yield* FileSystem.FileSystem;
117 const path = yield* Path.Path;
118 const document = yield* fileSystem
119 .readFileString(path.join(root, fileName))
120 .pipe(Effect.flatMap(decodeCodeWorkspace), Effect.option);
121 if (Option.isNone(document)) return null;
122 return (document.value.folders ?? []).flatMap((folder) => {
123 const folderPath = folder.path?.trim();
124 if (folderPath === undefined || folderPath === "") return [];
125 const resolved = path.resolve(root, folderPath);
126 return [{ path: resolved, name: folder.name?.trim() || path.basename(resolved) }];
127 });
128});
129
130/**
131 * Finds the folders worth tracking beside `workspaceRoot`. Exported for the CLI, which scans in
132 * its own process: it runs on the server's machine and may have no server to ask.
133 */
134export const scanFolders = Effect.fn("WorkspaceFolders.scan")(function* (
135 input: WorkspaceScanFoldersInput,
136): Effect.fn.Return<
137 WorkspaceScanFoldersResult,
138 WorkspaceFoldersError,
139 FileSystem.FileSystem | Path.Path
140> {
141 const fileSystem = yield* FileSystem.FileSystem;
142 const path = yield* Path.Path;
143 const { exists, realPath, classify } = yield* folderProbes;
144 const root = path.resolve(
145 expandHomePath(input.workspaceRoot.trim(), yield* HostProcess.HomeDirectory),
146 );
147 const names = (yield* fileSystem
148 .readDirectory(root)
149 .pipe(
150 Effect.mapError(
151 () => new WorkspaceFoldersError({ operation: "scan", detail: `Could not read ${root}.` }),
152 ),
153 )).toSorted();
154 const codeWorkspaceFile = names.find((name) => name.endsWith(CODE_WORKSPACE_EXTENSION)) ?? null;
155 const listed =
156 codeWorkspaceFile === null ? null : yield* readCodeWorkspaceFolders(root, codeWorkspaceFile);
157 const children = yield* Effect.forEach(
158 names.filter((name) => !name.startsWith(".") && name !== "node_modules"),
159 (name) => {
160 const folderPath = path.join(root, name);
161 return exists(path.join(folderPath, ".git")).pipe(
162 Effect.map((isRepository) => (isRepository ? [{ path: folderPath, name }] : [])),
163 );
164 },
165 { concurrency: DETECTION_CONCURRENCY },
166 );
167 const submodules = new Set(
168 parseGitmodulesPaths(
169 yield* fileSystem
170 .readFileString(path.join(root, ".gitmodules"))
171 .pipe(Effect.orElseSucceed(() => "")),
172 ),
173 );
174 const realRoot = yield* realPath(root);
175 const resolved = yield* Effect.forEach(
176 [
177 ...(listed ?? []).map((folder) => ({ ...folder, source: "code-workspace" as const })),
178 ...children.flat().map((folder) => ({ ...folder, source: "child" as const })),
179 ],
180 (folder) => realPath(folder.path).pipe(Effect.map((real) => ({ folder, real }))),
181 { concurrency: DETECTION_CONCURRENCY },
182 );
183 const seen = new Set<string>();
184 const candidates = resolved.flatMap(({ folder, real }) => {
185 // The scanned folder and its parents are never tracked, however a symlink names them.
186 if (seen.has(real) || isWithinRoot(path, realRoot, real)) return [];
187 seen.add(real);
188 // Submodules follow their parent repository.
189 return submodules.has(path.relative(root, folder.path).split(path.sep).join("/"))
190 ? []
191 : [folder];
192 });
193 const folders = yield* Effect.forEach(
194 candidates.slice(0, PROJECT_TRACKED_FOLDERS_MAX),
195 (folder) =>
196 classify(folder).pipe(
197 Effect.map((classified) =>
198 classified.state === "missing"
199 ? []
200 : [{ ...folder, isGitRepository: classified.state === "git" }],
201 ),
202 ),
203 { concurrency: DETECTION_CONCURRENCY },
204 );
205 return {
206 workspaceRoot: root,
207 isGitRepository: yield* exists(path.join(root, ".git")),
208 codeWorkspaceFile:
209 listed === null || codeWorkspaceFile === null ? null : path.join(root, codeWorkspaceFile),
210 folders: folders.flat(),
211 };
212});
213
214const make = Effect.gen(function* () {
215 const fileSystem = yield* FileSystem.FileSystem;
216 const path = yield* Path.Path;
217 const projects = yield* ProjectStore.ProjectStoreV2;
218
219 const { realPath, classify } = yield* folderProbes;
220
221 const readProject = Effect.fn("WorkspaceFolders.readProject")(function* (projectId: ProjectId) {
222 const row = yield* projects
223 .get(projectId)
224 .pipe(
225 Effect.mapError(
226 () => new WorkspaceFoldersError({ operation: "list", detail: "Failed to read project." }),
227 ),
228 );
229 if (Option.isNone(row)) {
230 return yield* new WorkspaceFoldersError({
231 operation: "list",
232 detail: `Project ${projectId} was not found.`,
233 });
234 }
235 return row.value;
236 });
237
238 const classifyAll = (folders: ReadonlyArray<ProjectTrackedFolder>) =>
239 Effect.forEach(folders, classify, { concurrency: DETECTION_CONCURRENCY });
240
241 const forThread: WorkspaceFolders["Service"]["forThread"] = Effect.fn(
242 "WorkspaceFolders.forThread",
243 )(function* (input) {
244 if (input.worktreePath !== null) return EMPTY_WORKSPACE;
245 const project = yield* readProject(input.projectId);
246 if (project.trackedFolders.length === 0) return EMPTY_WORKSPACE;
247 const folders = (yield* classifyAll(project.trackedFolders)).flatMap((folder) =>
248 folder.state === "missing"
249 ? []
250 : [{ name: folder.name, path: folder.path, isGitRepository: folder.state === "git" }],
251 );
252 const projectRoot = yield* realPath(project.workspaceRoot);
253 // Both spellings are granted: agents are told the stored path, sandboxes check the real one.
254 const outside = yield* Effect.forEach(
255 folders,
256 (folder) =>
257 realPath(folder.path).pipe(
258 Effect.map((real) => (isWithinRoot(path, real, projectRoot) ? [] : [folder.path, real])),
259 ),
260 { concurrency: DETECTION_CONCURRENCY },
261 );
262 return { folders, extraRoots: [...new Set(outside.flat())] };
263 });
264
265 const list: WorkspaceFolders["Service"]["list"] = Effect.fn("WorkspaceFolders.list")(
266 function* (input) {
267 return { folders: yield* classifyAll((yield* readProject(input.projectId)).trackedFolders) };
268 },
269 );
270
271 const scan: WorkspaceFolders["Service"]["scan"] = (input) =>
272 scanFolders(input).pipe(
273 Effect.provideService(FileSystem.FileSystem, fileSystem),
274 Effect.provideService(Path.Path, path),
275 );
276
277 return WorkspaceFolders.of({ forThread, list, scan });
278});
279
280export const layer = Layer.effect(WorkspaceFolders, make);