Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed
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=205&format=json
481 linesFirst import 93% · speed 6% · review 1% · pinch 1%Last change pinch in version 78, 5 versions changed it

You're reading version 205. The newest is 318, and no version since then changed this file. Go to the newestCompare with 318

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