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