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