Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2/**
3 * WorkspaceFileSystem - Effect service contract for workspace file mutations.
4 *
5 * Owns workspace-root-relative file read/write operations and their associated
6 * safety checks and cache invalidation hooks. Reads also accept absolute host
7 * paths so clients can show files an agent left outside the workspace; writes
8 * never leave the root.
9 *
10 * @module WorkspaceFileSystem
11 */
12import * as NodeFS from "node:fs";
13import * as NodeFSP from "node:fs/promises";
14
15import type {
16 ProjectReadFileInput,
17 ProjectReadFileResult,
18 ProjectWriteFileInput,
19 ProjectWriteFileResult,
20} from "@t3tools/contracts";
21import * as Context from "effect/Context";
22import * as Effect from "effect/Effect";
23import * as FileSystem from "effect/FileSystem";
24import * as Layer from "effect/Layer";
25import * as Path from "effect/Path";
26import * as Schema from "effect/Schema";
27
28import * as WorkspaceEntries from "./WorkspaceEntries.ts";
29import * as WorkspacePaths from "./WorkspacePaths.ts";
30
31const PROJECT_READ_FILE_MAX_BYTES = 1024 * 1024;
32
33export class WorkspaceFileSystemOperationError extends Schema.TaggedError<WorkspaceFileSystemOperationError>()(
34 "WorkspaceFileSystemOperationError",
35 {
36 workspaceRoot: Schema.String,
37 relativePath: Schema.String,
38 resolvedPath: Schema.String,
39 operationPath: Schema.String,
40 operation: Schema.Literals([
41 "realpath-workspace-root",
42 "realpath-target",
43 "open",
44 "stat",
45 "read",
46 "close",
47 "make-directory",
48 "write-file",
49 ]),
50 cause: Schema.Defect(),
51 },
52) {
53 override get message(): string {
54 return `Workspace file operation '${this.operation}' failed at '${this.operationPath}' for resolved path '${this.resolvedPath}' (requested as '${this.relativePath}' in '${this.workspaceRoot}').`;
55 }
56}
57
58export class WorkspaceFilePathEscapeError extends Schema.TaggedError<WorkspaceFilePathEscapeError>()(
59 "WorkspaceFilePathEscapeError",
60 {
61 workspaceRoot: Schema.String,
62 relativePath: Schema.String,
63 resolvedWorkspaceRoot: Schema.String,
64 resolvedPath: Schema.String,
65 },
66) {
67 override get message(): string {
68 return `Workspace file '${this.relativePath}' resolves outside workspace root '${this.workspaceRoot}': ${this.resolvedPath}`;
69 }
70}
71
72export class WorkspacePathNotFileError extends Schema.TaggedError<WorkspacePathNotFileError>()(
73 "WorkspacePathNotFileError",
74 {
75 workspaceRoot: Schema.String,
76 relativePath: Schema.String,
77 resolvedPath: Schema.String,
78 },
79) {
80 override get message(): string {
81 return `Workspace path '${this.relativePath}' in '${this.workspaceRoot}' is not a file: ${this.resolvedPath}`;
82 }
83}
84
85export class WorkspaceBinaryFileError extends Schema.TaggedError<WorkspaceBinaryFileError>()(
86 "WorkspaceBinaryFileError",
87 {
88 workspaceRoot: Schema.String,
89 relativePath: Schema.String,
90 resolvedPath: Schema.String,
91 },
92) {
93 override get message(): string {
94 return `Workspace file '${this.relativePath}' in '${this.workspaceRoot}' is binary and cannot be previewed as text.`;
95 }
96}
97
98export const WorkspaceFileSystemError = Schema.Union([
99 WorkspaceFileSystemOperationError,
100 WorkspaceFilePathEscapeError,
101 WorkspacePathNotFileError,
102 WorkspaceBinaryFileError,
103]);
104export type WorkspaceFileSystemError = typeof WorkspaceFileSystemError.Type;
105
106/** Service tag for workspace file operations. */
107export class WorkspaceFileSystem extends Context.Service<
108 WorkspaceFileSystem,
109 {
110 /**
111 * Read a UTF-8 text file relative to the workspace root, or any host file by
112 * absolute path.
113 */
114 readonly readFile: (
115 input: ProjectReadFileInput,
116 ) => Effect.Effect<
117 ProjectReadFileResult,
118 WorkspaceFileSystemError | WorkspacePaths.WorkspacePathOutsideRootError
119 >;
120 /**
121 * Write a file relative to the workspace root.
122 *
123 * Creates parent directories as needed and rejects paths that escape the
124 * workspace root.
125 */
126 readonly writeFile: (
127 input: ProjectWriteFileInput,
128 ) => Effect.Effect<
129 ProjectWriteFileResult,
130 WorkspaceFileSystemError | WorkspacePaths.WorkspacePathOutsideRootError
131 >;
132 }
133>()("t3/workspace/WorkspaceFileSystem") {}
134
135/** @public Service construction is part of the canonical Effect module API. */
136export const make = Effect.gen(function* () {
137 const fileSystem = yield* FileSystem.FileSystem;
138 const path = yield* Path.Path;
139 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
140 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
141
142 /**
143 * Resolves the file a read targets. Workspace-relative paths must stay inside the
144 * root, symlinks included. An absolute path reads a host file in place, such as a
145 * report an agent wrote to a temp directory; it gets no root check.
146 */
147 const resolveReadTarget = Effect.fn("WorkspaceFileSystem.resolveReadTarget")(function* (
148 input: ProjectReadFileInput,
149 ) {
150 const requestedPath = input.relativePath.trim();
151 if (path.isAbsolute(requestedPath)) {
152 const realTargetPath = yield* Effect.tryPromise({
153 try: () => NodeFSP.realpath(requestedPath),
154 catch: (cause) =>
155 new WorkspaceFileSystemOperationError({
156 workspaceRoot: input.cwd,
157 relativePath: input.relativePath,
158 resolvedPath: requestedPath,
159 operationPath: requestedPath,
160 operation: "realpath-target",
161 cause,
162 }),
163 });
164 return { relativePath: requestedPath, realTargetPath };
165 }
166
167 const target = yield* workspacePaths.resolveRelativePathWithinRoot({
168 workspaceRoot: input.cwd,
169 relativePath: input.relativePath,
170 });
171
172 const realWorkspaceRoot = yield* Effect.tryPromise({
173 try: () => NodeFSP.realpath(input.cwd),
174 catch: (cause) =>
175 new WorkspaceFileSystemOperationError({
176 workspaceRoot: input.cwd,
177 relativePath: input.relativePath,
178 resolvedPath: target.absolutePath,
179 operationPath: input.cwd,
180 operation: "realpath-workspace-root",
181 cause,
182 }),
183 });
184 const realTargetPath = yield* Effect.tryPromise({
185 try: () => NodeFSP.realpath(target.absolutePath),
186 catch: (cause) =>
187 new WorkspaceFileSystemOperationError({
188 workspaceRoot: input.cwd,
189 relativePath: input.relativePath,
190 resolvedPath: target.absolutePath,
191 operationPath: target.absolutePath,
192 operation: "realpath-target",
193 cause,
194 }),
195 });
196 const relativeRealPath = path.relative(realWorkspaceRoot, realTargetPath);
197 if (
198 relativeRealPath.startsWith(`..${path.sep}`) ||
199 relativeRealPath === ".." ||
200 path.isAbsolute(relativeRealPath)
201 ) {
202 return yield* new WorkspaceFilePathEscapeError({
203 workspaceRoot: input.cwd,
204 relativePath: input.relativePath,
205 resolvedWorkspaceRoot: realWorkspaceRoot,
206 resolvedPath: realTargetPath,
207 });
208 }
209 return { relativePath: target.relativePath, realTargetPath };
210 });
211
212 const readFile: WorkspaceFileSystem["Service"]["readFile"] = Effect.fn(
213 "WorkspaceFileSystem.readFile",
214 )(function* (input) {
215 const target = yield* resolveReadTarget(input);
216 const realTargetPath = target.realTargetPath;
217
218 return yield* Effect.acquireUseRelease(
219 Effect.tryPromise({
220 // Non-blocking so a FIFO cannot hang the open; the stat below rejects
221 // it. Regular files ignore the flag. Windows lacks it.
222 try: () =>
223 NodeFSP.open(
224 realTargetPath,
225 NodeFS.constants.O_RDONLY | (NodeFS.constants.O_NONBLOCK ?? 0),
226 ),
227 catch: (cause) =>
228 new WorkspaceFileSystemOperationError({
229 workspaceRoot: input.cwd,
230 relativePath: input.relativePath,
231 resolvedPath: realTargetPath,
232 operationPath: realTargetPath,
233 operation: "open",
234 cause,
235 }),
236 }),
237 (handle) =>
238 Effect.gen(function* () {
239 const stat = yield* Effect.tryPromise({
240 try: () => handle.stat(),
241 catch: (cause) =>
242 new WorkspaceFileSystemOperationError({
243 workspaceRoot: input.cwd,
244 relativePath: input.relativePath,
245 resolvedPath: realTargetPath,
246 operationPath: realTargetPath,
247 operation: "stat",
248 cause,
249 }),
250 });
251 if (!stat.isFile()) {
252 return yield* new WorkspacePathNotFileError({
253 workspaceRoot: input.cwd,
254 relativePath: input.relativePath,
255 resolvedPath: realTargetPath,
256 });
257 }
258
259 const bytesToRead = Math.min(stat.size, PROJECT_READ_FILE_MAX_BYTES);
260 const buffer = Buffer.alloc(bytesToRead);
261 const { bytesRead } = yield* Effect.tryPromise({
262 try: () => handle.read(buffer, 0, bytesToRead, 0),
263 catch: (cause) =>
264 new WorkspaceFileSystemOperationError({
265 workspaceRoot: input.cwd,
266 relativePath: input.relativePath,
267 resolvedPath: realTargetPath,
268 operationPath: realTargetPath,
269 operation: "read",
270 cause,
271 }),
272 });
273 const fileBytes = buffer.subarray(0, bytesRead);
274 if (fileBytes.includes(0)) {
275 return yield* new WorkspaceBinaryFileError({
276 workspaceRoot: input.cwd,
277 relativePath: input.relativePath,
278 resolvedPath: realTargetPath,
279 });
280 }
281
282 return {
283 relativePath: target.relativePath,
284 contents: new TextDecoder("utf-8").decode(fileBytes),
285 byteLength: stat.size,
286 truncated: stat.size > PROJECT_READ_FILE_MAX_BYTES,
287 };
288 }),
289 (handle) =>
290 Effect.tryPromise({
291 try: () => handle.close(),
292 catch: (cause) =>
293 new WorkspaceFileSystemOperationError({
294 workspaceRoot: input.cwd,
295 relativePath: input.relativePath,
296 resolvedPath: realTargetPath,
297 operationPath: realTargetPath,
298 operation: "close",
299 cause,
300 }),
301 }),
302 );
303 });
304
305 const writeFile: WorkspaceFileSystem["Service"]["writeFile"] = Effect.fn(
306 "WorkspaceFileSystem.writeFile",
307 )(function* (input) {
308 const target = yield* workspacePaths.resolveRelativePathWithinRoot({
309 workspaceRoot: input.cwd,
310 relativePath: input.relativePath,
311 });
312
313 yield* fileSystem.makeDirectory(path.dirname(target.absolutePath), { recursive: true }).pipe(
314 Effect.mapError(
315 (cause) =>
316 new WorkspaceFileSystemOperationError({
317 workspaceRoot: input.cwd,
318 relativePath: input.relativePath,
319 resolvedPath: target.absolutePath,
320 operationPath: path.dirname(target.absolutePath),
321 operation: "make-directory",
322 cause,
323 }),
324 ),
325 );
326 yield* fileSystem.writeFileString(target.absolutePath, input.contents).pipe(
327 Effect.mapError(
328 (cause) =>
329 new WorkspaceFileSystemOperationError({
330 workspaceRoot: input.cwd,
331 relativePath: input.relativePath,
332 resolvedPath: target.absolutePath,
333 operationPath: target.absolutePath,
334 operation: "write-file",
335 cause,
336 }),
337 ),
338 );
339 yield* workspaceEntries.refresh(input.cwd);
340 return { relativePath: target.relativePath };
341 });
342
343 return WorkspaceFileSystem.of({ readFile, writeFile });
344});
345
346export const layer = Layer.effect(WorkspaceFileSystem, make);