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?version=11&format=json
608 linesFirst import 99% · review 1%Last change review in version 11, 2 versions changed it

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

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