- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/client/src/history.ts?format=json
309 linesFirst import 65% · whytrail 30% · rename 2% · speed 1% · engine 1% · readspeed 1% · Last change readspeed in version 271, 9 versions changed it
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 { type GitOrigin, gitOrigin, issueLinks } from "./git-origin.ts";
12import { byWhom, type TrailStep, type WhyAnswer } from "./history-answers.ts";
14function open(env: Env): { root: string; api: Api; agent: string } {
15 const root = findRoot(env.cwd);
16 if (root === undefined)
17 throw new UsageError(`${env.cwd} is not in an abso folder (no .abso/config.json here or above)`);
18 const config = readConfig(root, env.env, env.tokenFile === true);
19 return { root, api: new Api(config), agent: config.agent };
20}
22/** A path as typed (relative to where the command runs) to the folder-relative form the server uses. */
23export function fileArg(root: string, cwd: string, typed: string): string {
24 const rel = relativeTo(root, resolve(cwd, typed));
25 if (rel === undefined) throw new UsageError(`${typed} is not inside the abso folder ${root}`);
26 return rel;
27}
29export function when(time: number): string {
30 return `${new Date(time).toISOString().slice(0, 16).replace("T", " ")} UTC`;
31}
33function lineNumber(raw: string | undefined, what: string): number | undefined {
34 if (raw === undefined) return undefined;
35 const n = Number(raw);
36 if (!Number.isInteger(n) || n < 1) throw new UsageError(`${what} must be a line number (got ${JSON.stringify(raw)})`);
37 return n;
38}
40/** --draft <name> reads a named draft; --mine reads this agent's own view, its unpublished lines marked. */
41function viewOf(args: Parsed, agent: string): View {
42 const draft = str(args, "draft");
43 const mine = bool(args, "mine");
44 if (draft !== undefined && mine) throw new UsageError("give --draft or --mine, not both");
45 if (mine && str(args, "version") !== undefined)
46 throw new UsageError("--mine reads your view as it is now; it takes no --version");
47 return mine ? { agent } : draft !== undefined ? { draft } : {};
48}
50function published(p: Publish | null): string {
51 return p === null ? "not pushed" : `version ${p.version} by ${byWhom(p)} (${when(p.time)}): "${p.message}"`;
52}
54/** published, with an imported push's git lines taken off its message (gitLines says them). */
55function pushed(p: Publish | null, issues: string | undefined): string {
56 const origin = p ? gitOrigin(p, issues) : undefined;
57 return p && origin ? published({ ...p, message: origin.message }) : published(p);
58}
60function gitLines(o: GitOrigin): string[] {
61 return [` From git: commit ${o.commit}${o.author ? ` by ${o.author}` : ""}${o.time ? `, ${o.time}` : ""}.`];
62}
64/** "1 formatting change and 2 moves": what why skipped. */
65function skippedKinds(steps: readonly TrailStep[]): string {
66 const moves = steps.filter((s) => s.movedFrom !== undefined).length;
67 const formatting = steps.length - moves;
68 return [
69 ...(formatting > 0 ? [`${formatting} formatting change${formatting === 1 ? "" : "s"}`] : []),
70 ...(moves > 0 ? [`${moves} move${moves === 1 ? "" : "s"}`] : []),
71 ].join(" and ");
72}
74/** A trail step in a few words: its version (or that it isn't pushed), who, and the first line of why. */
75function stepName(s: TrailStep, long = false): string {
76 const first = (s.publish ? (gitOrigin(s.publish)?.message ?? s.publish.message) : s.message).split("\n")[0]!;
77 const subject = first.length > 100 ? `${first.slice(0, 97).trimEnd()}...` : first;
78 const where = s.publish === null ? "not pushed" : `version ${s.publish.version}`;
79 const who = s.publish ? byWhom(s.publish) : s.author;
80 return long
81 ? `${where} by ${who} (${when(s.publish?.time ?? s.time)}): "${subject}"`
82 : `${where} (${who}, "${subject}")`;
83}
85export async function runBlame(args: Parsed, env: Env): Promise<Output> {
86 if (args.positionals.length !== 1)
87 throw new UsageError("blame takes one file: abso blame <file> [--from <n>] [--to <n>]");
88 const { root, api, agent } = open(env);
89 const file = fileArg(root, env.cwd, args.positionals[0]!);
90 const rawVersion = str(args, "version");
91 if (rawVersion !== undefined && !/^\d+$/.test(rawVersion))
92 throw new UsageError(`--version is a version number (got ${JSON.stringify(rawVersion)})`);
93 const view = viewOf(args, agent);
94 const b = await api.blame(
95 file,
96 lineNumber(str(args, "from"), "--from"),
97 lineNumber(str(args, "to"), "--to"),
98 rawVersion === undefined ? undefined : Number(rawVersion),
99 view,
100 );
101 const width = Math.max(4, ...b.lines.map((l) => l.author.length));
102 const digits = String(b.to).length;
103 const versions = new Map<number, string>();
104 for (const a of b.atoms) {
105 if (a.publish === null) continue;
106 const own = a.message && a.message !== a.publish.message ? ` (the change itself: "${a.message}")` : "";
107 const origin = gitOrigin(a.publish);
108 const message = origin
109 ? `${origin.message.split("\n")[0]} (from git commit ${origin.commit.slice(0, 12)}${origin.author ? ` by ${origin.author}` : ""})`
110 : a.publish.message;
111 const line = ` v${a.publish.version} by ${byWhom(a.publish)}, ${when(a.publish.time)}: ${message}${own}`;
112 if (!versions.has(a.publish.version) || own) versions.set(a.publish.version, line);
113 }
114 const whose =
115 b.agent !== undefined
116 ? `as your view has it now`
117 : b.draft !== undefined
118 ? `as draft ${b.draft} has it at version ${b.version}`
119 : `as shared has it at version ${b.version}`;
120 const unpublished = b.lines.some((l) => l.unpublished);
121 // A line in a draft but not yet in shared has no shared version: "draft" says where it is.
122 const tag = (l: BlameAnswer["lines"][number]) =>
123 l.unpublished ? "*" : l.version === null ? "draft" : `v${l.version}`;
124 const tagWidth = Math.max(4, ...b.lines.map((l) => tag(l).length));
125 const lines = [
126 `${b.file} ${whose} (lines ${b.from}-${b.to} of ${b.total}):`,
127 ...b.lines.map(
128 (l) => ` ${String(l.n).padStart(digits)} ${tag(l).padEnd(tagWidth)} ${l.author.padEnd(width)} ${l.text}`,
129 ),
130 ...(unpublished ? ["", "* not pushed yet: your own unpushed change."] : []),
131 "",
132 "Pushes:",
133 ...[...versions].sort(([x], [y]) => x - y).map(([, line]) => line),
134 ];
135 return { text: lines.join("\n"), json: { ...b } };
136}
138export async function runWhy(args: Parsed, env: Env): Promise<Output> {
139 // abso why <file>:<line>, or abso why <file> <line>
140 let typed: string | undefined;
141 let raw: string | undefined;
142 if (args.positionals.length === 2) [typed, raw] = args.positionals;
143 else if (args.positionals.length === 1) {
144 const m = /^(.*):(\d+)$/.exec(args.positionals[0]!);
145 if (m) [typed, raw] = [m[1], m[2]];
146 }
147 if (typed === undefined || raw === undefined)
148 throw new UsageError("why takes a file and a line: abso why <file>:<line>");
149 const { root, api, agent } = open(env);
150 const file = fileArg(root, env.cwd, typed);
151 const rawAt = str(args, "at");
152 if (rawAt !== undefined && !/^\d+$/.test(rawAt))
153 throw new UsageError(`--at is a version number (got ${JSON.stringify(rawAt)})`);
154 const at = rawAt === undefined ? undefined : Number(rawAt);
155 const view = viewOf(args, agent);
156 if (at !== undefined && "agent" in view)
157 throw new UsageError("--mine reads your view as it is now; it takes no --at");
158 const w = await api.why(file, lineNumber(raw, "the line")!, view, at);
159 if (at !== undefined && w.version !== at)
160 throw new UsageError(`this server doesn't read why at a version yet; abso blame ${w.file} --version ${at} does`);
161 return { text: whyText(w, { at, all: bool(args, "all") }), json: { ...w } };
162}
164/**
165 * What abso why prints for an answer. The line's changes (abso-core issue
166 * 20): the newest one that changed what it does leads, past formatting-only
167 * ones, unless `all`.
168 */
169export function whyText(w: WhyAnswer, { at, all = false }: { at?: number; all?: boolean } = {}): string {
170 const trail = w.trail ?? [];
171 const lead = (all ? trail[0] : trail.find((s) => !s.formatting)) ?? trail[0];
172 const leadAt = lead === undefined ? 0 : trail.indexOf(lead);
173 const skipped = trail.slice(0, leadAt);
174 const earlier = trail.slice(leadAt + 1).filter((s) => all || !s.formatting);
175 const origin = lead?.publish ? gitOrigin(lead.publish, w.gitIssues) : undefined;
176 const lines = [
177 `${w.file} line ${w.line}${at !== undefined ? ` at version ${at}` : ""}: ${w.text}`,
178 ...(lead === undefined || leadAt === 0
179 ? [`Written by ${w.change.author} (${when(w.change.time)}), pushed in ${pushed(w.publish, w.gitIssues)}.`]
180 : [
181 `Written by ${lead.author} (${when(lead.time)}), pushed in ${pushed(lead.publish, w.gitIssues)}.`,
182 ...(lead.text.trim() !== w.text.trim() ? [` It read: ${lead.text.trim()}`] : []),
183 ]),
184 ...(origin ? gitLines(origin) : []),
185 ...issueLinks(`${w.text}\n${origin?.message ?? ""}`, origin?.issues).map((l) => ` ${l}`),
186 ...(skipped.length > 0
187 ? [
188 `Skipped ${skippedKinds(skipped)} since: ${skipped.map((s) => `${stepName(s)}${s.movedFrom ? `, moved from ${s.movedFrom}` : ""}`).join("; ")}. abso why --all shows ${skipped.length === 1 ? "it" : "them"}.`,
189 ]
190 : []),
191 ...(earlier.length > 0
192 ? [
193 "Earlier changes, newest first:",
194 ...earlier.flatMap((s, i) => {
195 const newer = i === 0 ? lead! : earlier[i - 1]!;
196 const o = s.publish ? gitOrigin(s.publish, w.gitIssues) : undefined;
197 return [
198 ` ${stepName(s, true)}${s.movedFrom ? ` (moved from ${s.movedFrom})` : s.formatting ? " (formatting only)" : ""}${o ? `, from git commit ${o.commit.slice(0, 12)}${o.author ? ` by ${o.author}` : ""}` : ""}`,
199 ...(s.text.trim() !== newer.text.trim() ? [` It read: ${s.text.trim()}`] : []),
200 ];
201 }),
202 ]
203 : []),
204 ...(w.trailMore ? [" (it goes back further than why follows)"] : []),
205 ...(w.change.message && leadAt === 0 ? [`The change says: "${w.change.message}"`] : []),
206 ...(w.settled.length > 0
207 ? [
208 w.settledBy
209 ? `It was kept when ${w.settledBy.author} settled a collision between:`
210 : "It settled a collision between:",
211 ...w.settled.map(
212 (s) => ` ${s.author}, ${published(s.publish)}${s.message ? ` (the change: "${s.message}")` : ""}`,
213 ),
214 ...(w.held ? [` ${w.held.agent}, a held push: "${w.held.message}"`] : []),
215 ]
216 : []),
217 ...(w.reasons.length > 0
218 ? [
219 "Its reasons:",
220 ...w.reasons.map((r) => ` ${r.kind}, about ${r.toAuthor}'s change "${r.toMessage}": ${r.text}`),
221 ]
222 : []),
223 ...(w.reasonsIn.length > 0
224 ? [
225 "Reasons other changes give about it:",
226 ...w.reasonsIn.map((r) => ` ${r.fromAuthor} (${r.kind}, "${r.fromMessage}"): ${r.text}`),
227 ]
228 : []),
229 ];
230 return lines.join("\n");
231}
233function ranges(rs: readonly [number, number][]): string {
234 return rs.map(([a, b]) => (a === b ? `${a}` : `${a}-${b}`)).join(", ");
235}
237/** Whether a starting note's file entry (a path, a folder, or a glob) names `file`. */
238function names(entry: string, file: string): boolean {
239 try {
240 return globTest(entry)(file);
241 } catch {
242 return false;
243 }
244}
246/**
247 * abso who <file...>: for each file, who last changed it, who has unpublished
248 * changes in it, and whose starting note names it (#37: "is anyone
249 * in here right now?" before touching someone's file).
250 */
251export async function runWho(args: Parsed, env: Env): Promise<Output> {
252 if (args.positionals.length === 0) throw new UsageError("name the files: abso who <file...>");
253 const { root, api, agent } = open(env);
254 const files = args.positionals.map((typed) => fileArg(root, env.cwd, typed));
255 const w = await api.where();
256 const lines: string[] = [];
257 const json: Record<string, unknown>[] = [];
258 for (const file of files) {
259 const last = (await api.log({ agent }, 1, file)).versions[0];
260 const drafts = w.files[file] ?? [];
261 const notes = (w.starting ?? []).filter((n) => n.files.some((f) => names(f, file)));
262 lines.push(
263 `${file}:`,
264 last
265 ? ` last changed in version ${last.version} by ${byWhom(last)}, ${when(last.time)}: ${last.message}`
266 : " in no pushed version yet",
267 ...(drafts.length > 0
268 ? drafts.map(
269 (s) =>
270 ` ${s.agent}${s.agent === agent ? " (you)" : ""} has unpushed changes at lines ${ranges(s.lines) || "(none left)"}, last at ${when(s.lastEdit)}`,
271 )
272 : [" nobody has unpushed changes in it"]),
273 ...notes.map(
274 (n) =>
275 ` ${n.agent}${n.agent === agent ? " (you)" : ""} started "${n.text}"${n.draft ? ` in draft ${n.draft}` : ""}, ${when(n.time)}`,
276 ),
277 );
278 json.push({ file, last: last ?? null, drafts, starting: notes });
279 }
280 return { text: lines.join("\n"), json: { version: w.version, files: json } };
281}
283export async function runWhere(_args: Parsed, env: Env): Promise<Output> {
284 const { api } = open(env);
285 const w = await api.where();
286 const files = Object.entries(w.files).sort(([a], [b]) => a.localeCompare(b));
287 // Starting notes (#37): what agents said they are taking on, edits or not.
288 const notes = (w.starting ?? []).map((n) => {
289 const names = n.files.length > 0 ? ` (${n.files.join(", ")})` : "";
290 return ` ${n.agent}${n.draft ? ` in draft ${n.draft}` : ""}: "${n.text}"${names}, since ${when(n.time)}`;
291 });
292 const starting = notes.length > 0 ? ["Starting on:", ...notes] : [];
293 if (files.length === 0)
294 return {
295 text: [`Nobody has unpushed changes. Shared is at version ${w.version}.`, ...starting].join("\n"),
296 json: { ...w },
297 };
298 const lines = [...starting, `Who's working where (shared is at version ${w.version}):`];
299 for (const [file, spots] of files) {
300 lines.push(` ${file}`);
301 for (const s of spots) {
302 const at = s.shared.length > 0 ? `, at shared lines ${ranges(s.shared)}` : "";
303 lines.push(
304 ` ${s.agent}: lines ${ranges(s.lines) || "(none left)"}${at}; ${s.changes} change${s.changes === 1 ? "" : "s"}, last at ${when(s.lastEdit)}`,
305 );
306 }
307 }
308 return { text: lines.join("\n"), json: { ...w } };
309}