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/review.ts?format=json
300 linesFirst import 94% · speed 3% · review 2% · infra-split 1%Last change speed in version 160, 6 versions changed it
1// Review (#44): review is reading what
2// landed. abso review lists the changes since you last looked, or shows one;
3// abso note leaves a note on lines, which follows them as the file changes;
4// abso notes lists them. The server holds changes and notes.
5
6import { readFileSync } from "node:fs";
7import { join } from "node:path";
8import type { ChangeAnswer, NoteAnswer } from "./api.ts";
9import { bool, type Parsed, str, UsageError } from "./args.ts";
10import { type Env, type Output, open, plural, recordFolder } from "./commands.ts";
11import { fromEnv } from "./env-names.ts";
12import { writeFileAtomic } from "./folder.ts";
13import { fileArg, when } from "./history.ts";
14import { stateDir } from "./state-dir.ts";
16/** Where this folder last looked: a log position, kept in .avcs/review.json. */
17const MARK = "review.json";
19function readMark(root: string): number | undefined {
20 try {
21 const n = (JSON.parse(readFileSync(join(stateDir(root), MARK), "utf8")) as { since?: unknown }).since;
22 return typeof n === "number" && Number.isInteger(n) && n >= 0 ? n : undefined;
23 } catch {
24 return undefined;
25 }
28function writeMark(root: string, since: number): void {
29 writeFileAtomic(join(stateDir(root), MARK), `${JSON.stringify({ since })}\n`);
32const SAID = { comment: "says", objection: "objects", read: "read it" } as const;
34function lines(n: NoteAnswer): string {
35 if (n.lines === null) return `${n.file} (its lines are gone)`;
36 return `${n.file} ${n.lines[0] === n.lines[1] ? `line ${n.lines[0]}` : `lines ${n.lines[0]}-${n.lines[1]}`}`;
39/** One note as a line; replies are indented under their note. */
40export function noteText(n: NoteAnswer): string {
41 const state = n.state === "open" ? "" : ` [${n.state}]`;
42 // Another agent's words, quoted as JSON so a quote or a line break in them can't print as another note (#30).
43 if (n.reply !== null) return ` note ${n.id}, ${n.agent} replies: ${JSON.stringify(n.text)}${state}`;
44 return ` note ${n.id}: ${n.agent} ${SAID[n.kind]} on ${lines(n)}${n.kind === "read" ? "" : `: ${JSON.stringify(n.text)}`}${state}`;
47/** Notes with their replies under them, oldest thread first. */
48function threads(notes: readonly NoteAnswer[]): string[] {
49 // A reply whose note isn't in the list (closed, or filtered out) stands on its own.
50 const ids = new Set(notes.map((n) => n.id));
51 const top = notes.filter((n) => n.reply === null || !ids.has(n.reply));
52 return top.flatMap((t) => [
53 noteText(t),
54 ...(t.reply === null ? notes.filter((r) => r.reply === t.id).map(noteText) : []),
55 ]);
58function versionsText(c: ChangeAnswer): string {
59 const v = c.versions.map((x) => (x.draft === null ? `${x.version}` : `${x.draft}@${x.version}`));
60 return v.length === 0 ? "no versions yet" : `${v.length === 1 ? "version" : "versions"} ${v.join(", ")}`;
63/** One change in a list. */
64/**
65 * A change's title as a list shows it (#43): the first line, cut
66 * to 100 characters, as git log --oneline does, with an imported commit's
67 * trailer (`git <sha12>, <author>, <time>`) as a short hash beside it. The
68 * change page keeps the whole message.
69 */
70export function titleLine(title: string): string {
71 const lines = title.trim().split("\n");
72 const git = lines.length > 1 ? /^git ([0-9a-f]{7})[0-9a-f]*, /.exec(lines[lines.length - 1]!) : null;
73 const first = lines[0]!.trim();
74 return `${JSON.stringify(first.length > 100 ? `${first.slice(0, 97)}...` : first)}${git ? ` (git ${git[1]})` : ""}`;
77function changeLine(c: ChangeAnswer): string {
78 const open = (c.notes ?? []).filter((n) => n.kind === "objection" && n.state === "open").length;
79 const files =
80 c.files.length === 0
81 ? ""
82 : `; ${plural(c.files.length, "file")}: ${c.files.slice(0, 4).join(", ")}${c.files.length > 4 ? ", ..." : ""}`;
83 return ` ${c.id} ${c.agent}, ${titleLine(c.title)}${c.open ? " (still going)" : ""}: ${versionsText(c)}${files}${open > 0 ? `; ${plural(open, "open objection")}` : ""}`;
86/** What a settle kept, read from outside: whose lines, not "yours" or "theirs". */
87function keptText(s: ChangeAnswer["settled"][number], settler: string): string {
88 if (s.kept === "yours") return `kept ${settler}'s`;
89 if (s.kept === "theirs") return `kept ${s.theirs.agent}'s`;
90 return s.kept === "both" ? "kept both" : "rewrote both sides";
93/** The change page, as text. */
94export function changePage(c: ChangeAnswer): string[] {
95 const out = [
96 `Change ${c.id} by ${c.agent}: ${JSON.stringify(c.title)}${c.open ? ` (still going: ${c.kind === "draft" ? "its draft has not landed" : "its start note lasts"})` : ""}.`,
97 ...(c.note
98 ? [
99 `Set out to do: ${JSON.stringify(c.note.text)}${c.note.files.length > 0 ? `, naming ${c.note.files.join(", ")}` : ""}.`,
100 ]
101 : []),
102 `${versionsText(c)[0]!.toUpperCase()}${versionsText(c).slice(1)}:`,
103 ...c.versions.map(
104 (v) =>
105 ` ${v.draft === null ? "" : `${v.draft}@`}${v.version}, ${when(v.time)}: ${v.message}${v.files.length > 0 ? ` (${v.files.join(", ")})` : ""}`,
106 ),
107 ...(c.settled.length > 0
108 ? [
109 `Settled: ${c.settled.map((s) => `${s.file} (${keptText(s, c.agent)}, against ${s.theirs.agent}'s version ${s.theirs.version})`).join("; ")}.`,
110 ]
111 : []),
112 ...(c.refusals.length > 0
113 ? [
114 `Refused ${plural(c.refusals.length, "time")} on the way: ${c.refusals.map((r) => `${r.kinds.join(", ")} (${r.files.join(", ")})${r.message ? `: ${JSON.stringify(r.message)}` : ""}`).join("; ")}.`,
115 ]
116 : []),
117 ...((c.reviewers ?? []).length > 0
118 ? [
119 `Reviewers: ${c.reviewers!.map((r) => `${r.agent} (${r.read ? "has read it" : "not yet"}; ${r.files.join(", ")})`).join("; ")}.`,
120 ]
121 : []),
122 ...((c.notes ?? []).length > 0 ? ["Notes:", ...threads(c.notes!)] : ["No notes yet."]),
123 `Each version's changes: abso show <version>. Leave a note: abso note <file>:<lines> "..." [--object].`,
124 ];
125 return out;
128/** A change named the way an agent thinks of it: its id, a version (v812), or an agent (its newest change). */
129async function findChange(api: ReturnType<typeof open>["api"], word: string): Promise<ChangeAnswer> {
130 if (/^\d+$/.test(word)) return api.change(Number(word));
131 const v = /^v(\d+)$/i.exec(word);
132 // show names a version's change; older servers don't, and the recent changes are searched.
133 if (v) {
134 const shown = await api.show(Number(v[1]), { draft: null }).catch(() => undefined);
135 if (shown?.change !== undefined) return api.change(shown.change);
136 }
137 const recent = (await api.changes(0, 200)).changes;
138 const found = v
139 ? recent.find((c) => c.versions.some((x) => x.draft === null && x.version === Number(v[1])))
140 : recent.find((c) => c.agent === word);
141 if (!found)
142 throw new UsageError(
143 v
144 ? `no recent change holds version ${v[1]} of shared`
145 : `no recent change by ${word}; abso review <id> takes a change id, v<version> or an agent`,
146 );
147 return api.change(found.id);
150/** "2h", "30m", "1d": a span back from now, in ms; undefined for anything else. */
151function span(raw: string): number | undefined {
152 const m = /^(\d+)\s*(m|min|h|d)$/.exec(raw);
153 return m
154 ? Number(m[1]) * { m: 60_000, min: 60_000, h: 3_600_000, d: 86_400_000 }[m[2] as "m" | "min" | "h" | "d"]
155 : undefined;
158export async function runReview(args: Parsed, env: Env): Promise<Output> {
159 if (args.positionals.length > 1)
160 throw new UsageError(
161 "review takes at most one change: abso review [<id> | v<version> | <agent>] [--since <position|2h>]",
162 );
163 const { root, api } = open(env);
164 const word = args.positionals[0];
165 if (word !== undefined) {
166 const c = await findChange(api, word);
167 return { text: changePage(c).join("\n"), json: { ...c } };
168 }
169 // The list: since the mark (moved after listing), or --since without moving it.
170 const raw = str(args, "since");
171 const back = raw === undefined ? undefined : span(raw);
172 if (raw !== undefined && back === undefined && !/^\d+$/.test(raw))
173 throw new UsageError("--since takes a log position (4400) or a span back from now (30m, 2h, 1d)");
174 const mark = readMark(root);
175 const since = raw !== undefined && back === undefined ? Number(raw) : back !== undefined ? 0 : (mark ?? 0);
176 const cutoff = back === undefined ? 0 : Date.now() - back;
177 const lastActive = (c: ChangeAnswer): number => Math.max(c.time, ...c.versions.map((v) => v.time));
178 // A first look shows the newest 20. Otherwise every change since the mark (or the span) is listed, page by
179 // page, before the mark moves past them: one page would drop the older ones.
180 const firstLook = mark === undefined && raw === undefined;
181 // ABSO_REVIEW_PAGE shortens the page in tests.
182 const pageSize = Number(fromEnv(process.env, "REVIEW_PAGE")) || 200;
183 const answer = await api.changes(since, firstLook ? 20 : pageSize);
184 const all = [...answer.changes];
185 for (
186 let older = answer.older;
187 !firstLook && older !== undefined && (back === undefined || lastActive(all[all.length - 1]!) >= cutoff);
188 ) {
189 const page = await api.changes(since, pageSize, older);
190 all.push(...page.changes);
191 older = page.older;
192 }
193 const list = back === undefined ? all : all.filter((c) => lastActive(c) >= cutoff);
194 if (raw === undefined) writeMark(root, answer.next);
195 const from =
196 raw !== undefined ? `since ${raw}` : mark === undefined ? "lately (your first look)" : "since you last looked";
197 return {
198 text: [
199 list.length === 0 ? `No changes ${from}.` : `${plural(list.length, "change")} ${from}, newest first:`,
200 ...list.map(changeLine),
201 ...(list.length > 0
202 ? ["abso review <id> shows one: what it set out to do, its versions, what it settled, its notes."]
203 : []),
204 ...(raw === undefined ? ["abso review --since 2h looks further back."] : []),
205 ].join("\n"),
206 json: { since, next: answer.next, changes: list },
207 };
210/** file:12 or file:12-30; not a Windows drive letter (C:...). */
211const LINES = /^(.+?):(\d+)(?:-(\d+))?$/;
213export async function runNote(args: Parsed, env: Env): Promise<Output> {
214 const { root, config, api } = open(env);
215 const reply = str(args, "reply");
216 const close = str(args, "close");
217 if (close !== undefined) {
218 if (!/^\d+$/.test(close)) throw new UsageError("--close takes a note id: abso note --close 77 --resolved");
219 const resolved = bool(args, "resolved");
220 if (resolved === bool(args, "withdrawn"))
221 throw new UsageError("say how it closes: abso note --close <id> --resolved, or --withdrawn");
222 await api.noteClose(Number(close), resolved ? "resolved" : "withdrawn");
223 return {
224 text: `Note ${close} is ${resolved ? "resolved" : "withdrawn"}.`,
225 json: { id: Number(close), how: resolved ? "resolved" : "withdrawn" },
226 };
227 }
228 if (reply !== undefined) {
229 if (!/^\d+$/.test(reply)) throw new UsageError('--reply takes a note id: abso note --reply 77 "fixed in v815"');
230 const text = args.positionals.join(" ").trim();
231 if (text === "") throw new UsageError('say what you reply: abso note --reply <id> "..."');
232 const a = await api.note({ reply: Number(reply), text });
233 return {
234 text: `Replied to note ${reply} (reply ${a.id}); its writer and the thread hear it as news.`,
235 json: { ...a },
236 };
237 }
238 const where = args.positionals[0];
239 const m = where === undefined ? null : LINES.exec(where);
240 if (!m || /^[A-Za-z]$/.test(m[1]!))
241 throw new UsageError(
242 'note takes lines and text: abso note <file>:<line>[-<line>] "..." [--object], or --reply <id>, or --close <id>',
243 );
244 const text = args.positionals.slice(1).join(" ").trim();
245 const read = bool(args, "read");
246 if (text === "" && !read) throw new UsageError('say what the note says: abso note <file>:<lines> "..."');
247 const from = Number(m[2]);
248 const to = Number(m[3] ?? m[2]);
249 if (to < from) throw new UsageError(`${where}: the range runs backwards`);
250 const file = fileArg(root, env.cwd, m[1]!);
251 const at = str(args, "at");
252 const of = str(args, "draft");
253 if (at !== undefined && !/^\d+$/.test(at)) throw new UsageError("--at takes a version of shared");
254 if (at !== undefined && of !== undefined) throw new UsageError("--at and --draft both say which lines; give one");
255 // The numbers mean the lines as this folder shows them: record it, then note them as this agent's own
256 // draft shows them, unless --at (a version of shared) or --draft <agent> (their unpublished work) says otherwise.
257 if (at === undefined && of === undefined && !config.reader) await recordFolder(root, api);
258 const kind = bool(args, "object") ? "objection" : read ? "read" : "comment";
259 const a = await api.note({
260 file,
261 from,
262 to,
263 text: text === "" ? "read" : text,
264 kind,
265 ...(at !== undefined ? { version: Number(at) } : { of: of ?? config.agent }),
266 });
267 const said = kind === "objection" ? "Objection" : kind === "read" ? "Read mark" : "Note";
268 return {
269 text: `${said} ${a.id} on ${file} ${from === to ? `line ${from}` : `lines ${from}-${to}`}${a.change === null ? "" : ` (change ${a.change})`}. ${kind === "read" ? "Nobody is told." : "The lines' authors and the change's agent hear it as news; it follows the lines as the file changes."}`,
270 json: { ...a, kind },
271 };
274export async function runNotes(args: Parsed, env: Env): Promise<Output> {
275 if (args.positionals.length > 1)
276 throw new UsageError("notes takes at most one file: abso notes [file] [--change <id>] [--all]");
277 const { root, api } = open(env);
278 const typed = args.positionals[0];
279 const file = typed === undefined ? undefined : fileArg(root, env.cwd, typed);
280 const change = str(args, "change");
281 if (change !== undefined && !/^\d+$/.test(change)) throw new UsageError("--change takes a change id");
282 const all = bool(args, "all");
283 const { notes } = await api.notes({
284 ...(file ? { file } : {}),
285 ...(change ? { change: Number(change) } : {}),
286 open: !all,
287 });
288 const scope = [file ? ` on ${file}` : "", change ? ` in change ${change}` : ""].join("");
289 return {
290 text:
291 notes.length === 0
292 ? `No ${all ? "" : "open "}notes${scope}.`
293 : [
294 `${plural(notes.length, all ? "note" : "open note")}${scope}:`,
295 ...threads(notes),
296 'abso note --reply <id> "..." answers one; abso note --close <id> --resolved closes yours.',
297 ].join("\n"),
298 json: { notes },
299 };