- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/worker/project/blame.ts?format=json
449 linesFirst import 50% · whytrail 19% · capacity 19% · speed 12% · infra-split 1%Last change capacity in version 258, 10 versions changed it
1// Blame and why for shared, read from the engine's graph (slice 2 of #18).
2// A line's id names the atom that inserted it, so blame is a lookup per line:
3// that change's author and message, and the publish that brought it into
4// shared, with its message. Why adds the change's reasons, what it settled,
5// and the reasons other changes give that point at it, and the line's
6// earlier changes (trail.ts).
7import { type Atom, type AtomId, type LineId, type ReadView, seqOf, View } from "../../src/engine/index.ts";
8import { isClosedSet, markClosed, StableSet } from "../../src/engine/state-source.ts";
9import { blocksIn, isMarkerLine } from "./markers.ts";
10import { pathKey } from "./pathkey.ts";
11import type { Project } from "./project.ts";
12import { projectFileIn } from "./project-helpers.ts";
13import { type TrailStep, trail } from "./trail.ts";
14import { authorsInView } from "./version-files.ts";
16export interface BlameLine {
17 n: number;
18 text: string;
19 atom: AtomId;
20 author: string;
21 /** The shared version that brought it in; null while it's only in a draft. */
22 version: number | null;
23 /** Not published anywhere yet: the agent's own unpublished change. */
24 unpublished?: true;
25}
27interface Publish {
28 /** null for shared, else the named draft it was published into. */
29 draft: string | null;
30 version: number;
31 agent: string;
32 message: string;
33 time: number;
34}
36/** Whose view: shared (the default, at `version`), a named draft (at `version`), or an agent's view now. */
37export interface BlameWhere {
38 version?: number;
39 draft?: string;
40 agent?: string;
41}
43function publishOf(project: Project, atom: AtomId): Publish | null {
44 return project.publishOf(atom) ?? null;
45}
47const badRequest = (message: string) => Object.assign(new Error(message), { code: "bad-request" });
49function viewOf(project: Project, where: BlameWhere) {
50 let view;
51 let name: string;
52 if (where.agent !== undefined) {
53 if (where.version !== undefined || where.draft !== undefined)
54 throw badRequest("an agent's view is its current one: give agent alone");
55 const draft = project.draftOf(where.agent);
56 if (!draft) throw badRequest(`there is no agent ${JSON.stringify(where.agent)}`);
57 view = draft.view;
58 name = `${where.agent}'s view`;
59 } else if (where.draft !== undefined) {
60 const version = where.version ?? project.lastVersion(where.draft);
61 view = project.viewAt(version, { draft: where.draft });
62 name = `draft ${where.draft} at version ${version}`;
63 } else {
64 view = where.version === undefined ? project.sharedView() : project.viewAt(where.version);
65 name = where.version === undefined ? "shared" : `shared at version ${where.version}`;
66 }
67 return { view, name };
68}
70/** A file's lines, by any spelling (#41, F7), and the stored spelling. */
71function lines(project: Project, asked: string, where: BlameWhere) {
72 const { view, name } = viewOf(project, where);
73 const file = project.spellingIn(view, asked);
74 if (!view.hasFile(file)) throw badRequest(`${asked} isn't in ${name}`);
75 return { file, all: view.lines(file), view };
76}
78/**
79 * Every line of a file (or lines from..to), with who wrote it and the
80 * publishes behind them: in shared, a named draft, or an agent's view with
81 * its unpublished changes.
82 */
83export function blame(
84 project: Project,
85 asked: string,
86 from?: number,
87 to?: number,
88 version?: number,
89 where: Omit<BlameWhere, "version"> = {},
90) {
91 const { file, all } = lines(project, asked, { version, ...where });
92 const first = Math.max(1, from ?? 1);
93 const last = Math.min(all.length, to ?? all.length);
94 const graph = project.graph;
95 // Each atom's author once (abso Capacity): on a stored writer, graph.atom reads and parses the whole atom, and
96 // most lines share a few big atoms.
97 const authors = new Map<AtomId, string>();
98 const authorOf = (id: AtomId): string => {
99 const known = authors.get(id);
100 if (known !== undefined) return known;
101 const author = graph.atom(id).author;
102 authors.set(id, author);
103 return author;
104 };
105 const rows: BlameLine[] = all.slice(first - 1, last).map((l, i) => ({
106 n: first + i,
107 text: l.text,
108 atom: l.atom,
109 author: authorOf(l.atom),
110 version: project.versionOf(l.atom) ?? null,
111 ...(project.publishOf(l.atom) === undefined ? { unpublished: true as const } : {}),
112 }));
113 const atoms = [...new Set(rows.map((r) => r.atom))]
114 .sort((a, b) => graph.atom(a).seq - graph.atom(b).seq)
115 .map((id) => {
116 const a = graph.atom(id);
117 return { atom: id, author: a.author, message: a.message, time: a.time, publish: publishOf(project, id) };
118 });
119 return {
120 file,
121 version: where.agent !== undefined ? null : (version ?? project.lastVersion(where.draft ?? null)),
122 ...(where.draft !== undefined ? { draft: where.draft } : {}),
123 ...(where.agent !== undefined ? { agent: where.agent } : {}),
124 total: all.length,
125 from: first,
126 to: last,
127 lines: rows,
128 atoms,
129 };
130}
132/**
133 * The settle a line was kept through, when its own change settled nothing:
134 * an edit that took out the markers of a block the line sat in (as yours or
135 * theirs), as abso settle --yours, --theirs or --both makes. The earliest,
136 * if several did.
137 */
138function keptThrough(project: Project, view: ReadView, file: string, line: LineId, author: Atom): Atom | undefined {
139 const graph = project.graph;
140 const set = view.set;
141 // Only atoms that write or take out the file's lines can take out its markers (abso Capacity): every atom in the
142 // history was read on a stored graph.
143 for (const id of graph.eachAtomIn(file)) {
144 if (seqOf(id) <= author.seq) continue;
145 const s = graph.atom(id);
146 if (s.resolves.length === 0 || !set.has(s.id)) continue;
147 const marks = s.deletes.filter((id) => {
148 const info = graph.line(id);
149 return info !== undefined && info.file === file && isMarkerLine(info.text);
150 });
151 if (marks.length === 0) continue;
152 // The file just before the settle, markers and all: of a closed set, its atoms before the settle, which a
153 // stored set answers one by one; otherwise listed.
154 const before = new View(
155 graph,
156 isClosedSet(set)
157 ? markClosed(new BeforeSet(set, s.seq))
158 : graph
159 .atoms()
160 .slice(0, s.seq)
161 .filter((a) => set.has(a.id))
162 .map((a) => a.id),
163 );
164 if (!before.hasFile(file)) continue;
165 const lines = before.lines(file);
166 const at = lines.findIndex((l) => l.id === line);
167 if (at < 0) continue;
168 const block = blocksIn(lines.map((l) => l.text)).find((b) => at > b.start && at < b.end);
169 if (block && marks.includes(lines[block.start]!.id)) return s;
170 }
171 return undefined;
172}
174/** A set's atoms numbered below a limit. Atoms depend only on earlier ones, so a closed set's prefix is closed. */
175class BeforeSet extends StableSet<AtomId> {
176 readonly #set: ReadonlySet<AtomId>;
177 readonly #limit: number;
178 readonly retainedBytes = 32;
179 constructor(set: ReadonlySet<AtomId>, limit: number) {
180 super();
181 this.#set = set;
182 this.#limit = limit;
183 }
184 has(id: AtomId): boolean {
185 const seq = seqOf(id);
186 return seq >= 0 && seq < this.#limit && this.#set.has(id);
187 }
188 *values(): SetIterator<AtomId> {
189 for (const id of this.#set) {
190 const seq = seqOf(id);
191 if (seq >= 0 && seq < this.#limit) yield id;
192 }
193 }
194}
196/** The settler's push that was held for this collision, newest first: its message is that side's reason. */
197function heldPush(project: Project, settle: Atom, file: string, after: number) {
198 const held = project
199 .refusals({ agent: settle.author, limit: 1000 })
200 .refusals.find(
201 (r) =>
202 r.via === "publish" &&
203 r.message !== undefined &&
204 r.time <= settle.time &&
205 r.time >= after &&
206 r.collisions.some((c) => c.file === file),
207 );
208 return held ? { agent: held.agent, message: held.message!, time: held.time } : undefined;
209}
211/** One line: the change that wrote it, the publish behind it, its reasons, and what it settled. */
212export function why(project: Project, asked: string, n: number, where: BlameWhere = {}) {
213 const { file, all, view } = lines(project, asked, where);
214 const line = all[n - 1];
215 if (!line)
216 throw Object.assign(new Error(`${file} has ${all.length} lines; ask for one in 1-${all.length}`), {
217 code: "bad-request",
218 });
219 const graph = project.graph;
220 const atom = graph.atom(line.atom);
221 const publish = publishOf(project, atom.id);
222 const reasons = atom.reasons.map((r) => ({
223 kind: r.kind,
224 text: r.text,
225 to: r.to,
226 toAuthor: graph.atom(r.to).author,
227 toMessage: graph.atom(r.to).message,
228 }));
229 const reasonsIn: { from: AtomId; kind: string; text: string; fromAuthor: string; fromMessage: string }[] = [];
230 // The atoms that point at it, where the graph keeps them (abso Capacity): looking at every atom read each one.
231 const pointing = graph.reasonsTo(atom.id);
232 for (const other of pointing ? pointing.map((id) => graph.atom(id)) : graph.atoms()) {
233 for (const r of other.reasons) {
234 if (r.to === atom.id)
235 reasonsIn.push({
236 from: other.id,
237 kind: r.kind,
238 text: r.text,
239 fromAuthor: other.author,
240 fromMessage: other.message,
241 });
242 }
243 }
244 // What it built on (#41, the line's story): the versions that brought in the changes it
245 // depends on (its needs, and the changes whose lines it edited beside), nearest first, once each.
246 const builtOn: { version: number; agent: string; message: string; draft?: string }[] = [];
247 const own = publish ? `${publish.draft ?? ""} ${publish.version}` : undefined;
248 const seen = new Set<string>(own ? [own] : []);
249 for (const id of atom.deps) {
250 const p = publishOf(project, id);
251 if (!p || seen.has(`${p.draft ?? ""} ${p.version}`)) continue;
252 seen.add(`${p.draft ?? ""} ${p.version}`);
253 builtOn.push({
254 version: p.version,
255 agent: p.agent,
256 message: p.message,
257 ...(p.draft !== null ? { draft: p.draft } : {}),
258 });
259 }
260 builtOn.sort((a, b) =>
261 (a.draft === undefined) !== (b.draft === undefined) ? (a.draft === undefined ? -1 : 1) : b.version - a.version,
262 );
263 // What it settled: its own change, or the settle that kept it (both sides of a block it sat in).
264 const kept = atom.resolves.length === 0 ? keptThrough(project, view, file, line.id, atom) : undefined;
265 const settle = kept ?? atom;
266 const settled = settle.resolves.map((id) => {
267 const a = graph.atom(id);
268 return { atom: id, author: a.author, message: a.message, publish: publishOf(project, id) };
269 });
270 const held =
271 settled.length > 0
272 ? heldPush(project, settle, file, Math.max(0, ...settled.map((s) => s.publish?.time ?? 0)))
273 : undefined;
274 const gitIssues = gitIssuesOf(project.sharedView());
275 return {
276 file,
277 line: n,
278 version: where.agent !== undefined ? null : (where.version ?? project.lastVersion(where.draft ?? null)),
279 text: line.text,
280 id: line.id,
281 ...(gitIssues !== undefined ? { gitIssues } : {}),
282 change: {
283 atom: atom.id,
284 author: atom.author,
285 message: atom.message,
286 time: atom.time,
287 needs: atom.needs,
288 deps: atom.deps,
289 },
290 publish,
291 reasons,
292 reasonsIn,
293 settled,
294 ...(kept ? { settledBy: { atom: kept.id, author: kept.author, publish: publishOf(project, kept.id) } } : {}),
295 ...(held ? { held } : {}),
296 builtOn,
297 ...lineTrail(project, view, file, line.id),
298 };
299}
301/**
302 * The line's changes, newest first (abso-core issue 20), its own change
303 * first: each change that rewrote it, with the line's text after it,
304 * whether it only changed formatting, and the file it moved from, if it did. Several changes in one push count as
305 * one, formatting only if all of them were.
306 */
307function lineTrail(project: Project, view: ReadView, file: string, line: LineId) {
308 const graph = project.graph;
309 // Changes pushed together: the same version of the same space, or both still in one agent's draft.
310 const samePush = (a: Atom, b: Atom) => samePublish(publishOf(project, a.id), publishOf(project, b.id));
311 // What was pushed with a published atom is its version's atoms; an atom still in a draft goes with every other one,
312 // so the trail looks near by as before.
313 const pushmates = (a: Atom) => {
314 const p = publishOf(project, a.id);
315 return p ? project.versionAtoms(p.version, p.draft) : undefined;
316 };
317 const { steps, more } = trail(graph, view, file, line, undefined, samePush, pushmates);
318 const groups: { steps: TrailStep[]; publish: Publish | null }[] = [];
319 for (const s of steps) {
320 const publish = publishOf(project, s.atom);
321 const prev = groups[groups.length - 1];
322 if (
323 prev &&
324 samePublish(prev.publish, publish) &&
325 (publish !== null || graph.atom(prev.steps[0]!.atom).author === graph.atom(s.atom).author)
326 )
327 prev.steps.push(s);
328 else groups.push({ steps: [s], publish });
329 }
330 const out = groups.map(({ steps: [newest, ...rest], publish }) => {
331 const a = graph.atom(newest!.atom);
332 const oldest = rest[rest.length - 1] ?? newest!;
333 const moved = [newest!, ...rest].some((s) => s.maybeMoved)
334 ? movedFrom(project, newest!.line, oldest.replaced, publish)
335 : undefined;
336 return {
337 atom: a.id,
338 author: a.author,
339 message: a.message,
340 time: a.time,
341 text: newest!.text,
342 formatting: [newest!, ...rest].every((s) => s.formatting),
343 ...(moved !== undefined ? { movedFrom: moved } : {}),
344 publish,
345 };
346 });
347 return { trail: out, ...(more ? { trailMore: true as const } : {}) };
348}
350/**
351 * The file a push moved a line from: where the line it replaced was just
352 * before the push, when that's not where the push left the line.
353 */
354function movedFrom(project: Project, line: LineId, replaced: LineId | undefined, publish: Publish | null) {
355 if (replaced === undefined || publish === null || publish.version < 1) return undefined;
356 const where = publish.draft === null ? {} : { draft: publish.draft };
357 const fileIn = (version: number, id: LineId) => {
358 try {
359 return project.viewAt(version, where).fileOf(id);
360 } catch {
361 return undefined;
362 }
363 };
364 const before = fileIn(publish.version - 1, replaced);
365 const after = fileIn(publish.version, line);
366 return before !== undefined && after !== undefined && before !== after ? before : undefined;
367}
369/** Where "#N" in history imported from git points (abso.json's "gitIssues"), when shared's project file says. */
370function gitIssuesOf(view: ReadView): string | undefined {
371 const file = projectFileIn(view);
372 if (!file) return undefined;
373 try {
374 const url = (JSON.parse(file.text) as { gitIssues?: unknown }).gitIssues;
375 return typeof url === "string" ? url : undefined;
376 } catch {
377 return undefined;
378 }
379}
381function samePublish(a: Publish | null, b: Publish | null): boolean {
382 return a === null || b === null ? a === b : a.draft === b.draft && a.version === b.version;
383}
385/**
386 * Who wrote a folder (#41, F33): every line of every file under it (the
387 * whole project for ""), counted by the agent that wrote it, most first.
388 * Binary files and files kept whole have no lines, so they count as files
389 * only. The folder is matched by any spelling.
390 */
391export function folderBlame(
392 project: Project,
393 folder: string,
394 version?: number,
395 where: Omit<BlameWhere, "version"> = {},
396) {
397 const { view, name } = viewOf(project, { version, ...where });
398 const want = folder.split("/").filter((s) => s !== "" && s !== ".");
399 const key = pathKey(want.join("/"));
400 const graph = project.graph;
401 const counts = new Map<string, number>();
402 // Each atom's author once (abso Capacity): on a stored writer, graph.atom reads and parses the whole atom, and
403 // most lines share a few big atoms.
404 const authors = new Map<AtomId, string>();
405 const authorOf = (id: AtomId): string => {
406 const known = authors.get(id);
407 if (known !== undefined) return known;
408 const author = graph.atom(id).author;
409 authors.set(id, author);
410 return author;
411 };
412 let files = 0;
413 let total = 0;
414 let stored: string | undefined;
415 // Each file's lines by author as kept when versions land (abso Capacity, version-files.ts), where they answer.
416 const totalsOf = project.authorTotalsFor({ version, ...where });
417 for (const path of view.paths()) {
418 const parts = path.split("/");
419 if (want.length > 0 && (parts.length <= want.length || pathKey(parts.slice(0, want.length).join("/")) !== key))
420 continue;
421 stored ??= parts.slice(0, want.length).join("/");
422 files++;
423 const totals = totalsOf?.(path);
424 if (totals) {
425 for (const [author, n] of totals.authors) {
426 counts.set(author, (counts.get(author) ?? 0) + n);
427 total += n;
428 }
429 continue;
430 }
431 for (const [author, n] of authorsInView(view, path, graph, authorOf)) {
432 counts.set(author, (counts.get(author) ?? 0) + n);
433 total += n;
434 }
435 }
436 if (want.length > 0 && stored === undefined)
437 throw Object.assign(new Error(`there is no folder ${want.join("/")} in ${name}`), { code: "not-found" });
438 return {
439 folder: stored ?? "",
440 version: where.agent !== undefined ? null : (version ?? project.lastVersion(where.draft ?? null)),
441 ...(where.draft !== undefined ? { draft: where.draft } : {}),
442 ...(where.agent !== undefined ? { agent: where.agent } : {}),
443 files,
444 lines: total,
445 authors: [...counts]
446 .map(([agent, lines]) => ({ agent, lines }))
447 .sort((a, b) => b.lines - a.lines || (a.agent < b.agent ? -1 : 1)),
448 };
449}