Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed
MCP
code on this site's /mcp
CLI
none: the JSON below is the answer
JSON
/christopher/abso-core/files/worker/project/draft-collisions.ts?version=239&format=json
218 linesFirst import 63% · capacity 33% · codex-capacity-chair 2% · pinch 1%Last change capacity in version 229, 5 versions changed it

You're reading version 239. The newest is 318, and 2 versions since then changed this file. Go to the newestCompare with 318

1// Whether agents' unpublished changes would collide (#41, F22), read through DraftCollisionHost; today the host
2// is the project in memory.
3
4import { type AtomId, type Graph, parseKey, type ReadView } from "../../src/engine/index.ts";
5import { StableSet, unionOverlay } from "../../src/engine/state-source.ts";
6import { claimantsAmong, describeSide, fileOfKey, pairsFrom } from "./collisions.ts";
7import type { DefinitionRule } from "./definition-rule.ts";
8import { type Definition, definedTwice } from "./definitions.ts";
9import { pathKey } from "./pathkey.ts";
10import type { CollisionSide, DraftCollision } from "./project-types.ts";
11import { last, SHARED, type Space } from "./spaces.ts";
13interface Agent {
14 readonly name: string;
15 readonly space: string;
18/** What the draft collision read needs from a project. */
19export interface DraftCollisionHost {
20 readonly graph: Graph;
21 readonly agents: ReadonlyMap<string, Agent>;
22 needInit(): void;
23 shared(): Space;
24 sharedView(): ReadView;
25 definitionRule(): DefinitionRule;
26 draft(agent: Agent): AtomId[];
27 agentView(agent: Agent): ReadView;
28 view(set: ReadonlySet<AtomId>): ReadView;
29 touchedFiles(ids: Iterable<AtomId>, views: readonly ReadView[]): Set<string>;
32/**
33 * Whether agents' unpublished changes would collide (#41, F22), by the
34 * publish rule: for each pair of agents working in shared, one agent's
35 * changes as if published on shared now, then the other's checked against
36 * them, both ways round. Same lines, a definition one changes that the
37 * other's new lines use, the same attribute, and a name both define at the
38 * top of a file (refused once the second syncs onto the first's work). Exact for shared at `version`; as shared moves on, so can
39 * the answer, as a real publish's would. `file` or `folder` narrows it.
40 */
41/**
42 * A set and some drafts' atoms, by lookup (abso Capacity): copying shared's atoms into a new set read every one of them
43 * from disk on a stored writer, once per pair of agents.
44 */
45class WithDrafts extends StableSet<AtomId> {
46 readonly retainedBytes: number;
47 readonly #base: ReadonlySet<AtomId>;
48 readonly #drafts: ReadonlySet<AtomId>;
49 constructor(base: ReadonlySet<AtomId>, drafts: Iterable<AtomId>) {
50 super();
51 this.#base = base;
52 this.#drafts = new Set(drafts);
53 this.retainedBytes = 64 + this.#drafts.size * 32;
54 }
55 has(atom: AtomId): boolean {
56 return this.#drafts.has(atom) || this.#base.has(atom);
57 }
58 *values(): SetIterator<AtomId> {
59 yield* this.#base;
60 for (const atom of this.#drafts) if (!this.#base.has(atom)) yield atom;
61 }
64export function draftCollisions(
65 host: DraftCollisionHost,
66 options: { file?: string; folder?: string } = {},
67): {
68 version: number;
69 agents: string[];
70 collisions: DraftCollision[];
71} {
72 host.needInit();
73 const working = [...host.agents.values()]
74 .filter((a) => a.space === SHARED && host.draft(a).length > 0)
75 .toSorted((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
76 const shared = host.shared().own;
77 const sharedView = host.sharedView();
78 const out: DraftCollision[] = [];
79 const side = (agent: string, file: string, s: CollisionSide) => ({ agent, file, lines: s.lines, text: s.text });
80 // Every draft change's claimants among all the drafts, found once (abso Capacity): a stored atom's keys are read
81 // from disk, and a draft deleting a big file has thousands, read again for every other agent.
82 let claimants: ReadonlyMap<AtomId, readonly AtomId[]> | undefined;
83 const claimantsOf = (agent: Agent): ReadonlyMap<AtomId, readonly AtomId[]> => {
84 claimants ??= claimantsAmong(
85 host.graph,
86 working.flatMap((a) => host.draft(a)),
87 );
88 const all = claimants;
89 return new Map(host.draft(agent).map((id) => [id, all.get(id) ?? []]));
90 };
91 // One set per draft, so the definition rule keeps what it worked out about it (abso Capacity).
92 const draftSets = new Map<Agent, ReadonlySet<AtomId>>();
93 const draftSet = (agent: Agent) => {
94 let set = draftSets.get(agent);
95 if (!set) draftSets.set(agent, (set = new Set(host.draft(agent))));
96 return set;
97 };
98 // Shared now with each agent's draft on top, once per agent. Over shared's view's own set (abso Capacity): a view's set
99 // is closed under dependencies anyway, so shared's closed set and the drafts lay out what shared's atoms and the drafts
100 // do, and only the drafts' atoms are walked to close it.
101 const withDraftsView = (...drafts: readonly AtomId[][]) => host.view(unionOverlay(sharedView.set, drafts.flat()));
102 const nowViews = new Map<Agent, ReadView>();
103 const nowViewOf = (agent: Agent) => {
104 let view = nowViews.get(agent);
105 if (!view) nowViews.set(agent, (view = withDraftsView(host.draft(agent))));
106 return view;
107 };
108 // Each agent's touched files once, not once per pair (abso Capacity).
109 const touched = new Map<Agent, Set<string>>();
110 const touchedBy = (agent: Agent) => {
111 let files = touched.get(agent);
112 if (!files) touched.set(agent, (files = host.touchedFiles(host.draft(agent), [host.agentView(agent)])));
113 return files;
114 };
115 for (let i = 0; i < working.length; i++) {
116 for (let j = 0; j < working.length; j++) {
117 if (i === j) continue;
118 const a = working[i]!;
119 const b = working[j]!;
120 const draftA = host.draft(a);
121 const draftB = host.draft(b);
122 const newer = draftSet(a);
123 const union = new WithDrafts(shared, [...draftA, ...draftB]);
124 const viewA = host.agentView(a);
125 const viewB = host.agentView(b);
126 if (i < j) {
127 // Lines and attributes: the same either way round, so once per pair.
128 const paired = new Set<string>();
129 for (const pair of pairsFrom(host.graph, claimantsOf(b), newer, union)) {
130 paired.add(`${pair.theirs} ${pair.yours}`);
131 const file = fileOfKey(pair.keys[0]!.key, viewB);
132 const fileKeys = pair.keys.filter((k) => fileOfKey(k.key, viewB) === file).map((k) => k.key);
133 const attrs = fileKeys.map((k) => parseKey(k)).filter((k) => k.kind === "attr");
134 const fileA = viewA.hasFile(file) ? file : fileOfKey(pair.keys[0]!.key, viewA);
135 if (attrs.length === fileKeys.length) {
136 const name = attrs[0]!.attr!;
137 const valueOf = (atom: AtomId) =>
138 (host.graph.atom(atom).attrs ?? []).find((x) => x.file === file && x.name === name)?.value ?? "";
139 out.push({
140 kind: "attribute",
141 name,
142 file,
143 first: { agent: a.name, file, lines: [1, 0], text: valueOf(pair.theirs) },
144 second: { agent: b.name, file, lines: [1, 0], text: valueOf(pair.yours) },
145 });
146 } else {
147 out.push({
148 kind: "lines",
149 file,
150 first: side(a.name, fileA, describeSide(viewA, pair.theirs, fileA, fileKeys)),
151 second: side(b.name, file, describeSide(viewB, pair.yours, file, fileKeys)),
152 });
153 }
154 }
155 // A name both define at the top level of one file: what the second meets once it syncs onto the
156 // first's work, as the publish rule checks it then. Not when the two definitions are one lines collision.
157 // The union's view only when the two share a file (abso Capacity): laying out shared plus both drafts
158 // cost a few seconds a pair on a stored writer.
159 let both: ReadView | undefined;
160 const mineA = new Set(draftA);
161 const mineB = new Set(draftB);
162 const filesA = touchedBy(a);
163 for (const file of [...touchedBy(b)].filter((f) => filesA.has(f)).toSorted()) {
164 both ??= withDraftsView(draftA, draftB);
165 if (!both.hasFile(file)) continue;
166 for (const [name, defs] of definedTwice(both, file)) {
167 const by = (mine: Set<AtomId>) => defs.find((d) => d.lines.some((l) => mine.has(host.graph.lineAtom(l)!)));
168 const dA = by(mineA);
169 const dB = by(mineB);
170 if (!dA || !dB || dA === dB) continue;
171 const atomsOf = (d: Definition, mine: Set<AtomId>) =>
172 d.lines.map((l) => host.graph.lineAtom(l)!).filter((x) => mine.has(x));
173 if (atomsOf(dA, mineA).some((x) => atomsOf(dB, mineB).some((y) => paired.has(`${x} ${y}`)))) continue;
174 out.push({
175 kind: "duplicate",
176 name,
177 file,
178 first: { agent: a.name, file, lines: [dA.start + 1, dA.end], text: `${dA.text}\n` },
179 second: { agent: b.name, file, lines: [dB.start + 1, dB.end], text: `${dB.text}\n` },
180 });
181 }
182 }
183 }
184 // Definitions: b's new lines use a name whose definition a's changes change.
185 const nowView = () => nowViewOf(a);
186 for (const d of host.definitionRule().collisions(draftSet(b), viewB, sharedView, nowView, newer, SHARED)) {
187 const c = d.collision;
188 out.push({
189 kind: "definition",
190 name: c.name!,
191 file: c.file,
192 first: { agent: a.name, file: c.theirs.file ?? c.file, lines: c.theirs.lines, text: c.theirs.text },
193 second: side(b.name, c.file, c.yours),
194 });
195 }
196 }
197 }
198 const fileKey = options.file !== undefined ? pathKey(options.file) : undefined;
199 const folderParts =
200 options.folder !== undefined ? options.folder.split("/").filter((s) => s !== "" && s !== ".") : undefined;
201 const under = (path: string): boolean => {
202 if (fileKey !== undefined && pathKey(path) !== fileKey) return false;
203 if (folderParts !== undefined && folderParts.length > 0) {
204 const parts = path.split("/");
205 if (
206 parts.length <= folderParts.length ||
207 pathKey(parts.slice(0, folderParts.length).join("/")) !== pathKey(folderParts.join("/"))
208 )
209 return false;
210 }
211 return true;
212 };
213 const narrowed =
214 fileKey === undefined && folderParts === undefined
215 ? out
216 : out.filter((c) => under(c.first.file) || under(c.second.file));
217 return { version: last(host.shared()), agents: working.map((a) => a.name), collisions: narrowed };