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