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