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/status-commands.ts?version=289&format=json
404 linesFirst import 83% · speed 5% · pinch 5% · review 3% · rename 2% · engine 1% · infra-split 1%Last change pinch in version 289, 12 versions changed it

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

1// abso status, and the small folder commands beside it: reader, mv, fix-eol
2// and settle.
3
4import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync } from "node:fs";
5import { dirname, join } from "node:path";
6import { isComposed, pathKey } from "../../worker/project/pathkey.ts";
7import type { OpenCollision } from "./api.ts";
8import { bool, type Parsed, UsageError } from "./args.ts";
9import { readKnownBlobs, writeKnownBlobs } from "./blobs.ts";
10import { ciText } from "./ci.ts";
11import { CleanFiles } from "./clean-files.ts";
12import { newerClientNote } from "./client-version.ts";
13import { type Env, heard, type Output, open, plural } from "./command-env.ts";
14import {
15 LISTED,
16 leftOutText,
17 pullUnfinishedText,
18 READER_REFUSES,
19 readUnwritten,
20 recordedFirst,
21 recordFolder,
22 turnedBinaryText,
23 unwrittenText,
24} from "./commands.ts";
25import { credentialLabel, type Settings, writeConfig } from "./config.ts";
26import { uncomposedText } from "./core.ts";
27import {
28 absolute,
29 forgetKnown,
30 isLocalOnly,
31 knownPath,
32 listKnown,
33 newFileEndings,
34 normalize,
35 readKnown,
36 readText,
37 unrecorded,
38 writeFileAtomic,
39 writeKnown,
40} from "./folder.ts";
41import { fileArg } from "./history.ts";
42import { modsBehindText } from "./install.ts";
43import { isLocal } from "./local-store.ts";
44import { withFolderLock } from "./lock.ts";
45import { readKnownModes, writeKnownModes } from "./modes.ts";
46import { queueText } from "./queue.ts";
47import { unsafePath } from "./safety.ts";
48import { keepFrom, settleText } from "./settle.ts";
49import { stateDir } from "./state-dir.ts";
51// --- status ---
53/**
54 * Files in the agent's view that the folder lacks (#37: a join that got only
55 * part of them). A file the agent deleted and hasn't recorded is in `pending`,
56 * not here.
57 */
58export function missingHere(root: string, view: readonly string[], pending: ReadonlySet<string>): string[] {
59 return view.filter((rel) => {
60 if (pending.has(rel) || isLocalOnly(rel)) return false;
61 try {
62 lstatSync(absolute(root, rel));
63 return false;
64 } catch {
65 return true;
66 }
67 });
70/**
71 * Recorded text files whose copy on disk differs from the record only by CRLF
72 * line endings (#37: Python's text mode on Windows writes CRLF).
73 * abso records them, and abso run sends them, with LF; a tool run here sees
74 * CRLF. Files git would check out with CRLF are left out of the list.
75 * With `clean` (status), a file found unchanged before is answered without reading it.
76 */
77export function crlfOnly(root: string, clean?: CleanFiles): string[] {
78 const out: string[] = [];
79 const state = stateDir(root);
80 for (const rel of listKnown(root)) {
81 const key = clean?.key(absolute(root, rel), knownPath(root, rel, state));
82 const was = key && clean!.check(rel, key);
83 if (was) {
84 if (was.cr) out.push(rel);
85 continue;
86 }
87 const disk = readText(absolute(root, rel));
88 if (disk === undefined || !disk.includes("\r")) continue;
89 if (normalize(disk) === readKnown(root, rel, state)) {
90 out.push(rel);
91 if (key) clean!.mark(rel, key, true);
92 }
93 }
94 const git = newFileEndings(root, out);
95 return out.filter((rel) => git.get(rel) !== "crlf").sort();
98/**
99 * Whether the last edit here came from an older edit mod than the one
100 * installed (#37, Reporter: a chat keeps the mod it started with, and an old
101 * one sent files nested ignore files leave out). The mod writes its version
102 * as the sixth field of each .avcs/hook.log line (from #33); the installed
103 * one's is in its plugin.json. Says nothing until the installed mod carries a
104 * commit, or when the last edit came from the mod as installed.
105 */
106export function staleModText(root: string, env: Readonly<Record<string, string | undefined>>): string[] {
107 let installed: string | undefined;
108 const skills = join(env.CLAUDE_CONFIG_DIR || join(env.USERPROFILE || env.HOME || "", ".claude"), "skills");
109 for (const name of ["abso-hooks", "avcs"]) {
110 try {
111 installed = String(
112 (JSON.parse(readFileSync(join(skills, name, ".claude-plugin", "plugin.json"), "utf8")) as { version?: unknown })
113 .version,
114 );
115 break;
116 } catch {}
117 }
118 if (installed === undefined) return [];
119 if (!installed.includes("+")) return [];
120 let last: string[] | undefined;
121 try {
122 const lines = readFileSync(join(stateDir(root), "hook.log"), "utf8")
123 .split("\n")
124 .filter((l) => l.includes("(in process"));
125 last = lines.at(-1)?.split("\t");
126 } catch {
127 return [];
128 }
129 if (last === undefined) return [];
130 const sent = last[5]?.replace(/^avcs-mod\//, "");
131 if (sent === installed || sent === "checkout") return [];
132 const when = last[0] ? ` (at ${last[0].slice(11, 16)} UTC)` : "";
133 return [
134 `The last edit here${when} came from edit mod ${sent ?? "from before mods carried a version"}, but ${installed} is installed. A chat keeps the mod it started with; restart the chat that edits this folder to load the installed one.`,
135 ];
138/** abso reader on|off: make this folder's agent a reader, or a writer again (#37, Reporter). */
139export async function runReader(args: Parsed, env: Env): Promise<Output> {
140 const word = args.positionals[0];
141 if (args.positionals.length !== 1 || (word !== "on" && word !== "off"))
142 throw new UsageError("abso reader on, or abso reader off");
143 const { root, api } = open(env);
144 const on = word === "on";
145 // The server first: it refuses a reader with unpublished or parked work (409), and then nothing here changes.
146 await api.reader(on);
147 const raw = JSON.parse(readFileSync(join(stateDir(root), "config.json"), "utf8")) as Record<string, unknown>;
148 if (on) raw.reader = true;
149 else delete raw.reader;
150 writeConfig(root, raw as unknown as Settings);
151 return {
152 text: on
153 ? "This folder is a reader now: status, pull, log, show, files and export work, and nothing it does is recorded or pushed. abso reader off undoes it."
154 : "This folder records and pushes again.",
155 json: { reader: on },
156 };
159/** Status's lines for marker blocks still in the draft (#11). */
160export function openCollisionsText(open: readonly OpenCollision[]): string[] {
161 if (open.length === 0) return [];
162 return [
163 `${plural(open.length, "collision")} to settle before you push (keep yours, theirs or a mix and delete the marker lines, or abso settle <file> --yours|--theirs|--both):`,
164 ...open.map(
165 (c) =>
166 ` ${c.file} lines ${c.lines[0]}-${c.lines[1]}, with ${c.theirs.agent}'s version ${c.theirs.version} ("${c.theirs.message}")`,
167 ),
168 ];
171/** abso fix-eol: rewrite the files that differ from the record only in line endings with LF, as recorded (#37). */
172/**
173 * abso mv <from> <to> (#49): move a file in the draft,
174 * its lines keeping their history, as git mv. The way to change a file's case
175 * (or its Unicode spelling), since two spellings of one name are one file.
176 */
177export async function runMv(args: Parsed, env: Env): Promise<Output> {
178 if (args.positionals.length !== 2) throw new UsageError("mv takes the file and its new name: abso mv <from> <to>");
179 const { root, config, api } = open(env);
180 if (config.reader) throw new UsageError(READER_REFUSES);
181 const from = fileArg(root, env.cwd, args.positionals[0]!);
182 const to = fileArg(root, env.cwd, args.positionals[1]!);
183 if (from === to) throw new UsageError(`${from} already has that name`);
184 const bad =
185 unsafePath(to) ??
186 (isLocalOnly(to) ? "it is under .git, .claude, .avcs or node_modules, which stay local" : undefined);
187 if (bad !== undefined) throw new UsageError(`can't move to ${to}: ${bad}`);
188 const fromPath = absolute(root, from);
189 const toPath = absolute(root, to);
190 if (!existsSync(fromPath)) throw new UsageError(`${from} isn't in this folder`);
191 // A new case (or Unicode spelling) of the same name is the same file on Windows and macOS; anything else must be free.
192 const sameFile = pathKey(from) === pathKey(to);
193 if (!sameFile && existsSync(toPath)) throw new UsageError(`${to} already exists; move or delete it first`);
194 // Edits not yet sent go first, so the move carries the file as it is.
195 await recordFolder(root, api);
196 const answer = await api.move(from, to);
197 heard(root, answer.news);
198 await withFolderLock(root, "mv", async () => {
199 mkdirSync(dirname(toPath), { recursive: true });
200 renameSync(fromPath, toPath);
201 const text = readKnown(root, from);
202 forgetKnown(root, from);
203 if (text !== undefined) writeKnown(root, to, text);
204 const modes = readKnownModes(root);
205 const mode = modes.get(from);
206 if (mode !== undefined) {
207 modes.delete(from);
208 modes.set(to, mode);
209 writeKnownModes(root, modes);
210 }
211 const blobs = readKnownBlobs(root);
212 const sha = blobs.get(from);
213 if (sha !== undefined) {
214 blobs.delete(from);
215 blobs.set(to, sha);
216 writeKnownBlobs(root, blobs);
217 }
218 });
219 return {
220 text: [
221 `Moved ${from} to ${to} in your draft; its lines keep their history. It reaches shared with your next push.`,
222 ...(isComposed(to) ? [] : [uncomposedText(to)]),
223 ].join("\n"),
224 json: { from: answer.from, to: answer.to },
225 };
228export async function runFixEol(_args: Parsed, env: Env): Promise<Output> {
229 const { root } = open(env);
230 const crlf = crlfOnly(root);
231 for (const rel of crlf) writeFileAtomic(absolute(root, rel), readText(absolute(root, rel))!.replace(/\r\n?/g, "\n"));
232 return {
233 text:
234 crlf.length === 0
235 ? "No file differs from the record only in line endings."
236 : `Rewrote ${plural(crlf.length, "file")} with LF line endings; their text is unchanged, so nothing is recorded.`,
237 json: { files: crlf },
238 };
241/** abso settle <file...> --yours | --theirs | --both: rewrite each file's marker blocks, then record (#11). */
242export async function runSettle(args: Parsed, env: Env): Promise<Output> {
243 if (args.positionals.length === 0)
244 throw new UsageError("name the files to settle: abso settle <file...> --yours, --theirs or --both");
245 const keep = keepFrom({ yours: bool(args, "yours"), theirs: bool(args, "theirs"), both: bool(args, "both") });
246 const { root, api } = open(env);
247 const files = args.positionals.map((typed) => fileArg(root, env.cwd, typed));
248 const counts: [string, number][] = [];
249 for (const rel of files) {
250 const text = readText(absolute(root, rel));
251 if (text === undefined) throw new UsageError(`${rel} is not a text file in this folder`);
252 const settled = settleText(text, keep);
253 if (settled.blocks === 0)
254 throw new UsageError(`${rel} has no collision markers to settle (abso status lists the files that do)`);
255 counts.push([rel, settled.blocks]);
256 }
257 // Each file checked first, so a typo settles nothing.
258 for (const [rel] of counts)
259 writeFileAtomic(absolute(root, rel), settleText(readText(absolute(root, rel))!, keep).text);
260 const recorded = await recordFolder(root, api);
261 const which = keep === "both" ? "both sides" : keep;
262 return {
263 text: [
264 ...recordedFirst(recorded).filter((l) => !l.startsWith("Recorded first")),
265 `Settled ${counts.map(([rel, n]) => `${plural(n, "block")} in ${rel}`).join(", ")}, keeping ${which}.${keep === "both" ? " Both sides stay in the file; when you push, the other author hears that you kept both." : ""}`,
266 ].join("\n"),
267 json: { keep, files: counts.map(([file, blocks]) => ({ file, blocks })), recorded: recorded.sent },
268 };
271/** The line status prints for files the folder is missing. */
272export function missingText(missing: readonly string[]): string[] {
273 if (missing.length === 0) return [];
274 const some =
275 missing.length <= LISTED
276 ? missing.join(", ")
277 : `${missing.slice(0, LISTED).join(", ")}, and ${missing.length - LISTED} more`;
278 return [
279 `Missing from this folder though your view has ${missing.length === 1 ? "it" : "them"} (abso pull --full writes ${missing.length === 1 ? "it" : "them"}; abso files lists them all): ${some}`,
280 ];
283export async function runStatus(args: Parsed, env: Env): Promise<Output> {
284 const { root, config, api } = open(env);
285 if (config.visitor) {
286 // A folder that reads signed out: shared's version and whether it's green. It holds no files to compare.
287 const status = await api.status();
288 return {
289 text: [
290 `Project ${config.project}: shared is at version ${status.version}. This folder reads it signed out, sending no sign-in: status, log, show, files, blame, why, where, issues, issue and search work here. To work on it: abso login, then abso join ${config.project} in a new folder.`,
291 ...ciText(status.ci ?? undefined, status.version),
292 ].join("\n"),
293 json: { project: config.project, version: status.version, visitor: true, ci: status.ci ?? null },
294 };
295 }
296 const short = bool(args, "short");
297 const { files: view, ...status } = short ? { ...(await api.status()), files: undefined } : await api.statusAndFiles();
298 const clean = CleanFiles.load(root);
299 const pending = unrecorded(root, false, new Set(), clean);
300 const local = new Set([...pending.files.keys(), ...pending.blobs.keys(), ...Object.keys(pending.modes)]);
301 if (short) {
302 clean.save();
303 // One word to stamp a build with (#37): 214, coast@3, 214+unpublished.
304 const me = status.agents.find((a) => a.agent === config.agent);
305 const unpublished = local.size > 0 || (me?.draftChanges ?? 0) > 0;
306 // +queued: published into the merge queue, not landed yet (#39).
307 const word = `${me?.draft ? `${me.draft}@` : ""}${me?.base ?? "none"}${unpublished ? "+unpushed" : ""}${(me?.queued?.length ?? 0) > 0 ? "+queued" : ""}`;
308 return { text: word, json: { version: me?.base ?? null, draft: me?.draft ?? null, unpublished, word } };
309 }
310 const missing = view === undefined ? [] : missingHere(root, view.files, local);
311 const unwritten = readUnwritten(root);
312 const crlf = crlfOnly(root, clean);
313 clean.save();
314 // Files an earlier record added to the draft and that are gone again (#37: scratch files a run
315 // recorded, deleted after): nothing reached shared, and the next record takes them out of the draft.
316 const deleted = [...pending.files].filter(([, text]) => text === null).map(([rel]) => rel);
317 const neverShared =
318 deleted.length === 0
319 ? []
320 : (await api.diff()).files
321 .filter((f) => f.before === null && deleted.includes(f.path))
322 .map((f) => f.path)
323 .sort();
324 for (const rel of neverShared) local.delete(rel);
325 const me = status.agents.find((a) => a.agent === config.agent);
326 const space = (draft: string | null | undefined): string => (draft ? `draft ${draft}` : "shared");
327 const parked = (me?.parked ?? []).filter((p) => p.draftChanges > 0);
328 const credential = credentialLabel(root, config.server, env.env);
329 // A local project reaches for nothing on the network, npm included.
330 const localProject = isLocal(config.server);
331 const behind = localProject ? undefined : await newerClientNote(config.server);
332 const lines = [
333 `Project ${config.project}: shared is at version ${status.version}. This folder is ${config.agent}${config.reader || me?.reader ? ", a reader (it records and pushes nothing)" : ""}, working in ${space(me?.draft)}.${config.follow ? ` It follows label ${config.follow}: pulls take it to the newest version with that label.` : ""}${localProject ? ` It's a local project, in ${join(config.localStore ?? "", config.project)}.` : ` Signed in with ${credential.kind}${credential.id ? ` ${credential.id}` : ""}.`}`,
334 ...(behind ? [behind] : []),
335 // Is shared green (#39)? Right under the first line, since it decides what to do next.
336 ...ciText(status.ci, status.version),
337 ...queueText(status.queue, config.agent),
338 ...(status.projectFile
339 ? [
340 `Shared has both ${status.projectFile.used} and ${status.projectFile.ignored}: ${status.projectFile.used} counts and ${status.projectFile.ignored} is ignored. Move anything you need into ${status.projectFile.used} and delete ${status.projectFile.ignored}.`,
341 ]
342 : []),
343 local.size === 0
344 ? "Everything in this folder is recorded."
345 : `Not yet recorded (abso record sends them): ${[...local.keys()].join(", ")}`,
346 ...(neverShared.length > 0
347 ? [
348 `Added to your draft by an earlier record and deleted since, so they never reach shared; the next record (pull, push, run) takes them out of your draft: ${neverShared.join(", ")}`,
349 ]
350 : []),
351 ...openCollisionsText(me?.collisions ?? []),
352 ...staleModText(root, env.env),
353 ...modsBehindText(env.env),
354 ...missingText(missing),
355 ...unwrittenText(unwritten),
356 ...pullUnfinishedText(root),
357 ...(crlf.length > 0
358 ? [
359 `${plural(crlf.length, "file")} differ${crlf.length === 1 ? "s" : ""} from what abso recorded only in line endings (CRLF here; abso records and abso run sends LF). Harmless; abso fix-eol rewrites ${crlf.length === 1 ? "it" : "them"} with LF.`,
360 ]
361 : []),
362 ...turnedBinaryText(pending.turnedBinary),
363 ...leftOutText(pending.leftOut),
364 ...(parked.length > 0
365 ? [
366 `You have work parked in ${parked.map((p) => `${space(p.draft)} (${plural(p.draftChanges, "change")})`).join(", ")}; abso switch brings it back.`,
367 ]
368 : []),
369 "Agents:",
370 ...status.agents.map((a) => {
371 const files = Array.isArray(a.files)
372 ? a.files.length === 0
373 ? ""
374 : `: ${a.files.join(", ")}`
375 : ` in ${plural(a.files as number, "file")}`;
376 const where = a.draft ? ` in draft ${a.draft},` : "";
377 return ` ${a.agent === config.agent ? "*" : " "} ${a.agent},${where} base ${a.base ?? "none"}, ${plural(a.draftChanges, "draft change")}${files}`;
378 }),
379 ...((status.drafts ?? []).length > 0
380 ? [
381 "Named drafts:",
382 ...(status.drafts ?? []).map(
383 (d) =>
384 ` ${d.name}: version ${d.version}, on shared version ${d.sharedBase}, ${plural(d.changes, "change")} not yet landed${d.agents.length > 0 ? `; ${d.agents.join(", ")}` : ""}`,
385 ),
386 ]
387 : []),
388 ];
389 return {
390 text: lines.join("\n"),
391 json: {
392 ...status,
393 agent: config.agent,
394 credential,
395 follow: config.follow ?? null,
396 unrecorded: [...local.keys()],
397 neverShared,
398 missing,
399 unwritten,
400 crlf,
401 leftOut: pending.leftOut,
402 },
403 };