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/publish-commands.ts?format=json
749 linesFirst import 71% · autosettle 16% · rename 5% · review 2% · onboard 2% · pinch 2% · Last change pinch in version 280, 19 versions changed it
1// The commands that move work between the folder and the server: publish and sync.
2
3import { existsSync, readFileSync } from "node:fs";
4import { join } from "node:path";
5import { autoTrailer } from "../../worker/project/autosettle.ts";
6import { type Advice, type Api, ApiError, type Collision, type Settled } from "./api.ts";
7import { bool, type Parsed, str, UsageError } from "./args.ts";
8import { boxOf, knownPrep, runRun, shellWord } from "./box-commands.ts";
9import { collisionsHeading, collisionText, mergedLinesText, mergedText } from "./collision-text.ts";
10import { type Env, EXIT, heard, type Output, open, plural } from "./command-env.ts";
11import {
12 changedFilesText,
13 FOLDER_LOG_LIMIT,
14 LISTED,
15 meantBinary,
16 pullUnfinished,
17 READER_REFUSES,
18 recordedFirst,
19 recordFolder,
20 syncFolder,
21 turnedBinaryText,
22 unwrittenText,
23 withLeftOut,
24} from "./commands.ts";
25import { type Config, isReader } from "./config.ts";
26import { fromEnv } from "./env-names.ts";
27import { ignoredHere } from "./fetch.ts";
28import { absolute, forgetKnown, isLocalOnly, type LeftOut, loadIgnore, readText, writeFileAtomic } from "./folder.ts";
29import { projectFileName, readProjectFile } from "./project-file.ts";
30import { pulledText, STILL_QUEUED, standing, WAIT_SECONDS, waitForQueued } from "./queue.ts";
31import { type Refused, refusedText, unsafePath } from "./safety.ts";
32import { blocksIn, settleText } from "./settle.ts";
33import { stateDir } from "./state-dir.ts";
35/**
36 * Files new in the draft that this folder's ignore rules leave out. An edit
37 * mod loaded before nested ignore files existed sends them (#37, Reporter:
38 * a chat's process keeps the mod it started with). They leave the draft and
39 * stay on disk. A file shared already has stays: as in git, ignoring a file
40 * doesn't take it out of the project.
41 */
42async function dropIgnoredFromDraft(root: string, api: Api): Promise<string[]> {
43 if (isReader(root)) return [];
44 const diff = await api.diff();
45 const ignore = loadIgnore(root);
46 const drop = diff.files
47 .filter(
48 (f) =>
49 f.before === null &&
50 (f.blob?.before ?? null) === null &&
51 unsafePath(f.path) === undefined &&
52 !isLocalOnly(f.path) &&
53 ignoredHere(ignore, f.path),
54 )
55 .map((f) => f.path);
56 if (drop.length === 0) return [];
57 heard(root, (await api.record(Object.fromEntries(drop.map((rel) => [rel, null])))).news);
58 for (const rel of drop) forgetKnown(root, rel);
59 return drop.sort();
62function droppedIgnoredText(dropped: readonly string[]): string[] {
63 if (dropped.length === 0) return [];
64 return [
65 `Dropped from your draft, kept on disk (your ignore rules leave ${dropped.length === 1 ? "it" : "them"} out; abso check-ignore says which line): ${dropped.join(", ")}`,
66 ];
69/**
70 * After "Pushed version N.": whether CI will check it, where the server says (its `ciWhere`). Nothing for the server's own
71 * compute, where pushes have always been checked, or for a server that doesn't say.
72 */
73export function ciWhereText(where: string | undefined, version: number): string[] {
74 if (where === "off")
75 return [
76 `CI is off for this project, so version ${version} isn't checked. Connect a Cloudflare account in the project's settings on the website to run it there.`,
77 ];
78 if (where === "account")
79 return [`CI checks it in the project's Cloudflare account: abso ci ${version} shows the result.`];
80 return [];
83export async function runPublish(args: Parsed, env: Env): Promise<Output> {
84 const message = str(args, "message");
85 if (!message) throw new UsageError('say why with -m "<message>"');
86 const { root, config, api } = open(env);
87 if (config.reader) throw new UsageError(READER_REFUSES);
88 let check = str(args, "check");
89 const rawWait = str(args, "wait");
90 if (rawWait !== undefined && !/^\d{1,4}$/.test(rawWait))
91 throw new UsageError(
92 `--wait is how many seconds to wait for a queued push to land, like 100 (got ${JSON.stringify(rawWait)})`,
93 );
94 const waitSeconds = bool(args, "no-wait") ? 0 : rawWait === undefined ? WAIT_SECONDS : Number(rawWait);
95 let skippedCheck = false;
96 if (check === "") {
97 // With the merge queue on, the queue runs the project's check on what actually lands (#39): --check alone adds nothing.
98 const pf = readProjectFile(root);
99 if (pf !== null && !("error" in pf) && pf.file.queue) {
100 check = undefined;
101 skippedCheck = true;
102 }
103 }
104 if (check === "") {
105 // --check alone: the build and check in the draft's own avcs.json, as the server's job runs them on
106 // each version, so a draft that changes them runs the new ones (#39).
107 const pf = readProjectFile(root);
108 const PROJECT_FILE = projectFileName(root);
109 if (pf === null || "error" in pf || pf.file.check === "") {
110 const why =
111 pf === null ? `there is no ${PROJECT_FILE}` : "error" in pf ? pf.error : `${PROJECT_FILE} has no "check"`;
112 throw new UsageError(
113 `--check alone runs the project's check, but ${why}. Set "check" in ${PROJECT_FILE} (e.g. {"check": "npm test"}), or give the command: --check "npm test"`,
114 );
115 }
116 check = pf.file.build === "" ? pf.file.check : `${pf.file.build} && ${pf.file.check}`;
117 }
118 if (check !== undefined) {
119 // Your draft on newest shared, as it would land, must pass the check (#37):
120 // two changes that each passed alone turned shared red twice. Sync first, then run it in the box.
121 const say = env.writeErr ?? env.write;
122 // Known to have no prep: refuse before syncing and running (#37). Unknown: the run below tells.
123 const noPrep =
124 "your box has no prep, so a check would run without node_modules and its result couldn't be trusted. Run abso prep 'npm ci --ignore-scripts' once (every fresh box then starts from it), then push --check again.";
125 if (knownPrep(root, boxOf(args, env)) === null && existsSync(join(root, "package-lock.json"))) {
126 return {
127 exit: EXIT.refused,
128 text: `Not pushed: ${noPrep} (Nothing was run: this folder's last run in that box said it had no prep.)`,
129 json: { check: { command: check, ran: false, prep: null } },
130 };
131 }
132 const synced = await unreached(
133 runSync({ positionals: [], flags: new Map() }, env),
134 "Nothing was pushed, and the check didn't run.",
135 );
136 const sj = synced.json as { collisions?: readonly unknown[]; refused?: readonly Refused[] };
137 if ((sj.collisions?.length ?? 0) > 0) {
138 return {
139 exit: EXIT.refused,
140 text: `${synced.text}\nNot pushed: the pull before the check left collisions. Settle them, then push --check again.`,
141 json: { check: null, sync: synced.json },
142 };
143 }
144 if (synced.text) say(`${synced.text}\n`);
145 // Paths the sync wouldn't write (safety.ts) don't block: the check just ran without them.
146 if ((sj.refused?.length ?? 0) > 0)
147 say(
148 `abso: the pull didn't write these: ${sj.refused!.map((r) => r.path).join(", ")}; the check runs without them.\n`,
149 );
150 say(`abso: checking your draft on newest shared in the box: ${check}\n`);
151 const flags = new Map<string, string | boolean>();
152 const box = str(args, "box");
153 if (box !== undefined) flags.set("box", box);
154 const ran = await runRun({ positionals: [check], flags }, { ...env, runKind: "publish-check" });
155 // No prep and a package-lock: the box had no node_modules, so the check can't be trusted either way
156 // (#37: npx tsc fetched an unrelated, deprecated tsc package).
157 if ((ran.json as { prep?: string | null }).prep === null && existsSync(join(root, "package-lock.json"))) {
158 return {
159 exit: EXIT.refused,
160 text: "Not pushed: your box has no prep, so the check ran without node_modules and its result can't be trusted. Run abso prep 'npm ci --ignore-scripts' once (every fresh box then starts from it), then push --check again.",
161 json: { check: { command: check, exit: ran.exit ?? 0, prep: null } },
162 };
163 }
164 if ((ran.exit ?? 0) !== 0) {
165 // Whose is it? Run the check once more on shared alone, at the version just synced to (#36:
166 // stopped by someone else's red test, nothing said whose). One extra run, only when the check fails.
167 const recent = (await api.log({ agent: config.agent }, 5)).versions;
168 const newest = recent[0]?.version;
169 let verdict: string[] = [];
170 let sharedExit: number | undefined;
171 if (newest !== undefined) {
172 say(`abso: the check failed; running it on shared alone (version ${newest}) to see whose it is.\n`);
173 const atFlags = new Map(flags);
174 atFlags.set("at", String(newest));
175 sharedExit =
176 (
177 await runRun(
178 { positionals: [check], flags: atFlags },
179 { ...env, write: () => {}, writeErr: () => {}, runKind: "publish-check" },
180 )
181 ).exit ?? 0;
182 const who = recent.map((v) => `${v.version} by ${v.agent} ("${v.message}")`).join("; ");
183 verdict =
184 sharedExit === 0
185 ? [`It passes on shared alone (version ${newest}), so your draft is what breaks it.`]
186 : [
187 `It fails on shared alone too (version ${newest}, exit ${sharedExit}), so it isn't your draft. The latest versions: ${who}.`,
188 `abso bisect -- ${check} finds the one that broke it; abso announce --to <agent> "..." reaches its author.`,
189 ];
190 }
191 return {
192 exit: EXIT.refused,
193 text: [
194 `Not pushed: the check failed (exit ${ran.exit}) on your draft with newest shared. Its output is above.`,
195 ...verdict,
196 ].join("\n"),
197 json: {
198 check: {
199 command: check,
200 exit: ran.exit,
201 ...(sharedExit === undefined ? {} : { sharedAlone: { version: newest, exit: sharedExit } }),
202 },
203 },
204 };
205 }
206 say("abso: the check passed; pushing.\n");
207 }
208 const checked = check !== undefined;
209 const leftOut: LeftOut[] = [];
210 const steps = publishSteps(args, env, root, config, api, message, checked, waitSeconds, skippedCheck, leftOut);
211 // Say how far it got when the server can't be reached (#37, GAME - UI/UX: did the check run? did the draft go up?).
212 const reached = await unreached(
213 steps,
214 checked ? "The check passed, but the push never reached the server: nothing was pushed." : "Nothing was pushed.",
215 `${checked ? "The check passed; " : ""}the push may have reached the server before its answer was lost: abso status shows whether your draft was pushed.`,
216 );
217 const out = withLeftOut(reached, leftOut);
218 // --done: this publish finishes the work the start note named (#44): take the note back once it's published.
219 // A publish still in the merge queue may yet be pulled, so its note and issue stay as they are until it lands.
220 if (!bool(args, "done")) return out;
221 const { version, queued, outcome } = out.json as { version?: unknown; queued?: unknown; outcome?: unknown };
222 if (version === undefined) {
223 if (queued === undefined || outcome === "pulled") return out;
224 return {
225 ...out,
226 text: `${out.text}\nYour start note stays (--done): push ${queued} hasn't landed yet. Once it has, abso start --done takes the note back and abso issue <N> --done closes the issue it names.`,
227 };
228 }
229 // done (#54): the work is finished, so an issue the note named is closed with this change.
230 await api.starting(null, undefined, { done: true });
231 return {
232 ...out,
233 text: `${out.text}\nYour start note is taken back (--done): this work is finished.`,
234 json: { ...out.json, startNote: null },
235 };
238/**
239 * When a publish's answer was lost (a 5xx, or the connection dropped after the
240 * request went out), whether it landed: shared's newest versions, or the merge
241 * queue, hold this agent's publish with this message from this attempt. Undefined
242 * when the error isn't that kind, or when looking fails too.
243 */
244async function afterLostPublish(
245 api: Api,
246 agent: string,
247 message: string,
248 started: number,
249 err: unknown,
250): Promise<Output | undefined> {
251 if (!(err instanceof ApiError) || err.notSent || (err.status !== undefined && err.status < 500)) return undefined;
252 const why = err.message;
253 try {
254 // A server clock a little apart from this one still counts; an older publish with the same message doesn't.
255 const recent = (v: { time: number }) => v.time >= started - 120_000;
256 const landed = (await api.log({ draft: null }, 10)).versions.find(
257 (v) => v.agent === agent && v.message === message.trim() && recent(v),
258 );
259 if (landed) {
260 return {
261 text: `Pushed version ${landed.version}. The server's answer was lost (${why}), but shared's log shows your push landed.`,
262 json: { version: landed.version, lostAnswer: why },
263 };
264 }
265 const queued = ((await api.queueState().catch(() => undefined))?.items ?? []).find(
266 (q) => q.agent === agent && q.message === message.trim() && recent(q),
267 );
268 if (queued) {
269 return {
270 exit: STILL_QUEUED,
271 text: `Queued as push ${queued.id}. The server's answer was lost (${why}), but the merge queue holds your push; the outcome comes as news on your next edit, and abso status shows the queue.`,
272 json: { queued: queued.id, outcome: "queued", lostAnswer: why },
273 };
274 }
275 return {
276 exit: EXIT.error,
277 text: `Not pushed: ${why}. Shared's newest versions and the merge queue don't have it, so it's safe to push again.`,
278 json: { published: false, lostAnswer: why },
279 };
280 } catch {
281 return undefined;
282 }
285/**
286 * A network failure, said with how far the command got: when nothing reached the
287 * server, `notSent` and "run it again"; when a request went out and its answer
288 * was lost, `sent` (or the error as it was).
289 */
290async function unreached<T>(work: Promise<T>, notSent: string, sent?: string): Promise<T> {
291 try {
292 return await work;
293 } catch (err) {
294 if (!(err instanceof ApiError) || err.status !== undefined) throw err;
295 if (err.notSent) throw new ApiError(`${err.message}. ${notSent} Run the same command again.`, undefined, true);
296 if (sent === undefined) throw err;
297 throw new ApiError(`${err.message}. ${sent}`);
298 }
301async function publishSteps(
302 args: Parsed,
303 env: Env,
304 root: string,
305 config: Config,
306 api: Api,
307 message: string,
308 checked: boolean,
309 waitSeconds: number,
310 skippedCheck: boolean,
311 leftOut: LeftOut[],
312 autoSettled = false,
313): Promise<Output> {
314 const recorded = await recordFolder(root, api, false, meantBinary(args));
315 leftOut.push(...recorded.leftOut);
316 const pre = [...recordedFirst(recorded), ...droppedIgnoredText(await dropIgnoredFromDraft(root, api))];
317 if (recorded.turnedBinary.length > 0) {
318 // Publishing now would leave the others on the file's old text without anyone noticing (#25).
319 return {
320 exit: EXIT.refused,
321 text: [...pre, ...turnedBinaryText(recorded.turnedBinary), "Not pushed."].join("\n"),
322 json: { turnedBinary: recorded.turnedBinary, recorded: recorded.sent },
323 };
324 }
325 const asIs = bool(args, "as-is");
326 if (asIs) {
327 const me = (await api.status()).agents.find((a) => a.agent === config.agent);
328 const marked = [...new Set((me?.collisions ?? []).map((c) => c.file))].filter(
329 (rel) => blocksIn(absolute(root, rel)) > 0,
330 );
331 for (const rel of marked)
332 writeFileAtomic(absolute(root, rel), settleText(readText(absolute(root, rel))!, "both").text);
333 if (marked.length > 0) await recordFolder(root, api);
334 }
335 const started = Date.now();
336 let answer: Awaited<ReturnType<Api["publish"]>>;
337 try {
338 answer = await api.publish(message, asIs);
339 } catch (err) {
340 // The answer can be lost after the publish committed (a storage reset killed the reply to
341 // two publishes that had landed). Look before saying it failed; never publish again by itself.
342 const found = await afterLostPublish(api, config.agent, message, started, err);
343 if (found) return { ...found, text: [...pre, found.text].join("\n") };
344 throw err;
345 }
346 if (answer.ok && "queued" in answer) {
347 // The merge queue (#39): it lands once a batch with it passes the project's check.
348 const say = env.writeErr ?? env.write;
349 const head = `Queued as push ${answer.queued}${answer.ahead === 0 ? "" : `, ${answer.ahead} ${answer.ahead === 1 ? "push" : "pushes"} ahead of it`}: it lands once the project's check passes on it in the merge queue.`;
350 const notes = [
351 ...pre,
352 ...(skippedCheck
353 ? ["The merge queue runs the project's check on what lands, so --check alone was skipped."]
354 : []),
355 ...settledText(answer.settled ?? [], undefined),
356 ];
357 const json = {
358 queued: answer.queued,
359 position: answer.position,
360 ahead: answer.ahead,
361 changes: answer.changes,
362 settled: answer.settled ?? [],
363 recorded: recorded.sent,
364 };
365 const later =
366 "The outcome comes as news on your next edit; abso status shows the queue, and abso unqueue takes it back.";
367 if (waitSeconds === 0)
368 return {
369 text: [...notes, head, `Not waiting (--no-wait). ${later}`].join("\n"),
370 json: { ...json, outcome: "queued" },
371 };
372 say(`abso: ${head} Waiting up to ${waitSeconds} s for it (--no-wait returns at once).\n`);
373 const out = await waitForQueued(
374 api,
375 answer.queued,
376 waitSeconds * 1000,
377 say,
378 Number(fromEnv(env.env, "QUEUE_POLL_MS")) || 3000,
379 );
380 if (out.kind !== "waiting") heard(root, out.news);
381 if (out.kind === "landed")
382 return {
383 text: [...notes, `Pushed version ${out.version}: it passed the project's check in the merge queue.`].join("\n"),
384 json: { ...json, version: out.version, outcome: "landed" },
385 };
386 if (out.kind === "pulled")
387 return {
388 exit: EXIT.refused,
389 text: [...notes, pulledText(out.text)].join("\n"),
390 json: { ...json, outcome: "pulled", reason: out.text },
391 };
392 if (out.kind === "gone") {
393 return {
394 exit: STILL_QUEUED,
395 text: [
396 ...notes,
397 `Push ${answer.queued} left the merge queue, but nothing said whether it landed: abso log -n 3 shows it if it did.`,
398 ].join("\n"),
399 json: { ...json, outcome: "unknown" },
400 };
401 }
402 const where = out.state
403 ? standing(out.state.items, answer.queued)
404 : "still in the queue (the queue could not be read)";
405 return {
406 exit: STILL_QUEUED,
407 text: [...notes, `Still queued after ${waitSeconds} s: push ${answer.queued} is ${where}. ${later}`].join("\n"),
408 json: { ...json, outcome: "queued" },
409 };
410 }
411 if (answer.ok) {
412 const merged = answer.mergedWith ?? [];
413 const what =
414 answer.changes === 0
415 ? await alreadyInShared(root, api, config.agent, recorded.paths, answer.version)
416 : `Pushed version ${answer.version}.${merged.length > 0 ? ` ${mergedText(merged)}` : ""}`;
417 // The check ran on shared as it was; what landed since went in unchecked.
418 const moved =
419 checked && merged.length > 0
420 ? [
421 `Shared moved during the check: ${merged.length === 1 ? "version" : "versions"} ${merged.map((m) => m.version).join(", ")} merged in without being checked.`,
422 ]
423 : [];
424 return {
425 text: [
426 ...pre,
427 what,
428 ...moved,
429 // --check alone was skipped for a queue that turned out not to be on: the answer, not the draft's avcs.json, says.
430 ...(skippedCheck
431 ? [
432 `It landed directly, with no check: your avcs.json says "queue": true, but shared's doesn't yet, so the merge queue isn't on and --check alone was skipped. abso ci ${answer.version} shows CI's result once it has run.`,
433 ]
434 : []),
435 ...settledText(answer.settled ?? [], answer.version),
436 ...(answer.changes === 0 ? [] : ciWhereText(answer.ciWhere, answer.version)),
437 ].join("\n"),
438 json: {
439 version: answer.version,
440 ...(answer.ciWhere === undefined ? {} : { ciWhere: answer.ciWhere }),
441 changes: answer.changes ?? null,
442 mergedWith: answer.mergedWith ?? [],
443 settled: answer.settled ?? [],
444 recorded: recorded.sent,
445 },
446 };
447 }
448 const collisions = answer.collisions ?? [];
449 // Marker blocks still in the draft (#11): settle them, or --as-is keeps both everywhere.
450 if (collisions.length > 0 && collisions.every((c) => c.marked)) {
451 const files = [...new Set(collisions.map((c) => c.file))];
452 return {
453 exit: EXIT.refused,
454 text: [
455 ...pre,
456 `Not pushed: ${files.join(", ")} still ${files.length === 1 ? "has" : "have"} collision markers (${plural(collisions.length, "block")}).`,
457 ...collisions.map(collisionText),
458 `Settle each: keep yours, theirs or a mix and delete the marker lines, or abso settle <file> --yours|--theirs|--both. Then push again. abso push --as-is keeps both sides everywhere; the other authors hear it.`,
459 ].join("\n"),
460 json: { collisions, recorded: recorded.sent },
461 };
462 }
463 // Lines both sides changed, still as the sync left them (#37): publishing would put both in shared.
464 if (collisions.length > 0 && collisions.every((c) => c.untouched)) {
465 return {
466 exit: EXIT.refused,
467 text: [
468 ...pre,
469 `Not pushed: ${plural(collisions.length, "collision")} you pulled into and haven't edited since. Both sides' lines are still in the file, so pushing now would put them in shared twice.`,
470 ...collisions.map(collisionText),
471 "Edit each to what it should be (keep yours, theirs, or a mix), then push again. If both really belong, abso push --as-is keeps both.",
472 ].join("\n"),
473 json: { collisions, recorded: recorded.sent },
474 };
475 }
476 const local = collisions.filter((c) => isLocalOnly(c.file));
477 const real = collisions.filter((c) => !isLocalOnly(c.file));
478 const twice = real.filter((c) => c.kind === "duplicate");
479 const newer = real.filter((c) => c.kind !== "duplicate");
480 // The server's first opinion on each collision (#19), when it runs AUTOSETTLE.
481 const advice = answer.advice ?? [];
482 // When the server says to settle (its AUTOSETTLE=act) and to keep a side of every collision, settle them here and
483 // push again (ABSO_AUTOSETTLE=off stops it).
484 const plan = autoSettled || answer.settle !== true ? null : autoPlan(collisions, advice, env);
485 if (plan) {
486 const pulled = await runSync({ positionals: [], flags: new Map() }, env);
487 const done: string[] = [];
488 for (const [file, a] of plan) {
489 const path = absolute(root, file);
490 const text = readText(path);
491 const settled =
492 text === null || text === undefined ? null : settleText(text, a.pick as "yours" | "theirs" | "both");
493 if (!settled) continue;
494 if (settled.blocks > 0) {
495 writeFileAtomic(path, settled.text);
496 done.push(file);
497 continue;
498 }
499 // No marker block: the pull merged the lines itself. That counts when the file already holds the
500 // advised side's lines (keep both: both sides').
501 const lines = new Set(text!.split(/\r?\n/).map((l) => l.trim()));
502 const sides = collisions
503 .filter((c) => c.file === file)
504 .flatMap((c) => [
505 ...(a.pick !== "theirs" ? [c.yours.text] : []),
506 ...(a.pick !== "yours" ? [c.theirs.text] : []),
507 ]);
508 const wanted = sides.flatMap((t) => t.split(/\r?\n/).map((l) => l.trim())).filter((l) => l !== "");
509 if (wanted.length > 0 && wanted.every((l) => lines.has(l))) done.push(file);
510 }
511 const left = [...plan.keys()].filter((f) => !done.includes(f));
512 if (left.length > 0)
513 return {
514 exit: EXIT.refused,
515 text: [
516 ...pre,
517 pulled.text,
518 `Not pushed: the server advised settling ${left.join(", ")}, but the pull left no marker block there. Settle as the pull says, then push again.`,
519 ].join("\n"),
520 json: { collisions, advice, autosettle: { pulled: true, settled: done, left } },
521 };
522 const again = await publishSteps(
523 args,
524 env,
525 root,
526 config,
527 api,
528 `${message}\n\n${autoTrailer(plan)}`,
529 checked,
530 waitSeconds,
531 skippedCheck,
532 leftOut,
533 true,
534 );
535 return {
536 ...again,
537 text: [
538 ...pre,
539 `Held: ${plural(collisions.length, "collision")} with work pushed since your last pull. Settled automatically, as the server advised:`,
540 ...[...plan].map(([file, a]) => ` ${file}: ${adviceWords(a)}`),
541 again.text,
542 "Check what was kept with abso show <version>:<file>; to change it, edit the file and push. ABSO_AUTOSETTLE=off settles nothing by itself.",
543 ].join("\n"),
544 json: { ...(again.json as object), autosettled: Object.fromEntries(plan) },
545 };
546 }
547 return {
548 exit: EXIT.refused,
549 text: [
550 ...pre,
551 // A name defined twice is already in your folder (sync listed it); the rest is newer work.
552 `Not pushed: ${plural(collisions.length, "collision")}${newer.length > 0 ? " with work pushed since your last pull" : ""}.${answer.reason ? ` (${answer.reason})` : ""}`,
553 ...real.map(collisionText),
554 ...(advice.some((a) => a)
555 ? [
556 "First opinion (a model on the server, with checks in code; you still settle):",
557 ...collisions.flatMap((c, i) => (advice[i] ? [` ${c.file}: ${adviceWords(advice[i]!)}`] : [])),
558 ]
559 : []),
560 ...(local.length > 0
561 ? [
562 ` ${local.map((c) => c.file).join(", ")}: local files that should never have been shared. abso pull drops them from your draft and leaves your copy on disk.`,
563 ]
564 : []),
565 ...(real.some((c) => c.theirs.queued !== undefined)
566 ? [
567 "Some of theirs are still in the merge queue, not in shared: once they land (abso status shows the queue), abso pull brings them in to settle; if they're turned back, push again as you are.",
568 ]
569 : []),
570 newer.length > 0
571 ? `Run abso pull: each of those files comes back holding both sides' lines, in a marker block where you both changed the same lines. Settle each as the pull says${twice.length > 0 ? ", keep one definition of each name defined twice" : ""}, then push again.`
572 : twice.length > 0
573 ? "Keep one definition of each name defined twice (delete yours, or theirs), then push again."
574 : "Run abso pull, then push again.",
575 ].join("\n"),
576 json: {
577 collisions,
578 recorded: recorded.sent,
579 ...(answer.reason ? { reason: answer.reason } : {}),
580 ...(advice.length > 0 ? { advice } : {}),
581 },
582 };
585function adviceWords(a: Advice): string {
586 const what = a.pick === "agent" ? "needs an agent" : `keep ${a.pick}`;
587 const how =
588 a.by === "rule"
589 ? "by a check in code"
590 : a.by === "turned down"
591 ? `the model said keep ${a.modelPick}, turned down`
592 : a.by === "unsure"
593 ? `the model leaned to keep ${a.modelPick} at ${a.confidence.toFixed(2)}`
594 : `confidence ${a.confidence.toFixed(2)}`;
595 return `${what} (${how}): ${a.reason}`;
598/**
599 * What to settle by itself (#19), file by file, or null to leave it to the agent: every collision a lines collision
600 * the server advised keeping a side of (it advises a side only at or above its threshold), each file's advice the
601 * same, nothing still queued or local-only, and ABSO_AUTOSETTLE not "off".
602 */
603function autoPlan(
604 collisions: readonly Collision[],
605 advice: readonly (Advice | null)[],
606 env: Env,
607): Map<string, Advice> | null {
608 if (fromEnv(env.env, "AUTOSETTLE") === "off" || collisions.length === 0) return null;
609 const plan = new Map<string, Advice>();
610 for (const [i, c] of collisions.entries()) {
611 const a = advice[i];
612 if ((c.kind ?? "lines") !== "lines" || c.untouched || c.marked || c.theirs.queued !== undefined) return null;
613 if (isLocalOnly(c.file) || !a || a.pick === "agent") return null;
614 const before = plan.get(c.file);
615 if (before && before.pick !== a.pick) return null;
616 if (!before || a.confidence < before.confidence) plan.set(c.file, a);
617 }
618 return plan;
621export async function runSync(args: Parsed, env: Env): Promise<Output> {
622 const { root, api } = open(env);
623 const recorded = await recordFolder(root, api);
624 const ignoredDropped = await dropIgnoredFromDraft(root, api);
625 // A pull here that never wrote its answer (abso-core 26): this one asks for every file to catch up.
626 const catchingUp = pullUnfinished(root) && !bool(args, "full");
627 const s = await syncFolder(root, api, bool(args, "full"));
628 const changes = s.written.length + s.deleted.length;
629 // A renamed file is one line, not an update and a delete.
630 const updated = s.written.filter((f) => !s.renamed.some((r) => r.to === f));
631 const removed = s.deleted.filter((f) => !s.renamed.some((r) => r.from === f));
632 const lines = [
633 ...turnedBinaryText(recorded.turnedBinary),
634 ...recordedFirst(recorded),
635 ...droppedIgnoredText(ignoredDropped),
636 `Pulled to version ${s.version}: ${changes === 0 ? "no files changed" : `${plural(updated.length, "file")} updated, ${removed.length} deleted${s.renamed.length > 0 ? `, ${s.renamed.length} renamed` : ""}`}.`,
637 ...changedFilesText("pull", updated, removed, s.renamed, bool(args, "verbose")),
638 ...(catchingUp
639 ? ["The last pull here didn't finish, so this one asked for every file and wrote the ones that differed."]
640 : []),
641 ...refusedText(s.refused),
642 // Ones an earlier sync couldn't write; this sync's are named just above.
643 ...unwrittenText(s.unwritten, new Set(s.refused.map((r) => r.path))),
644 ...mergedLinesText(s.merged),
645 ...(s.kept.length > 0
646 ? [`Left alone because they changed while pulling (run abso pull again): ${s.kept.join(", ")}`]
647 : []),
648 ...(s.dropped.length > 0
649 ? [`Dropped from your draft, kept on disk (these stay local): ${s.dropped.join(", ")}`]
650 : []),
651 ...(s.collisions.length > 0
652 ? [collisionsHeading(s.collisions), ...s.collisions.map(collisionText), ...sameVersionHint(s.collisions)]
653 : []),
654 ];
655 return {
656 text: lines.join("\n"),
657 json: {
658 version: s.version,
659 written: s.written,
660 deleted: s.deleted,
661 renamed: s.renamed,
662 kept: s.kept,
663 dropped: s.dropped,
664 collisions: s.collisions,
665 merged: s.merged,
666 refused: s.refused,
667 recorded: recorded.sent,
668 ignoredDropped,
669 },
670 };
673/** What a publish settled, and that each other author hears it (#11). */
674function settledText(settled: readonly Settled[], version: number | undefined): string[] {
675 if (settled.length === 0) return [];
676 const said = { yours: "kept yours", theirs: "kept theirs", both: "kept both", rewrote: "rewrote them" } as const;
677 // Lines both sides still had that the settled file no longer has (#37): the settler should look.
678 const quote = (l: string) => `"${l.trim().length > 60 ? `${l.trim().slice(0, 57)}...` : l.trim()}"`;
679 return [
680 `Settled ${plural(settled.length, "collision")}: ${settled.map((s) => `${s.file} (${said[s.kept]}, against ${s.theirs.agent}'s version ${s.theirs.version})`).join("; ")}. ${[...new Set(settled.map((s) => s.theirs.agent))].join(", ")} will hear what you kept.`,
681 ...settled
682 .filter((s) => (s.lost?.length ?? 0) > 0)
683 .map(
684 (s) =>
685 ` ${s.file}: lost ${plural(s.lost!.length, "line")} you both had: ${s.lost!.slice(0, 3).map(quote).join(", ")}${s.lost!.length > 3 ? `, and ${s.lost!.length - 3} more` : ""}; check ${version === undefined ? s.file : `abso show ${version}:${s.file}`}`,
686 ),
687 ];
690/**
691 * What an empty publish says (#37: "Nothing to publish: your draft
692 * is empty" read as lost work). The files this folder edited since its last
693 * publish (this record's, and the edit hook's sends in .avcs/hook.log) that
694 * someone else changed in shared since then: shared already has them as you
695 * do, so nothing of yours is lost.
696 */
697async function alreadyInShared(
698 root: string,
699 api: Api,
700 agent: string,
701 recordedPaths: readonly string[],
702 version: number,
703): Promise<string> {
704 const empty = `Nothing to push: your draft is empty. Shared is at version ${version}.`;
705 const log = await api.log({ agent }, FOLDER_LOG_LIMIT);
706 const since = log.versions.find((v) => v.agent === agent)?.time ?? 0;
707 const edited = new Set(recordedPaths);
708 try {
709 for (const line of readFileSync(join(stateDir(root), "hook.log"), "utf8").split("\n")) {
710 const [at, , rel, outcome] = line.split("\t");
711 if (rel && outcome?.startsWith("sent") && Date.parse(at ?? "") >= since) edited.add(rel);
712 }
713 } catch {
714 // No hook log: only this record's files.
715 }
716 const found: string[] = [];
717 for (const rel of [...edited].sort().slice(0, LISTED)) {
718 const last = (await api.log({ agent }, 1, rel)).versions[0];
719 if (last && last.agent !== agent && last.time >= since)
720 found.push(`${rel} (version ${last.version}, ${last.agent}: "${last.message}")`);
721 }
722 if (found.length === 0) return empty;
723 return `Nothing pushed: shared already has ${found.length === 1 ? "the file you changed" : "the files you changed"} as you have ${found.length === 1 ? "it" : "them"}, so nothing of yours is lost. Last changed in ${found.join("; ")}. Shared is at version ${version}.`;
726/**
727 * Several files marked against one version (#37: twenty tool
728 * scripts muted twice at once): if that version already does what yours do,
729 * one settle takes theirs in all of them.
730 */
731export function sameVersionHint(collisions: readonly Collision[]): string[] {
732 const groups = new Map<number, { agent: string; message: string; files: Set<string> }>();
733 for (const c of collisions) {
734 if (!c.marked || c.theirs.agent === "") continue;
735 const g = groups.get(c.theirs.version) ?? {
736 agent: c.theirs.agent,
737 message: c.theirs.message,
738 files: new Set<string>(),
739 };
740 g.files.add(c.file);
741 groups.set(c.theirs.version, g);
742 }
743 return [...groups]
744 .filter(([, g]) => g.files.size >= 2)
745 .map(([version, g]) => {
746 const files = [...g.files].sort();
747 return `${files.length} files collide with ${g.agent}'s version ${version} ("${g.message}"). If it already does what yours does, abso settle ${files.map(shellWord).join(" ")} --theirs takes theirs in all of them.`;
748 });