- 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=163&format=json
371 linesFirst import 89% · codex-capacity-chair 6% · engine 1% · rename 1% · speed 1% · pinch 1%Last change codex-capacity-chair in version 163, 7 versions changed it
You're reading version 163. The newest is 318, and 2 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 { 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 = host.sharedOverlay
241 ? host.sharedOverlay(changes)
242 : host.view(unionOverlay(host.setOf(host.shared()), changes));
243 const files = view.files();
244 const modes = modesOf(view);
245 const blobs = view.blobs();
246 return { ids: items.map((q) => q.id), files, modes, blobs, tree: treeHash({ files, modes, blobs }) };
247}
249/**
250 * Land the first `n` queued publishes (#39), in order, each as its own
251 * version, after their batch passed. Each tells others what arrived, its
252 * author that it landed, and the authors of what it settled what it kept.
253 */
254export function queueLand(host: QueueHost, n: number, time: number): { versions: { id: number; version: number }[] } {
255 const entries: Entry[] = [];
256 const out: { id: number; version: number }[] = [];
257 try {
258 for (const q of host.queued().slice(0, Math.max(0, n))) {
259 const agent = host.agentOf(q.agent);
260 const space = host.shared();
261 const union = unionOverlay(host.setOf(space), q.changes);
262 const view = host.sharedOverlay ? host.sharedOverlay(q.changes) : host.view(union);
263 const tie = buildAtom(view, {
264 author: q.agent,
265 message: q.message,
266 time,
267 needs: [...q.changes],
268 resolves: q.resolves.filter((id) => union.has(id)),
269 });
270 host.requireClosed(tie, union);
271 const version = last(space) + 1;
272 const entry: Entry = {
273 type: "publish",
274 agent: q.agent,
275 version,
276 message: q.message,
277 time,
278 changes: q.changes,
279 tie,
280 // The agent may have edited since it queued, so its draft isn't reset as an immediate publish's is.
281 rebase: false,
282 ...(q.settled ? { settled: q.settled } : {}),
283 queued: q.id,
284 change: q.change ?? host.nextAt(),
285 };
286 entries.push(entry);
287 host.apply(entry);
288 host.uncheck(q.id);
289 host.newsForOthers(agent, space, version, entries);
290 host.settledNews(agent, version, q.settled ?? [], entries);
291 host.addressedNews(agent, version, entries);
292 host.reviewNews(agent, version, entries);
293 host.queueNews(
294 agent,
295 [{ key: `landed ${q.id}`, text: `Your queued push "${clip(q.message)}" landed as version ${version}.` }],
296 entries,
297 );
298 out.push({ id: q.id, version });
299 }
300 } finally {
301 host.flush(entries);
302 }
303 return { versions: out };
304}
306/**
307 * Take a queued publish out (#39): its check failed, or its author withdrew
308 * it. Its changes are simply still in its author's draft. Later queued
309 * publishes that build on its changes come out with it.
310 */
311export function queuePull(
312 host: QueueHost,
313 id: number,
314 reason: Exclude<PullReason, "depends">,
315 time: number,
316 output?: string,
317): { pulled: number[] } {
318 const entries: Entry[] = [];
319 const pulled: number[] = [];
320 try {
321 const first = host.queued().find((q) => q.id === id);
322 if (!first) throw new ProjectError("not-found", `nothing is queued with id ${id}`);
323 const gone = new Set<AtomId>();
324 for (const q of [...host.queued()]) {
325 const builds = q.id !== id && q.changes.some((c) => host.graph.atom(c).deps.some((d) => gone.has(d)));
326 if (q.id !== id && !builds) continue;
327 const why: PullReason = q.id === id ? reason : "depends";
328 const tail = output ? output.split("\n").slice(-20).join("\n").slice(-4000) : undefined;
329 const entry: Entry = { type: "pulled", id: q.id, time, reason: why, ...(tail ? { output: tail } : {}) };
330 entries.push(entry);
331 host.apply(entry);
332 for (const c of q.changes) gone.add(c);
333 pulled.push(q.id);
334 const said =
335 why === "failed"
336 ? `the project's check failed on it on top of version ${last(host.shared())}${tail ? `:\n${tail}` : ""}`
337 : why === "withdrawn"
338 ? "you withdrew it"
339 : `it builds on queued push ${id}, which was turned back`;
340 host.queueNews(
341 host.agentOf(q.agent),
342 [
343 {
344 key: `pulled ${q.id}`,
345 text: `Your queued push "${clip(q.message)}" was turned back: ${said}. Its changes are still in your draft.`,
346 },
347 ],
348 entries,
349 );
350 }
351 } finally {
352 host.flush(entries);
353 }
354 return { pulled };
355}
357/** The agent withdraws its queued publishes (#39): refused while one is in the batch being checked. */
358export function unqueue(host: QueueHost, agentName: string, time: number): { pulled: number[] } {
359 const mine = host.queued().filter((q) => q.agent === agentName);
360 if (mine.length === 0) throw new ProjectError("not-found", `${agentName} has nothing queued`);
361 const busy = mine.find((q) => host.checkingHas(q.id));
362 if (busy)
363 throw new ProjectError(
364 "conflict",
365 `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)`,
366 );
367 const pulled: number[] = [];
368 for (const q of mine)
369 if (host.queued().some((x) => x.id === q.id)) pulled.push(...queuePull(host, q.id, "withdrawn", time).pulled);
370 return { pulled };
371}