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