Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

WorkspaceFolders.ts

545 lines21.3 KB

1import {
2 PROJECT_TRACKED_FOLDERS_MAX,
3 type ProjectId,
4 type ProjectTrackedFolder,
5 type TaskFolder,
6 type WorkspaceFolder,
7 WorkspaceFoldersError,
8 type WorkspaceListFoldersInput,
9 type WorkspaceListFoldersResult,
10 type WorkspaceScanFoldersInput,
11 type WorkspaceScanFoldersResult,
12} from "@t3tools/contracts";
13import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
14import * as HostProcess from "@t3tools/shared/HostProcess";
15import { fromLenientJson } from "@t3tools/shared/schemaJson";
16import { T3_PROJECT_FILE_NAME } from "@t3tools/contracts";
17import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile";
18import * as Context from "effect/Context";
19import * as Effect from "effect/Effect";
20import * as FileSystem from "effect/FileSystem";
21import * as Layer from "effect/Layer";
22import * as Option from "effect/Option";
23import * as Path from "effect/Path";
24import * as Schema from "effect/Schema";
25​
26import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";
27import { isWithinRoot } from "./KnownWorkspaces.ts";
28import * as TaskFolderStore from "./TaskFolderStore.ts";
29​
30/** A tracked folder a thread works in, besides its own cwd. */
31export interface ThreadFolder {
32 readonly name: string;
33 readonly path: string;
34 readonly isGitRepository: boolean;
35 /** The folder `path` is a checkout of. Absent when `path` is that folder. */
36 readonly repositoryPath?: string;
38​
39export interface ThreadWorkspace {
40 readonly folders: ReadonlyArray<ThreadFolder>;
41 /** Paths of the folders outside the thread's cwd, which an agent needs granted to reach. */
42 readonly extraRoots: ReadonlyArray<string>;
44​
45const EMPTY_WORKSPACE: ThreadWorkspace = { folders: [], extraRoots: [] };
46// Each one costs a status per turn.
47const THREAD_SUBMODULES_MAX = 32;
48​
49export class WorkspaceFolders extends Context.Service<
50 WorkspaceFolders,
51 {
52 /**
53 * The tracked folders a thread reaches. A thread in a task folder reaches that folder's
54 * worktrees; one in a single worktree reaches none, since the project's checkouts are shared.
55 */
56 readonly forThread: (input: {
57 readonly projectId: ProjectId;
58 readonly worktreePath: string | null;
59 }) => Effect.Effect<ThreadWorkspace, WorkspaceFoldersError>;
60 /**
61 * Submodules checked out inside the thread's cwd or its folders. Their repository owns how
62 * they get there, so they are reviewed like the folders but never granted or announced.
63 */
64 readonly submodules: (input: {
65 readonly projectId: ProjectId;
66 readonly worktreePath: string | null;
67 }) => Effect.Effect<ReadonlyArray<ThreadFolder>, WorkspaceFoldersError>;
68 readonly list: (
69 input: WorkspaceListFoldersInput,
70 ) => Effect.Effect<WorkspaceListFoldersResult, WorkspaceFoldersError>;
71 readonly scan: (
72 input: WorkspaceScanFoldersInput,
73 ) => Effect.Effect<WorkspaceScanFoldersResult, WorkspaceFoldersError>;
74 }
75>()("t3/workspace/WorkspaceFolders") {}
76​
77const DETECTION_CONCURRENCY = 8;
78// What `ProjectTrackedFolder.name` allows.
79const FOLDER_NAME_MAX = 128;
80const boundedName = (name: string) => name.slice(0, FOLDER_NAME_MAX).trim();
81const CODE_WORKSPACE_EXTENSION = ".code-workspace";
82​
83const decodeCodeWorkspace = Schema.decodeUnknownEffect(
84 fromLenientJson(
85 Schema.Struct({
86 folders: Schema.optional(
87 Schema.Array(
88 Schema.Struct({
89 path: Schema.optional(Schema.String),
90 name: Schema.optional(Schema.String),
91 }),
92 ),
93 ),
94 }),
95 ),
96);
97​
98/** Submodule paths a `.gitmodules` file declares, relative to its folder with `/` separators. */
99export const parseGitmodulesPaths = (text: string): ReadonlyArray<string> =>
100 text.split(/\r?\n/).flatMap((line) => {
101 const value = /^\s*path\s*=\s*(.*?)\s*$/.exec(line)?.[1];
102 if (value === undefined) return [];
103 const normalized = value.replaceAll('"', "").replaceAll("\\", "/").replace(/\/+$/, "");
104 return normalized === "" ? [] : [normalized];
105 });
106​
107// Built once per operation: the probes share the caller's file system and path services.
108const folderProbes = Effect.gen(function* () {
109 const fileSystem = yield* FileSystem.FileSystem;
110 const path = yield* Path.Path;
111​
112 const exists = (target: string) =>
113 fileSystem.exists(target).pipe(Effect.orElseSucceed(() => false));
114​
115 // Sandboxes and containment checks work on what a path resolves to, not on a symlink's name.
116 const realPath = (target: string) =>
117 fileSystem.realPath(target).pipe(Effect.orElseSucceed(() => target));
118​
119 // A repository is a folder with its own `.git`; a folder deeper inside one is plain files.
120 // Untraced: it runs once per folder inside the calling operation's span.
121 const classify = Effect.fnUntraced(function* (
122 folder: ProjectTrackedFolder,
123 ): Effect.fn.Return<WorkspaceFolder> {
124 if (yield* exists(path.join(folder.path, ".git"))) return { ...folder, state: "git" };
125 return { ...folder, state: (yield* exists(folder.path)) ? "plain" : "missing" };
126 });
127​
128 // A linked worktree and a submodule keep `.git` as a file; both follow another repository.
129 const ownsHistory = (folder: string) =>
130 fileSystem.stat(path.join(folder, ".git")).pipe(
131 Effect.map((info) => info.type === "Directory"),
132 Effect.orElseSucceed(() => false),
133 );
134​
135 const childFolders = (folder: string) =>
136 fileSystem.readDirectory(folder).pipe(
137 Effect.orElseSucceed((): ReadonlyArray<string> => []),
138 Effect.map((names) =>
139 names
140 .filter((name) => !name.startsWith(".") && name !== "node_modules")
141 .toSorted()
142 .map((name) => path.join(folder, name)),
143 ),
144 );
145​
146 return { exists, realPath, classify, ownsHistory, childFolders };
147});
148​
149const readCodeWorkspaceFolders = Effect.fn("WorkspaceFolders.readCodeWorkspaceFolders")(function* (
150 root: string,
151 fileName: string,
152) {
153 const fileSystem = yield* FileSystem.FileSystem;
154 const path = yield* Path.Path;
155 const document = yield* fileSystem
156 .readFileString(path.join(root, fileName))
157 .pipe(Effect.flatMap(decodeCodeWorkspace), Effect.option);
158 if (Option.isNone(document)) return null;
159 return (document.value.folders ?? []).flatMap((folder) => {
160 const folderPath = folder.path?.trim();
161 if (folderPath === undefined || folderPath === "") return [];
162 const resolved = path.resolve(root, folderPath);
163 return [
164 {
165 path: resolved,
166 name: boundedName(folder.name?.trim() ?? "") || boundedName(path.basename(resolved)),
167 },
168 ];
169 });
170});
171​
172/**
173 * Finds the repositories under `workspaceRoot` and the folders its `.code-workspace` file lists.
174 */
175const scanFolders = Effect.fn("WorkspaceFolders.scan")(function* (
176 input: WorkspaceScanFoldersInput,
177 limit: number = PROJECT_TRACKED_FOLDERS_MAX,
178): Effect.fn.Return<
179 WorkspaceScanFoldersResult,
180 WorkspaceFoldersError,
181 FileSystem.FileSystem | Path.Path
182> {
183 const fileSystem = yield* FileSystem.FileSystem;
184 const path = yield* Path.Path;
185 const { exists, realPath, classify, ownsHistory, childFolders } = yield* folderProbes;
186 const root = path.resolve(
187 expandHomePath(input.workspaceRoot.trim(), yield* HostProcess.HomeDirectory),
188 );
189 const names = (yield* fileSystem
190 .readDirectory(root)
191 .pipe(
192 Effect.mapError(
193 () => new WorkspaceFoldersError({ operation: "scan", detail: `Could not read ${root}.` }),
194 ),
195 )).toSorted();
196 const codeWorkspaceFile = names.find((name) => name.endsWith(CODE_WORKSPACE_EXTENSION)) ?? null;
197 const listed =
198 codeWorkspaceFile === null ? null : yield* readCodeWorkspaceFolders(root, codeWorkspaceFile);
199 // A worktree of another repository is that repository's, so only folders with their own
200 // history are offered. A plain child is looked into once: wrappers keep repositories under
201 // folders such as `src` or `packages`.
202 const children = yield* Effect.forEach(
203 names.filter((name) => !name.startsWith(".") && name !== "node_modules"),
204 (name) => {
205 const folderPath = path.join(root, name);
206 return Effect.gen(function* () {
207 if (yield* ownsHistory(folderPath)) return [{ path: folderPath, name: boundedName(name) }];
208 if (yield* exists(path.join(folderPath, ".git"))) return [];
209 const nested = yield* Effect.filter(yield* childFolders(folderPath), ownsHistory, {
210 concurrency: DETECTION_CONCURRENCY,
211 });
212 return nested.map((nestedPath) => ({
213 path: nestedPath,
214 name: boundedName(path.basename(nestedPath)),
215 }));
216 });
217 },
218 { concurrency: DETECTION_CONCURRENCY },
219 );
220 const submodules = new Set(
221 parseGitmodulesPaths(
222 yield* fileSystem
223 .readFileString(path.join(root, ".gitmodules"))
224 .pipe(Effect.orElseSucceed(() => "")),
225 ),
226 );
227 const realRoot = yield* realPath(root);
228 const resolved = yield* Effect.forEach(
229 [
230 ...(listed ?? []).map((folder) => ({ ...folder, source: "code-workspace" as const })),
231 ...children.flat().map((folder) => ({ ...folder, source: "child" as const })),
232 ],
233 (folder) => realPath(folder.path).pipe(Effect.map((real) => ({ folder, real }))),
234 { concurrency: DETECTION_CONCURRENCY },
235 );
236 const seen = new Set<string>();
237 const candidates = resolved.flatMap(({ folder, real }) => {
238 // The scanned folder and its parents are never tracked, however a symlink names them.
239 if (seen.has(real) || isWithinRoot(path, realRoot, real)) return [];
240 seen.add(real);
241 // Submodules follow their parent repository.
242 return submodules.has(path.relative(root, folder.path).split(path.sep).join("/"))
243 ? []
244 : [folder];
245 });
246 // Capped after the missing ones are dropped: dead entries must not hide the folders that exist.
247 const folders = yield* Effect.forEach(
248 candidates,
249 (folder) =>
250 classify(folder).pipe(
251 Effect.map((classified) =>
252 classified.state === "missing"
253 ? []
254 : [{ ...folder, isGitRepository: classified.state === "git" }],
255 ),
256 ),
257 { concurrency: DETECTION_CONCURRENCY },
258 );
259 return {
260 workspaceRoot: root,
261 isGitRepository: yield* exists(path.join(root, ".git")),
262 codeWorkspaceFile:
263 listed === null || codeWorkspaceFile === null ? null : path.join(root, codeWorkspaceFile),
264 folders: folders.flat().slice(0, limit),
265 };
266});
267​
268/**
269 * The repositories inside a project folder, read from disk: the ones a scan finds there, less
270 * those the project's `t3.json` leaves out. A folder outside it is never found this way, since
271 * tracking one grants agents a place they could not reach before.
272 */
273export const discoverFolders = Effect.fn("WorkspaceFolders.discover")(function* (
274 workspaceRoot: string,
275): Effect.fn.Return<ReadonlyArray<ProjectTrackedFolder>, never, FileSystem.FileSystem | Path.Path> {
276 const fileSystem = yield* FileSystem.FileSystem;
277 const path = yield* Path.Path;
278 const { realPath, ownsHistory } = yield* folderProbes;
279 // Uncapped: the folders outside the project are dropped below, and must not use up the room.
280 const scan = yield* scanFolders({ workspaceRoot }, Number.POSITIVE_INFINITY).pipe(Effect.option);
281 if (Option.isNone(scan)) return [];
282 const root = scan.value.workspaceRoot;
283 const realRoot = yield* realPath(root);
284 const ignored = (
285 parseT3ProjectFile(
286 yield* fileSystem
287 .readFileString(path.join(root, T3_PROJECT_FILE_NAME))
288 .pipe(Effect.orElseSucceed(() => "")),
289 )?.ignoreRepositories ?? []
290 ).map((entry) => path.resolve(root, entry));
291 const inside = yield* Effect.filter(
292 scan.value.folders.filter(
293 (folder) =>
294 folder.isGitRepository &&
295 !ignored.some((entry) => folder.path === entry || isWithinRoot(path, folder.path, entry)),
296 ),
297 // A link to a repository elsewhere is not inside the project, whatever its name says, and a
298 // worktree a workspace file lists follows another repository.
299 (folder) =>
300 Effect.all([realPath(folder.path), ownsHistory(folder.path)]).pipe(
301 Effect.map(
302 ([real, owns]) => owns && real !== realRoot && isWithinRoot(path, real, realRoot),
303 ),
304 ),
305 { concurrency: DETECTION_CONCURRENCY },
306 );
307 return inside.map((folder) => ({ path: folder.path, name: folder.name, discovered: true }));
308});
309​
310/**
311 * The found repositories, then the folders someone added. Someone chose the added ones, so the
312 * found ones give way when both do not fit.
313 */
314export const mergeProjectFolders = (
315 discovered: ReadonlyArray<ProjectTrackedFolder>,
316 trackedFolders: ReadonlyArray<ProjectTrackedFolder>,
317): ReadonlyArray<ProjectTrackedFolder> => {
318 const found = new Set(discovered.map((folder) => folder.path));
319 const added = trackedFolders
320 .filter((folder) => folder.discovered !== true && !found.has(folder.path))
321 .slice(0, PROJECT_TRACKED_FOLDERS_MAX);
322 return [...discovered.slice(0, PROJECT_TRACKED_FOLDERS_MAX - added.length), ...added];
323};
324​
325/**
326 * Every folder a project works in besides its own: the repositories found inside it now, then
327 * the folders someone added. Read from disk each time, so a clone or a removal shows at once.
328 */
329export const projectFolders = Effect.fn("WorkspaceFolders.projectFolders")(function* (project: {
330 readonly workspaceRoot: string;
331 readonly trackedFolders: ReadonlyArray<ProjectTrackedFolder>;
332}): Effect.fn.Return<
333 ReadonlyArray<ProjectTrackedFolder>,
334 never,
335 FileSystem.FileSystem | Path.Path
336> {
337 return mergeProjectFolders(yield* discoverFolders(project.workspaceRoot), project.trackedFolders);
338});
339​
340/** Whether two tracked lists name the same folders in the same order. */
341export const sameProjectFolders = (
342 left: ReadonlyArray<ProjectTrackedFolder>,
343 right: ReadonlyArray<ProjectTrackedFolder>,
344) =>
345 left.length === right.length &&
346 left.every((folder, index) => {
347 const other = right[index]!;
348 return (
349 folder.path === other.path &&
350 folder.name === other.name &&
351 (folder.discovered === true) === (other.discovered === true)
352 );
353 });
354​
355const make = Effect.gen(function* () {
356 const fileSystem = yield* FileSystem.FileSystem;
357 const path = yield* Path.Path;
358 const projects = yield* ProjectStore.ProjectStoreV2;
359 const taskFolders = yield* TaskFolderStore.TaskFolderStore;
360​
361 const { exists, realPath, classify } = yield* folderProbes;
362​
363 const readProject = Effect.fn("WorkspaceFolders.readProject")(function* (projectId: ProjectId) {
364 const row = yield* projects
365 .get(projectId)
366 .pipe(
367 Effect.mapError(
368 () => new WorkspaceFoldersError({ operation: "list", detail: "Failed to read project." }),
369 ),
370 );
371 if (Option.isNone(row)) {
372 return yield* new WorkspaceFoldersError({
373 operation: "list",
374 detail: `Project ${projectId} was not found.`,
375 });
376 }
377 return row.value;
378 });
379​
380 const classifyAll = (folders: ReadonlyArray<ProjectTrackedFolder>) =>
381 Effect.forEach(folders, classify, { concurrency: DETECTION_CONCURRENCY });
382 const foldersOf = (project: {
383 readonly workspaceRoot: string;
384 readonly trackedFolders: ReadonlyArray<ProjectTrackedFolder>;
385 }) =>
386 projectFolders(project).pipe(
387 Effect.provideService(FileSystem.FileSystem, fileSystem),
388 Effect.provideService(Path.Path, path),
389 );
390​
391 // `identity` is `root` in the checkout the thread's was made from: it names the same submodule
392 // in every worktree. `budget` is shared by one listing: a `.gitmodules` file is untrusted, and
393 // one that repeats a path or links back to its parent would otherwise be walked without end.
394 const submodulesBelow = (
395 root: { readonly path: string; readonly identity: string },
396 budget: { left: number; readonly visited: Set<string> },
397 ): Effect.Effect<ReadonlyArray<ThreadFolder>> =>
398 fileSystem.readFileString(path.join(root.path, ".gitmodules")).pipe(
399 Effect.orElseSucceed(() => ""),
400 Effect.flatMap((text) =>
401 Effect.forEach(
402 [...new Set(parseGitmodulesPaths(text))],
403 Effect.fnUntraced(function* (relative) {
404 const folder = path.resolve(root.path, relative);
405 const identity = path.resolve(root.identity, relative);
406 if (folder === root.path || !isWithinRoot(path, folder, root.path)) return [];
407 // One that was never initialized is an empty folder.
408 if (budget.left <= 0 || !(yield* exists(path.join(folder, ".git")))) return [];
409 const real = yield* realPath(folder);
410 // A committed symlink on the way must not lead the thread out of its repository.
411 if (!isWithinRoot(path, real, yield* realPath(root.path))) return [];
412 if (budget.left <= 0 || budget.visited.has(real)) return [];
413 budget.visited.add(real);
414 budget.left -= 1;
415 return [
416 {
417 name: path.basename(folder),
418 path: folder,
419 isGitRepository: true,
420 ...(identity === folder ? {} : { repositoryPath: identity }),
421 },
422 ...(yield* submodulesBelow({ path: folder, identity }, budget)),
423 ];
424 }),
425 { concurrency: DETECTION_CONCURRENCY },
426 ),
427 ),
428 Effect.map((found) => found.flat()),
429 );
430​
431 const submodulesOf = Effect.fnUntraced(function* (
432 roots: ReadonlyArray<{ readonly path: string; readonly identity: string }>,
433 ) {
434 const budget = {
435 left: THREAD_SUBMODULES_MAX,
436 visited: new Set(
437 yield* Effect.forEach(roots, (root) => realPath(root.path), {
438 concurrency: DETECTION_CONCURRENCY,
439 }),
440 ),
441 };
442 const found = yield* Effect.forEach(roots, (root) => submodulesBelow(root, budget), {
443 concurrency: DETECTION_CONCURRENCY,
444 });
445 const taken = new Set(roots.map((root) => root.path));
446 return found.flat().filter((folder) => !taken.has(folder.path));
447 });
448​
449 // A task folder's worktrees stand in for the tracked folders: the thread is told about, granted
450 // and checkpoints only those, never the checkouts they were made from.
451 const forTaskFolder = Effect.fnUntraced(function* (worktreePath: string, taskFolder: TaskFolder) {
452 const cwd = yield* realPath(worktreePath);
453 const folders = taskFolder.repositories.map((repository) => ({
454 name: repository.name,
455 path: repository.worktreePath,
456 isGitRepository: true,
457 repositoryPath: repository.repositoryPath,
458 }));
459 const outside = yield* Effect.forEach(
460 folders,
461 (folder) =>
462 realPath(folder.path).pipe(
463 Effect.map((real) => (isWithinRoot(path, real, cwd) ? [] : [folder.path, real])),
464 ),
465 { concurrency: DETECTION_CONCURRENCY },
466 );
467 return { folders, extraRoots: [...new Set(outside.flat())] };
468 });
469​
470 const forThread: WorkspaceFolders["Service"]["forThread"] = Effect.fn(
471 "WorkspaceFolders.forThread",
472 )(function* (input) {
473 if (input.worktreePath !== null) {
474 const taskFolder = yield* taskFolders
475 .findContaining(input.worktreePath)
476 .pipe(
477 Effect.mapError(
478 (cause) => new WorkspaceFoldersError({ operation: "list", detail: cause.detail }),
479 ),
480 );
481 return taskFolder === null
482 ? EMPTY_WORKSPACE
483 : yield* forTaskFolder(input.worktreePath, taskFolder);
484 }
485 const project = yield* readProject(input.projectId);
486 const tracked = yield* foldersOf(project);
487 if (tracked.length === 0) return EMPTY_WORKSPACE;
488 const folders = (yield* classifyAll(tracked)).flatMap((folder) =>
489 folder.state === "missing"
490 ? []
491 : [{ name: folder.name, path: folder.path, isGitRepository: folder.state === "git" }],
492 );
493 const projectRoot = yield* realPath(project.workspaceRoot);
494 // Both spellings are granted: agents are told the stored path, sandboxes check the real one.
495 const outside = yield* Effect.forEach(
496 folders,
497 (folder) =>
498 realPath(folder.path).pipe(
499 Effect.map((real) => (isWithinRoot(path, real, projectRoot) ? [] : [folder.path, real])),
500 ),
501 { concurrency: DETECTION_CONCURRENCY },
502 );
503 return { folders, extraRoots: [...new Set(outside.flat())] };
504 });
505​
506 const submodules: WorkspaceFolders["Service"]["submodules"] = Effect.fn(
507 "WorkspaceFolders.submodules",
508 )(function* (input) {
509 const { folders } = yield* forThread(input);
510 // A worktree can outlive its project record; its submodules are then named by where they are.
511 const projectRoot = yield* readProject(input.projectId).pipe(
512 Effect.map((project) => path.resolve(project.workspaceRoot)),
513 Effect.option,
514 );
515 const own = input.worktreePath === null ? null : path.resolve(input.worktreePath);
516 const root = own ?? Option.getOrNull(projectRoot);
517 if (root === null) return [];
518 const identity = Option.getOrElse(projectRoot, () => root);
519 return yield* submodulesOf([
520 { path: root, identity },
521 ...folders.flatMap((folder) =>
522 folder.isGitRepository
523 ? [{ path: folder.path, identity: folder.repositoryPath ?? folder.path }]
524 : [],
525 ),
526 ]);
527 });
528​
529 const list: WorkspaceFolders["Service"]["list"] = Effect.fn("WorkspaceFolders.list")(
530 function* (input) {
531 const project = yield* readProject(input.projectId);
532 return { folders: yield* classifyAll(yield* foldersOf(project)) };
533 },
534 );
535​
536 const scan: WorkspaceFolders["Service"]["scan"] = (input) =>
537 scanFolders(input).pipe(
538 Effect.provideService(FileSystem.FileSystem, fileSystem),
539 Effect.provideService(Path.Path, path),
540 );
541​
542 return WorkspaceFolders.of({ forThread, submodules, list, scan });
543});
544​
545export const layer = Layer.effect(WorkspaceFolders, make);