- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/client/src/history.ts?version=13&format=json
220 linesFirst import 98% · engine 2%Last change engine in version 13, 2 versions changed it
You're reading version 13. The newest is 318, and 7 versions since then changed this file.
1// abso blame, why and where: reading who wrote what, and who is working where.
2// Blame and why read shared; where reads every agent's unpublished draft.
4import { resolve } from "node:path";
5import { Api, type BlameAnswer, type Publish, type View } from "./api.ts";
6import { bool, type Parsed, str, UsageError } from "./args.ts";
7import { globTest } from "./at.ts";
8import type { Env, Output } from "./commands.ts";
9import { findRoot, readConfig } from "./config.ts";
10import { relativeTo } from "./folder.ts";
11import { byWhom } from "./history-answers.ts";
13function open(env: Env): { root: string; api: Api; agent: string } {
14 const root = findRoot(env.cwd);
15 if (root === undefined)
16 throw new UsageError(`${env.cwd} is not in an abso folder (no .avcs/config.json here or above)`);
17 const config = readConfig(root, env.env);
18 return { root, api: new Api(config), agent: config.agent };
19}
21/** A path as typed (relative to where the command runs) to the folder-relative form the server uses. */
22export function fileArg(root: string, cwd: string, typed: string): string {
23 const rel = relativeTo(root, resolve(cwd, typed));
24 if (rel === undefined) throw new UsageError(`${typed} is not inside the abso folder ${root}`);
25 return rel;
26}
28export function when(time: number): string {
29 return `${new Date(time).toISOString().slice(0, 16).replace("T", " ")} UTC`;
30}
32function lineNumber(raw: string | undefined, what: string): number | undefined {
33 if (raw === undefined) return undefined;
34 const n = Number(raw);
35 if (!Number.isInteger(n) || n < 1) throw new UsageError(`${what} must be a line number (got ${JSON.stringify(raw)})`);
36 return n;
37}
39/** --draft <name> reads a named draft; --mine reads this agent's own view, its unpublished lines marked. */
40function viewOf(args: Parsed, agent: string): View {
41 const draft = str(args, "draft");
42 const mine = bool(args, "mine");
43 if (draft !== undefined && mine) throw new UsageError("give --draft or --mine, not both");
44 if (mine && str(args, "version") !== undefined)
45 throw new UsageError("--mine reads your view as it is now; it takes no --version");
46 return mine ? { agent } : draft !== undefined ? { draft } : {};
47}
49function published(p: Publish | null): string {
50 return p === null ? "not published" : `version ${p.version} by ${byWhom(p)} (${when(p.time)}): "${p.message}"`;
51}
53export async function runBlame(args: Parsed, env: Env): Promise<Output> {
54 if (args.positionals.length !== 1)
55 throw new UsageError("blame takes one file: abso blame <file> [--from <n>] [--to <n>]");
56 const { root, api, agent } = open(env);
57 const file = fileArg(root, env.cwd, args.positionals[0]!);
58 const rawVersion = str(args, "version");
59 if (rawVersion !== undefined && !/^\d+$/.test(rawVersion))
60 throw new UsageError(`--version is a version number (got ${JSON.stringify(rawVersion)})`);
61 const view = viewOf(args, agent);
62 const b = await api.blame(
63 file,
64 lineNumber(str(args, "from"), "--from"),
65 lineNumber(str(args, "to"), "--to"),
66 rawVersion === undefined ? undefined : Number(rawVersion),
67 view,
68 );
69 const width = Math.max(4, ...b.lines.map((l) => l.author.length));
70 const digits = String(b.to).length;
71 const versions = new Map<number, string>();
72 for (const a of b.atoms) {
73 if (a.publish === null) continue;
74 const own = a.message && a.message !== a.publish.message ? ` (the change itself: "${a.message}")` : "";
75 const line = ` v${a.publish.version} by ${byWhom(a.publish)}, ${when(a.publish.time)}: ${a.publish.message}${own}`;
76 if (!versions.has(a.publish.version) || own) versions.set(a.publish.version, line);
77 }
78 const whose =
79 b.agent !== undefined
80 ? `as your view has it now`
81 : b.draft !== undefined
82 ? `as draft ${b.draft} has it at version ${b.version}`
83 : `as shared has it at version ${b.version}`;
84 const unpublished = b.lines.some((l) => l.unpublished);
85 // A line in a draft but not yet in shared has no shared version: "draft" says where it is.
86 const tag = (l: BlameAnswer["lines"][number]) =>
87 l.unpublished ? "*" : l.version === null ? "draft" : `v${l.version}`;
88 const tagWidth = Math.max(4, ...b.lines.map((l) => tag(l).length));
89 const lines = [
90 `${b.file} ${whose} (lines ${b.from}-${b.to} of ${b.total}):`,
91 ...b.lines.map(
92 (l) => ` ${String(l.n).padStart(digits)} ${tag(l).padEnd(tagWidth)} ${l.author.padEnd(width)} ${l.text}`,
93 ),
94 ...(unpublished ? ["", "* not published yet: your own unpublished change."] : []),
95 "",
96 "Publishes:",
97 ...[...versions].sort(([x], [y]) => x - y).map(([, line]) => line),
98 ];
99 return { text: lines.join("\n"), json: { ...b } };
100}
102export async function runWhy(args: Parsed, env: Env): Promise<Output> {
103 // abso why <file>:<line>, or abso why <file> <line>
104 let typed: string | undefined;
105 let raw: string | undefined;
106 if (args.positionals.length === 2) [typed, raw] = args.positionals;
107 else if (args.positionals.length === 1) {
108 const m = /^(.*):(\d+)$/.exec(args.positionals[0]!);
109 if (m) [typed, raw] = [m[1], m[2]];
110 }
111 if (typed === undefined || raw === undefined)
112 throw new UsageError("why takes a file and a line: abso why <file>:<line>");
113 const { root, api, agent } = open(env);
114 const file = fileArg(root, env.cwd, typed);
115 const w = await api.why(file, lineNumber(raw, "the line")!, viewOf(args, agent));
116 const lines = [
117 `${w.file} line ${w.line}: ${w.text}`,
118 `Written by ${w.change.author} (${when(w.change.time)}), published in ${published(w.publish)}.`,
119 ...(w.change.message ? [`The change says: "${w.change.message}"`] : []),
120 ...(w.settled.length > 0
121 ? [
122 "It settled a collision between:",
123 ...w.settled.map(
124 (s) => ` ${s.author}, ${published(s.publish)}${s.message ? ` (the change: "${s.message}")` : ""}`,
125 ),
126 ]
127 : []),
128 ...(w.reasons.length > 0
129 ? [
130 "Its reasons:",
131 ...w.reasons.map((r) => ` ${r.kind}, about ${r.toAuthor}'s change "${r.toMessage}": ${r.text}`),
132 ]
133 : []),
134 ...(w.reasonsIn.length > 0
135 ? [
136 "Reasons other changes give about it:",
137 ...w.reasonsIn.map((r) => ` ${r.fromAuthor} (${r.kind}, "${r.fromMessage}"): ${r.text}`),
138 ]
139 : []),
140 ];
141 return { text: lines.join("\n"), json: { ...w } };
142}
144function ranges(rs: readonly [number, number][]): string {
145 return rs.map(([a, b]) => (a === b ? `${a}` : `${a}-${b}`)).join(", ");
146}
148/** Whether a starting note's file entry (a path, a folder, or a glob) names `file`. */
149function names(entry: string, file: string): boolean {
150 try {
151 return globTest(entry)(file);
152 } catch {
153 return false;
154 }
155}
157/**
158 * abso who <file...>: for each file, who last changed it, who has unpublished
159 * changes in it, and whose starting note names it (#37, Artist 1: "is anyone
160 * in here right now?" before touching someone's file).
161 */
162export async function runWho(args: Parsed, env: Env): Promise<Output> {
163 if (args.positionals.length === 0) throw new UsageError("name the files: abso who <file...>");
164 const { root, api, agent } = open(env);
165 const files = args.positionals.map((typed) => fileArg(root, env.cwd, typed));
166 const w = await api.where();
167 const lines: string[] = [];
168 const json: Record<string, unknown>[] = [];
169 for (const file of files) {
170 const last = (await api.log({ agent }, 1, file)).versions[0];
171 const drafts = w.files[file] ?? [];
172 const notes = (w.starting ?? []).filter((n) => n.files.some((f) => names(f, file)));
173 lines.push(
174 `${file}:`,
175 last
176 ? ` last changed in version ${last.version} by ${byWhom(last)}, ${when(last.time)}: ${last.message}`
177 : " in no published version yet",
178 ...(drafts.length > 0
179 ? drafts.map(
180 (s) =>
181 ` ${s.agent}${s.agent === agent ? " (you)" : ""} has unpublished changes at lines ${ranges(s.lines) || "(none left)"}, last at ${when(s.lastEdit)}`,
182 )
183 : [" nobody has unpublished changes in it"]),
184 ...notes.map(
185 (n) =>
186 ` ${n.agent}${n.agent === agent ? " (you)" : ""} started "${n.text}"${n.draft ? ` in draft ${n.draft}` : ""}, ${when(n.time)}`,
187 ),
188 );
189 json.push({ file, last: last ?? null, drafts, starting: notes });
190 }
191 return { text: lines.join("\n"), json: { version: w.version, files: json } };
192}
194export async function runWhere(_args: Parsed, env: Env): Promise<Output> {
195 const { api } = open(env);
196 const w = await api.where();
197 const files = Object.entries(w.files).sort(([a], [b]) => a.localeCompare(b));
198 // Starting notes (#37): what agents said they are taking on, edits or not.
199 const notes = (w.starting ?? []).map((n) => {
200 const names = n.files.length > 0 ? ` (${n.files.join(", ")})` : "";
201 return ` ${n.agent}${n.draft ? ` in draft ${n.draft}` : ""}: "${n.text}"${names}, since ${when(n.time)}`;
202 });
203 const starting = notes.length > 0 ? ["Starting on:", ...notes] : [];
204 if (files.length === 0)
205 return {
206 text: [`Nobody has unpublished changes. Shared is at version ${w.version}.`, ...starting].join("\n"),
207 json: { ...w },
208 };
209 const lines = [...starting, `Who's working where (shared is at version ${w.version}):`];
210 for (const [file, spots] of files) {
211 lines.push(` ${file}`);
212 for (const s of spots) {
213 const at = s.shared.length > 0 ? `, at shared lines ${ranges(s.shared)}` : "";
214 lines.push(
215 ` ${s.agent}: lines ${ranges(s.lines) || "(none left)"}${at}; ${s.changes} change${s.changes === 1 ? "" : "s"}, last at ${when(s.lastEdit)}`,
216 );
217 }
218 }
219 return { text: lines.join("\n"), json: { ...w } };
220}