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