- MCP
- blame on this site's /mcp
- CLI
- abso blame client/src/status-commands.ts --version 17 --json
- JSON
- /christopher/abso-core/blame/client/src/status-commands.ts?version=17&format=json
364 linesFirst import 99% · review 1%Last change review in version 17,
364 lines from 2 changes in 2 versions.
2// and settle.
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 { newerCommitNote } from "./client-version.ts";
12import { type Env, heard, type Output, open, plural } from "./command-env.ts";
13import {
14 LISTED,
15 leftOutText,
16 READER_REFUSES,
17 readUnwritten,
18 recordedFirst,
19 recordFolder,
20 turnedBinaryText,
21 unwrittenText,
22} from "./commands.ts";
23import { credentialLabel, type Settings, writeConfig } from "./config.ts";
24import { uncomposedText } from "./core.ts";
25import {
26 absolute,
27 forgetKnown,
28 isLocalOnly,
29 listKnown,
30 newFileEndings,
31 normalize,
32 readKnown,
33 readText,
34 unrecorded,
35 writeFileAtomic,
36 writeKnown,
37} from "./folder.ts";
38import { fileArg } from "./history.ts";
39import { modsBehindText } from "./install.ts";
40import { withFolderLock } from "./lock.ts";
41import { readKnownModes, writeKnownModes } from "./modes.ts";
42import { queueText } from "./queue.ts";
43import { unsafePath } from "./safety.ts";
44import { keepFrom, settleText } from "./settle.ts";
review17New folders keep their state in .abso/, and the machine's sign-in, servers and admin token are read from ~/.abso/ first, then ~/.avcs/. A folder made before, with only .avcs/, is untouched: it keeps working, is never half-moved, and no older client or mod loses it. stateDir(root) and homeFile/homeWritePath are in the new client/src/state-dir.ts and replace the old AVCS_DIR constant everywhere. abso login writes only to ~/.abso/ and leaves ~/.avcs/ alone; logout removes both copies. The edit mod and the view mod read either folder. .abso is skipped like .avcs (including its odd spellings), the git exclude names whichever folder is in use, and the messages name .abso. Not changed: avcs.json (the server reads that name, so abso.json needs the server to learn it first), .avcsignore, env var names and wire headers. Tests: 709 run, 708 pass (one is skipped), including new ones for the folder choice, the home-file order and box sign-in; biome ci has no errors.Compare45import { stateDir } from "./state-dir.ts";
47// --- status ---
49/**
50 * Files in the agent's view that the folder lacks (#37: a join that got only
51 * part of them). A file the agent deleted and hasn't recorded is in `pending`,
52 * not here.
53 */
54export function missingHere(root: string, view: readonly string[], pending: ReadonlySet<string>): string[] {
55 return view.filter((rel) => {
56 if (pending.has(rel) || isLocalOnly(rel)) return false;
57 try {
58 lstatSync(absolute(root, rel));
59 return false;
60 } catch {
61 return true;
62 }
63 });
64}
66/**
67 * Recorded text files whose copy on disk differs from the record only by CRLF
68 * line endings (#37, Builder 2: Python's text mode on Windows writes CRLF).
69 * abso records them, and abso run sends them, with LF; a tool run here sees
70 * CRLF. Files git would check out with CRLF are left out of the list.
71 */
72export function crlfOnly(root: string): string[] {
73 const out: string[] = [];
74 for (const rel of listKnown(root)) {
75 const disk = readText(absolute(root, rel));
76 if (disk === undefined || !disk.includes("\r")) continue;
77 if (normalize(disk) === readKnown(root, rel)) out.push(rel);
78 }
79 const git = newFileEndings(root, out);
80 return out.filter((rel) => git.get(rel) !== "crlf").sort();
81}
83/**
84 * Whether the last edit here came from an older edit mod than the one
85 * installed (#37, Reporter: a chat keeps the mod it started with, and an old
86 * one sent files nested ignore files leave out). The mod writes its version
87 * as the sixth field of each .avcs/hook.log line (from #33); the installed
88 * one's is in its plugin.json. Says nothing until the installed mod carries a
89 * commit, or when the last edit came from the mod as installed.
90 */
91export function staleModText(root: string, env: Readonly<Record<string, string | undefined>>): string[] {
92 let installed: string | undefined;
93 try {
94 const dir = join(env.CLAUDE_CONFIG_DIR || join(env.USERPROFILE || env.HOME || "", ".claude"), "skills", "avcs");
95 installed = String(
96 (JSON.parse(readFileSync(join(dir, ".claude-plugin", "plugin.json"), "utf8")) as { version?: unknown }).version,
97 );
98 } catch {
99 return [];
100 }
101 if (!installed.includes("+")) return [];
102 let last: string[] | undefined;
103 try {
review17New folders keep their state in .abso/, and the machine's sign-in, servers and admin token are read from ~/.abso/ first, then ~/.avcs/. A folder made before, with only .avcs/, is untouched: it keeps working, is never half-moved, and no older client or mod loses it. stateDir(root) and homeFile/homeWritePath are in the new client/src/state-dir.ts and replace the old AVCS_DIR constant everywhere. abso login writes only to ~/.abso/ and leaves ~/.avcs/ alone; logout removes both copies. The edit mod and the view mod read either folder. .abso is skipped like .avcs (including its odd spellings), the git exclude names whichever folder is in use, and the messages name .abso. Not changed: avcs.json (the server reads that name, so abso.json needs the server to learn it first), .avcsignore, env var names and wire headers. Tests: 709 run, 708 pass (one is skipped), including new ones for the folder choice, the home-file order and box sign-in; biome ci has no errors.Compare104 const lines = readFileSync(join(stateDir(root), "hook.log"), "utf8")
106 .filter((l) => l.includes("(in process"));
107 last = lines.at(-1)?.split("\t");
108 } catch {
109 return [];
110 }
111 if (last === undefined) return [];
112 const sent = last[5]?.replace(/^avcs-mod\//, "");
113 if (sent === installed || sent === "checkout") return [];
114 const when = last[0] ? ` (at ${last[0].slice(11, 16)} UTC)` : "";
115 return [
116 `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.`,
117 ];
118}
120/** abso reader on|off: make this folder's agent a reader, or a writer again (#37, Reporter). */
121export async function runReader(args: Parsed, env: Env): Promise<Output> {
122 const word = args.positionals[0];
123 if (args.positionals.length !== 1 || (word !== "on" && word !== "off"))
124 throw new UsageError("abso reader on, or abso reader off");
125 const { root, api } = open(env);
126 const on = word === "on";
127 // The server first: it refuses a reader with unpublished or parked work (409), and then nothing here changes.
128 await api.reader(on);
review17New folders keep their state in .abso/, and the machine's sign-in, servers and admin token are read from ~/.abso/ first, then ~/.avcs/. A folder made before, with only .avcs/, is untouched: it keeps working, is never half-moved, and no older client or mod loses it. stateDir(root) and homeFile/homeWritePath are in the new client/src/state-dir.ts and replace the old AVCS_DIR constant everywhere. abso login writes only to ~/.abso/ and leaves ~/.avcs/ alone; logout removes both copies. The edit mod and the view mod read either folder. .abso is skipped like .avcs (including its odd spellings), the git exclude names whichever folder is in use, and the messages name .abso. Not changed: avcs.json (the server reads that name, so abso.json needs the server to learn it first), .avcsignore, env var names and wire headers. Tests: 709 run, 708 pass (one is skipped), including new ones for the folder choice, the home-file order and box sign-in; biome ci has no errors.Compare129 const raw = JSON.parse(readFileSync(join(stateDir(root), "config.json"), "utf8")) as Record<string, unknown>;
131 else delete raw.reader;
132 writeConfig(root, raw as unknown as Settings);
133 return {
134 text: on
135 ? "This folder is a reader now: status, sync, log, show, files and export work, and nothing it does is recorded or published. abso reader off undoes it."
136 : "This folder records and publishes again.",
137 json: { reader: on },
138 };
139}
141/** Status's lines for marker blocks still in the draft (#11). */
142export function openCollisionsText(open: readonly OpenCollision[]): string[] {
143 if (open.length === 0) return [];
144 return [
145 `${plural(open.length, "collision")} to settle before you publish (keep yours, theirs or a mix and delete the marker lines, or abso settle <file> --yours|--theirs|--both):`,
146 ...open.map(
147 (c) =>
148 ` ${c.file} lines ${c.lines[0]}-${c.lines[1]}, with ${c.theirs.agent}'s version ${c.theirs.version} ("${c.theirs.message}")`,
149 ),
150 ];
151}
153/** abso fix-eol: rewrite the files that differ from the record only in line endings with LF, as recorded (#37, Writer 1). */
154/**
155 * abso mv <from> <to> (#49): move a file in the draft,
156 * its lines keeping their history, as git mv. The way to change a file's case
157 * (or its Unicode spelling), since two spellings of one name are one file.
158 */
159export async function runMv(args: Parsed, env: Env): Promise<Output> {
160 if (args.positionals.length !== 2) throw new UsageError("mv takes the file and its new name: abso mv <from> <to>");
161 const { root, config, api } = open(env);
162 if (config.reader) throw new UsageError(READER_REFUSES);
163 const from = fileArg(root, env.cwd, args.positionals[0]!);
164 const to = fileArg(root, env.cwd, args.positionals[1]!);
165 if (from === to) throw new UsageError(`${from} already has that name`);
166 const bad =
167 unsafePath(to) ??
168 (isLocalOnly(to) ? "it is under .git, .claude, .avcs or node_modules, which stay local" : undefined);
169 if (bad !== undefined) throw new UsageError(`can't move to ${to}: ${bad}`);
170 const fromPath = absolute(root, from);
171 const toPath = absolute(root, to);
172 if (!existsSync(fromPath)) throw new UsageError(`${from} isn't in this folder`);
173 // A new case (or Unicode spelling) of the same name is the same file on Windows and macOS; anything else must be free.
174 const sameFile = pathKey(from) === pathKey(to);
175 if (!sameFile && existsSync(toPath)) throw new UsageError(`${to} already exists; move or delete it first`);
176 // Edits not yet sent go first, so the move carries the file as it is.
177 await recordFolder(root, api);
178 const answer = await api.move(from, to);
179 heard(root, answer.news);
180 await withFolderLock(root, "mv", async () => {
181 mkdirSync(dirname(toPath), { recursive: true });
182 renameSync(fromPath, toPath);
183 const text = readKnown(root, from);
184 forgetKnown(root, from);
185 if (text !== undefined) writeKnown(root, to, text);
186 const modes = readKnownModes(root);
187 const mode = modes.get(from);
188 if (mode !== undefined) {
189 modes.delete(from);
190 modes.set(to, mode);
191 writeKnownModes(root, modes);
192 }
193 const blobs = readKnownBlobs(root);
194 const sha = blobs.get(from);
195 if (sha !== undefined) {
196 blobs.delete(from);
197 blobs.set(to, sha);
198 writeKnownBlobs(root, blobs);
199 }
200 });
201 return {
202 text: [
203 `Moved ${from} to ${to} in your draft; its lines keep their history. It reaches shared with your next publish.`,
204 ...(isComposed(to) ? [] : [uncomposedText(to)]),
205 ].join("\n"),
206 json: { from: answer.from, to: answer.to },
207 };
208}
210export async function runFixEol(_args: Parsed, env: Env): Promise<Output> {
211 const { root } = open(env);
212 const crlf = crlfOnly(root);
213 for (const rel of crlf) writeFileAtomic(absolute(root, rel), readText(absolute(root, rel))!.replace(/\r\n?/g, "\n"));
214 return {
215 text:
216 crlf.length === 0
217 ? "No file differs from the record only in line endings."
218 : `Rewrote ${plural(crlf.length, "file")} with LF line endings; their text is unchanged, so nothing is recorded.`,
219 json: { files: crlf },
220 };
221}
223/** abso settle <file...> --yours | --theirs | --both: rewrite each file's marker blocks, then record (#11). */
224export async function runSettle(args: Parsed, env: Env): Promise<Output> {
225 if (args.positionals.length === 0)
226 throw new UsageError("name the files to settle: abso settle <file...> --yours, --theirs or --both");
227 const keep = keepFrom({ yours: bool(args, "yours"), theirs: bool(args, "theirs"), both: bool(args, "both") });
228 const { root, api } = open(env);
229 const files = args.positionals.map((typed) => fileArg(root, env.cwd, typed));
230 const counts: [string, number][] = [];
231 for (const rel of files) {
232 const text = readText(absolute(root, rel));
233 if (text === undefined) throw new UsageError(`${rel} is not a text file in this folder`);
234 const settled = settleText(text, keep);
235 if (settled.blocks === 0)
236 throw new UsageError(`${rel} has no collision markers to settle (abso status lists the files that do)`);
237 counts.push([rel, settled.blocks]);
238 }
239 // Each file checked first, so a typo settles nothing.
240 for (const [rel] of counts)
241 writeFileAtomic(absolute(root, rel), settleText(readText(absolute(root, rel))!, keep).text);
242 const recorded = await recordFolder(root, api);
243 const which = keep === "both" ? "both sides" : keep;
244 return {
245 text: [
246 ...recordedFirst(recorded).filter((l) => !l.startsWith("Recorded first")),
247 `Settled ${counts.map(([rel, n]) => `${plural(n, "block")} in ${rel}`).join(", ")}, keeping ${which}.${keep === "both" ? " Both sides stay in the file; when you publish, the other author hears that you kept both." : ""}`,
248 ].join("\n"),
249 json: { keep, files: counts.map(([file, blocks]) => ({ file, blocks })), recorded: recorded.sent },
250 };
251}
253/** The line status prints for files the folder is missing. */
254export function missingText(missing: readonly string[]): string[] {
255 if (missing.length === 0) return [];
256 const some =
257 missing.length <= LISTED
258 ? missing.join(", ")
259 : `${missing.slice(0, LISTED).join(", ")}, and ${missing.length - LISTED} more`;
260 return [
261 `Missing from this folder though your view has ${missing.length === 1 ? "it" : "them"} (abso sync --full writes ${missing.length === 1 ? "it" : "them"}; abso files lists them all): ${some}`,
262 ];
263}
265export async function runStatus(args: Parsed, env: Env): Promise<Output> {
266 const { root, config, api } = open(env);
267 const short = bool(args, "short");
268 const { files: view, ...status } = short ? { ...(await api.status()), files: undefined } : await api.statusAndFiles();
269 const pending = unrecorded(root);
270 const local = new Set([...pending.files.keys(), ...pending.blobs.keys(), ...Object.keys(pending.modes)]);
271 if (short) {
272 // One word to stamp a build with (#37, Playtester 1): 214, coast@3, 214+unpublished.
273 const me = status.agents.find((a) => a.agent === config.agent);
274 const unpublished = local.size > 0 || (me?.draftChanges ?? 0) > 0;
275 // +queued: published into the merge queue, not landed yet (#39).
276 const word = `${me?.draft ? `${me.draft}@` : ""}${me?.base ?? "none"}${unpublished ? "+unpublished" : ""}${(me?.queued?.length ?? 0) > 0 ? "+queued" : ""}`;
277 return { text: word, json: { version: me?.base ?? null, draft: me?.draft ?? null, unpublished, word } };
278 }
279 const missing = view === undefined ? [] : missingHere(root, view.files, local);
280 const unwritten = readUnwritten(root);
281 const crlf = crlfOnly(root);
282 // Files an earlier record added to the draft and that are gone again (#37, Builder 6: scratch files a run
283 // recorded, deleted after): nothing reached shared, and the next record takes them out of the draft.
284 const deleted = [...pending.files].filter(([, text]) => text === null).map(([rel]) => rel);
285 const neverShared =
286 deleted.length === 0
287 ? []
288 : (await api.diff()).files
289 .filter((f) => f.before === null && deleted.includes(f.path))
290 .map((f) => f.path)
291 .sort();
292 for (const rel of neverShared) local.delete(rel);
293 const me = status.agents.find((a) => a.agent === config.agent);
294 const space = (draft: string | null | undefined): string => (draft ? `draft ${draft}` : "shared");
295 const parked = (me?.parked ?? []).filter((p) => p.draftChanges > 0);
296 const credential = credentialLabel(root, config.server, env.env);
297 const behind = await newerCommitNote(config.server);
298 const lines = [
299 `Project ${config.project}: shared is at version ${status.version}. This folder is ${config.agent}${config.reader || me?.reader ? ", a reader (it records and publishes nothing)" : ""}, working in ${space(me?.draft)}.${config.follow ? ` It follows label ${config.follow}: syncs take it to the newest version with that label.` : ""} Signed in with ${credential.kind}${credential.id ? ` ${credential.id}` : ""}.`,
300 ...(behind ? [behind] : []),
301 // Is shared green (#39)? Right under the first line, since it decides what to do next.
302 ...ciText(status.ci, status.version),
303 ...queueText(status.queue, config.agent),
304 local.size === 0
305 ? "Everything in this folder is recorded."
306 : `Not yet recorded (abso record sends them): ${[...local.keys()].join(", ")}`,
307 ...(neverShared.length > 0
308 ? [
309 `Added to your draft by an earlier record and deleted since, so they never reach shared; the next record (sync, publish, run) takes them out of your draft: ${neverShared.join(", ")}`,
310 ]
311 : []),
312 ...openCollisionsText(me?.collisions ?? []),
313 ...staleModText(root, env.env),
314 ...modsBehindText(env.env),
315 ...missingText(missing),
316 ...unwrittenText(unwritten),
317 ...(crlf.length > 0
318 ? [
319 `${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.`,
320 ]
321 : []),
322 ...turnedBinaryText(pending.turnedBinary),
323 ...leftOutText(pending.leftOut),
324 ...(parked.length > 0
325 ? [
326 `You have work parked in ${parked.map((p) => `${space(p.draft)} (${plural(p.draftChanges, "change")})`).join(", ")}; abso switch brings it back.`,
327 ]
328 : []),
329 "Agents:",
330 ...status.agents.map((a) => {
331 const files = Array.isArray(a.files)
332 ? a.files.length === 0
333 ? ""
334 : `: ${a.files.join(", ")}`
335 : ` in ${plural(a.files as number, "file")}`;
336 const where = a.draft ? ` in draft ${a.draft},` : "";
337 return ` ${a.agent === config.agent ? "*" : " "} ${a.agent},${where} base ${a.base ?? "none"}, ${plural(a.draftChanges, "draft change")}${files}`;
338 }),
339 ...((status.drafts ?? []).length > 0
340 ? [
341 "Named drafts:",
342 ...(status.drafts ?? []).map(
343 (d) =>
344 ` ${d.name}: version ${d.version}, on shared version ${d.sharedBase}, ${plural(d.changes, "change")} not yet landed${d.agents.length > 0 ? `; ${d.agents.join(", ")}` : ""}`,
345 ),
346 ]
347 : []),
348 ];
349 return {
350 text: lines.join("\n"),
351 json: {
352 ...status,
353 agent: config.agent,
354 credential,
355 follow: config.follow ?? null,
356 unrecorded: [...local.keys()],
357 neverShared,
358 missing,
359 unwritten,
360 crlf,
361 leftOut: pending.leftOut,
362 },
363 };
364}