- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/client/src/review.ts?draft=login-timeout&format=json
293 linesFirst import 97% · review 2% · infra-split 1%0 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.
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 }
26}
28function writeMark(root: string, since: number): void {
29 writeFileAtomic(join(stateDir(root), MARK), `${JSON.stringify({ since })}\n`);
30}
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]}`}`;
37}
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}`;
45}
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 ]);
56}
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(", ")}`;
61}
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]})` : ""}`;
75}
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")}` : ""}`;
84}
86/** The change page, as text. */
87export function changePage(c: ChangeAnswer): string[] {
88 const out = [
89 `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"})` : ""}.`,
90 ...(c.note
91 ? [
92 `Set out to do: ${JSON.stringify(c.note.text)}${c.note.files.length > 0 ? `, naming ${c.note.files.join(", ")}` : ""}.`,
93 ]
94 : []),
95 `${versionsText(c)[0]!.toUpperCase()}${versionsText(c).slice(1)}:`,
96 ...c.versions.map(
97 (v) =>
98 ` ${v.draft === null ? "" : `${v.draft}@`}${v.version}, ${when(v.time)}: ${v.message}${v.files.length > 0 ? ` (${v.files.join(", ")})` : ""}`,
99 ),
100 ...(c.settled.length > 0
101 ? [
102 `Settled: ${c.settled.map((s) => `${s.file} (kept ${s.kept}, against ${s.theirs.agent}'s version ${s.theirs.version})`).join("; ")}.`,
103 ]
104 : []),
105 ...(c.refusals.length > 0
106 ? [
107 `Refused ${plural(c.refusals.length, "time")} on the way: ${c.refusals.map((r) => `${r.kinds.join(", ")} (${r.files.join(", ")})`).join("; ")}.`,
108 ]
109 : []),
110 ...((c.reviewers ?? []).length > 0
111 ? [
112 `Reviewers: ${c.reviewers!.map((r) => `${r.agent} (${r.read ? "has read it" : "not yet"}; ${r.files.join(", ")})`).join("; ")}.`,
113 ]
114 : []),
115 ...((c.notes ?? []).length > 0 ? ["Notes:", ...threads(c.notes!)] : ["No notes yet."]),
116 `Each version's changes: abso show <version>. Leave a note: abso note <file>:<lines> "..." [--object].`,
117 ];
118 return out;
119}
121/** A change named the way an agent thinks of it: its id, a version (v812), or an agent (its newest change). */
122async function findChange(api: ReturnType<typeof open>["api"], word: string): Promise<ChangeAnswer> {
123 if (/^\d+$/.test(word)) return api.change(Number(word));
124 const v = /^v(\d+)$/i.exec(word);
125 // show names a version's change; older servers don't, and the recent changes are searched.
126 if (v) {
127 const shown = await api.show(Number(v[1]), { draft: null }).catch(() => undefined);
128 if (shown?.change !== undefined) return api.change(shown.change);
129 }
130 const recent = (await api.changes(0, 200)).changes;
131 const found = v
132 ? recent.find((c) => c.versions.some((x) => x.draft === null && x.version === Number(v[1])))
133 : recent.find((c) => c.agent === word);
134 if (!found)
135 throw new UsageError(
136 v
137 ? `no recent change holds version ${v[1]} of shared`
138 : `no recent change by ${word}; abso review <id> takes a change id, v<version> or an agent`,
139 );
140 return api.change(found.id);
141}
143/** "2h", "30m", "1d": a span back from now, in ms; undefined for anything else. */
144function span(raw: string): number | undefined {
145 const m = /^(\d+)\s*(m|min|h|d)$/.exec(raw);
146 return m
147 ? Number(m[1]) * { m: 60_000, min: 60_000, h: 3_600_000, d: 86_400_000 }[m[2] as "m" | "min" | "h" | "d"]
148 : undefined;
149}
151export async function runReview(args: Parsed, env: Env): Promise<Output> {
152 if (args.positionals.length > 1)
153 throw new UsageError(
154 "review takes at most one change: abso review [<id> | v<version> | <agent>] [--since <position|2h>]",
155 );
156 const { root, api } = open(env);
157 const word = args.positionals[0];
158 if (word !== undefined) {
159 const c = await findChange(api, word);
160 return { text: changePage(c).join("\n"), json: { ...c } };
161 }
162 // The list: since the mark (moved after listing), or --since without moving it.
163 const raw = str(args, "since");
164 const back = raw === undefined ? undefined : span(raw);
165 if (raw !== undefined && back === undefined && !/^\d+$/.test(raw))
166 throw new UsageError("--since takes a log position (4400) or a span back from now (30m, 2h, 1d)");
167 const mark = readMark(root);
168 const since = raw !== undefined && back === undefined ? Number(raw) : back !== undefined ? 0 : (mark ?? 0);
169 const cutoff = back === undefined ? 0 : Date.now() - back;
170 const lastActive = (c: ChangeAnswer): number => Math.max(c.time, ...c.versions.map((v) => v.time));
171 // A first look shows the newest 20. Otherwise every change since the mark (or the span) is listed, page by
172 // page, before the mark moves past them: one page would drop the older ones.
173 const firstLook = mark === undefined && raw === undefined;
174 // ABSO_REVIEW_PAGE shortens the page in tests.
175 const pageSize = Number(fromEnv(process.env, "REVIEW_PAGE")) || 200;
176 const answer = await api.changes(since, firstLook ? 20 : pageSize);
177 const all = [...answer.changes];
178 for (
179 let older = answer.older;
180 !firstLook && older !== undefined && (back === undefined || lastActive(all[all.length - 1]!) >= cutoff);
181 ) {
182 const page = await api.changes(since, pageSize, older);
183 all.push(...page.changes);
184 older = page.older;
185 }
186 const list = back === undefined ? all : all.filter((c) => lastActive(c) >= cutoff);
187 if (raw === undefined) writeMark(root, answer.next);
188 const from =
189 raw !== undefined ? `since ${raw}` : mark === undefined ? "lately (your first look)" : "since you last looked";
190 return {
191 text: [
192 list.length === 0 ? `No changes ${from}.` : `${plural(list.length, "change")} ${from}, newest first:`,
193 ...list.map(changeLine),
194 ...(list.length > 0
195 ? ["abso review <id> shows one: what it set out to do, its versions, what it settled, its notes."]
196 : []),
197 ...(raw === undefined ? ["abso review --since 2h looks further back."] : []),
198 ].join("\n"),
199 json: { since, next: answer.next, changes: list },
200 };
201}
203/** file:12 or file:12-30; not a Windows drive letter (C:...). */
204const LINES = /^(.+?):(\d+)(?:-(\d+))?$/;
206export async function runNote(args: Parsed, env: Env): Promise<Output> {
207 const { root, config, api } = open(env);
208 const reply = str(args, "reply");
209 const close = str(args, "close");
210 if (close !== undefined) {
211 if (!/^\d+$/.test(close)) throw new UsageError("--close takes a note id: abso note --close 77 --resolved");
212 const resolved = bool(args, "resolved");
213 if (resolved === bool(args, "withdrawn"))
214 throw new UsageError("say how it closes: abso note --close <id> --resolved, or --withdrawn");
215 await api.noteClose(Number(close), resolved ? "resolved" : "withdrawn");
216 return {
217 text: `Note ${close} is ${resolved ? "resolved" : "withdrawn"}.`,
218 json: { id: Number(close), how: resolved ? "resolved" : "withdrawn" },
219 };
220 }
221 if (reply !== undefined) {
222 if (!/^\d+$/.test(reply)) throw new UsageError('--reply takes a note id: abso note --reply 77 "fixed in v815"');
223 const text = args.positionals.join(" ").trim();
224 if (text === "") throw new UsageError('say what you reply: abso note --reply <id> "..."');
225 const a = await api.note({ reply: Number(reply), text });
226 return {
227 text: `Replied to note ${reply} (reply ${a.id}); its writer and the thread hear it as news.`,
228 json: { ...a },
229 };
230 }
231 const where = args.positionals[0];
232 const m = where === undefined ? null : LINES.exec(where);
233 if (!m || /^[A-Za-z]$/.test(m[1]!))
234 throw new UsageError(
235 'note takes lines and text: abso note <file>:<line>[-<line>] "..." [--object], or --reply <id>, or --close <id>',
236 );
237 const text = args.positionals.slice(1).join(" ").trim();
238 const read = bool(args, "read");
239 if (text === "" && !read) throw new UsageError('say what the note says: abso note <file>:<lines> "..."');
240 const from = Number(m[2]);
241 const to = Number(m[3] ?? m[2]);
242 if (to < from) throw new UsageError(`${where}: the range runs backwards`);
243 const file = fileArg(root, env.cwd, m[1]!);
244 const at = str(args, "at");
245 const of = str(args, "draft");
246 if (at !== undefined && !/^\d+$/.test(at)) throw new UsageError("--at takes a version of shared");
247 if (at !== undefined && of !== undefined) throw new UsageError("--at and --draft both say which lines; give one");
248 // The numbers mean the lines as this folder shows them: record it, then note them as this agent's own
249 // draft shows them, unless --at (a version of shared) or --draft <agent> (their unpublished work) says otherwise.
250 if (at === undefined && of === undefined && !config.reader) await recordFolder(root, api);
251 const kind = bool(args, "object") ? "objection" : read ? "read" : "comment";
252 const a = await api.note({
253 file,
254 from,
255 to,
256 text: text === "" ? "read" : text,
257 kind,
258 ...(at !== undefined ? { version: Number(at) } : { of: of ?? config.agent }),
259 });
260 const said = kind === "objection" ? "Objection" : kind === "read" ? "Read mark" : "Note";
261 return {
262 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."}`,
263 json: { ...a, kind },
264 };
265}
267export async function runNotes(args: Parsed, env: Env): Promise<Output> {
268 if (args.positionals.length > 1)
269 throw new UsageError("notes takes at most one file: abso notes [file] [--change <id>] [--all]");
270 const { root, api } = open(env);
271 const typed = args.positionals[0];
272 const file = typed === undefined ? undefined : fileArg(root, env.cwd, typed);
273 const change = str(args, "change");
274 if (change !== undefined && !/^\d+$/.test(change)) throw new UsageError("--change takes a change id");
275 const all = bool(args, "all");
276 const { notes } = await api.notes({
277 ...(file ? { file } : {}),
278 ...(change ? { change: Number(change) } : {}),
279 open: !all,
280 });
281 const scope = [file ? ` on ${file}` : "", change ? ` in change ${change}` : ""].join("");
282 return {
283 text:
284 notes.length === 0
285 ? `No ${all ? "" : "open "}notes${scope}.`
286 : [
287 `${plural(notes.length, all ? "note" : "open note")}${scope}:`,
288 ...threads(notes),
289 'abso note --reply <id> "..." answers one; abso note --close <id> --resolved closes yours.',
290 ].join("\n"),
291 json: { notes },
292 };
293}