- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/client/src/commands.ts?version=2&format=json
561 linesFirst import 100%Last change First import in version 0, 1 version changed it
You're reading version 2. The newest is 318, and 8 versions since then changed this file.
1// The abso commands other than `hook`: init, join, record, publish, sync, run
2// and status. Each returns what to print and the exit code, so tests can call
3// them directly.
5import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
6import { join } from "node:path";
7// The engine's own key, so both sides match spellings the same way (#49). Not in core.ts: the edit mod installs core.ts alone.
8import {
9 type Api,
10 type Collision,
11 type FileChange,
12 type MergedLine,
13 type News,
14 newsLines,
15 type SyncAnswer,
16} from "./api.ts";
17import { bool, type Parsed, str, UsageError } from "./args.ts";
18import { blobOf, keptWholeAs, MAX_BLOB_BYTES, readKnownBlobs, writeKnownBlobs } from "./blobs.ts";
19import { type Env, EXIT, heard, type Output, open } from "./command-env.ts";
20import { AVCS_DIR, findRoot, isReader } from "./config.ts";
21import { spellingText, uncomposedText } from "./core.ts";
22import { pairRenames } from "./diff.ts";
23import type { BlobToSend, TurnedBinary } from "./folder.ts";
24import {
25 absolute,
26 forgetKnown,
27 isLocalOnly,
28 isPaused,
29 type LeftOut,
30 listKnown,
31 MAX_TEXT_BYTES,
32 newFileEndings,
33 normalize,
34 pausedPath,
35 readKnown,
36 removeFile,
37 unrecorded,
38 withEndingsOf,
39 writeFileAtomic,
40 writeKnown,
41} from "./folder.ts";
42import { withFolderLock } from "./lock.ts";
43import type { OnDisk } from "./modes.ts";
44import { applyMode, type FullMode, foldModes, onDisk, PLAIN, readKnownModes, writeKnownModes } from "./modes.ts";
45import { type Refused, screenAnswer, unsafePath } from "./safety.ts";
47export {
48 knownPrep,
49 parallelScript,
50 type RunStamp,
51 runBisect,
52 runCommand,
53 runLogs,
54 runPrep,
55 runRun,
56 shellWord,
57 undoGitBashPaths,
58 withEntries,
59} from "./box-commands.ts";
60export { collisionsHeading, collisionText, mergedLinesText } from "./collision-text.ts";
61export { type Env, EXIT, newsText, type Output, open, plural, takeNews } from "./command-env.ts";
62export { runInit, runJoin } from "./join-commands.ts";
63export { runPublish, runSync, sameVersionHint } from "./publish-commands.ts";
64export { imageTokens, runFetch, runServe, runShot } from "./serve-commands.ts";
65export {
66 crlfOnly,
67 missingHere,
68 missingText,
69 openCollisionsText,
70 runFixEol,
71 runMv,
72 runReader,
73 runSettle,
74 runStatus,
75 staleModText,
76} from "./status-commands.ts";
78// --- record ---
80interface Recorded {
81 readonly sent: number;
82 /** The paths sent. */
83 readonly paths: readonly string[];
84 /** Those of them sent as deleted (gone from the folder). */
85 readonly deleted: readonly string[];
86 /** Those of them new to avcs: no copy recorded before (#37, Builder 7: a file a script made is easy to miss). */
87 readonly added?: readonly string[];
88 /** Nothing was sent because the folder is paused (abso pause). */
89 readonly paused?: boolean;
90 readonly changed: readonly string[] | number | undefined;
91 readonly news: News;
92 readonly leftOut: readonly LeftOut[];
93 readonly turnedBinary: readonly TurnedBinary[];
94}
96/** The warning for text files that turned binary: what, where, and what to do. Empty when there are none. */
97export function turnedBinaryText(list: readonly TurnedBinary[]): string[] {
98 return list.map(
99 (t) =>
100 `NOT SENT: ${t.path} was text and now has ${t.why} at line ${t.line} (byte ${t.offset}). The server keeps its last text, so the other agents still have the old file. Fix the file; or, if it is meant to be binary now, pass --binary ${t.path}.`,
101 );
102}
104/** The paths given with --binary (comma-separated, relative to the folder). */
105export function meantBinary(args: Parsed): Set<string> {
106 return new Set(
107 (str(args, "binary") ?? "")
108 .split(",")
109 .map((p) => p.trim().replace(/\\/g, "/").replace(/^\.\//, ""))
110 .filter((p) => p !== ""),
111 );
112}
114/** One line naming the files left out, or none. */
115export function leftOutText(leftOut: readonly LeftOut[]): string[] {
116 if (leftOut.length === 0) return [];
117 const why = (f: LeftOut) => `${f.path}${f.kept ? " (the server keeps its last version)" : ""}`;
118 return [
119 `Left out, over the server's ${MAX_BLOB_BYTES / 1024 / 1024} MB limit for one file: ${leftOut.map(why).join(", ")}.`,
120 ];
121}
123/** Upload binary files' bytes before the record or init that names them, each hash once. */
124export async function uploadBlobs(api: Api, blobs: ReadonlyMap<string, BlobToSend>): Promise<void> {
125 const seen = new Set<string>();
126 for (const b of blobs.values()) {
127 if (seen.has(b.sha)) continue;
128 seen.add(b.sha);
129 await api.putBlob(b.sha, b.bytes);
130 }
131}
133/**
134 * Whether the file at `rel` is as the server last gave it (or gone), so a sync
135 * may replace it: text compared with the known copy, a binary file by hash.
136 */
137function untouchedOnDisk(
138 root: string,
139 rel: string,
140 now: OnDisk | undefined,
141 knownBlobs: ReadonlyMap<string, string>,
142): boolean {
143 if (now === undefined) return true;
144 if (now.text !== undefined) {
145 const known = readKnown(root, rel);
146 // A file the server keeps whole (#46) is known by its hash.
147 return known !== undefined ? normalize(now.text) === known : keptWholeAs(normalize(now.text), knownBlobs.get(rel));
148 }
149 const blob = knownBlobs.get(rel);
150 const b = blobOf(absolute(root, rel));
151 return blob !== undefined && b !== undefined && "sha" in b && b.sha === blob;
152}
154/** Send what differs from the known copy. Used by record, publish and sync. */
155/** Record the folder, holding its lock (#51): known copies, modes and blobs are rewritten. */
156export async function recordFolder(
157 root: string,
158 api: Api,
159 all = false,
160 binary: ReadonlySet<string> = new Set(),
161): Promise<Recorded> {
162 return withFolderLock(root, "record", () => recordFolderLocked(root, api, all, binary));
163}
165async function recordFolderLocked(
166 root: string,
167 api: Api,
168 all: boolean,
169 binary: ReadonlySet<string>,
170): Promise<Recorded> {
171 if (isPaused(root))
172 return {
173 sent: 0,
174 paths: [],
175 deleted: [],
176 paused: true,
177 changed: [],
178 news: undefined,
179 leftOut: [],
180 turnedBinary: [],
181 };
182 // A reader records nothing (#37); the server would refuse it anyway.
183 if (isReader(root))
184 return { sent: 0, paths: [], deleted: [], changed: [], news: undefined, leftOut: [], turnedBinary: [] };
185 const { files, blobs, modes, leftOut, turnedBinary } = unrecorded(root, all, binary);
186 const paths = [...new Set([...files.keys(), ...blobs.keys(), ...Object.keys(modes)])].sort();
187 const knownBefore = new Set([...listKnown(root), ...readKnownBlobs(root).keys()]);
188 const added = paths.filter((p) => files.get(p) !== null && !knownBefore.has(p));
189 const sent = paths.length;
190 const deleted = [...files]
191 .filter(([, text]) => text === null)
192 .map(([rel]) => rel)
193 .sort();
194 if (sent === 0) return { sent: 0, paths, deleted, changed: [], news: undefined, leftOut, turnedBinary };
195 await uploadBlobs(api, blobs);
196 const answer = await api.record(
197 Object.fromEntries(files),
198 {},
199 modes,
200 Object.fromEntries([...blobs].map(([rel, b]) => [rel, b.sha])),
201 );
202 if (!answer.ok) throw new Error(`the server refused the record: ${answer.reason ?? "no reason given"}`);
203 // Forget before writing: after a rename that changes only case, known/a.ts and known/A.ts are one file on Windows and macOS.
204 for (const [rel, text] of files) if (text === null) forgetKnown(root, rel);
205 for (const [rel, text] of files) if (text !== null) writeKnown(root, rel, text);
206 const knownBlobs = readKnownBlobs(root);
207 if (blobs.size > 0 || [...files.keys()].some((rel) => knownBlobs.has(rel))) {
208 for (const rel of files.keys()) knownBlobs.delete(rel);
209 for (const [rel, b] of blobs) {
210 forgetKnown(root, rel);
211 knownBlobs.set(rel, b.sha);
212 }
213 writeKnownBlobs(root, knownBlobs);
214 }
215 const gone = [...files].filter(([, text]) => text === null).map(([rel]) => rel);
216 const knownModes = readKnownModes(root);
217 if (Object.keys(modes).length > 0 || gone.some((rel) => knownModes.has(rel))) {
218 foldModes(knownModes, modes, gone);
219 writeKnownModes(root, knownModes);
220 }
221 // Another spelling of an existing file went in as that file (#49); a new name not in composed form gets a gentle word.
222 heard(root, [
223 ...newsLines(answer.news),
224 ...(answer.spelling ?? []).map(spellingText),
225 ...(answer.uncomposed ?? []).map(uncomposedText),
226 ]);
227 return { sent, paths, deleted, added, changed: answer.changed, news: answer.news, leftOut, turnedBinary };
228}
230/** "Recorded 3 files first: a, b, c." (names cut short past 8), or a word that the folder is paused. Empty when nothing was sent. */
231export function recordedFirst(r: Recorded): string[] {
232 if (r.paused) return ["Recording is paused (abso resume): your folder's changes were not sent first."];
233 if (r.sent === 0) return [];
234 return [`Recorded first: ${recordedList(r)}.`];
235}
237/** "2 changed (a, b), 3 deleted (x, y, z)": deletions said as such (#37, Builder 2 read its rm'd files as edits). */
238function recordedList(r: Recorded): string {
239 const names = (list: readonly string[]) =>
240 list.length <= LISTED ? list.join(", ") : `${list.slice(0, LISTED).join(", ")}, and ${list.length - LISTED} more`;
241 const gone = new Set(r.deleted);
242 const fresh = new Set(r.added ?? []);
243 const changed = r.paths.filter((p) => !gone.has(p) && !fresh.has(p));
244 // New files are named in full: they are the ones a script made and nobody remembers (#37, Builder 7).
245 return [
246 ...(fresh.size > 0 ? [`${fresh.size} new (${[...fresh].join(", ")})`] : []),
247 ...(changed.length > 0 ? [`${changed.length} changed (${names(changed)})`] : []),
248 ...(r.deleted.length > 0 ? [`${r.deleted.length} deleted (${names(r.deleted)})`] : []),
249 ].join(", ");
250}
252export const READER_REFUSES =
253 "this folder is a reader: it records and publishes nothing (abso reader off makes it a writer again)";
255/** abso pause: send nothing from the folder (no hook, no record) until abso resume. */
256export async function runPause(_args: Parsed, env: Env): Promise<Output> {
257 const { root } = open(env);
258 const was = isPaused(root);
259 writeFileSync(pausedPath(root), `${new Date().toISOString()}\n`);
260 return {
261 text: `${was ? "Recording was already paused." : "Recording is paused."} The edit hook sends nothing, abso record refuses, and other commands skip recording first. abso run still sends the folder as it is to the box. abso resume ends it.`,
262 json: { paused: true },
263 };
264}
266export async function runResume(_args: Parsed, env: Env): Promise<Output> {
267 const { root } = open(env);
268 const was = isPaused(root);
269 rmSync(pausedPath(root), { force: true });
270 return {
271 text: was
272 ? "Recording again. Changes made while paused go at the next abso record (or publish, sync, ...); abso status lists them."
273 : "Recording was not paused.",
274 json: { paused: false },
275 };
276}
278export async function runRecord(args: Parsed, env: Env): Promise<Output> {
279 if (isReader(findRoot(env.cwd) ?? env.cwd)) throw new UsageError(READER_REFUSES);
280 const { root, api } = open(env);
281 if (isPaused(root))
282 return {
283 exit: EXIT.refused,
284 text: "Not recorded: recording is paused. abso resume, then abso record.",
285 json: { paused: true },
286 };
287 const r = await recordFolder(root, api, bool(args, "all"), meantBinary(args));
288 const changed = Array.isArray(r.changed) ? r.changed.length : r.changed;
289 const text =
290 r.sent === 0
291 ? "Nothing to record: the folder matches what the server has."
292 : `Recorded ${recordedList(r)}${changed === undefined ? "" : `; ${changed} changed on the server`}.`;
293 return {
294 text: [...turnedBinaryText(r.turnedBinary), text, ...leftOutText(r.leftOut)].join("\n"),
295 json: {
296 sent: r.sent,
297 changed: r.changed ?? null,
298 news: newsLines(r.news),
299 leftOut: r.leftOut,
300 turnedBinary: r.turnedBinary,
301 },
302 };
303}
305// --- writing answers into the folder ---
307/**
308 * Bring the folder to shared and set the agent's base. Writes only files that
309 * still match the known copy (or are new), so unrecorded work is never
310 * overwritten.
311 */
312export async function syncFolder(root: string, api: Api, full = false): Promise<Applied> {
313 return applyAnswer(root, api, await api.sync({ full }));
314}
316/** What writing a sync or switch answer into the folder did. */
317export interface Applied {
318 readonly version: number;
319 readonly written: string[];
320 readonly deleted: string[];
321 readonly kept: string[];
322 readonly dropped: string[];
323 readonly collisions: readonly Collision[];
324 /** Text files the answer deleted and wrote again under a new path, paired as git pairs renames. Each is in `written` and `deleted` too. */
325 readonly renamed: readonly { readonly from: string; readonly to: string }[];
326 /** Paths in the answer that were not touched: outside the folder, into .git/.claude/.avcs, a device, or through a link (safety.ts). */
327 readonly refused: readonly Refused[];
328 /** Lines both sides changed that the server merged item by item. */
329 readonly merged: readonly MergedLine[];
330 /** Files a sync couldn't write here, this one or an earlier one, still stale (#51): path -> when and why. */
331 readonly unwritten: Readonly<Record<string, Unwritten>>;
332}
334/** How many names a summary line shows before "and N more". */
335export const LISTED = 8;
336/** How far back an empty publish looks for this agent's last publish. */
337export const FOLDER_LOG_LIMIT = 200;
339/**
340 * The files a sync or switch changed. A line per kind, with the names cut
341 * short past LISTED (a big sync used to print a line per file); --verbose
342 * gives a line per file.
343 */
344export function changedFilesText(
345 command: string,
346 written: readonly string[],
347 deleted: readonly string[],
348 renamed: readonly { readonly from: string; readonly to: string }[],
349 verbose: boolean,
350): string[] {
351 const moves = renamed.map((r) => `${r.from} -> ${r.to}`);
352 if (verbose)
353 return [
354 ...written.map((f) => ` updated ${f}`),
355 ...deleted.map((f) => ` deleted ${f}`),
356 ...moves.map((m) => ` renamed ${m}`),
357 ];
358 const some = (names: readonly string[]) =>
359 names.length <= LISTED
360 ? names.join(", ")
361 : `${names.slice(0, LISTED).join(", ")}, and ${names.length - LISTED} more`;
362 return [
363 ...(written.length > 0 ? [` updated: ${some(written)}`] : []),
364 ...(deleted.length > 0 ? [` deleted: ${some(deleted)}`] : []),
365 ...(moves.length > 0 ? [` renamed: ${some(moves)}`] : []),
366 ...([written, deleted, moves].some((l) => l.length > LISTED)
367 ? [` (abso ${command} --verbose lists every file)`]
368 : []),
369 ];
370}
372/** A file a sync couldn't write (#51): the server takes the folder to have `version`'s text, so no later sync sends it again. */
373export interface Unwritten {
374 readonly version: number;
375 readonly why: string;
376}
378const UNWRITTEN_FILE = "unwritten.json";
380/** Files earlier syncs couldn't write here, kept in .avcs/unwritten.json until a write of them works. */
381export function readUnwritten(root: string): Record<string, Unwritten> {
382 try {
383 return JSON.parse(readFileSync(join(root, AVCS_DIR, UNWRITTEN_FILE), "utf8")) as Record<string, Unwritten>;
384 } catch {
385 return {};
386 }
387}
389/** Status's line for them, and sync's for ones an earlier sync named. */
390export function unwrittenText(
391 unwritten: Readonly<Record<string, Unwritten>>,
392 skip: ReadonlySet<string> = new Set(),
393): string[] {
394 const paths = Object.keys(unwritten)
395 .filter((p) => !skip.has(p))
396 .sort();
397 if (paths.length === 0) return [];
398 const list = paths.map((p) => `${p} (version ${unwritten[p]!.version}: ${unwritten[p]!.why})`).join(", ");
399 return [
400 `Stale here: a sync couldn't write ${paths.length === 1 ? "this file" : "these files"}, and no later sync sends ${paths.length === 1 ? "it" : "them"} again. Close whatever holds ${paths.length === 1 ? "it" : "them"}, then abso sync --full: ${list}`,
401 ];
402}
404/** Write the files a sync or switch answer lists into the folder (the same rules as sync). */
405/** Write a sync's answer into the folder, holding its lock (#51). */
406export async function applyAnswer(root: string, api: Api, unscreened: SyncAnswer): Promise<Applied> {
407 return withFolderLock(root, "sync", () => applyAnswerLocked(root, api, unscreened));
408}
410async function applyAnswerLocked(root: string, api: Api, unscreened: SyncAnswer): Promise<Applied> {
411 // Other agents' paths: nothing outside this folder, in .git/.claude/.avcs, or through a link.
412 const { answer, refused } = screenAnswer(root, unscreened);
413 // A write the disk refuses anyway is named and skipped, so the rest of the sync still lands with its
414 // known copies and modes, rather than stopping partway (AVCS - Git Lessons; git checks every path first).
415 const failed = new Set<string>();
416 // Remembered until a write works (#51): the server won't send these files again.
417 const unwritten = readUnwritten(root);
418 const unwrittenBefore = JSON.stringify(unwritten);
419 const tryWrite = (rel: string, write: () => void): boolean => {
420 try {
421 write();
422 delete unwritten[rel];
423 return true;
424 } catch (e) {
425 failed.add(rel);
426 const code = (e as NodeJS.ErrnoException).code ?? (e as Error).message;
427 refused.push({ path: rel, why: `writing it here failed (${code})` });
428 unwritten[rel] = { version: answer.version, why: code };
429 return false;
430 }
431 };
432 const written: string[] = [];
433 const deleted: string[] = [];
434 const kept: string[] = [];
435 // Text that left one path and arrived at a new one, to tell renames from a delete and an add.
436 const gone: FileChange[] = [];
437 const arrived: FileChange[] = [];
438 // Local-only files (.claude/, ...) the server still holds: never written here,
439 // and sent back as deleted so they leave this agent's view and draft.
440 const dropped = new Set<string>();
441 const knownModes = readKnownModes(root);
442 const knownBlobs = readKnownBlobs(root);
443 const blobsBefore = JSON.stringify([...knownBlobs]);
444 for (const c of answer.collisions ?? [])
445 if (isLocalOnly(c.file) && unsafePath(c.file) === undefined) dropped.add(c.file);
446 // Deletions first: on a case-insensitive disk a rename from a.ts to A.ts is one file, and
447 // writing A.ts before deleting a.ts would delete the new file.
448 const entries = Object.entries(answer.files).sort(([, a], [, b]) => Number(a !== null) - Number(b !== null));
449 // Files new to the folder get the line endings git would give them, asked once for all of them.
450 const fresh = newFileEndings(
451 root,
452 entries
453 .filter(([rel, text]) => text !== null && !isLocalOnly(rel) && !existsSync(absolute(root, rel)))
454 .map(([rel]) => rel),
455 );
456 for (const [rel, text] of entries) {
457 if (isLocalOnly(rel)) {
458 if (text !== null) dropped.add(rel);
459 forgetKnown(root, rel);
460 continue;
461 }
462 const path = absolute(root, rel);
463 // Judged by its mode: a link is "" and is never followed.
464 const now = onDisk(path, knownModes.get(rel) ?? PLAIN);
465 const raw = now?.text;
466 const disk = raw === undefined ? undefined : normalize(raw);
467 const untouched = untouchedOnDisk(root, rel, now, knownBlobs);
468 if (text === null) {
469 if (!untouched) {
470 kept.push(rel);
471 continue;
472 }
473 const was = readKnown(root, rel);
474 if (was !== undefined) gone.push({ path: rel, before: was, after: null });
475 removeFile(path);
476 forgetKnown(root, rel);
477 knownModes.delete(rel);
478 knownBlobs.delete(rel);
479 delete unwritten[rel];
480 deleted.push(rel);
481 } else {
482 if (disk === text) {
483 writeKnown(root, rel, text);
484 knownBlobs.delete(rel);
485 delete unwritten[rel];
486 continue;
487 }
488 if (!untouched) {
489 kept.push(rel);
490 continue;
491 }
492 if (!tryWrite(rel, () => writeFileAtomic(path, withEndingsOf(text, raw, fresh.get(rel))))) continue;
493 if (now === undefined) arrived.push({ path: rel, before: null, after: text });
494 writeKnown(root, rel, text);
495 knownBlobs.delete(rel);
496 written.push(rel);
497 }
498 }
499 // Binary files: fetch the bytes the answer names, with the same care for unrecorded work.
500 for (const [rel, sha] of Object.entries(answer.blobs ?? {})) {
501 if (sha === null || isLocalOnly(rel)) continue;
502 const path = absolute(root, rel);
503 const now = onDisk(path, knownModes.get(rel) ?? PLAIN);
504 const b = now === undefined ? undefined : blobOf(path);
505 // Already this file: the same bytes, or (a file kept whole, #46) the same text with any line endings.
506 if (
507 (b !== undefined && "sha" in b && b.sha === sha) ||
508 (now?.text !== undefined && keptWholeAs(normalize(now.text), sha))
509 ) {
510 forgetKnown(root, rel);
511 knownBlobs.set(rel, sha);
512 delete unwritten[rel];
513 continue;
514 }
515 if (!untouchedOnDisk(root, rel, now, knownBlobs)) {
516 kept.push(rel);
517 continue;
518 }
519 const bytes = await api.getBlob(sha);
520 if (!tryWrite(rel, () => writeFileAtomic(path, bytes))) continue;
521 forgetKnown(root, rel);
522 knownBlobs.set(rel, sha);
523 written.push(rel);
524 }
525 if (JSON.stringify([...knownBlobs]) !== blobsBefore) writeKnownBlobs(root, knownBlobs);
526 // Modes after text: a link replaces the "" just written, and the bit goes on the file as written.
527 for (const [rel, m] of Object.entries(answer.modes ?? {})) {
528 if (isLocalOnly(rel) || kept.includes(rel) || answer.files[rel] === null || failed.has(rel)) continue;
529 const was = knownModes.get(rel) ?? PLAIN;
530 const mode: FullMode = { exec: m.exec ?? was.exec, link: m.link === undefined ? was.link : m.link };
531 if (!tryWrite(rel, () => applyMode(absolute(root, rel), mode))) continue;
532 knownModes.set(rel, mode);
533 if (!written.includes(rel)) written.push(rel);
534 }
535 writeKnownModes(root, knownModes);
536 if (dropped.size > 0) {
537 heard(root, (await api.record(Object.fromEntries([...dropped].map((rel) => [rel, null])))).news);
538 for (const rel of dropped) forgetKnown(root, rel);
539 }
540 const collisions = (answer.collisions ?? []).filter((c) => !isLocalOnly(c.file));
541 const renamed =
542 gone.length > 0 && arrived.length > 0
543 ? pairRenames([...gone, ...arrived])
544 .filter((f) => f.from !== undefined)
545 .map((f) => ({ from: f.from!, to: f.path }))
546 : [];
547 if (JSON.stringify(unwritten) !== unwrittenBefore)
548 writeFileAtomic(join(root, AVCS_DIR, UNWRITTEN_FILE), `${JSON.stringify(unwritten, null, 1)}\n`);
549 return {
550 version: answer.version,
551 written,
552 deleted,
553 kept,
554 dropped: [...dropped].sort(),
555 collisions,
556 renamed,
557 refused,
558 merged: answer.merged ?? [],
559 unwritten,
560 };
561}