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

WorkspaceFolders.ts

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