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