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/queue.ts?version=315&format=json
378 linesFirst import 88% · codex-capacity-chair 7% · engine 1% · rename 1% · speed 1% · autosettle 1% · pinch 1%Last change autosettle in version 211, 9 versions changed it

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

1// The merge queue: publishes to shared waiting for their batch's check.
2// Writes go through QueueHost; today the host is Project.
3
4import { type AtomId, buildAtom, type Graph, type ReadView } from "../../src/engine/index.ts";
5import { unionOverlay } from "../../src/engine/state-source.ts";
6import { autoSettledOf } from "./autosettle.ts";
7import type { Pair } from "./collisions.ts";
8import { definedTwice } from "./definitions.ts";
9import { heldMessage, keptOf, lostLines } from "./markers.ts";
10import { clip } from "./news.ts";
11import { ProjectError } from "./project-error.ts";
12import { projectFileIn } from "./project-helpers.ts";
13import type {
14 AgentState,
15 Blobs,
16 Collision,
17 Entry,
18 Modes,
19 PublishAnswer,
20 PullReason,
21 QueuedPublish,
22 Settled,
23} from "./project-types.ts";
24import { last, SHARED, type Space } from "./spaces.ts";
25import { treeHash } from "./tree.ts";
26import { modesOf } from "./view-changes.ts";
28/** What the merge queue needs from a project. */
29export interface QueueHost {
30 readonly graph: Graph;
31 checkerReady(): boolean;
32 sharedView(): ReadView;
33 sharedOverlay?(atoms: readonly AtomId[]): ReadView;
34 sharedAgentOverlay?(agent: AgentState, atoms: readonly AtomId[]): ReadView;
35 queued(): readonly QueuedPublish[];
36 queuedId(): number;
37 checkingHas(id: number): boolean;
38 replaceChecking(ids: Iterable<number>): void;
39 uncheck(id: number): void;
40 needInit(): void;
41 shared(): Space;
42 setOf(space: Space): ReadonlySet<AtomId>;
43 view(set: ReadonlySet<AtomId>): ReadView;
44 agentSet(agent: AgentState): Set<AtomId>;
45 agentView(agent: AgentState): ReadView;
46 pairs(draft: readonly AtomId[], against: ReadonlySet<AtomId>, settled: ReadonlySet<AtomId>): Pair[];
47 describe(pair: Pair, yoursView: ReadView, theirsView: ReadView, spaceName: string): Collision;
48 touchedFiles(ids: Iterable<AtomId>, views: readonly ReadView[]): Set<string>;
49 refuse(
50 agent: AgentState,
51 space: Space,
52 via: "publish" | "land",
53 time: number,
54 collisions: Collision[],
55 entries: Entry[],
56 message?: string,
57 ): { ok: false; collisions: Collision[] };
58 currentChange(agent: AgentState, time: number): number | undefined;
59 nextAt(): number;
60 apply(entry: Entry): void;
61 agentOf(name: string): AgentState;
62 requireClosed(tie: { deps: readonly AtomId[] }, union: ReadonlySet<AtomId>): void;
63 newsForOthers(publisher: AgentState, space: Space, version: number, entries: Entry[]): void;
64 settledNews(agent: AgentState, version: number, settled: readonly Settled[], entries: Entry[]): void;
65 addressedNews(agent: AgentState, version: number, entries: Entry[]): void;
66 reviewNews(agent: AgentState, version: number, entries: Entry[]): void;
67 queueNews(agent: AgentState, items: readonly { key: string; text: string }[], entries: Entry[]): void;
68 flush(entries: Entry[]): void;
71/** Whether shared's project file (abso.json, else avcs.json) turns the merge queue on (`"queue": true`). */
72export function queueOn(host: QueueHost): boolean {
73 if (!host.checkerReady()) return false;
74 const file = projectFileIn(host.sharedView());
75 if (!file) return false;
76 try {
77 return (JSON.parse(file.text) as { queue?: unknown }).queue === true;
78 } catch {
79 return false;
80 }
83/** With the queue on, nothing lands in shared unchecked; land and pluck don't go through the queue yet. */
84export function notQueuedYet(host: QueueHost, what: string): void {
85 if (queueOn(host))
86 throw new ProjectError(
87 "conflict",
88 `${what} doesn't go through the merge queue yet; switch to shared, take the changes into your draft, and push`,
89 );
92/** Atoms of every queued publish, or only other agents' with `except`. */
93export function queuedAtoms(host: QueueHost, except?: string): Set<AtomId> {
94 return new Set(
95 host
96 .queued()
97 .filter((q) => q.agent !== except)
98 .flatMap((q) => q.changes),
99 );
102/**
103 * Queue the agent's publish (#39). It is checked first against shared and
104 * every publish queued ahead of it, as if those had landed: lines both
105 * changed, and names defined twice, are refused now, so the queue only ever
106 * holds publishes that merge cleanly with each other.
107 */
108export function enqueue(
109 host: QueueHost,
110 agent: AgentState,
111 message: string,
112 time: number,
113 draft: readonly AtomId[],
114 resolves: readonly AtomId[],
115 entries: Entry[],
116): PublishAnswer {
117 const space = host.shared();
118 const mineQueued = queuedAtoms(host);
119 const changes = draft.filter((id) => !mineQueued.has(id));
120 if (changes.length === 0) return { ok: true, version: last(space), changes: 0 };
121 const ahead = queuedAtoms(host, agent.name);
122 const now = host.setOf(space);
123 if (ahead.size > 0) {
124 const landed = unionOverlay(now, ahead);
125 const theirsView = host.sharedOverlay ? host.sharedOverlay([...ahead]) : host.view(landed);
126 const yoursView = host.sharedAgentOverlay
127 ? host.sharedAgentOverlay(agent, [...ahead])
128 : host.view(unionOverlay(landed, host.agentSet(agent)));
129 const queuedBy = (id: AtomId) => host.queued().find((q) => q.changes.includes(id));
130 const collisions: Collision[] = host.pairs(changes, ahead, unionOverlay(landed, changes)).map((p) => {
131 const c = host.describe(p, host.agentView(agent), theirsView, agent.space);
132 const q = queuedBy(p.theirs);
133 return q ? { ...c, theirs: { ...c.theirs, agent: q.agent, message: q.message, queued: q.id } } : c;
134 });
135 const mine = new Set(changes);
136 for (const file of [...host.touchedFiles(changes, [yoursView])].sort()) {
137 if (!yoursView.hasFile(file)) continue;
138 for (const [name, defs] of definedTwice(yoursView, file)) {
139 const yours = defs.find((d) => d.lines.some((l) => mine.has(host.graph.line(l)!.atom)));
140 const theirs = defs.find((d) => d.lines.some((l) => ahead.has(host.graph.line(l)!.atom)));
141 if (!yours || !theirs) continue;
142 const q = queuedBy(host.graph.line(theirs.lines.find((l) => ahead.has(host.graph.line(l)!.atom))!)!.atom)!;
143 collisions.push({
144 kind: "duplicate",
145 name,
146 file,
147 yours: { lines: [yours.start + 1, yours.end], text: `${yours.text}\n` },
148 theirs: {
149 lines: [theirs.start + 1, theirs.end],
150 text: `${theirs.text}\n`,
151 agent: q.agent,
152 message: q.message,
153 version: last(space),
154 queued: q.id,
155 },
156 });
157 }
158 }
159 if (collisions.length > 0) return host.refuse(agent, space, "publish", time, collisions, entries, message);
160 }
161 const view = host.agentView(agent);
162 const auto = autoSettledOf(message);
163 const settled: Settled[] = agent.marked
164 .filter((r) => r.space === SHARED)
165 .map((r) => {
166 const lines = view.hasFile(r.file) ? view.lines(r.file).map((l) => l.text) : [];
167 const lost = lostLines(lines, r);
168 const held = heldMessage(agent, r.file);
169 const by = auto.get(r.file);
170 return {
171 file: r.file,
172 kept: keptOf(lines, r),
173 theirs: { agent: r.agent, version: r.version },
174 ...(lost.length > 0 ? { lost } : {}),
175 ...(held ? { held } : {}),
176 ...(by ? { auto: by } : {}),
177 };
178 });
179 const id = host.queuedId() + 1;
180 const entry: Entry = {
181 type: "queued",
182 agent: agent.name,
183 id,
184 message,
185 time,
186 changes,
187 resolves: [...resolves],
188 ...(settled.length > 0 ? { settled } : {}),
189 change: host.currentChange(agent, time) ?? host.nextAt(),
190 };
191 entries.push(entry);
192 host.apply(entry);
193 const queued = host.queued();
194 return {
195 ok: true,
196 queued: id,
197 position: queued.length,
198 ahead: queued.length - 1,
199 changes: changes.length,
200 ...(settled.length > 0 ? { settled } : {}),
201 };
204/** The merge queue now (#39): waiting publishes in order, and which are in the batch being checked. */
205export function queue(host: QueueHost): {
206 items: { id: number; agent: string; message: string; time: number; changes: number; checking: boolean }[];
207} {
208 return {
209 items: host.queued().map((q) => ({
210 id: q.id,
211 agent: q.agent,
212 message: q.message,
213 time: q.time,
214 changes: q.changes.length,
215 checking: host.checkingHas(q.id),
216 })),
217 };
220/** Mark the first `n` queued publishes as the batch being checked (0 ends it). Not logged. */
221export function queueChecking(host: QueueHost, n: number): number[] {
222 const ids = host
223 .queued()
224 .slice(0, Math.max(0, n))
225 .map((q) => q.id);
226 host.replaceChecking(ids);
227 return [...ids];
230/** Shared with the first `n` queued publishes on top (#39): the files a batch's check runs on, and their tree hash. */
231export function queueCandidate(
232 host: QueueHost,
233 n: number,
234): {
235 ids: number[];
236 files: Record<string, string>;
237 modes: Modes;
238 blobs: Blobs;
239 tree: string;
240} {
241 host.needInit();
242 const items = host.queued().slice(0, Math.max(0, n));
243 const changes = items.flatMap((q) => q.changes);
244 const view =
245 changes.length === 0
246 ? host.sharedView()
247 : host.sharedOverlay
248 ? host.sharedOverlay(changes)
249 : host.view(unionOverlay(host.setOf(host.shared()), changes));
250 const files = view.files();
251 const modes = modesOf(view);
252 const blobs = view.blobs();
253 return { ids: items.map((q) => q.id), files, modes, blobs, tree: treeHash({ files, modes, blobs }) };
256/**
257 * Land the first `n` queued publishes (#39), in order, each as its own
258 * version, after their batch passed. Each tells others what arrived, its
259 * author that it landed, and the authors of what it settled what it kept.
260 */
261export function queueLand(host: QueueHost, n: number, time: number): { versions: { id: number; version: number }[] } {
262 const entries: Entry[] = [];
263 const out: { id: number; version: number }[] = [];
264 try {
265 for (const q of host.queued().slice(0, Math.max(0, n))) {
266 const agent = host.agentOf(q.agent);
267 const space = host.shared();
268 const union = unionOverlay(host.setOf(space), q.changes);
269 const view = host.sharedOverlay ? host.sharedOverlay(q.changes) : host.view(union);
270 const tie = buildAtom(view, {
271 author: q.agent,
272 message: q.message,
273 time,
274 needs: [...q.changes],
275 resolves: q.resolves.filter((id) => union.has(id)),
276 });
277 host.requireClosed(tie, union);
278 const version = last(space) + 1;
279 const entry: Entry = {
280 type: "publish",
281 agent: q.agent,
282 version,
283 message: q.message,
284 time,
285 changes: q.changes,
286 tie,
287 // The agent may have edited since it queued, so its draft isn't reset as an immediate publish's is.
288 rebase: false,
289 ...(q.settled ? { settled: q.settled } : {}),
290 queued: q.id,
291 change: q.change ?? host.nextAt(),
292 };
293 entries.push(entry);
294 host.apply(entry);
295 host.uncheck(q.id);
296 host.newsForOthers(agent, space, version, entries);
297 host.settledNews(agent, version, q.settled ?? [], entries);
298 host.addressedNews(agent, version, entries);
299 host.reviewNews(agent, version, entries);
300 host.queueNews(
301 agent,
302 [{ key: `landed ${q.id}`, text: `Your queued push "${clip(q.message)}" landed as version ${version}.` }],
303 entries,
304 );
305 out.push({ id: q.id, version });
306 }
307 } finally {
308 host.flush(entries);
309 }
310 return { versions: out };
313/**
314 * Take a queued publish out (#39): its check failed, or its author withdrew
315 * it. Its changes are simply still in its author's draft. Later queued
316 * publishes that build on its changes come out with it.
317 */
318export function queuePull(
319 host: QueueHost,
320 id: number,
321 reason: Exclude<PullReason, "depends">,
322 time: number,
323 output?: string,
324): { pulled: number[] } {
325 const entries: Entry[] = [];
326 const pulled: number[] = [];
327 try {
328 const first = host.queued().find((q) => q.id === id);
329 if (!first) throw new ProjectError("not-found", `nothing is queued with id ${id}`);
330 const gone = new Set<AtomId>();
331 for (const q of [...host.queued()]) {
332 const builds = q.id !== id && q.changes.some((c) => host.graph.atom(c).deps.some((d) => gone.has(d)));
333 if (q.id !== id && !builds) continue;
334 const why: PullReason = q.id === id ? reason : "depends";
335 const tail = output ? output.split("\n").slice(-20).join("\n").slice(-4000) : undefined;
336 const entry: Entry = { type: "pulled", id: q.id, time, reason: why, ...(tail ? { output: tail } : {}) };
337 entries.push(entry);
338 host.apply(entry);
339 for (const c of q.changes) gone.add(c);
340 pulled.push(q.id);
341 const said =
342 why === "failed"
343 ? `the project's check failed on it on top of version ${last(host.shared())}${tail ? `:\n${tail}` : ""}`
344 : why === "withdrawn"
345 ? "you withdrew it"
346 : `it builds on queued push ${id}, which was turned back`;
347 host.queueNews(
348 host.agentOf(q.agent),
349 [
350 {
351 key: `pulled ${q.id}`,
352 text: `Your queued push "${clip(q.message)}" was turned back: ${said}. Its changes are still in your draft.`,
353 },
354 ],
355 entries,
356 );
357 }
358 } finally {
359 host.flush(entries);
360 }
361 return { pulled };
364/** The agent withdraws its queued publishes (#39): refused while one is in the batch being checked. */
365export function unqueue(host: QueueHost, agentName: string, time: number): { pulled: number[] } {
366 const mine = host.queued().filter((q) => q.agent === agentName);
367 if (mine.length === 0) throw new ProjectError("not-found", `${agentName} has nothing queued`);
368 const busy = mine.find((q) => host.checkingHas(q.id));
369 if (busy)
370 throw new ProjectError(
371 "conflict",
372 `queued push ${busy.id} is being checked; it lands or is turned back in about a minute (abso drop takes it back after it lands)`,
373 );
374 const pulled: number[] = [];
375 for (const q of mine)
376 if (host.queued().some((x) => x.id === q.id)) pulled.push(...queuePull(host, q.id, "withdrawn", time).pulled);
377 return { pulled };