- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/client/src/folder.ts?version=33&format=json
460 linesFirst import 98% · review 2%Last change review in version 27, 3 versions changed it
You're reading version 33. The newest is 318, and 2 versions since then changed this file.
1// The agent's folder: which files count, reading them as text, and the
2// known copy.
3//
4// The known copy (.avcs/known/<path>) is each file as the server's view of
5// this agent has it, as far as the client knows. `record` sends the files
6// that differ from it, the hook checks an edit against it before sending the
7// edit, and `sync` only overwrites files that still match it.
8//
9// Skipped everywhere: .git, .avcs, .claude and node_modules, plus what git's
10// ignore rules leave out: every .gitignore and .absoignore in the folder,
11// .git/info/exclude and git's global excludes file (core.ts has the rules).
13import { execFileSync } from "node:child_process";
14import {
15 appendFileSync,
16 existsSync,
17 mkdirSync,
18 readdirSync,
19 readFileSync,
20 renameSync,
21 rmSync,
22 statSync,
23 unlinkSync,
24 writeFileSync,
25} from "node:fs";
26import { homedir } from "node:os";
27import { dirname, join, relative, sep } from "node:path";
28import { blobOf, keptWholeAs, readKnownBlobs } from "./blobs.ts";
29import { type GitHome, gitIgnoreSetup, type Ignore, isLocalOnly, makeIgnore, normalize, readAllSync } from "./core.ts";
30import { type Mode, modeChange, onDisk, PLAIN, readKnownModes } from "./modes.ts";
31import { stateDir } from "./state-dir.ts";
33export { type Ignore, isLocalOnly, normalize, withEndingsOf } from "./core.ts";
34/** Files bigger than this are not sent as text. */
35export const MAX_TEXT_BYTES = 2 * 1024 * 1024;
37const KNOWN = "known";
39export function toPosix(path: string): string {
40 return sep === "/" ? path : path.split(sep).join("/");
41}
43export function absolute(root: string, rel: string): string {
44 return join(root, ...insideParts(rel));
45}
47/**
48 * A folder-relative path's parts, refusing any that would leave the folder
49 * (.., an absolute path, a drive). Answers from the server are screened
50 * before this (safety.ts); this is the last line, so a path that slipped
51 * through throws instead of being written.
52 */
53function insideParts(rel: string): string[] {
54 const parts = rel.split("/");
55 const bad =
56 rel === "" ||
57 rel.startsWith("/") ||
58 /^[A-Za-z]:/.test(rel) ||
59 parts.some((p) => p === ".." || p === "." || p === "" || (sep === "\\" && p.includes("\\")));
60 if (bad) throw new Error(`refusing a path that would leave the folder: ${JSON.stringify(rel)}`);
61 return parts;
62}
64/** The folder-relative path of an absolute path, or undefined when it is outside the folder. */
65export function relativeTo(root: string, path: string): string | undefined {
66 const rel = relative(root, path);
67 if (rel === "" || rel.startsWith("..") || /^[a-zA-Z]:/.test(rel) || rel.startsWith(sep)) return undefined;
68 return toPosix(rel);
69}
71// --- ignore rules ---
73/** Where git looks for its global files, from the environment. */
74export function gitHome(env: Readonly<Record<string, string | undefined>> = process.env): GitHome {
75 return { home: env.HOME || homedir(), ...(env.XDG_CONFIG_HOME ? { xdgConfigHome: env.XDG_CONFIG_HOME } : {}) };
76}
78function readOrUndefined(path: string): string | undefined {
79 try {
80 return readFileSync(path, "utf8");
81 } catch {
82 return undefined;
83 }
84}
86/** The folder's ignore rules. Ignore files are read when a question first reaches their folder. */
87export function loadIgnore(root: string, where: GitHome = gitHome()): Ignore {
88 const git = readAllSync(gitIgnoreSetup(root, where), readOrUndefined);
89 return makeIgnore((rel) => readOrUndefined(absolute(root, rel)), git);
90}
92// --- walking and reading ---
94/** Every file in the folder that the ignore rules keep, as sorted folder-relative paths. */
95export function walk(root: string, ignore: Ignore = loadIgnore(root)): string[] {
96 const out: string[] = [];
97 const visit = (dir: string, prefix: string): void => {
98 for (const entry of readdirSync(dir, { withFileTypes: true })) {
99 const rel = prefix === "" ? entry.name : `${prefix}/${entry.name}`;
100 if (entry.isDirectory()) {
101 if (!ignore(rel, true)) visit(join(dir, entry.name), rel);
102 } else if (entry.isFile() || entry.isSymbolicLink()) {
103 // A link is a file of its own (its target is its mode); it is never followed.
104 if (!ignore(rel, false)) out.push(rel);
105 }
106 }
107 };
108 visit(root, "");
109 return out.sort();
110}
112const DECODER = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
114/** The bytes as text, or undefined when they are binary (a NUL byte or invalid UTF-8) or too big. */
115export function asText(bytes: Uint8Array): string | undefined {
116 if (bytes.length > MAX_TEXT_BYTES || bytes.includes(0)) return undefined;
117 try {
118 return DECODER.decode(bytes);
119 } catch {
120 return undefined;
121 }
122}
124/** A file's text, undefined when missing or not text. */
125export function readText(path: string): string | undefined {
126 try {
127 return asText(readFileSync(path));
128 } catch {
129 return undefined;
130 }
131}
133/**
134 * A file the client doesn't send: over the server's limit for one file
135 * (MAX_BLOB_BYTES). `kept` is set when the server still has the file's last
136 * version, which stays.
137 */
138export interface LeftOut {
139 readonly path: string;
140 readonly reason: "too big";
141 readonly kept?: boolean;
142}
144/**
145 * A file the server has as text that now reads as binary: almost always an
146 * accident (a stray NUL byte), so it is not sent until it is fixed or
147 * `--binary` says it is meant. `offset` and `line` say where the first bad
148 * byte is.
149 */
150export interface TurnedBinary {
151 readonly path: string;
152 readonly why: "a NUL byte" | "bytes that are not UTF-8";
153 readonly offset: number;
154 readonly line: number;
155}
157/** Where a would-be text file first stops being text. */
158export function firstBadByte(bytes: Uint8Array): { why: TurnedBinary["why"]; offset: number; line: number } {
159 let offset = bytes.indexOf(0);
160 let why: TurnedBinary["why"] = "a NUL byte";
161 // Before any NUL, look for the first byte that breaks UTF-8.
162 const end = offset < 0 ? bytes.length : offset;
163 for (let i = 0; i < end; ) {
164 const b = bytes[i]!;
165 const need = b < 0x80 ? 0 : b >= 0xc2 && b < 0xe0 ? 1 : b >= 0xe0 && b < 0xf0 ? 2 : b >= 0xf0 && b < 0xf5 ? 3 : -1;
166 let ok = need >= 0 && i + need < bytes.length;
167 for (let k = 1; ok && k <= need; k++) ok = (bytes[i + k]! & 0xc0) === 0x80;
168 if (!ok) {
169 offset = i;
170 why = "bytes that are not UTF-8";
171 break;
172 }
173 i += need + 1;
174 }
175 if (offset < 0) offset = 0;
176 let line = 1;
177 for (let i = 0; i < offset; i++) if (bytes[i] === 0x0a) line++;
178 return { why, offset, line };
179}
181/** A binary file (or text too big to diff) to send as a blob: its hash and bytes. */
182export interface BlobToSend {
183 readonly sha: string;
184 readonly bytes: Uint8Array;
185}
187/**
188 * Every file in the folder, in the server's form: text files (empty ones too)
189 * as text, binary files and text over MAX_TEXT_BYTES as blobs, the modes that
190 * aren't plain, and the files over the server's limit, left out.
191 */
192export function readFolder(
193 root: string,
194 ignore: Ignore = loadIgnore(root),
195): { files: Map<string, string>; blobs: Map<string, BlobToSend>; modes: Record<string, Mode>; leftOut: LeftOut[] } {
196 const files = new Map<string, string>();
197 const blobs = new Map<string, BlobToSend>();
198 const modes: Record<string, Mode> = {};
199 const leftOut: LeftOut[] = [];
200 for (const rel of walk(root, ignore)) {
201 const d = onDisk(absolute(root, rel));
202 if (d === undefined) continue;
203 if (d.text === undefined) {
204 const b = blobOf(absolute(root, rel));
205 if (b === undefined) continue;
206 if ("tooBig" in b) {
207 leftOut.push({ path: rel, reason: "too big" });
208 continue;
209 }
210 blobs.set(rel, { sha: b.sha, bytes: b.bytes });
211 } else {
212 files.set(rel, normalize(d.text));
213 }
214 const change = modeChange(PLAIN, d);
215 if (change) modes[rel] = change;
216 }
217 return { files, blobs, modes, leftOut };
218}
220/** Waits between rename tries, about a second in all: Windows refuses a rename while an editor, a scanner or an indexer holds the file. */
221const RENAME_WAITS_MS = [10, 30, 100, 250, 600];
222/** The errors a held file gives on Windows; anything else fails at once. */
223const HELD = new Set(["EPERM", "EACCES", "EBUSY"]);
225/**
226 * Write a file by way of a temporary file and a rename, so a reader sees the
227 * old file or the new one, never half (#51, as git writes its index). A held
228 * file is tried again for about a second; then it throws, rather than write
229 * in place, where a crash would leave half a file.
230 */
231export function writeFileAtomic(
232 path: string,
233 text: string | Uint8Array,
234 rename: (from: string, to: string) => void = renameSync,
235): void {
236 mkdirSync(dirname(path), { recursive: true });
237 const tmp = `${path}.${process.pid}.tmp`;
238 writeFileSync(tmp, text);
239 for (let attempt = 0; ; attempt++) {
240 try {
241 rename(tmp, path);
242 return;
243 } catch (err) {
244 const code = (err as NodeJS.ErrnoException).code ?? "";
245 const wait = RENAME_WAITS_MS[attempt];
246 if (!HELD.has(code) || wait === undefined) {
247 rmSync(tmp, { force: true });
248 throw Object.assign(
249 new Error(
250 `couldn't replace ${path} (${code || (err as Error).message}${HELD.has(code) ? ", still held by another program after a second" : ""})`,
251 ),
252 { code },
253 );
254 }
255 // A short synchronous wait: callers write file by file, in order.
256 Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, wait);
257 }
258 }
259}
261export function removeFile(path: string): void {
262 try {
263 unlinkSync(path);
264 } catch (err) {
265 if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
266 }
267}
269// --- pausing ---
271/** .avcs/paused: while it exists, nothing from the folder is sent (abso pause, abso resume). */
272export function pausedPath(root: string): string {
273 return join(stateDir(root), "paused");
274}
276export function isPaused(root: string): boolean {
277 return existsSync(pausedPath(root));
278}
280// --- the known copy ---
282function knownPath(root: string, rel: string): string {
283 return join(stateDir(root), KNOWN, ...insideParts(rel));
284}
286export function readKnown(root: string, rel: string): string | undefined {
287 return readText(knownPath(root, rel));
288}
290export function writeKnown(root: string, rel: string, text: string): void {
291 writeFileAtomic(knownPath(root, rel), text);
292}
294/** Forget a file, so the next `record` sends it whole. */
295export function forgetKnown(root: string, rel: string): void {
296 removeFile(knownPath(root, rel));
297}
299/** Every path in the known copy. */
300export function listKnown(root: string): string[] {
301 const base = join(stateDir(root), KNOWN);
302 if (!existsSync(base)) return [];
303 const out: string[] = [];
304 const visit = (dir: string, prefix: string): void => {
305 for (const entry of readdirSync(dir, { withFileTypes: true })) {
306 const rel = prefix === "" ? entry.name : `${prefix}/${entry.name}`;
307 if (entry.isDirectory()) visit(join(dir, entry.name), rel);
308 else if (entry.isFile() && !entry.name.endsWith(".tmp")) out.push(rel);
309 }
310 };
311 visit(base, "");
312 return out.sort();
313}
315export function clearKnown(root: string): void {
316 rmSync(join(stateDir(root), KNOWN), { recursive: true, force: true });
317}
319/**
320 * What `record` would send: files that differ from the known copy (in the
321 * server's form), known files that are gone (null), and the modes that differ
322 * from the known modes. An empty file is a file like any other (""); a link's
323 * text is "".
324 */
325export function unrecorded(
326 root: string,
327 all = false,
328 meantBinary: ReadonlySet<string> = new Set(),
329): {
330 files: Map<string, string | null>;
331 blobs: Map<string, BlobToSend>;
332 modes: Record<string, Mode>;
333 leftOut: LeftOut[];
334 turnedBinary: TurnedBinary[];
335} {
336 const ignore = loadIgnore(root);
337 const out = new Map<string, string | null>();
338 const blobs = new Map<string, BlobToSend>();
339 const modes: Record<string, Mode> = {};
340 const present = new Set<string>();
341 const leftOut: LeftOut[] = [];
342 const turnedBinary: TurnedBinary[] = [];
343 // Exact names: on a case-insensitive disk, known/a.ts would also answer for A.ts, hiding a rename that changes only case.
344 const knownPaths = new Set(listKnown(root));
345 const knownBlobs = readKnownBlobs(root);
346 const knownModes = readKnownModes(root);
347 for (const rel of walk(root, ignore)) {
348 const was = knownModes.get(rel) ?? PLAIN;
349 const d = onDisk(absolute(root, rel), was);
350 if (d === undefined) continue;
351 if (d.text === undefined) {
352 const b = blobOf(absolute(root, rel));
353 if (b === undefined) continue;
354 if ("tooBig" in b) {
355 // Over the server's limit: what the server has stays, nothing is deleted.
356 const kept = knownPaths.has(rel) || knownBlobs.has(rel);
357 if (kept) present.add(rel);
358 leftOut.push({ path: rel, reason: "too big", ...(kept ? { kept } : {}) });
359 continue;
360 }
361 present.add(rel);
362 if (knownPaths.has(rel) && b.size <= MAX_TEXT_BYTES && !meantBinary.has(rel)) {
363 // Was text, now binary: hold it back (the server keeps its text) and say where.
364 turnedBinary.push({ path: rel, ...firstBadByte(b.bytes) });
365 continue;
366 }
367 if (all || knownBlobs.get(rel) !== b.sha) blobs.set(rel, { sha: b.sha, bytes: b.bytes });
368 } else {
369 const text = normalize(d.text);
370 const known = knownPaths.has(rel) ? readKnown(root, rel) : undefined;
371 present.add(rel);
372 // A file the server keeps whole has no known copy, only its hash (#46).
373 if (all || (known !== text && !(known === undefined && keptWholeAs(text, knownBlobs.get(rel)))))
374 out.set(rel, text);
375 }
376 // --all sends every file's whole mode, as it sends every file's text.
377 const change = all ? { exec: d.exec, link: d.link } : modeChange(was, d);
378 if (change) modes[rel] = change;
379 }
380 for (const rel of new Set([...knownPaths, ...knownBlobs.keys()])) {
381 // A local-only file the server still has (recorded before the client skipped
382 // it) is sent once as deleted, so it leaves the draft; the file on disk stays.
383 if (isLocalOnly(rel) || (!present.has(rel) && !ignore(rel, false))) out.set(rel, null);
384 }
385 return { files: out, blobs, modes, leftOut, turnedBinary };
386}
388/** Keep the news the agent was given in .avcs/news.log, one dated line each, for anything that shows it later. */
389export function logNews(root: string, news: readonly string[]): void {
390 if (news.length === 0) return;
391 const at = new Date().toISOString();
392 try {
393 appendFileSync(join(stateDir(root), "news.log"), news.map((n) => `${at}\t${n}\n`).join(""));
394 } catch {
395 // Best effort.
396 }
397}
399export function isFile(path: string): boolean {
400 try {
401 return statSync(path).isFile();
402 } catch {
403 return false;
404 }
405}
407// --- line endings for new files ---
409/**
410 * The line endings git would give each of these files if it wrote them new
411 * into the folder: from .gitattributes (text, eol) and git's config
412 * (core.autocrlf, core.eol), asked of git itself so its rules hold exactly.
413 * LF outside a git repository, or when git can't be run. A file already on
414 * disk keeps its own endings instead (withEndingsOf).
415 */
416export function newFileEndings(root: string, rels: readonly string[]): Map<string, "crlf" | "lf"> {
417 const out = new Map<string, "crlf" | "lf">(rels.map((r) => [r, "lf"]));
418 if (rels.length === 0 || !existsSync(join(root, ".git"))) return out;
419 const git = (args: string[], input?: string): string | undefined => {
420 try {
421 return execFileSync("git", ["-C", root, ...args], {
422 input,
423 stdio: ["pipe", "pipe", "ignore"],
424 maxBuffer: 64 << 20,
425 }).toString();
426 } catch {
427 return undefined;
428 }
429 };
430 const config = new Map<string, string>();
431 for (const line of (git(["config", "--get-regexp", "^core.(autocrlf|eol)$"]) ?? "").split("\n")) {
432 const [k, v] = line.trim().split(/\s+/);
433 if (k && v) config.set(k.toLowerCase(), v.toLowerCase());
434 }
435 const autocrlf = config.get("core.autocrlf");
436 const coreEol = config.get("core.eol") ?? "native";
437 const attrs = git(["check-attr", "--stdin", "-z", "text", "eol"], rels.join("\0") + "\0");
438 if (attrs === undefined) return out;
439 const f = attrs.split("\0");
440 const seen = new Map<string, { text?: string; eol?: string }>();
441 for (let i = 0; i + 2 < f.length; i += 3) {
442 const a = seen.get(f[i]!) ?? {};
443 if (f[i + 1] === "text") a.text = f[i + 2];
444 else a.eol = f[i + 2];
445 seen.set(f[i]!, a);
446 }
447 for (const rel of rels) {
448 const { text = "unspecified", eol = "unspecified" } = seen.get(rel) ?? {};
449 // As git's checkout does: -text (or binary) is left alone; eol= decides; then core.autocrlf; then core.eol for text files.
450 let crlf = false;
451 if (text === "unset") crlf = false;
452 else if (eol === "crlf" || eol === "lf") crlf = eol === "crlf";
453 else if (autocrlf === "true") crlf = true;
454 else if (autocrlf === "input") crlf = false;
455 else if (text === "set" || text === "auto")
456 crlf = coreEol === "crlf" || (coreEol === "native" && process.platform === "win32");
457 out.set(rel, crlf ? "crlf" : "lf");
458 }
459 return out;
460}