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

WorkspaceFolders.ts

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