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