- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/client/src/commands.ts?format=json
728 linesFirst import 70% · review 13% · codex-prose-authorship-1 10% · pinch 6% · rename 1% · infra-split 1%Last change pinch in version 280, 9 versions changed it
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 ApiError,
11 type Collision,
12 type FileChange,
13 type MergedLine,
14 type News,
15 newsLines,
16 type SyncAnswer,
17} from "./api.ts";
18import { bool, type Parsed, str, UsageError } from "./args.ts";
19import { blobOf, keptWholeAs, MAX_BLOB_BYTES, readKnownBlobs, writeKnownBlobs } from "./blobs.ts";
20import { type Env, EXIT, heard, type Output, open } from "./command-env.ts";
21import { findRoot, isReader } from "./config.ts";
22import { spellingText, uncomposedText } from "./core.ts";
23import { pairRenames } from "./diff.ts";
24import type { BlobToSend, TurnedBinary } from "./folder.ts";
25import {
26 absolute,
27 forgetKnown,
28 isLocalOnly,
29 isPaused,
30 type LeftOut,
31 listKnown,
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 { batchRecordItems, sendRecordBatches } from "./record-batches.ts";
46import { type Refused, screenAnswer, unsafePath } from "./safety.ts";
48export {
49 knownPrep,
50 parallelScript,
51 type RunStamp,
52 runBisect,
53 runCommand,
54 runLogs,
55 runPrep,
56 runRun,
57 shellWord,
58 undoGitBashPaths,
59 withEntries,
60} from "./box-commands.ts";
61export { collisionsHeading, collisionText, mergedLinesText } from "./collision-text.ts";
62export { type Env, EXIT, newsText, type Output, open, plural, takeNews } from "./command-env.ts";
63export { runInit, runJoin } from "./join-commands.ts";
64export { runPublish, runSync, sameVersionHint } from "./publish-commands.ts";
65export { imageTokens, runFetch, runServe, runShot } from "./serve-commands.ts";
66export {
67 crlfOnly,
68 missingHere,
69 missingText,
70 openCollisionsText,
71 runFixEol,
72 runMv,
73 runReader,
74 runSettle,
75 runStatus,
76 staleModText,
77} from "./status-commands.ts";
79import { gitMarkerLine } from "./settle.ts";
80import { stateDir } from "./state-dir.ts";
82// --- record ---
84interface Recorded {
85 readonly sent: number;
86 /** The paths sent. */
87 readonly paths: readonly string[];
88 /** Those of them sent as deleted (gone from the folder). */
89 readonly deleted: readonly string[];
90 /** Those of them new to avcs: no copy recorded before (#37: a file a script made is easy to miss). */
91 readonly added?: readonly string[];
92 /** Nothing was sent because the folder is paused (abso pause). */
93 readonly paused?: boolean;
94 readonly changed: readonly string[] | number | undefined;
95 readonly news: News;
96 readonly leftOut: readonly LeftOut[];
97 readonly turnedBinary: readonly TurnedBinary[];
98 /** Text files sent that hold what looks like a git conflict (a merge git left unfinished, or markers typed by hand). */
99 readonly gitMarkers?: readonly { path: string; line: number }[];
100 /** Sent files whose path is long enough to fail on Windows, here or in another agent's folder. */
101 readonly longPaths?: readonly { path: string; length: number }[];
102}
104/** The warning for text files that turned binary: what, where, and what to do. Empty when there are none. */
105export function turnedBinaryText(list: readonly TurnedBinary[]): string[] {
106 return list.map(
107 (t) =>
108 `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}.`,
109 );
110}
112/** The paths given with --binary (comma-separated, relative to the folder). */
113export function meantBinary(args: Parsed): Set<string> {
114 return new Set(
115 (str(args, "binary") ?? "")
116 .split(",")
117 .map((p) => p.trim().replace(/\\/g, "/").replace(/^\.\//, ""))
118 .filter((p) => p !== ""),
119 );
120}
122/** One line naming the files left out, or none. */
123export function leftOutText(leftOut: readonly LeftOut[]): string[] {
124 if (leftOut.length === 0) return [];
125 const why = (f: LeftOut) => `${f.path}${f.kept ? " (the server keeps its last version)" : ""}`;
126 return [
127 `Left out, over the server's ${MAX_BLOB_BYTES / 1024 / 1024} MB limit for one file: ${leftOut.map(why).join(", ")}.`,
128 ];
129}
131/**
132 * A command that left files out for size did not do everything it was asked: say so in the exit code too, so
133 * a script, CI or an agent cannot read "ok" while a file is missing. Other exits (refused, queued) stay as they are.
134 */
135export function withLeftOut(out: Output, leftOut: readonly LeftOut[]): Output {
136 if (leftOut.length === 0) return out;
137 const text = out.text.includes("Left out,") ? out.text : [out.text, ...leftOutText(leftOut)].join("\n");
138 return {
139 ...out,
140 text: `${text}\nExit ${EXIT.error}: ${leftOut.length} file${leftOut.length === 1 ? " was" : "s were"} not sent.`,
141 json: { ...out.json, leftOut },
142 exit: out.exit === undefined || out.exit === EXIT.ok ? EXIT.error : out.exit,
143 };
144}
146/** Upload binary files' bytes before the record or init that names them, each hash once. */
147export async function uploadBlobs(api: Api, blobs: ReadonlyMap<string, BlobToSend>): Promise<void> {
148 const seen = new Set<string>();
149 for (const b of blobs.values()) {
150 if (seen.has(b.sha)) continue;
151 seen.add(b.sha);
152 await api.putBlob(b.sha, b.bytes);
153 }
154}
156/**
157 * Whether the file at `rel` is as the server last gave it (or gone), so a sync
158 * may replace it: text compared with the known copy, a binary file by hash.
159 */
160function untouchedOnDisk(
161 root: string,
162 rel: string,
163 now: OnDisk | undefined,
164 knownBlobs: ReadonlyMap<string, string>,
165): boolean {
166 if (now === undefined) return true;
167 if (now.text !== undefined) {
168 const known = readKnown(root, rel);
169 // A file the server keeps whole (#46) is known by its hash.
170 return known !== undefined ? normalize(now.text) === known : keptWholeAs(normalize(now.text), knownBlobs.get(rel));
171 }
172 const blob = knownBlobs.get(rel);
173 const b = blobOf(absolute(root, rel));
174 return blob !== undefined && b !== undefined && "sha" in b && b.sha === blob;
175}
177/** Send what differs from the known copy. Used by record, publish and sync. */
178/** Record the folder, holding its lock (#51): known copies, modes and blobs are rewritten. */
179export async function recordFolder(
180 root: string,
181 api: Api,
182 all = false,
183 binary: ReadonlySet<string> = new Set(),
184): Promise<Recorded> {
185 return withFolderLock(root, "record", () => recordFolderLocked(root, api, all, binary));
186}
188async function recordFolderLocked(
189 root: string,
190 api: Api,
191 all: boolean,
192 binary: ReadonlySet<string>,
193): Promise<Recorded> {
194 if (isPaused(root))
195 return {
196 sent: 0,
197 paths: [],
198 deleted: [],
199 paused: true,
200 changed: [],
201 news: undefined,
202 leftOut: [],
203 turnedBinary: [],
204 };
205 // A reader records nothing (#37); the server would refuse it anyway.
206 if (isReader(root))
207 return { sent: 0, paths: [], deleted: [], changed: [], news: undefined, leftOut: [], turnedBinary: [] };
208 const { files, blobs, modes, leftOut, turnedBinary } = unrecorded(root, all, binary);
209 const paths = [...new Set([...files.keys(), ...blobs.keys(), ...Object.keys(modes)])].sort();
210 const knownBefore = new Set([...listKnown(root), ...readKnownBlobs(root).keys()]);
211 const added = paths.filter((p) => files.get(p) !== null && !knownBefore.has(p));
212 const sent = paths.length;
213 const deleted = [...files]
214 .filter(([, text]) => text === null)
215 .map(([rel]) => rel)
216 .sort();
217 if (sent === 0) return { sent: 0, paths, deleted, changed: [], news: undefined, leftOut, turnedBinary };
218 const items = paths.map((path) => ({
219 path,
220 ...(files.has(path) ? { text: files.get(path) } : {}),
221 ...(modes[path] !== undefined ? { mode: modes[path] } : {}),
222 ...(blobs.has(path) ? { blob: blobs.get(path)?.sha } : {}),
223 }));
224 const batches = batchRecordItems(items);
225 let batchBlobs = new Map<string, BlobToSend>();
226 const uploaded = new Set<string>();
227 const answers = await sendRecordBatches(
228 api,
229 batches,
230 async (batch) => {
231 batchBlobs = new Map(
232 batch.paths.flatMap((path) => {
233 const blob = blobs.get(path);
234 return blob === undefined ? [] : [[path, blob] as const];
235 }),
236 );
237 for (const [path, blob] of batchBlobs) {
238 if (uploaded.has(blob.sha)) continue;
239 await uploadBlobs(api, new Map([[path, blob]]));
240 uploaded.add(blob.sha);
241 }
242 },
243 async (batch, answer) => {
244 const batchFiles = new Map(Object.entries(batch.files));
245 // Commit known state only after this batch is confirmed; earlier successful batches stay committed on later failure.
246 for (const [rel, text] of batchFiles) if (text === null) forgetKnown(root, rel);
247 for (const [rel, text] of batchFiles) if (text !== null) writeKnown(root, rel, text);
248 const knownBlobs = readKnownBlobs(root);
249 if (Object.keys(batch.blobs).length > 0 || batch.paths.some((rel) => knownBlobs.has(rel))) {
250 for (const rel of new Set([...Object.keys(batch.files), ...Object.keys(batch.blobs)])) knownBlobs.delete(rel);
251 for (const [rel, sha] of Object.entries(batch.blobs)) {
252 forgetKnown(root, rel);
253 knownBlobs.set(rel, sha);
254 }
255 writeKnownBlobs(root, knownBlobs);
256 }
257 const gone = Object.entries(batch.files)
258 .filter(([, text]) => text === null)
259 .map(([rel]) => rel);
260 const knownModes = readKnownModes(root);
261 if (Object.keys(batch.modes).length > 0 || gone.some((rel) => knownModes.has(rel))) {
262 foldModes(knownModes, batch.modes, gone);
263 writeKnownModes(root, knownModes);
264 }
265 heard(root, [
266 ...newsLines(answer.news),
267 ...(answer.spelling ?? []).map(spellingText),
268 ...(answer.uncomposed ?? []).map(uncomposedText),
269 ]);
270 },
271 );
272 const changed = answers.flatMap((answer) => (Array.isArray(answer.changed) ? answer.changed : []));
273 const changedCount = answers.some((answer) => typeof answer.changed === "number")
274 ? answers.reduce(
275 (sum, answer) =>
276 sum +
277 (typeof answer.changed === "number"
278 ? answer.changed
279 : Array.isArray(answer.changed)
280 ? answer.changed.length
281 : 0),
282 0,
283 )
284 : changed;
285 const news = answers.flatMap((answer) => newsLines(answer.news));
286 const spelling = answers.flatMap((answer) => answer.spelling ?? []);
287 const uncomposed = answers.flatMap((answer) => answer.uncomposed ?? []);
288 const answer = { changed: changedCount, news, spelling, uncomposed };
289 const longPaths = longPathsOf(
290 root,
291 [...files].filter(([, text]) => text !== null).map(([path]) => path),
292 );
293 const gitMarkers = [...files]
294 .flatMap(([path, text]) => {
295 const line = text === null ? undefined : gitMarkerLine(text);
296 return line === undefined ? [] : [{ path, line }];
297 })
298 .sort((a, b) => (a.path < b.path ? -1 : 1));
299 return {
300 sent,
301 paths,
302 deleted,
303 added,
304 changed: answer.changed,
305 news: answer.news,
306 leftOut,
307 turnedBinary,
308 gitMarkers,
309 longPaths,
310 };
311}
313/** A note per file that holds what looks like a git conflict: abso records it as it is, as text, and does not call it a collision. */
314export function gitMarkerText(list: readonly { path: string; line: number }[] | undefined): string[] {
315 return (list ?? []).map(
316 (m) =>
317 `Note: ${m.path} has lines that look like a git conflict (from line ${m.line}). abso records them as ordinary text and will push them as they are. If a merge was left unfinished, fix the file first.`,
318 );
319}
321/** Windows stops at 260 characters for a whole path, and another agent's folder may sit deeper than this one. */
322const LONG_FULL_PATH = 240;
323const LONG_RELATIVE_PATH = 160;
325/** The sent files whose path will likely fail to write on Windows: the whole path is near its limit here, or the part inside the folder is already long. */
326export function longPathsOf(root: string, paths: Iterable<string>): { path: string; length: number }[] {
327 return [...paths]
328 .map((path) => ({ path, length: absolute(root, path).length }))
329 .filter((p) => p.length >= LONG_FULL_PATH || p.path.length >= LONG_RELATIVE_PATH)
330 .sort((a, b) => (a.path < b.path ? -1 : 1));
331}
333/** A note per long path: abso keeps it, but a Windows agent may not be able to write the file. */
334export function longPathText(list: readonly { path: string; length: number }[] | undefined): string[] {
335 return (list ?? []).map(
336 (p) =>
337 `Note: ${p.path} is ${p.path.length} characters inside the folder (${p.length} with this folder's location). Windows stops at 260 for a whole path, so an agent on Windows may be unable to write it. A shorter path avoids that.`,
338 );
339}
341/** "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. */
342export function recordedFirst(r: Recorded): string[] {
343 if (r.paused) return ["Recording is paused (abso resume): your folder's changes were not sent first."];
344 if (r.sent === 0) return [];
345 return [`Recorded first: ${recordedList(r)}.`, ...gitMarkerText(r.gitMarkers), ...longPathText(r.longPaths)];
346}
348/** "2 changed (a, b), 3 deleted (x, y, z)": deletions said as such (#37: deleted files were read as edits). */
349function recordedList(r: Recorded): string {
350 const names = (list: readonly string[]) =>
351 list.length <= LISTED ? list.join(", ") : `${list.slice(0, LISTED).join(", ")}, and ${list.length - LISTED} more`;
352 const gone = new Set(r.deleted);
353 const fresh = new Set(r.added ?? []);
354 const changed = r.paths.filter((p) => !gone.has(p) && !fresh.has(p));
355 // New files are named in full: they are the ones a script made and nobody remembers (#37).
356 return [
357 ...(fresh.size > 0 ? [`${fresh.size} new (${[...fresh].join(", ")})`] : []),
358 ...(changed.length > 0 ? [`${changed.length} changed (${names(changed)})`] : []),
359 ...(r.deleted.length > 0 ? [`${r.deleted.length} deleted (${names(r.deleted)})`] : []),
360 ].join(", ");
361}
363export const READER_REFUSES =
364 "this folder is a reader: it records and pushes nothing (abso reader off makes it a writer again)";
366/** abso pause: send nothing from the folder (no hook, no record) until abso resume. */
367export async function runPause(_args: Parsed, env: Env): Promise<Output> {
368 const { root } = open(env);
369 const was = isPaused(root);
370 writeFileSync(pausedPath(root), `${new Date().toISOString()}\n`);
371 return {
372 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.`,
373 json: { paused: true },
374 };
375}
377export async function runResume(_args: Parsed, env: Env): Promise<Output> {
378 const { root } = open(env);
379 const was = isPaused(root);
380 rmSync(pausedPath(root), { force: true });
381 return {
382 text: was
383 ? "Recording again. Changes made while paused go at the next abso record (or push, pull, ...); abso status lists them."
384 : "Recording was not paused.",
385 json: { paused: false },
386 };
387}
389export async function runRecord(args: Parsed, env: Env): Promise<Output> {
390 if (isReader(findRoot(env.cwd) ?? env.cwd)) throw new UsageError(READER_REFUSES);
391 const { root, api } = open(env);
392 if (isPaused(root))
393 return {
394 exit: EXIT.refused,
395 text: "Not recorded: recording is paused. abso resume, then abso record.",
396 json: { paused: true },
397 };
398 const r = await recordFolder(root, api, bool(args, "all"), meantBinary(args));
399 const changed = Array.isArray(r.changed) ? r.changed.length : r.changed;
400 const text =
401 r.sent === 0
402 ? "Nothing to record: the folder matches what the server has."
403 : `Recorded ${recordedList(r)}${changed === undefined ? "" : `; ${changed} changed on the server`}.`;
404 return withLeftOut(
405 {
406 text: [
407 ...turnedBinaryText(r.turnedBinary),
408 text,
409 ...gitMarkerText(r.gitMarkers),
410 ...longPathText(r.longPaths),
411 ...leftOutText(r.leftOut),
412 ].join("\n"),
413 json: {
414 sent: r.sent,
415 changed: r.changed ?? null,
416 news: newsLines(r.news),
417 leftOut: r.leftOut,
418 turnedBinary: r.turnedBinary,
419 gitMarkers: r.gitMarkers ?? [],
420 longPaths: r.longPaths ?? [],
421 },
422 },
423 r.leftOut,
424 );
425}
427// --- writing answers into the folder ---
429/**
430 * Bring the folder to shared and set the agent's base. Writes only files that
431 * still match the known copy (or are new), so unrecorded work is never
432 * overwritten.
433 */
434export async function syncFolder(root: string, api: Api, full = false): Promise<Applied> {
435 const applied = await applyAnswer(root, api, await pullAnswer(root, api, full));
436 pullWritten(root);
437 return applied;
438}
440const PULLING_FILE = "pulling.json";
442/**
443 * Whether a pull here asked the server and never wrote its answer (abso-core 26): it timed out, or stopped
444 * partway. The server moved the agent's base when it answered, and later pulls send only what changed since
445 * that base, so the files it would have written stay behind until a pull asks for every file.
446 */
447export function pullUnfinished(root: string): boolean {
448 return existsSync(join(stateDir(root), PULLING_FILE));
449}
451/**
452 * Ask the server for a pull, noting first that one is under way, so a pull whose answer never gets written
453 * leaves the note behind. With that note, or `full`, it asks for every file in the agent's view, which the
454 * folder's own checks then write only where the folder differs. pullWritten takes the note away.
455 */
456export async function pullAnswer(root: string, api: Api, full = false): Promise<SyncAnswer> {
457 const unfinished = pullUnfinished(root);
458 writeFileAtomic(join(stateDir(root), PULLING_FILE), `${JSON.stringify({ at: new Date().toISOString() })}\n`);
459 if (!full && !unfinished) return api.sync();
460 try {
461 return await api.sync({ full: true });
462 } catch (err) {
463 // A server from before full pulls (501): the plain pull is still better than none.
464 if (unfinished && !full && err instanceof ApiError && err.status === 501) return api.sync();
465 throw err;
466 }
467}
469/** The pull's answer is written into the folder: take away pullAnswer's note. */
470export function pullWritten(root: string): void {
471 rmSync(join(stateDir(root), PULLING_FILE), { force: true });
472}
474/** Status's line, and pull's when it caught up. */
475export function pullUnfinishedText(root: string): string[] {
476 return pullUnfinished(root)
477 ? [
478 "A pull here didn't finish (its answer never arrived or wasn't written), so files may be behind this folder's base. abso pull fetches every file and writes the ones that differ.",
479 ]
480 : [];
481}
483/** What writing a sync or switch answer into the folder did. */
484export interface Applied {
485 readonly version: number;
486 readonly written: string[];
487 readonly deleted: string[];
488 readonly kept: string[];
489 readonly dropped: string[];
490 readonly collisions: readonly Collision[];
491 /** Text files the answer deleted and wrote again under a new path, paired as git pairs renames. Each is in `written` and `deleted` too. */
492 readonly renamed: readonly { readonly from: string; readonly to: string }[];
493 /** Paths in the answer that were not touched: outside the folder, into .git/.claude/.avcs, a device, or through a link (safety.ts). */
494 readonly refused: readonly Refused[];
495 /** Lines both sides changed that the server merged item by item. */
496 readonly merged: readonly MergedLine[];
497 /** Files a sync couldn't write here, this one or an earlier one, still stale (#51): path -> when and why. */
498 readonly unwritten: Readonly<Record<string, Unwritten>>;
499}
501/** How many names a summary line shows before "and N more". */
502export const LISTED = 8;
503/** How far back an empty publish looks for this agent's last publish. */
504export const FOLDER_LOG_LIMIT = 200;
506/**
507 * The files a sync or switch changed. A line per kind, with the names cut
508 * short past LISTED (a big sync used to print a line per file); --verbose
509 * gives a line per file.
510 */
511export function changedFilesText(
512 command: string,
513 written: readonly string[],
514 deleted: readonly string[],
515 renamed: readonly { readonly from: string; readonly to: string }[],
516 verbose: boolean,
517): string[] {
518 const moves = renamed.map((r) => `${r.from} -> ${r.to}`);
519 if (verbose)
520 return [
521 ...written.map((f) => ` updated ${f}`),
522 ...deleted.map((f) => ` deleted ${f}`),
523 ...moves.map((m) => ` renamed ${m}`),
524 ];
525 const some = (names: readonly string[]) =>
526 names.length <= LISTED
527 ? names.join(", ")
528 : `${names.slice(0, LISTED).join(", ")}, and ${names.length - LISTED} more`;
529 return [
530 ...(written.length > 0 ? [` updated: ${some(written)}`] : []),
531 ...(deleted.length > 0 ? [` deleted: ${some(deleted)}`] : []),
532 ...(moves.length > 0 ? [` renamed: ${some(moves)}`] : []),
533 ...([written, deleted, moves].some((l) => l.length > LISTED)
534 ? [` (abso ${command} --verbose lists every file)`]
535 : []),
536 ];
537}
539/** 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. */
540export interface Unwritten {
541 readonly version: number;
542 readonly why: string;
543}
545const UNWRITTEN_FILE = "unwritten.json";
547/** Files earlier syncs couldn't write here, kept in .avcs/unwritten.json until a write of them works. */
548export function readUnwritten(root: string): Record<string, Unwritten> {
549 try {
550 return JSON.parse(readFileSync(join(stateDir(root), UNWRITTEN_FILE), "utf8")) as Record<string, Unwritten>;
551 } catch {
552 return {};
553 }
554}
556/** Status's line for them, and sync's for ones an earlier sync named. */
557export function unwrittenText(
558 unwritten: Readonly<Record<string, Unwritten>>,
559 skip: ReadonlySet<string> = new Set(),
560): string[] {
561 const paths = Object.keys(unwritten)
562 .filter((p) => !skip.has(p))
563 .sort();
564 if (paths.length === 0) return [];
565 const list = paths.map((p) => `${p} (version ${unwritten[p]!.version}: ${unwritten[p]!.why})`).join(", ");
566 return [
567 `Stale here: a pull couldn't write ${paths.length === 1 ? "this file" : "these files"}, and no later pull sends ${paths.length === 1 ? "it" : "them"} again. Close whatever holds ${paths.length === 1 ? "it" : "them"}, then abso pull --full: ${list}`,
568 ];
569}
571/** Write the files a sync or switch answer lists into the folder (the same rules as sync). */
572/** Write a sync's answer into the folder, holding its lock (#51). */
573export async function applyAnswer(root: string, api: Api, unscreened: SyncAnswer): Promise<Applied> {
574 return withFolderLock(root, "pull", () => applyAnswerLocked(root, api, unscreened));
575}
577async function applyAnswerLocked(root: string, api: Api, unscreened: SyncAnswer): Promise<Applied> {
578 // Other agents' paths: nothing outside this folder, in .git/.claude/.avcs, or through a link.
579 const { answer, refused } = screenAnswer(root, unscreened);
580 // A write the disk refuses anyway is named and skipped, so the rest of the sync still lands with its
581 // known copies and modes, rather than stopping partway (git checks every path first).
582 const failed = new Set<string>();
583 // Remembered until a write works (#51): the server won't send these files again.
584 const unwritten = readUnwritten(root);
585 const unwrittenBefore = JSON.stringify(unwritten);
586 const tryWrite = (rel: string, write: () => void): boolean => {
587 try {
588 write();
589 delete unwritten[rel];
590 return true;
591 } catch (e) {
592 failed.add(rel);
593 const code = (e as NodeJS.ErrnoException).code ?? (e as Error).message;
594 refused.push({ path: rel, why: `writing it here failed (${code})` });
595 unwritten[rel] = { version: answer.version, why: code };
596 return false;
597 }
598 };
599 const written: string[] = [];
600 const deleted: string[] = [];
601 const kept: string[] = [];
602 // Text that left one path and arrived at a new one, to tell renames from a delete and an add.
603 const gone: FileChange[] = [];
604 const arrived: FileChange[] = [];
605 // Local-only files (.claude/, ...) the server still holds: never written here,
606 // and sent back as deleted so they leave this agent's view and draft.
607 const dropped = new Set<string>();
608 const knownModes = readKnownModes(root);
609 const knownBlobs = readKnownBlobs(root);
610 const blobsBefore = JSON.stringify([...knownBlobs]);
611 for (const c of answer.collisions ?? [])
612 if (isLocalOnly(c.file) && unsafePath(c.file) === undefined) dropped.add(c.file);
613 // Deletions first: on a case-insensitive disk a rename from a.ts to A.ts is one file, and
614 // writing A.ts before deleting a.ts would delete the new file.
615 const entries = Object.entries(answer.files).sort(([, a], [, b]) => Number(a !== null) - Number(b !== null));
616 // Files new to the folder get the line endings git would give them, asked once for all of them.
617 const fresh = newFileEndings(
618 root,
619 entries
620 .filter(([rel, text]) => text !== null && !isLocalOnly(rel) && !existsSync(absolute(root, rel)))
621 .map(([rel]) => rel),
622 );
623 for (const [rel, text] of entries) {
624 if (isLocalOnly(rel)) {
625 if (text !== null) dropped.add(rel);
626 forgetKnown(root, rel);
627 continue;
628 }
629 const path = absolute(root, rel);
630 // Judged by its mode: a link is "" and is never followed.
631 const now = onDisk(path, knownModes.get(rel) ?? PLAIN);
632 const raw = now?.text;
633 const disk = raw === undefined ? undefined : normalize(raw);
634 const untouched = untouchedOnDisk(root, rel, now, knownBlobs);
635 if (text === null) {
636 if (!untouched) {
637 kept.push(rel);
638 continue;
639 }
640 const was = readKnown(root, rel);
641 if (was !== undefined) gone.push({ path: rel, before: was, after: null });
642 removeFile(path);
643 forgetKnown(root, rel);
644 knownModes.delete(rel);
645 knownBlobs.delete(rel);
646 delete unwritten[rel];
647 deleted.push(rel);
648 } else {
649 if (disk === text) {
650 writeKnown(root, rel, text);
651 knownBlobs.delete(rel);
652 delete unwritten[rel];
653 continue;
654 }
655 if (!untouched) {
656 kept.push(rel);
657 continue;
658 }
659 if (!tryWrite(rel, () => writeFileAtomic(path, withEndingsOf(text, raw, fresh.get(rel))))) continue;
660 if (now === undefined) arrived.push({ path: rel, before: null, after: text });
661 writeKnown(root, rel, text);
662 knownBlobs.delete(rel);
663 written.push(rel);
664 }
665 }
666 // Binary files: fetch the bytes the answer names, with the same care for unrecorded work.
667 for (const [rel, sha] of Object.entries(answer.blobs ?? {})) {
668 if (sha === null || isLocalOnly(rel)) continue;
669 const path = absolute(root, rel);
670 const now = onDisk(path, knownModes.get(rel) ?? PLAIN);
671 const b = now === undefined ? undefined : blobOf(path);
672 // Already this file: the same bytes, or (a file kept whole, #46) the same text with any line endings.
673 if (
674 (b !== undefined && "sha" in b && b.sha === sha) ||
675 (now?.text !== undefined && keptWholeAs(normalize(now.text), sha))
676 ) {
677 forgetKnown(root, rel);
678 knownBlobs.set(rel, sha);
679 delete unwritten[rel];
680 continue;
681 }
682 if (!untouchedOnDisk(root, rel, now, knownBlobs)) {
683 kept.push(rel);
684 continue;
685 }
686 const bytes = await api.getBlob(sha);
687 if (!tryWrite(rel, () => writeFileAtomic(path, bytes))) continue;
688 forgetKnown(root, rel);
689 knownBlobs.set(rel, sha);
690 written.push(rel);
691 }
692 if (JSON.stringify([...knownBlobs]) !== blobsBefore) writeKnownBlobs(root, knownBlobs);
693 // Modes after text: a link replaces the "" just written, and the bit goes on the file as written.
694 for (const [rel, m] of Object.entries(answer.modes ?? {})) {
695 if (isLocalOnly(rel) || kept.includes(rel) || answer.files[rel] === null || failed.has(rel)) continue;
696 const was = knownModes.get(rel) ?? PLAIN;
697 const mode: FullMode = { exec: m.exec ?? was.exec, link: m.link === undefined ? was.link : m.link };
698 if (!tryWrite(rel, () => applyMode(absolute(root, rel), mode))) continue;
699 knownModes.set(rel, mode);
700 if (!written.includes(rel)) written.push(rel);
701 }
702 writeKnownModes(root, knownModes);
703 if (dropped.size > 0) {
704 heard(root, (await api.record(Object.fromEntries([...dropped].map((rel) => [rel, null])))).news);
705 for (const rel of dropped) forgetKnown(root, rel);
706 }
707 const collisions = (answer.collisions ?? []).filter((c) => !isLocalOnly(c.file));
708 const renamed =
709 gone.length > 0 && arrived.length > 0
710 ? pairRenames([...gone, ...arrived])
711 .filter((f) => f.from !== undefined)
712 .map((f) => ({ from: f.from!, to: f.path }))
713 : [];
714 if (JSON.stringify(unwritten) !== unwrittenBefore)
715 writeFileAtomic(join(stateDir(root), UNWRITTEN_FILE), `${JSON.stringify(unwritten, null, 1)}\n`);
716 return {
717 version: answer.version,
718 written,
719 deleted,
720 kept,
721 dropped: [...dropped].sort(),
722 collisions,
723 renamed,
724 refused,
725 merged: answer.merged ?? [],
726 unwritten,
727 };
728}