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=100&format=json
359 linesFirst import 97% · engine 1% · rename 1% · pinch 1%Last change rename in version 100, 4 versions changed it

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