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