Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFS from "node:fs";
3import * as NodeFSP from "node:fs/promises";
4import * as NodePath from "node:path";
5
6import { OrchestrationWorkflowFileError } from "@t3tools/contracts";
7import * as Effect from "effect/Effect";
8import * as HostProcess from "@t3tools/shared/HostProcess";
9
10export interface WorkflowFileIdentity {
11 readonly dev: number;
12 readonly ino: number;
13}
14
15function workflowFilesRoot(home: string, configDir?: string): string {
16 return NodePath.join(configDir?.trim() || NodePath.join(home, ".claude"), "projects");
17}
18
19export const readContainedWorkflowFile = Effect.fn("orchestration.readContainedWorkflowFile")(
20 function* (input: {
21 readonly path: string;
22 readonly extension: string;
23 readonly byteCap: number;
24 readonly tail?: boolean;
25 readonly configDir?: string;
26 /**
27 * Read only complete lines from this byte offset of the file `identity`
28 * names. A different file (shrunk or another inode) is read from 0.
29 */
30 readonly fromOffset?: {
31 readonly offset: number;
32 readonly identity: WorkflowFileIdentity | null;
33 };
34 }) {
35 if (!NodePath.isAbsolute(input.path) || NodePath.extname(input.path) !== input.extension) {
36 return yield* new OrchestrationWorkflowFileError({
37 reason: "invalid-path",
38 path: input.path,
39 });
40 }
41
42 const home = yield* HostProcess.HomeDirectory;
43 const root = yield* Effect.tryPromise({
44 try: () => NodeFSP.realpath(workflowFilesRoot(home, input.configDir)),
45 catch: (cause) =>
46 new OrchestrationWorkflowFileError({
47 reason: "root-unavailable",
48 path: input.path,
49 cause,
50 }),
51 });
52
53 // Realpath the FILE itself (not just its directory): a symlink named
54 // like a transcript inside a contained directory must not escape.
55 const resolved = yield* Effect.tryPromise({
56 try: () => NodeFSP.realpath(input.path),
57 catch: (cause) =>
58 new OrchestrationWorkflowFileError({ reason: "not-found", path: input.path, cause }),
59 });
60
61 if (resolved !== root && !resolved.startsWith(`${root}${NodePath.sep}`)) {
62 return yield* new OrchestrationWorkflowFileError({ reason: "outside-root", path: resolved });
63 }
64 if (NodePath.extname(resolved) !== input.extension) {
65 return yield* new OrchestrationWorkflowFileError({
66 reason: "wrong-extension",
67 path: resolved,
68 });
69 }
70
71 // fd inode vs path inode catches a swapped leaf, not a swapped intermediate
72 // dir; root is 0700 ~/.claude, so that already needs the uid we run as.
73 const read = yield* Effect.tryPromise({
74 try: async () => {
75 const handle = await NodeFSP.open(
76 resolved,
77 NodeFS.constants.O_RDONLY | (NodeFS.constants.O_NONBLOCK ?? 0),
78 );
79 try {
80 const stat = await handle.stat();
81 if (!stat.isFile()) {
82 return { failure: "not-regular-file" as const };
83 }
84 const pathStat = await NodeFSP.lstat(resolved);
85 if (stat.ino !== pathStat.ino || stat.dev !== pathStat.dev) {
86 return { failure: "changed-during-read" as const };
87 }
88 const identity = { dev: stat.dev, ino: stat.ino };
89 if (input.fromOffset !== undefined) {
90 const previous = input.fromOffset.identity;
91 const start =
92 previous !== null &&
93 previous.dev === identity.dev &&
94 previous.ino === identity.ino &&
95 input.fromOffset.offset <= stat.size
96 ? input.fromOffset.offset
97 : 0;
98 const buffer = Buffer.alloc(Math.min(stat.size - start, input.byteCap));
99 const { bytesRead } = await handle.read(buffer, 0, buffer.length, start);
100 const read = buffer.subarray(0, bytesRead);
101 // A writer may be mid-line; leave it for the next read. A single
102 // line over the cap is skipped so the cursor can't stall on it.
103 const lineEnd = read.lastIndexOf(0x0a) + 1;
104 const consumed = lineEnd === 0 && bytesRead === input.byteCap ? bytesRead : lineEnd;
105 return {
106 contents: read.subarray(0, lineEnd).toString("utf8"),
107 // Only the cap can leave complete lines unread; a half-written
108 // last line is not truncation.
109 truncated: stat.size - start > input.byteCap,
110 startOffset: start,
111 endOffset: start + consumed,
112 identity,
113 };
114 }
115 const buffer = Buffer.alloc(Math.min(stat.size, input.byteCap + (input.tail ? 1 : 0)));
116 const truncated = stat.size > buffer.length;
117 const offset = input.tail ? stat.size - buffer.length : 0;
118 const { bytesRead } = await handle.read(buffer, 0, buffer.length, offset);
119 return {
120 contents: buffer.subarray(0, bytesRead).toString("utf8"),
121 truncated,
122 startOffset: offset,
123 endOffset: offset + bytesRead,
124 identity,
125 };
126 } finally {
127 await handle.close();
128 }
129 },
130 catch: (cause) =>
131 new OrchestrationWorkflowFileError({ reason: "read-failed", path: resolved, cause }),
132 });
133 if ("failure" in read) {
134 return yield* new OrchestrationWorkflowFileError({ reason: read.failure, path: resolved });
135 }
136
137 return {
138 path: resolved,
139 contents: read.contents,
140 truncated: read.truncated,
141 startOffset: read.startOffset,
142 endOffset: read.endOffset,
143 identity: read.identity,
144 };
145 },
146);