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/project.ts?version=166&format=json
2,899 linesFirst import 80% · codex-capacity-chair 18% · engine 1% · speed 1% · pinch 1% · infra-split 1% · rename 1%Last change codex-capacity-chair in version 163, 23 versions changed it

You're reading version 166. The newest is 318, and 35 versions since then changed this file. Go to the newestCompare with 318

1// The project a Durable Object holds: shared (the published set), named
2// drafts, each agent's draft, publish, sync and news. Pure TypeScript with no
3// Node or Workers imports; the object passes the time in and stores what
4// `append` hands it. The contract is docs/v2-slice1.md.
5//
6// Every change goes through an entry. A call works out its entries, applies
7// them, and hands them to the store in one `append`. Loading applies the same
8// entries again, so a reloaded project is the same project.
9//
10// A space is somewhere agents publish to. Shared is one. A named draft (#10)
11// is another: a small shared that builds on a version of shared, that its
12// agents publish into under the same rules, and that lands in shared as one
13// unit. Every agent works in one space at a time.
15import { type Atom, type AtomId, EngineError, Graph, type LineId, type ReadView } from "../../src/engine/index.ts";
16import {
17 CachedStateStorage,
18 differenceSet,
19 type GraphStateStorage,
20 StableOverlaySet,
21 StableSet,
22 StableUnionSet,
23 StoredMap,
24 storedArray,
25 unionOverlay,
26} from "../../src/engine/state-source.ts";
27import { type AddDraftHost, addDraft as hostedAddDraft } from "./add-draft.ts";
28import { type AmendHost, amend as hostedAmend } from "./amend.ts";
29import { type AnnounceHost, announce as hostedAnnounce, announcePerson as hostedAnnouncePerson } from "./announce.ts";
30import { type ApplyEntryHost, applyEntry as hostedApplyEntry } from "./apply-entry.ts";
31import {
32 type ChangeHost,
33 change as hostedChange,
34 changeRecord as hostedChangeRecord,
35 changes as hostedChanges,
36 joinChange as hostedJoinChange,
37 namedFiles as hostedNamedFiles,
38} from "./change-records.ts";
39import { type ChangesSinceHost, changesSince as hostedChangesSince } from "./changes-since.ts";
40import { type CheckClashHost, checkClash as hostedCheckClash } from "./check-clash.ts";
41import {
42 type CollisionHost,
43 describePair,
44 duplicateCollisions,
45 openPairs as hostedOpenPairs,
46 type Origin,
47 originOf,
48 type Pair,
49 pairsIn,
50 strandedFiles,
51 touchedFiles,
52} from "./collisions.ts";
53import { type DefinitionCollision, DefinitionRule } from "./definition-rule.ts";
54import { type DraftCollisionHost, draftCollisions } from "./draft-collisions.ts";
55import { type DraftDiffHost, diffOfAgent, diffOf as draftDiffOf } from "./draft-diff.ts";
56import { type DraftStateHost, draftState as hostedDraftState } from "./draft-state.ts";
57import { type DropHost, drop as hostedDrop } from "./drop.ts";
58import { type EditHost, edit as hostedEdit } from "./edit.ts";
59import { type ExpressMovesHost, expressMoves as hostedExpressMoves } from "./express-moves.ts";
60import {
61 type HistoryHost,
62 follow as historyFollow,
63 pathLife as historyPathLife,
64 tree as historyTree,
65} from "./history.ts";
66import { ingest as hostedIngest, type IngestHost } from "./ingest.ts";
67import { init as hostedInit, type InitHost } from "./init.ts";
68import { label as hostedLabel, type LabelHost } from "./label.ts";
69import {
70 land as hostedLand,
71 landCollisions as hostedLandCollisions,
72 landDraft as hostedLandDraft,
73 type LandHost,
74} from "./land.ts";
75import {
76 blocksIn,
77 markedCollisions as hostedMarkedCollisions,
78 markedFiles as hostedMarkedFiles,
79 markerCollisions as hostedMarkerCollisions,
80 markersSettled as hostedMarkersSettled,
81 openCollisions as hostedOpenCollisions,
82 type MarkerHost,
83} from "./markers.ts";
84import { MemoryStore } from "./memory-store.ts";
85import { mergeIdentical as hostedMergeIdentical, type MergeHost } from "./merge-identical.ts";
86import { move as hostedMove, type MoveHost } from "./move.ts";
87import {
88 addressedItem,
89 newsAboutOwnDraft as hostedNewsAboutOwnDraft,
90 newsForOthers as hostedNewsForOthers,
91 markedItem,
92 type NewsHost,
93 type NewsItem,
94 reviewItem,
95 settledItem,
96} from "./news.ts";
97import {
98 closeNote as hostedCloseNote,
99 noteAnswer as hostedNoteAnswer,
100 notes as hostedNotes,
101 startingNotes as hostedStartingNotes,
102 writeNote as hostedWriteNote,
103 type NoteHost,
104 type NoteWriteHost,
105 type ReviewRule,
106 reviewersOf,
107 reviewRulesIn,
108} from "./notes.ts";
109import {
110 draftFiles as hostedDraftFiles,
111 overlapNews as hostedOverlapNews,
112 overlaps as hostedOverlaps,
113 type OverlapHost,
114} from "./overlaps.ts";
115import { checkPath } from "./path-rules.ts";
116import { PathIndex } from "./pathindex.ts";
117import { pathKey } from "./pathkey.ts";
118import { pluck as hostedPluck, type PluckHost } from "./pluck.ts";
119import { ProjectError } from "./project-error.ts";
120import { checkDraftName, checkPerson, NAME, projectFileIn } from "./project-helpers.ts";
121import {
122 type SnapshotHost,
123 agentPaths as snapshotAgentPaths,
124 labels as snapshotLabels,
125 pathsAt as snapshotPathsAt,
126 pathsOf as snapshotPathsOf,
127 status as snapshotStatus,
128} from "./project-status.ts";
129import type {
130 AgentState,
131 AgentStatus,
132 ChangeAnswer,
133 ChangeRecord,
134 Collision,
135 DiffAnswer,
136 DraftSyncAnswer,
137 DropAnswer,
138 EditsVia,
139 Entry,
140 LandAnswer,
141 MergedLine,
142 Modes,
143 NoteAnswer,
144 NoteBody,
145 NoteRecord,
146 PersonSender,
147 PluckAnswer,
148 ProjectOptions,
149 ProjectStore,
150 PublishAnswer,
151 QueuedPublish,
152 Refusal,
153 Settled,
154 Starting,
155 Tail,
156 TellRecord,
157} from "./project-types.ts";
158import { publish as hostedPublish, publishDraft as hostedPublishDraft, type PublishHost } from "./publish.ts";
159import { publishOf as hostedPublishOf, type PublishOfHost } from "./publish-of.ts";
160import {
161 enqueue as hostedEnqueue,
162 notQueuedYet as hostedNotQueuedYet,
163 queue as hostedQueue,
164 queueCandidate as hostedQueueCandidate,
165 queueChecking as hostedQueueChecking,
166 queuedAtoms as hostedQueuedAtoms,
167 queueLand as hostedQueueLand,
168 queueOn as hostedQueueOn,
169 queuePull as hostedQueuePull,
170 unqueue as hostedUnqueue,
171 type QueueHost,
172} from "./queue.ts";
173import { record as hostedRecord, type RecordHost } from "./record.ts";
174import { recordFile as hostedRecordFile, type RecordFileHost } from "./record-file.ts";
175import { refusals as hostedRefusals, refuse as hostedRefuse, type RefuseHost } from "./refuse.ts";
176import { restore as hostedRestore, type RestoreHost } from "./restore.ts";
177import { last, Membership, SHARED, SharedAdditions, type Space, sharedBaseOf } from "./spaces.ts";
178import { starting as hostedStarting, type StartingHost } from "./start.ts";
179import { switchTo as hostedSwitchTo, type SwitchHost } from "./switch-to.ts";
180import { sync as hostedSync, type SyncHost } from "./sync.ts";
181import { treeHash } from "./tree.ts";
182import {
183 type LogHost,
184 compare as versionCompare,
185 fileAt as versionFileAt,
186 log as versionLog,
187 ribbon as versionRibbon,
188 show as versionShow,
189 viewAt as versionViewAt,
190} from "./version-log.ts";
191import {
192 checkVersion as hostedCheckVersion,
193 lastVersion as hostedLastVersion,
194 versionMeta as hostedVersionMeta,
195 type VersionMetaHost,
196} from "./version-meta.ts";
197import { modesOf } from "./view-changes.ts";
198import { ViewCache } from "./views.ts";
199import {
200 isWhole as hostedIsWhole,
201 wholeOut as hostedWholeOut,
202 wholeRules as hostedWholeRules,
203 type WholeHost,
204} from "./whole-files.ts";
205import { WriterAgents } from "./writer-agents.ts";
207export { MemoryStore } from "./memory-store.ts";
208export { checkReadPath, pathProblem } from "./path-rules.ts";
209export { ProjectError } from "./project-error.ts";
210export { shapeStamp, utf8Bytes } from "./project-helpers.ts";
211export type * from "./project-types.ts";
212export { differs } from "./view-changes.ts";
214/** Entry kinds that had no time before #41; new ones get one. */
215const UNTIMED = new Set<Entry["type"]>(["join", "sync", "news", "heard", "discard", "switch"]);
217/** A start note lasts this long after the agent's last activity (#44). */
218const NOTE_IDLE = 2 * 60 * 60 * 1000;
219const WRITER_REOPEN = Symbol("verified writer checkpoint");
220export interface WriterSource {
221 readonly generation: number;
222 readonly logLength: number;
223 readonly sharedVersion: number;
225interface WriterAdoption {
226 source: WriterSource;
227 next: number;
228 ready: boolean;
231/** A decoded entry is supplied by a host that binds its bytes to canonical authority. */
232export type WriterAdoptionFrame = { seq: number; json: string } | { seq: number; bytes: number; entry: Entry };
233function adoptionFrameBytes(frame: WriterAdoptionFrame): number {
234 return "json" in frame
235 ? typeof frame.json === "string"
236 ? new TextEncoder().encode(frame.json).byteLength
237 : NaN
238 : frame.bytes;
240function adoptionFrameEntry(frame: WriterAdoptionFrame): Entry {
241 return "json" in frame ? (JSON.parse(frame.json) as Entry) : frame.entry;
244export class Project {
245 readonly #store: ProjectStore;
246 readonly #writerStorage?: GraphStateStorage;
247 readonly #graph: Graph;
248 /** Views laid out from atom sets, cached under a byte budget (views.ts). */
249 readonly #views: ViewCache;
250 /** Each agent's draft files, under the key they were worked out for (#draftFiles). */
251 readonly #draftFilesKept = new Map<string, { key: string; files: Set<string> }>();
252 /** Each version's files and each path's history (pathindex.ts). */
253 readonly #paths: PathIndex;
254 /** For each atom (by seq) that wrote lines, the log position of the entry that recorded it (#46). */
255 readonly #atomAt: number[] = [];
256 /** Which atoms are in which space at which version (#46, disk-first 1): the rules live in spaces.ts. */
257 readonly #membership = new Membership();
258 get #spaces(): Map<string, Space> {
259 return this.#membership.spaces;
260 }
261 readonly #agents = new Map<string, AgentState>();
262 readonly #refusals: Refusal[] = [];
263 /** Labels on shared's versions: name -> versions, ascending. */
264 readonly #labels = new Map<string, number[]>();
265 /** The newest tells and who has heard each (apply-entry.ts). */
266 readonly #tells = new Map<number, TellRecord>();
267 /**
268 * Entries applied but not stored yet, in order. Every applied entry is
269 * stored at the next flush, even when the call that applied it threw
270 * afterwards; otherwise the log could miss a join that later entries rely on.
271 */
272 #pending: Entry[] = [];
273 /**
274 * Whether something runs the merge queue's check (#39). Until the Worker has
275 * a checker it stays false, and `"queue": true` in avcs.json does nothing:
276 * publishes would otherwise wait for a check that never comes. Replay
277 * doesn't depend on it.
278 */
279 checkerReady = false;
280 readonly #now: (() => number) | undefined;
281 readonly #whole: ProjectOptions["whole"];
282 readonly #shapes: ProjectOptions["shapes"];
283 /** For each log position, the newest time up to it (#41): time to position in one search. */
284 readonly #timeAt: number[] = [];
285 /** For each version of shared, the log position of the entry that made it (#41). */
286 readonly #versionAt: number[] = [];
287 /** The newest time any applied entry carries: the clock when none was given. */
288 #lastTimeMemory = 0;
289 get #lastTime(): number {
290 return this.#writerStorage
291 ? ((this.#writerStorage.read("project:meta", "lastTime") as number | undefined) ?? 0)
292 : this.#lastTimeMemory;
293 }
294 set #lastTime(value: number) {
295 if (this.#writerStorage) this.#writerStorage.write("project:meta", "lastTime", value);
296 else this.#lastTimeMemory = value;
297 }
298 /** Every change (#44), by id. */
299 readonly #changes = new Map<number, ChangeRecord>();
300 /** Each version's change, by "<draft or ''> <version>" (#44): what a note on its lines belongs to. */
301 readonly #versionChange = new Map<string, number>();
302 /** Every note (#44), by id. */
303 readonly #notes = new Map<number, NoteRecord>();
304 /** Mod versions (X-Abso-Client) in the order they first sent an edit (#41): the last is taken as the installed one. */
305 #mods: string[] = [];
306 /** The merge queue (#39), in order: publishes to shared waiting for their batch's check. */
307 #queue: QueuedPublish[] = [];
308 /** The newest note's id (#44). */
309 #lastNoteMemory = 0;
310 get #lastNote(): number {
311 return this.#writerStorage
312 ? ((this.#writerStorage.read("project:meta", "lastNote") as number | undefined) ?? 0)
313 : this.#lastNoteMemory;
314 }
315 set #lastNote(value: number) {
316 if (this.#writerStorage) this.#writerStorage.write("project:meta", "lastNote", value);
317 else this.#lastNoteMemory = value;
318 }
319 #queuedIdMemory = 0;
320 get #queuedId(): number {
321 return this.#writerStorage
322 ? ((this.#writerStorage.read("project:meta", "queuedId") as number | undefined) ?? 0)
323 : this.#queuedIdMemory;
324 }
325 set #queuedId(value: number) {
326 if (this.#writerStorage) this.#writerStorage.write("project:meta", "queuedId", value);
327 else this.#queuedIdMemory = value;
328 }
329 /** Queued ids in the batch being checked now: not in the log, only for refusing an unqueue mid-check. */
330 #checking = new Set<number>();
331 /** How many entries the store holds: the log position of the next one (#41, the website's feed and replay). */
332 #storedMemory = 0;
333 get #stored(): number {
334 return this.#writerStorage
335 ? ((this.#writerStorage.read("project:meta", "stored") as number | undefined) ?? 0)
336 : this.#storedMemory;
337 }
338 set #stored(value: number) {
339 if (this.#writerStorage) this.#writerStorage.write("project:meta", "stored", value);
340 else this.#storedMemory = value;
341 }
342 /** Names on the lines a change replaced, by "<atom> <last replaced line>" (atoms never change). */
343 #rule?: DefinitionRule;
344 get #definitionRule(): DefinitionRule {
345 this.#rule ??= new DefinitionRule(this.#graph, (atom, space) => this.#origin(atom, space));
346 return this.#rule;
347 }
348 /** The newest announcement's id (announcements are news entries keyed "announce <id>"). */
349 #announcedMemory = 0;
350 get #announced(): number {
351 return this.#writerStorage
352 ? ((this.#writerStorage.read("project:meta", "announced") as number | undefined) ?? 0)
353 : this.#announcedMemory;
354 }
355 set #announced(value: number) {
356 if (this.#writerStorage) this.#writerStorage.write("project:meta", "announced", value);
357 else this.#announcedMemory = value;
358 }
359 #loading = false;
361 readonly #hasBlob: (sha256: string) => boolean;
363 constructor(store: ProjectStore, options: ProjectOptions = {}, checkpoint?: typeof WRITER_REOPEN) {
364 if (options.indexAcceptedAtom && !options.writerStorage)
365 throw Error("accepted atom indexing requires writer storage");
366 this.#store = store;
367 this.#writerStorage = options.writerStorage ? new CachedStateStorage(options.writerStorage) : undefined;
368 if (this.#writerStorage) {
369 const storage = this.#writerStorage;
370 // A stored Graph cannot be replayed over itself. Check before any
371 // constructor writes so an accidental reopen preserves the namespace.
372 if (
373 checkpoint !== WRITER_REOPEN &&
374 ((storage.read("atoms:meta", "length") as number | undefined) ||
375 (storage.read('membership:"":versions:meta', "length") as number | undefined))
376 )
377 throw new Error("writer indexes already contain history; Project checkpoint reopen is required");
378 this.#membership = new Membership(storage);
379 this.#atomAt = storedArray(storage, "project:atom-at");
380 this.#timeAt = storedArray(storage, "project:time-at");
381 this.#versionAt = storedArray(storage, "project:version-at");
382 this.#notes = new StoredMap(storage, "project:notes");
383 this.#changes = new StoredMap(storage, "project:changes");
384 this.#labels = new StoredMap(storage, "project:labels");
385 this.#versionChange = new StoredMap(storage, "project:version-change");
386 this.#refusals = storedArray(storage, "project:refusals");
387 this.#agents = new WriterAgents(storage);
388 if (checkpoint === WRITER_REOPEN) {
389 this.#mods = storage.read("project:meta", "mods") as string[];
390 this.#queue = storage.read("project:meta", "queue") as QueuedPublish[];
391 const tells = storage.read("project:meta", "tells") as [
392 number,
393 Omit<TellRecord, "heard"> & { heard: [string, { at: number | undefined } | null][] },
394 ][];
395 this.#tells = new Map(tells.map(([id, tell]) => [id, { ...tell, heard: new Map(tell.heard) }]));
396 }
397 }
398 this.#hasBlob = options.hasBlob ?? (() => false);
399 this.#now = options.now;
400 this.#whole = options.whole;
401 this.#shapes = options.shapes;
402 // For tests (#46): AVCS_TEXT_FROM_LOG=1 runs a project on a MemoryStore with its text read back from the store.
403 const testing =
404 (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env?.AVCS_TEXT_FROM_LOG ===
405 "1";
406 const entryAt =
407 options.entryAt ??
408 (testing && store instanceof MemoryStore ? (at: number) => (store as MemoryStore).entries[at]! : undefined);
409 // An atom as its log entry stores it. Not stored yet: still in this call's pending entries; while loading, every entry is stored.
410 const stored = (seq: number): Atom => {
411 const at = this.#atomAt[seq]!;
412 const entry = !this.#loading && at >= this.#stored ? this.#pending[at - this.#stored]! : entryAt!(at);
413 if (entry?.type === "init" || entry?.type === "draft") return entry.atom;
414 // A publish's or land's tie atom (#46: its lists are read back too).
415 if (entry?.type === "publish" || entry?.type === "land") return entry.tie;
416 throw new Error(`log entry ${at} holds no atom ${seq}`);
417 };
418 // Line text and each atom's deletes and claim keys stay in the log (#46), read back when asked for.
419 this.#graph = this.#writerStorage
420 ? new Graph({ storage: this.#writerStorage, indexAcceptedAtom: options.indexAcceptedAtom })
421 : entryAt
422 ? new Graph({ texts: (seq) => stored(seq).inserts.map((r) => r.lines), lists: (seq) => stored(seq) })
423 : new Graph();
424 this.#views = new ViewCache(this.#graph, options.readViewProvider);
425 this.#paths = new PathIndex({
426 graph: this.#graph,
427 at: (space, version) => this.#at(space, version),
428 viewAt: (space, version) => this.#viewAt(space, version),
429 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
430 shapes: this.#shapes,
431 });
432 }
434 /** Rebuild a project from its stored entries. New entries go to `store`. */
435 static load(entries: Iterable<Entry>, store: ProjectStore, options: ProjectOptions = {}): Project {
436 const testing =
437 (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env?.AVCS_TEXT_FROM_LOG ===
438 "1";
439 if (testing && !options.entryAt && Array.isArray(entries)) {
440 // Loaded from someone else's entries: its text is read back from them (and from the new store after them).
441 const from = entries as Entry[];
442 const after = store instanceof MemoryStore ? store : undefined;
443 options = { ...options, entryAt: (at) => (at < from.length ? from[at]! : after!.entries[at - from.length]!) };
444 }
445 const project = new Project(store, options);
446 project.#loading = true;
447 for (const entry of entries) {
448 project.#apply(entry);
449 project.#stored++;
450 project.#persistMutable();
451 }
452 project.#loading = false;
453 project.#writeCheckpoint();
454 return project;
455 }
457 /** Reopen committed writer indexes. The host supplies the authoritative canonical log length. */
458 static openWriter(
459 store: ProjectStore,
460 storage: GraphStateStorage,
461 logLength: number,
462 options: Omit<ProjectOptions, "writerStorage"> = {},
463 ): Project {
464 const adoption = storage.read("project:meta", "adoption") as WriterAdoption | undefined;
465 if (adoption && !adoption.ready) throw new Error("writer adoption is incomplete");
466 return Project.#openWriter(store, storage, logLength, options);
467 }
469 static #openWriter(
470 store: ProjectStore,
471 storage: GraphStateStorage,
472 logLength: number,
473 options: Omit<ProjectOptions, "writerStorage">,
474 ): Project {
475 const checkpoint = storage.read("project:meta", "checkpoint") as
476 | { format: number; logLength: number; atoms: number; version: number }
477 | undefined;
478 const length = (name: string) => (storage.read(`${name}:meta`, "length") as number | undefined) ?? 0;
479 if (
480 !Number.isSafeInteger(logLength) ||
481 logLength < 1 ||
482 checkpoint?.format !== 1 ||
483 checkpoint.logLength !== logLength ||
484 storage.read("project:meta", "stored") !== logLength ||
485 length("project:time-at") !== logLength ||
486 length("atoms") !== checkpoint.atoms ||
487 length("project:atom-at") !== checkpoint.atoms ||
488 length('membership:"":versions') !== checkpoint.version + 1 ||
489 length("project:version-at") !== checkpoint.version + 1 ||
490 !["mods", "queue", "tells"].every((key) => Array.isArray(storage.read("project:meta", key)))
491 )
492 throw new Error("writer checkpoint does not match the canonical log and indexes");
493 return new Project(store, { ...options, writerStorage: storage }, WRITER_REOPEN);
494 }
496 /** Open a host-verified historical prefix. Its state must be immutable and
497 * scoped to canonical authority; adoption readiness describes the live writer,
498 * not whether this individual prefix has a complete checkpoint. */
499 static openHistorical(
500 storage: GraphStateStorage,
501 logLength: number,
502 scratch: GraphStateStorage,
503 assertScope: () => void = () => {
504 storage.read("project:meta", "checkpoint");
505 },
506 readViewProvider?: ProjectOptions["readViewProvider"],
507 ): Project {
508 const refuse = (): never => {
509 throw new Error("historical project is read-only");
510 };
511 const selected = (collection: string) => {
512 // Revalidate the historical scope even when accessing derived scratch.
513 assertScope();
514 return collection.startsWith("projection-scratch:") ? scratch : storage;
515 };
516 return Project.#openWriter(
517 { append: refuse },
518 {
519 read: (collection, key) => selected(collection).read(collection, key),
520 entries: (collection) => selected(collection).entries(collection),
521 write: (collection, key, value) => {
522 if (selected(collection) !== scratch) refuse();
523 scratch.write(collection, key, value);
524 },
525 remove: (collection, key) => {
526 if (selected(collection) !== scratch) refuse();
527 scratch.remove(collection, key);
528 },
529 transaction: (body) => storage.transaction(() => scratch.transaction(body)),
530 },
531 logLength,
532 { readViewProvider },
533 );
534 }
536 /**
537 * Derive one bounded page from the host's canonical frames. The host reads
538 * those frames from its own log and revalidates the source inside this same
539 * transaction. Partial adoption cannot be opened for normal operations.
540 */
541 static adoptWriterPage(
542 storage: GraphStateStorage,
543 input: {
544 source: WriterSource;
545 from: number;
546 frames: Iterable<WriterAdoptionFrame>;
547 maxEntries: number;
548 maxBytes: number;
549 /** The host supplies disk-backed decoded entries and verified byte counts. */
550 decodedFrames?: boolean;
551 currentSource(): WriterSource;
552 /** Select the host's derived historical revision before applying a frame.
553 * Each selected revision receives a complete Project checkpoint. */
554 beginRevision?(logLength: number): void;
555 },
556 options: Omit<ProjectOptions, "writerStorage"> = {},
557 ): { next: number; ready: boolean; entries: number; bytes: number } {
558 const same = (a: WriterSource, b: WriterSource) =>
559 a.generation === b.generation && a.logLength === b.logLength && a.sharedVersion === b.sharedVersion;
560 if (
561 ![input.source.generation, input.source.logLength, input.source.sharedVersion, input.from].every(
562 (n) => Number.isSafeInteger(n) && n >= 0,
563 ) ||
564 input.source.logLength < 1 ||
565 !Number.isSafeInteger(input.maxEntries) ||
566 input.maxEntries < 1 ||
567 input.maxEntries > 256 ||
568 !Number.isSafeInteger(input.maxBytes) ||
569 input.maxBytes < 1 ||
570 (input.maxBytes > 8_000_000 && input.decodedFrames !== true)
571 )
572 throw new Error("invalid writer adoption bounds or source");
573 return storage.transaction(() => {
574 if (!same(input.currentSource(), input.source))
575 throw new Error("canonical source changed before writer adoption");
576 const previous = storage.read("project:meta", "adoption") as WriterAdoption | undefined;
577 if (
578 (previous && (!same(previous.source, input.source) || previous.ready || previous.next !== input.from)) ||
579 (!previous && input.from !== 0)
580 )
581 throw new Error("writer adoption source or cursor does not match");
582 const noAppend: ProjectStore = {
583 append: () => {
584 throw new Error("adoption must never append canonical history");
585 },
586 };
587 const project = previous
588 ? Project.#openWriter(noAppend, storage, input.from, options)
589 : new Project(noAppend, { ...options, writerStorage: storage });
590 project.#loading = true;
591 let count = 0;
592 let bytes = 0;
593 for (const frame of input.frames) {
594 if (input.decodedFrames && "json" in frame) throw new Error("decoded adoption requires decoded frames");
595 const size = adoptionFrameBytes(frame);
596 if (
597 count >= input.maxEntries ||
598 frame.seq !== input.from + count ||
599 frame.seq >= input.source.logLength ||
600 !Number.isSafeInteger(size) ||
601 size < 1 ||
602 size > input.maxBytes - bytes
603 )
604 throw new Error("writer adoption page exceeds bounds or has a noncontiguous frame");
605 bytes += size;
606 if (bytes > input.maxBytes) throw new Error("writer adoption page exceeds byte bound");
607 input.beginRevision?.(frame.seq + 1);
608 project.#apply(adoptionFrameEntry(frame));
609 project.#stored++;
610 project.#persistMutable();
611 if (input.beginRevision) project.#writeCheckpoint();
612 count++;
613 }
614 if (count === 0) throw new Error("writer adoption page must advance");
615 project.#loading = false;
616 const next = input.from + count;
617 const ready = next === input.source.logLength;
618 if (!same(input.currentSource(), input.source))
619 throw new Error("canonical source changed during writer adoption");
620 if (ready && project.version !== input.source.sharedVersion)
621 throw new Error("adopted shared version differs from canonical source");
622 project.#writeCheckpoint();
623 storage.write("project:meta", "adoption", { source: input.source, next, ready } satisfies WriterAdoption);
624 return { next, ready, entries: count, bytes };
625 });
626 }
628 /**
629 * Extend derived historical indexes from an already checkpointed prefix.
630 * The host supplies only new canonical frames inside its commit transaction.
631 */
632 static extendHistoricalPage(
633 storage: GraphStateStorage,
634 input: {
635 from: number;
636 frames: Iterable<WriterAdoptionFrame>;
637 maxEntries: number;
638 maxBytes: number;
639 /** The host supplies disk-backed decoded entries and verified byte counts. */
640 decodedFrames?: boolean;
641 beginRevision(logLength: number): void;
642 /** Verify both the saved prefix and the new frames against canonical authority. */
643 validateAuthority(): void;
644 },
645 ): { next: number; entries: number; bytes: number } {
646 if (
647 !Number.isSafeInteger(input.from) ||
648 input.from < 1 ||
649 !Number.isSafeInteger(input.maxEntries) ||
650 input.maxEntries < 1 ||
651 input.maxEntries > 256 ||
652 !Number.isSafeInteger(input.maxBytes) ||
653 input.maxBytes < 1 ||
654 (input.maxBytes > 8_000_000 && input.decodedFrames !== true)
655 )
656 throw new Error("invalid historical extension bounds");
657 const validate = () => {
658 const result: unknown = input.validateAuthority();
659 if (result && (typeof result === "object" || typeof result === "function") && "then" in result)
660 throw new Error("historical authority must be synchronous");
661 };
662 return storage.transaction(() => {
663 validate();
664 const project = Project.#openWriter(
665 {
666 append: () => {
667 throw new Error("history derivation cannot append canonical entries");
668 },
669 },
670 storage,
671 input.from,
672 {},
673 );
674 project.#loading = true;
675 let entries = 0,
676 bytes = 0;
677 for (const frame of input.frames) {
678 if (input.decodedFrames && "json" in frame) throw new Error("decoded adoption requires decoded frames");
679 const size = adoptionFrameBytes(frame);
680 if (
681 entries >= input.maxEntries ||
682 frame.seq !== input.from + entries ||
683 !Number.isSafeInteger(size) ||
684 size < 1 ||
685 size > input.maxBytes - bytes
686 )
687 throw new Error("historical extension exceeds bounds or is not contiguous");
688 bytes += size;
689 if (bytes > input.maxBytes) throw new Error("historical extension exceeds byte bound");
690 input.beginRevision(frame.seq + 1);
691 project.#apply(adoptionFrameEntry(frame));
692 project.#stored++;
693 project.#persistMutable();
694 project.#writeCheckpoint();
695 entries++;
696 }
697 if (!entries) throw new Error("historical extension must advance");
698 validate();
699 return { next: input.from + entries, entries, bytes };
700 });
701 }
703 /** Apply more entries to a replay copy. Never for the live project. */
704 catchUp(entries: Iterable<Entry>): void {
705 this.#loading = true;
706 try {
707 for (const entry of entries) {
708 this.#apply(entry);
709 this.#stored++;
710 }
711 } finally {
712 this.#loading = false;
713 }
714 }
716 /** The log position of the next entry: how many entries the log holds (#41). */
717 get logLength(): number {
718 return this.#stored;
719 }
721 get initialized(): boolean {
722 return this.#shared.versions.length > 0;
723 }
725 /** The current shared version. */
726 get version(): number {
727 this.#needInit();
728 return this.#shared.versions.length - 1;
729 }
731 /** Shared's files, for the push out to Artifacts. */
732 files(): Record<string, string> {
733 return this.#sharedView().files();
734 }
736 /** Shared's binary files, for the push out to Artifacts: path -> the SHA-256 of its bytes. Not in `files()`. */
737 blobs(): Record<string, string> {
738 return this.#sharedView().blobs();
739 }
741 /** Shared's executable files and links, for the push out to Artifacts: path -> mode. Other files are plain. */
742 modes(): Modes {
743 return modesOf(this.#sharedView());
744 }
746 /** Shared as a ReadView, for reading lines (blame, why). Don't hold on to it across calls. */
747 sharedView(): ReadView {
748 return this.#sharedView();
749 }
751 /** The agents the project knows, by name. */
752 agents(): string[] {
753 return [...this.#agents.keys()].sort();
754 }
756 /**
757 * An agent's unpublished changes, oldest first, and its view (its space at its base plus its changes). Read only.
758 * The view is laid out on first use: where asks every agent, most have no changes, and a big project has more
759 * agents than the view cache holds, so building every view cost each call about 0.7 s.
760 */
761 draftOf(agentName: string): { atoms: AtomId[]; readonly view: ReadView } | undefined {
762 const agent = this.#agents.get(agentName);
763 if (!agent) return undefined;
764 const view = () => this.#agentView(agent);
765 return {
766 atoms: this.#draft(agent),
767 get view() {
768 return view();
769 },
770 };
771 }
773 /** The shared version an atom was published in, or undefined while it's only in a draft. */
774 versionOf(atom: AtomId): number | undefined {
775 return this.#shared.publishedIn.get(atom);
776 }
778 /**
779 * Where an atom was published: shared if it's there, else the named draft
780 * that has it (by name), else undefined (it's only in a draft so far).
781 */
782 publishOf(...args: Tail<Parameters<typeof hostedPublishOf>>): ReturnType<typeof hostedPublishOf> {
783 return hostedPublishOf(this.#publishOfHost, ...args);
784 }
786 /** The newest version of shared, or of a named draft. */
787 lastVersion(...args: Tail<Parameters<typeof hostedLastVersion>>): ReturnType<typeof hostedLastVersion> {
788 return hostedLastVersion(this.#versionMetaHost, ...args);
789 }
791 /** Shared (null), then each named draft by name: every space with versions (abso issue 80). */
792 spaceNames(): (string | null)[] {
793 return [null, ...[...this.#spaces.keys()].filter((n) => n !== SHARED).sort()];
794 }
796 /** Who made a version of shared or a named draft, why and when, and a draft's shared base (abso issue 80). */
797 versionMeta(...args: Tail<Parameters<typeof hostedVersionMeta>>): ReturnType<typeof hostedVersionMeta> {
798 return hostedVersionMeta(this.#versionMetaHost, ...args);
799 }
801 /** Who published a version of shared, and why. */
802 published(version: number): { agent: string; message: string; time: number } | undefined {
803 const p = this.#shared.versions[version];
804 return p && { agent: p.agent, message: p.message, time: p.time };
805 }
807 /** The graph, for reading (blame, history). Don't add to it. */
808 get graph(): Graph {
809 return this.#graph;
810 }
812 // Calls -------------------------------------------------------------------
814 /** Create the project from a folder's text files. Empty files are skipped (the engine can't hold them). */
815 init(...args: Tail<Parameters<typeof hostedInit>>): ReturnType<typeof hostedInit> {
816 return hostedInit(this.#initHost, ...args);
817 }
819 /** An Edit, Write or MultiEdit from the hook, against the agent's view. */
820 edit(...args: Tail<Parameters<typeof hostedEdit>>): ReturnType<typeof hostedEdit> {
821 return hostedEdit(this.#editHost, ...args);
822 }
824 /** Whole files as the agent's folder has them; each is diffed against its view. */
825 record(...args: Tail<Parameters<typeof hostedRecord>>): ReturnType<typeof hostedRecord> {
826 return hostedRecord(this.#recordHost, ...args);
827 }
829 /** Add the agent's draft to its space (publish.ts). */
830 publish(...args: Tail<Parameters<typeof hostedPublish>>): ReturnType<typeof hostedPublish> {
831 return hostedPublish(this.#publishHost, ...args);
832 }
834 #publish(
835 agent: AgentState,
836 message: string,
837 time: number,
838 entries: Entry[],
839 asIs = false,
840 direct = false,
841 ): PublishAnswer {
842 return hostedPublishDraft(this.#publishHost, agent, message, time, entries, asIs, direct);
843 }
845 /**
846 * How the agent's newest edit arrived (#41). The mod sends X-Abso-Client
847 * avcs-mod/<stamp>; the hook sends abso-cli/<version> (avcs-cli/ before #59) with the chat's
848 * session; abso record and git pushes send no session. Edits stored before
849 * the client was recorded have only the session: those count as the mod
850 * (the hook stands down where the mod is installed), with modCurrent null.
851 */
852 #editsOf(agent: AgentState): {
853 edits: EditsVia;
854 modCurrent: boolean | null;
855 lastEdit: number | null;
856 joined: number | null;
857 } {
858 const last = agent.lastEdit;
859 const joined = agent.joined ?? null;
860 if (!last) return { edits: "none", modCurrent: null, lastEdit: null, joined };
861 const { client, session } = last;
862 if (client?.startsWith("avcs-mod/"))
863 return { edits: "mod", modCurrent: client === this.#mods[this.#mods.length - 1], lastEdit: last.time, joined };
864 if (client === undefined && session) return { edits: "mod", modCurrent: null, lastEdit: last.time, joined };
865 return { edits: session ? "hook" : "commands", modCurrent: null, lastEdit: last.time, joined };
866 }
868 // Spellings and moves (#49) --------------------------------------------------------
870 /** Refuse work whose paths would clash in shared (#49), before anything of it is written. */
871 #checkClash(...args: Tail<Parameters<typeof hostedCheckClash>>): ReturnType<typeof hostedCheckClash> {
872 return hostedCheckClash(this.#checkClashHost, ...args);
873 }
875 /**
876 * Move a file in the agent's draft (#49): its lines keep their ids, as with
877 * git mv, so blame and why follow it. The only way to change a file's case.
878 * Refused when `to` is another existing file, ignoring case.
879 */
880 move(...args: Tail<Parameters<typeof hostedMove>>): ReturnType<typeof hostedMove> {
881 return hostedMove(this.#moveHost, ...args);
882 }
884 // Files kept whole (#46) ----------------------------------------------------------
886 /** avcs.json's `"whole": [globs]`: paths kept whole. From `config` when given (init), else shared's. */
887 #wholeRules(config?: string): string[] {
888 return hostedWholeRules(this.#wholeHost, config);
889 }
891 /**
892 * Whether a file is kept whole: its path matches avcs.json's "whole", its
893 * text passes WHOLE_LIMIT, or it is already a blob where it's going. The
894 * last makes it one-way: a file kept whole stays whole while it exists,
895 * even if it shrinks or the rule changes, so it never flips back and forth.
896 */
897 #isWhole(path: string, length: number, view: ReadView | undefined, rules: readonly string[]): boolean {
898 return hostedIsWhole(this.#wholeHost, path, length, view, rules);
899 }
901 /** Files and blobs with every whole file's text moved into the blob store. */
902 #wholeOut(
903 files: Readonly<Record<string, string | null>>,
904 blobs: Readonly<Record<string, string>>,
905 view: ReadView | undefined,
906 config?: string,
907 ): { files: Record<string, string | null>; blobs: Record<string, string> } {
908 return hostedWholeOut(this.#wholeHost, files, blobs, view, config);
909 }
911 // Changes (#44) -------------------------------------------------------------------
913 /** The agent did something at `time`: its start note ends first if it had been idle over 2 hours. */
914 #active(agent: AgentState, time: number): void {
915 if (agent.starting && agent.lastActive !== undefined && time - agent.lastActive > NOTE_IDLE) {
916 delete agent.starting;
917 delete agent.noteAt;
918 }
919 if (agent.lastActive === undefined || time > agent.lastActive) agent.lastActive = time;
920 }
922 /** The agent's start note, unless it has been idle over 2 hours. */
923 #liveNote(agent: AgentState): Starting | undefined {
924 if (!agent.starting) return undefined;
925 const now = this.#now?.() ?? this.#lastTime;
926 return agent.lastActive !== undefined && now - agent.lastActive > NOTE_IDLE ? undefined : agent.starting;
927 }
929 /** The change the agent is working on at `time`: its named draft's, or its start note's; none for a lone publish. */
930 #currentChange(agent: AgentState, time: number): number | undefined {
931 if (agent.space !== SHARED) return this.#spaces.get(agent.space)?.startedAt;
932 if (!agent.starting || agent.noteAt === undefined) return undefined;
933 return agent.lastActive !== undefined && time - agent.lastActive > NOTE_IDLE ? undefined : agent.noteAt;
934 }
936 /** The position the next entry written will have. */
937 get #nextAt(): number {
938 return this.#stored + this.#pending.length;
939 }
941 #changeRecord(id: number, agent: AgentState, time: number, queuedNote?: Starting): ChangeRecord {
942 return hostedChangeRecord(this.#changeHost, id, agent, time, queuedNote);
943 }
945 /** A publish or land joins its change. Entries from before changes: the start note named it, and the publish ended the note. */
946 #joinChange(
947 agent: AgentState,
948 entry: Extract<Entry, { type: "publish" | "land" }>,
949 at: number,
950 draft: string | null,
951 landed?: string,
952 ): void {
953 hostedJoinChange(this.#changeHost, agent, entry, at, draft, landed);
954 }
956 /**
957 * One change (#44): the start note, named draft or publish that began it,
958 * each of its versions and the files they changed, what it settled, and its
959 * refusals. `id` is the log position of the entry that began it.
960 */
961 change(id: number): ChangeAnswer {
962 return hostedChange(this.#changeHost, id);
963 }
965 /** The files a version's changes name: cheap, for lists (the change page works out the net changes). */
966 #namedFiles(space: Space, version: number): string[] {
967 return hostedNamedFiles(this.#graph, space, version);
968 }
970 /**
971 * "Since you last looked" (#44): the changes with anything new at or after
972 * log position `since`, newest first, at most `limit`. Their files are the
973 * ones their changes name; the change page has the net changes.
974 */
975 changes(
976 since = 0,
977 limit = 50,
978 before?: number,
979 issue?: number,
980 ): { since: number; next: number; changes: ChangeAnswer[]; older?: number } {
981 return hostedChanges(this.#changeHost, since, limit, before, issue);
982 }
984 // Notes on lines (#44) --------------------------------------------------------------
986 /**
987 * Leave a note on lines of a file (#44): lines `from` to `to` (1-based) as
988 * shared shows them now, as `of`'s draft shows them (to note work before
989 * it's published), or at `version`. Or answer a note with `reply`. The
990 * lines' authors, the change's agent and the thread hear it as news.
991 */
992 note(
993 agentName: string,
994 body: NoteBody,
995 time: number,
996 ): { id: number; change: number | null; lines: [number, number] } {
997 this.#needInit();
998 const entries: Entry[] = [];
999 return this.#note(entries, () => ({ name: this.#agent(agentName, entries).name }), body, time);
1002 /**
1003 * A signed-in person's note from the website (#41). The Worker has checked
1004 * who it is. The writer is recorded as "person:<id>" with `person`, never
1005 * as an agent, and the news quotes the text.
1006 */
1007 notePerson(
1008 person: { id: unknown; name: unknown },
1009 body: NoteBody,
1010 time: number,
1011 ): { id: number; change: number | null; lines: [number, number] } {
1012 this.#needInit();
1013 const from = checkPerson(person);
1014 return this.#note([], () => ({ name: `person:${from.person.id}`, person: from }), body, time);
1017 /** Close a person's own note (#41): only the person who wrote it can. */
1018 closeNotePerson(person: { id: unknown; name: unknown }, id: number, how: unknown, time: number): NoteAnswer {
1019 const from = checkPerson(person);
1020 return this.#closeNote(`person:${from.person.id}`, id, how, time, from);
1023 #note(
1024 entries: Entry[],
1025 writerOf: () => { name: string; person?: PersonSender },
1026 body: NoteBody,
1027 time: number,
1028 ): { id: number; change: number | null; lines: [number, number] } {
1029 return hostedWriteNote(this.#noteWriteHost, entries, writerOf, body, time);
1032 /** The project's reviewers per area (#44): avcs.json's `"review": [{"paths": [...], "reviewer": "..."}]` in shared. */
1033 #reviewRules(): ReviewRule[] {
1034 if (["abso.json", "avcs.json"].every((path) => this.#graph.startCodeOf(path) === undefined)) return [];
1035 return reviewRulesIn(projectFileIn(this.#sharedView())?.text);
1038 /** Each reviewer whose area these files fall in, the files that do, and whether it has noted change `id`. */
1039 #reviewersOf(files: readonly string[], id: number): { agent: string; files: string[]; read: boolean }[] {
1040 return reviewersOf(this.#reviewRules(), files, (agent) =>
1041 [...this.#notes.values()].some((n) => n.change === id && n.agent === agent),
1042 );
1045 /** After a version of shared: the reviewers whose areas it touches hear of its change, once per change (#44). */
1046 #reviewNews(agent: AgentState, version: number, entries: Entry[]): void {
1047 const id = this.#versionChange.get(` ${version}`);
1048 if (id === undefined) return;
1049 const rec = this.#changes.get(id);
1050 const files = this.#namedFiles(this.#shared, version);
1051 for (const r of this.#reviewersOf(files, id)) {
1052 if (r.agent === agent.name) continue;
1053 const reviewer = this.#agents.get(r.agent);
1054 if (!reviewer) continue;
1055 const title =
1056 rec?.note?.text ?? (rec?.kind === "draft" ? `draft ${rec.draft}` : (rec?.versions[0]?.message ?? ""));
1057 this.#queueNews(reviewer, [reviewItem(agent.name, id, title, r.files, version)], entries);
1061 /** After a version of shared: each open objection whose lines it took out tells its writer (#44). */
1062 #addressedNews(agent: AgentState, version: number, entries: Entry[]): void {
1063 for (const n of this.#notes.values()) {
1064 if (n.kind !== "objection" || n.closed || n.reply !== undefined || n.agent === agent.name) continue;
1065 if (this.#noteAnswer(n).state !== "addressed") continue;
1066 const writer = this.#agents.get(n.agent);
1067 if (writer) this.#queueNews(writer, [addressedItem(agent.name, version, n)], entries);
1071 /** Close a note: only its writer can (#44). */
1072 closeNote(agentName: string, id: number, how: unknown, time: number): NoteAnswer {
1073 return this.#closeNote(agentName, id, how, time);
1076 #closeNote(agentName: string, id: number, how: unknown, time: number, person?: PersonSender): NoteAnswer {
1077 return hostedCloseNote(this.#noteWriteHost, agentName, id, how, time, person);
1080 /** Notes, oldest first: on a file, on a change, or only the ones still open. */
1081 notes(...args: Tail<Parameters<typeof hostedNotes>>): ReturnType<typeof hostedNotes> {
1082 return hostedNotes(this.#notesHost, ...args);
1085 /** The change the newest of these lines was written in: its version's, or its author's current one if unpublished. */
1086 #changeOfLines(lines: readonly LineId[]): number | undefined {
1087 let newest: Atom | undefined;
1088 for (const l of lines) {
1089 const info = this.#graph.line(l);
1090 const atom = info && this.#graph.atom(info.atom);
1091 if (atom && (!newest || atom.seq > newest.seq)) newest = atom;
1093 if (!newest) return undefined;
1094 for (const space of [this.#shared, ...[...this.#spaces.values()].filter((s) => s.name !== SHARED)]) {
1095 const v = space.publishedIn.get(newest.id);
1096 if (v !== undefined) return this.#versionChange.get(`${space.name === SHARED ? "" : space.name} ${v}`);
1098 const author = this.#agents.get(newest.author);
1099 return author ? this.#currentChange(author, this.#now?.() ?? this.#lastTime) : undefined;
1102 #noteAnswer(n: NoteRecord): NoteAnswer {
1103 return hostedNoteAnswer(this.#notesHost, n);
1106 // The merge queue (#39) ------------------------------------------------------------
1108 /** Whether shared's avcs.json turns the merge queue on (`"queue": true`). */
1109 #queueOn(): boolean {
1110 return hostedQueueOn(this.#queueHost);
1113 /** With the queue on, nothing lands in shared unchecked; land and pluck don't go through the queue yet. */
1114 #notQueuedYet(what: string): void {
1115 hostedNotQueuedYet(this.#queueHost, what);
1118 /** Atoms of every queued publish, or only other agents' with `except`. */
1119 #queuedAtoms(except?: string): Set<AtomId> {
1120 return hostedQueuedAtoms(this.#queueHost, except);
1123 /** Queue the agent's publish (#39). */
1124 #enqueue(
1125 agent: AgentState,
1126 message: string,
1127 time: number,
1128 draft: readonly AtomId[],
1129 resolves: readonly AtomId[],
1130 entries: Entry[],
1131 ): PublishAnswer {
1132 return hostedEnqueue(this.#queueHost, agent, message, time, draft, resolves, entries);
1135 /** The merge queue now (#39): waiting publishes in order, and which are in the batch being checked. */
1136 queue(...args: Tail<Parameters<typeof hostedQueue>>): ReturnType<typeof hostedQueue> {
1137 return hostedQueue(this.#queueHost, ...args);
1140 /** Mark the first `n` queued publishes as the batch being checked (0 ends it). Not logged. */
1141 queueChecking(...args: Tail<Parameters<typeof hostedQueueChecking>>): ReturnType<typeof hostedQueueChecking> {
1142 return hostedQueueChecking(this.#queueHost, ...args);
1145 /** Shared with the first `n` queued publishes on top (#39): the files a batch's check runs on, and their tree hash. */
1146 queueCandidate(...args: Tail<Parameters<typeof hostedQueueCandidate>>): ReturnType<typeof hostedQueueCandidate> {
1147 return hostedQueueCandidate(this.#queueHost, ...args);
1150 /** The tree hash of a version of shared (#39): it equals a candidate's when that's what landed. */
1151 treeAt(version: number): string {
1152 const view = this.viewAt(version);
1153 return treeHash({ files: view.files(), modes: modesOf(view), blobs: view.blobs() });
1156 /**
1157 * Land the first `n` queued publishes (#39), in order, each as its own
1158 * version, after their batch passed. Each tells others what arrived, its
1159 * author that it landed, and the authors of what it settled what it kept.
1160 */
1161 queueLand(...args: Tail<Parameters<typeof hostedQueueLand>>): ReturnType<typeof hostedQueueLand> {
1162 return hostedQueueLand(this.#queueHost, ...args);
1165 /**
1166 * Take a queued publish out (#39): its check failed, or its author withdrew
1167 * it. Its changes are simply still in its author's draft. Later queued
1168 * publishes that build on its changes come out with it.
1169 */
1170 queuePull(...args: Tail<Parameters<typeof hostedQueuePull>>): ReturnType<typeof hostedQueuePull> {
1171 return hostedQueuePull(this.#queueHost, ...args);
1174 /** The agent withdraws its queued publishes (#39): refused while one is in the batch being checked. */
1175 unqueue(...args: Tail<Parameters<typeof hostedUnqueue>>): ReturnType<typeof hostedUnqueue> {
1176 return hostedUnqueue(this.#queueHost, ...args);
1179 /**
1180 * Correct the message of the agent's newest publish in its space (#27).
1181 * Only the message changes: shared only grows, so a version's changes are
1182 * fixed by publishing again (or dropping it). The log keeps the original.
1183 */
1184 amend(...args: Tail<Parameters<typeof hostedAmend>>): ReturnType<typeof hostedAmend> {
1185 return hostedAmend(this.#amendHost, ...args);
1188 /**
1189 * Put a label on a version of shared (the newest by default), or take it
1190 * off with `remove`. A label can mark many versions ("passed-ci"); a folder
1191 * follows the newest with `sync {label}`.
1192 */
1193 label(...args: Tail<Parameters<typeof hostedLabel>>): ReturnType<typeof hostedLabel> {
1194 return hostedLabel(this.#labelHost, ...args);
1197 /**
1198 * Drop published versions of shared (#10): a new shared version whose set
1199 * leaves out their changes. Later work that doesn't depend on them stays;
1200 * history keeps them. When later published work built on them, they are
1201 * refused with that work listed, unless `withDependents`, which drops it
1202 * too. Unpublished work that builds on them (an agent's draft, a named
1203 * draft not yet landed) always refuses it: drop never touches it.
1204 */
1205 drop(
1206 agentName: string,
1207 versions: readonly number[],
1208 message: string,
1209 time: number,
1210 options: { withDependents?: boolean } = {},
1211 ): DropAnswer {
1212 return hostedDrop(this.#dropHost, agentName, versions, message, time, options);
1215 /**
1216 * After a sync, merge files where the agent's draft and the newer work
1217 * collide, the way git merges a file (#25, Fuzzer): from the agent's old
1218 * base, its draft's text and the newer text. Changes both made identically
1219 * are kept once; changes on one side are kept. Only when every file
1220 * involved merges with no conflict are the draft's changes to them dropped
1221 * (a discard entry) and made again as the merged text. Otherwise nothing
1222 * changes, and the collision stands with both sides' lines in the file.
1223 */
1224 #mergeIdentical(
1225 agent: AgentState,
1226 before: ReadView,
1227 oldBase: ReadonlySet<AtomId>,
1228 oldVersion: number,
1229 time: number,
1230 entries: Entry[],
1231 ): MergedLine[] {
1232 return hostedMergeIdentical(this.#mergeHost, agent, before, oldBase, oldVersion, time, entries);
1235 /**
1236 * Names the agent's draft defines at the top level of a file where other
1237 * work defines them too, so they are defined twice there (#25, Fuzzer).
1238 */
1239 #duplicates(agent: AgentState): Collision[] {
1240 return duplicateCollisions(this.#collisionHost, agent);
1243 /**
1244 * Draft changes that build on atoms a set doesn't have (a drop took them
1245 * out): the files they touch. Those changes can't move onto that set.
1246 */
1247 #strandedFiles(draft: readonly AtomId[], set: ReadonlySet<AtomId>): string[] {
1248 return strandedFiles(this.#graph, draft, set);
1251 /** Answer a refusal, and log it (an entry that changes nothing but the counts). */
1252 #refuse(...args: Tail<Parameters<typeof hostedRefuse>>): ReturnType<typeof hostedRefuse> {
1253 return hostedRefuse(this.#refuseHost, ...args);
1256 /**
1257 * Tell other agents something, as news: "Announcement from <agent>:
1258 * <text>". It reaches each one with its next edit, record or news call.
1259 * `to` names agents; without it, every other agent the project has now.
1260 */
1261 announce(...args: Tail<Parameters<typeof hostedAnnounce>>): ReturnType<typeof hostedAnnounce> {
1262 return hostedAnnounce(this.#announceHost, ...args);
1265 /**
1266 * A signed-in person's announcement from the website (#41). The Worker has
1267 * checked who sent it; the engine records it on each recipient's news with
1268 * `from`, and never makes the person an agent. The text is JSON-quoted, so
1269 * a line break in it can't pass for another item.
1270 */
1271 announcePerson(...args: Tail<Parameters<typeof hostedAnnouncePerson>>): ReturnType<typeof hostedAnnouncePerson> {
1272 return hostedAnnouncePerson(this.#announceHost, ...args);
1275 /**
1276 * Say what the agent is starting on (#37, #13), before any edit lands:
1277 * `text`, and the files it expects to change if it knows them. Nothing is
1278 * locked or refused. where and status show it until the agent publishes,
1279 * lands, or sends null. The answer names who already has unpublished
1280 * changes in, or a starting note on, those files; they hear of it too.
1281 */
1282 starting(...args: Tail<Parameters<typeof hostedStarting>>): ReturnType<typeof hostedStarting> {
1283 return hostedStarting(this.#startingHost, ...args);
1286 /** Every agent's starting note, by agent name. */
1287 startingNotes(): ReturnType<typeof hostedStartingNotes> {
1288 return hostedStartingNotes(this.#notesHost);
1291 #openCollisions(agent: AgentState): { collisions?: AgentStatus["collisions"] } {
1292 return hostedOpenCollisions(this.#markerHost, agent);
1295 /**
1296 * News when an edit leaves a file holding blocks of collision markers
1297 * (#11): how many, and how to settle them. Again whenever the count changes.
1298 */
1299 #markedNews(agent: AgentState, files: readonly string[], entries: Entry[]): void {
1300 const marked = new Set(this.#markedFiles(agent));
1301 const view = this.#agentView(agent);
1302 const items: NewsItem[] = [];
1303 for (const file of [...new Set(files)].sort()) {
1304 if (!marked.has(file) || !view.hasFile(file)) continue;
1305 const n = blocksIn(view.lines(file).map((l) => l.text)).length;
1306 if (n === 0) continue;
1307 items.push(markedItem(this.#draft(agent)[0] ?? "", file, n));
1309 this.#queueNews(agent, items, entries);
1312 /** The collided changes behind each block whose marker lines `atom` deletes (#11). */
1313 #markersSettled(agent: AgentState, view: ReadView, atom: Atom): AtomId[] {
1314 return hostedMarkersSettled(this.#markerHost, agent, view, atom);
1317 /** Files where a sync wrote the agent collision markers in its current space (#11). */
1318 #markedFiles(agent: AgentState): string[] {
1319 return hostedMarkedFiles(agent);
1322 /** The blocks of markers still in the agent's files, as collisions (#11): listed by sync and status. */
1323 #markedCollisions(agent: AgentState): Collision[] {
1324 return hostedMarkedCollisions(this.#markerHost, agent);
1327 /**
1328 * Marker lines the agent's draft adds (#11), as collisions: each
1329 * well-formed block, and any marker line left outside one. Only the labeled
1330 * lines the engine writes count, so a document that shows markers can be
1331 * published.
1332 */
1333 #markerCollisions(agent: AgentState): Collision[] {
1334 return hostedMarkerCollisions(this.#markerHost, agent);
1337 /** One line of news for each other author whose marked collision a publish settled (#11): what was kept, and any lines lost. */
1338 #settledNews(agent: AgentState, version: number, settled: readonly Settled[], entries: Entry[]): void {
1339 for (const s of settled) {
1340 const other = this.#agents.get(s.theirs.agent);
1341 if (!other || other === agent) continue;
1342 this.#queueNews(other, [settledItem(agent.name, version, s)], entries);
1346 /**
1347 * The files the agent's unpublished changes touch, in its own view. Kept per agent under what they're
1348 * made of: its view's key and its draft. Most agents haven't moved since the last
1349 * status, and the view cache holds fewer views than a big project has agents, so working them out again
1350 * on every call cost about 0.5 s on abso. A copy goes out, so no caller can change what's kept.
1351 */
1352 #draftFiles(agent: AgentState): Set<string> {
1353 const key = `${this.#agentViewKey(agent)}|${this.#draft(agent).join(",")}`;
1354 let kept = this.#draftFilesKept.get(agent.name);
1355 if (kept?.key !== key) {
1356 kept = { key, files: hostedDraftFiles(this.#overlapHost, agent) };
1357 this.#draftFilesKept.set(agent.name, kept);
1359 return new Set(kept.files);
1362 /** Other agents in the agent's space whose unpublished changes or starting note meet `patterns`. */
1363 #overlaps(...args: Tail<Parameters<typeof hostedOverlaps>>): ReturnType<typeof hostedOverlaps> {
1364 return hostedOverlaps(this.#overlapHost, ...args);
1367 /**
1368 * News the first time a draft touches a file someone else in its space has
1369 * unpublished changes in, or a starting note on (#37): one line per file and agent, once per draft. It tells; it never stops
1370 * the edit.
1371 */
1372 #overlapNews(...args: Tail<Parameters<typeof hostedOverlapNews>>): ReturnType<typeof hostedOverlapNews> {
1373 return hostedOverlapNews(this.#overlapHost, ...args);
1376 /** Hand over the news waiting for an agent (collisions, definitions, moves, announcements), once. */
1377 news(agentName: string): { news: string[]; items: { text: string; at: number | null }[] } {
1378 const entries: Entry[] = [];
1379 const agent = this.#agent(agentName, entries);
1380 const items = agent.news.map((text, i) => ({ text, at: agent.newsAt[i] ?? null }));
1381 const news = this.#takeNews(agent, entries);
1382 this.#flush(entries);
1383 return { news, items };
1386 /** Refused publishes and lands, newest first (`limit` defaults to 50), with counts over all of them. */
1387 refusals(...args: Tail<Parameters<typeof hostedRefusals>>): ReturnType<typeof hostedRefusals> {
1388 return hostedRefusals(this.#refuseHost, ...args);
1391 /**
1392 * Move the agent's base to its space's newest version. Returns every file
1393 * whose text in its view changes (null when it's gone), and the collisions
1394 * it now has to settle. A first sync returns every file (that's how a
1395 * folder joins).
1396 */
1397 sync(...args: Tail<Parameters<typeof hostedSync>>): ReturnType<typeof hostedSync> {
1398 return hostedSync(this.#syncHost, ...args);
1401 /**
1402 * Move the agent to a named draft, or back to shared with null. Its
1403 * unpublished changes stay parked on the server in the space it leaves,
1404 * and what it parked in the space it moves to comes back. Nothing is lost
1405 * and nothing has to be published or stashed first. A new named draft
1406 * starts on shared's newest version; with `carry`, the agent's current
1407 * unpublished changes move into it instead of being parked. Answers like a
1408 * sync: the files that change in its folder.
1409 */
1410 switchTo(...args: Tail<Parameters<typeof hostedSwitchTo>>): ReturnType<typeof hostedSwitchTo> {
1411 return hostedSwitchTo(this.#switchHost, ...args);
1414 /**
1415 * Move the agent's named draft onto shared's newest version. The draft's
1416 * agents see it when they next sync; anything it collides with is theirs
1417 * to settle before the draft lands.
1418 */
1419 syncDraft(agentName: string, time: number): DraftSyncAnswer {
1420 const entries: Entry[] = [];
1421 const agent = this.#agent(agentName, entries);
1422 const space = this.#namedSpaceOf(agent);
1423 const ownOnly = [...space.own].filter((id) => !this.#shared.own.has(id) && !this.#shared.droppedIn.has(id));
1424 const stranded = this.#strandedFiles(ownOnly, this.#shared.own);
1425 if (stranded.length > 0) {
1426 throw new ProjectError(
1427 "conflict",
1428 `draft ${space.name} has changes to ${stranded.join(", ")} that build on lines a drop took out of shared`,
1429 );
1431 if (sharedBaseOf(space) !== this.version) {
1432 entries.push({
1433 type: "space-sync",
1434 space: space.name,
1435 agent: agent.name,
1436 time,
1437 version: last(space) + 1,
1438 sharedBase: this.version,
1439 });
1440 this.#apply(entries[entries.length - 1]!);
1442 this.#flush(entries);
1443 return { draft: space.name, version: last(space), sharedBase: sharedBaseOf(space) };
1446 /**
1447 * Land the agent's named draft in shared as one unit: every change
1448 * published into it that shared doesn't have yet. Refused, like a publish,
1449 * when those changes collide with work that landed in shared after the
1450 * draft's base; sync the draft, settle, and land again.
1451 */
1452 land(...args: Tail<Parameters<typeof hostedLand>>): ReturnType<typeof hostedLand> {
1453 return hostedLand(this.#landHost, ...args);
1456 /**
1457 * What landing `changes` of a named draft would collide with in shared now (#41, the Drafts page reads it
1458 * too): the same pairs and definitions land refuses on.
1459 */
1460 #landCollisions(
1461 space: Space,
1462 changes: AtomId[],
1463 pick: boolean,
1464 ): { collisions: Collision[]; newer: ReadonlySet<AtomId>; union: ReadonlySet<AtomId> } {
1465 return hostedLandCollisions(this.#landHost, space, changes, pick);
1468 /**
1469 * A named draft's state in one read (#41, the Drafts page, D3 and D16): the shared version it builds on and
1470 * how far behind shared that is, its versions, when its first edit was, who works in it, and what landing it
1471 * now would collide with (the same check land makes, so nothing is written).
1472 */
1473 draftState(...args: Tail<Parameters<typeof hostedDraftState>>): ReturnType<typeof hostedDraftState> {
1474 return hostedDraftState(this.#draftStateHost, ...args);
1477 #land(
1478 agent: AgentState,
1479 message: string,
1480 time: number,
1481 entries: Entry[],
1482 pick?: { space: Space; changes: AtomId[] },
1483 ): LandAnswer {
1484 return hostedLandDraft(this.#landHost, agent, message, time, entries, pick);
1487 /**
1488 * Take part of a named draft into shared (#27): the changes of some of its
1489 * versions, as one new version of shared, checked for collisions like a
1490 * land. When they build on other versions of the draft, those are listed
1491 * and it is refused, unless `withDependencies` takes them too. The draft
1492 * stays as it is; landing it later brings in only what's left.
1493 */
1494 pluck(
1495 agentName: string,
1496 draftName: string,
1497 versions: readonly number[],
1498 message: string,
1499 time: number,
1500 options: { withDependencies?: boolean } = {},
1501 ): PluckAnswer {
1502 return hostedPluck(this.#pluckHost, agentName, draftName, versions, message, time, options);
1505 /**
1506 * Take in commits a person pushed with plain git (demo moment 5, #5, #8).
1507 * `base` is the shared version their first commit builds on (the
1508 * `avcs-version` of the commit they cloned). Each commit gives its whole
1509 * tree as text; a file of the view missing from it is deleted. The commits
1510 * go into a named draft `git-<sha>` on that version, one publish each, and
1511 * the draft lands in shared at once if nothing collides. The push already
1512 * happened, so a collision isn't refused: the draft waits, with its
1513 * collisions listed, for someone to switch to it, settle and land it.
1514 */
1515 ingest(...args: Tail<Parameters<typeof hostedIngest>>): ReturnType<typeof hostedIngest> {
1516 return hostedIngest(this.#ingestHost, ...args);
1519 // Reading history, and discarding -------------------------------------------
1521 #checkVersion(space: Space, version: number): void {
1522 hostedCheckVersion(space, version);
1525 /**
1526 * Discard the agent's unpublished changes to some files (all of them with
1527 * `files` null), like git restore. Changes that touch only those files and
1528 * that no kept change builds on leave the draft; anything left over is
1529 * undone by a new change that puts the files back. Answers with each
1530 * file's text now, for the folder.
1531 */
1532 restore(...args: Tail<Parameters<typeof hostedRestore>>): ReturnType<typeof hostedRestore> {
1533 return hostedRestore(this.#restoreHost, ...args);
1536 /** The space options name: an agent's current space with `agent`, else the named draft, else shared. */
1537 #spaceFor(options: { draft?: string | null; agent?: string }): Space {
1538 if (options.agent !== undefined) {
1539 const agent = this.#agents.get(options.agent);
1540 if (!agent) throw new ProjectError("bad-request", `there is no agent ${JSON.stringify(options.agent)}`);
1541 return this.#spaceOf(agent);
1543 return this.#spaceNamed(options.draft ?? null);
1546 #spaceNamed(name: string | null): Space {
1547 const key = name === null ? SHARED : checkDraftName(name);
1548 const space = this.#spaces.get(key);
1549 if (!space) throw new ProjectError("bad-request", `there is no draft ${String(name)}`);
1550 return space;
1553 /**
1554 * The stored spelling a read means (#41, F7, the rule #49 set for writes):
1555 * the path itself, else the one file it matches by pathKey; failing that,
1556 * the one file ever in the view it matches, for a file since taken out.
1557 * A path that matches two files is answered exactly.
1558 */
1559 spellingIn(view: ReadView, path: string): string {
1560 if (view.hasFile(path)) return path;
1561 const key = pathKey(path);
1562 const live = view.knownPaths().filter((p) => pathKey(p) === key && view.hasFile(p));
1563 if (live.length > 0) return live.length === 1 ? live[0]! : path;
1564 const known = view.knownPaths();
1565 if (known.includes(path)) return path;
1566 const gone = known.filter((p) => pathKey(p) === key);
1567 return gone.length === 1 ? gone[0]! : path;
1570 // Applying entries ------------------------------------------------------------
1572 #apply(entry: Entry): void {
1573 // Entries written before #41 have no time on these kinds; new ones do, so replay can place them.
1574 const kept =
1575 this.#loading || !UNTIMED.has(entry.type) || "time" in entry ? entry : ({ ...entry, time: Date.now() } as Entry);
1576 if (!this.#loading) this.#pending.push(kept);
1577 const at = this.#loading ? this.#stored : this.#stored + this.#pending.length - 1;
1578 // Positions by time (#41, the website): the newest time up to each position, as the log holds it.
1579 const keptTime =
1580 kept.type === "draft" ? kept.atom.time : "time" in kept && typeof kept.time === "number" ? kept.time : undefined;
1581 const prior = at > 0 ? this.#timeAt[at - 1]! : 0;
1582 this.#timeAt[at] = keptTime !== undefined && keptTime > prior ? keptTime : prior;
1583 const versionsBefore = this.#spaces.get(SHARED)?.versions.length ?? 0;
1584 try {
1585 this.#applyEntry(entry, at, keptTime);
1586 } finally {
1587 // Positions by version: where each version of shared was made.
1588 const versionsAfter = this.#spaces.get(SHARED)?.versions.length ?? 0;
1589 for (let v = versionsBefore; v < versionsAfter; v++) this.#versionAt[v] = at;
1593 /**
1594 * The log position for a time or a version of shared (#41, the website):
1595 * for `time`, the position just after the last entry no later than it
1596 * (entries with no time take their predecessor's); for `version`, the
1597 * position just after the entry that made it. `end` is the log's length.
1598 */
1599 position(q: { time?: number; version?: number }): { position: number; end: number } {
1600 const end = this.#timeAt.length;
1601 if (q.version !== undefined) {
1602 if (!Number.isInteger(q.version) || q.version < 0 || q.version >= this.#versionAt.length)
1603 throw new ProjectError("not-found", `there is no version ${String(q.version)}`);
1604 return { position: this.#versionAt[q.version]! + 1, end };
1606 if (typeof q.time !== "number" || !Number.isFinite(q.time))
1607 throw new ProjectError("bad-request", "position needs ?time= or ?version=");
1608 // The newest time up to each position never goes down, so halve.
1609 let lo = 0;
1610 let hi = end;
1611 while (lo < hi) {
1612 const mid = (lo + hi) >> 1;
1613 if (this.#timeAt[mid]! <= q.time) lo = mid + 1;
1614 else hi = mid;
1616 return { position: lo, end };
1619 #applyEntry(entry: Entry, at: number, time: number | undefined): void {
1620 hostedApplyEntry(this.#applyEntryHost, entry, at, time);
1623 /** Apply entries and store them. */
1624 #commit(entries: Entry[]): void {
1625 for (const e of entries) this.#apply(e);
1626 this.#flush(entries);
1629 /** Store entries that are already applied. */
1630 #flush(_entries: readonly Entry[]): void {
1631 if (this.#pending.length === 0) return;
1632 const out = this.#pending;
1633 this.#store.append(out);
1634 this.#persistMutable();
1635 this.#pending = [];
1636 this.#stored += out.length;
1637 this.#writeCheckpoint();
1640 #writeCheckpoint(): void {
1641 this.#writerStorage?.write("project:meta", "checkpoint", {
1642 format: 1,
1643 logLength: this.#stored,
1644 atoms: this.#graph.size,
1645 version: this.version,
1646 });
1649 #persistMutable(): void {
1650 if (!this.#writerStorage) return;
1651 if (this.#agents instanceof WriterAgents) this.#agents.flush();
1652 this.#writerStorage.write("project:meta", "mods", this.#mods);
1653 this.#writerStorage.write("project:meta", "queue", this.#queue);
1654 this.#writerStorage.write(
1655 "project:meta",
1656 "tells",
1657 [...this.#tells].map(([id, tell]) => [id, { ...tell, heard: [...tell.heard] }]),
1658 );
1661 /**
1662 * The agent an entry names. Before every applied entry was stored, a call
1663 * that joined an agent and then threw could leave the join out of the log
1664 * while later entries named the agent. The lost join had the version the
1665 * project was at then, which is the version now, during replay.
1666 */
1667 #agentOf(name: string): AgentState {
1668 let agent = this.#agents.get(name);
1669 if (!agent) {
1670 this.#apply({ type: "join", agent: name, version: this.#shared.versions.length - 1 });
1671 agent = this.#agents.get(name)!;
1673 return agent;
1676 // Agents, spaces and views ----------------------------------------------------
1678 get #shared(): Space {
1679 return this.#spaces.get(SHARED)!;
1682 #needInit(): void {
1683 if (!this.initialized) throw new ProjectError("not-initialized", "the project has no files yet; init it first");
1686 #agent(name: string, entries: Entry[]): AgentState {
1687 this.#needInit();
1688 if (typeof name !== "string" || !NAME.test(name) || name === "init") {
1689 throw new ProjectError(
1690 "bad-agent",
1691 `bad agent name ${JSON.stringify(name)}: letters, digits, '.', '_' and '-', up to 64`,
1692 );
1694 let agent = this.#agents.get(name);
1695 if (!agent) {
1696 const join: Entry = { type: "join", agent: name, version: this.version };
1697 entries.push(join);
1698 this.#apply(join);
1699 agent = this.#agents.get(name)!;
1701 return agent;
1704 #spaceOf(agent: AgentState): Space {
1705 return this.#spaces.get(agent.space)!;
1708 #namedSpaceOf(agent: AgentState): Space {
1709 if (agent.space === SHARED) {
1710 throw new ProjectError("bad-request", `${agent.name} works in shared, not a named draft; switch to one first`);
1712 return this.#spaceOf(agent);
1715 // History reads (#41), in history.ts behind HistoryHost (#46, disk-first 1) ------------------------
1717 #host?: HistoryHost;
1718 /** The project as the history reads see it: the seam the derived tables plug into (abso issues 48, 79). */
1719 get #history(): HistoryHost {
1720 this.#host ??= {
1721 graph: this.#graph,
1722 agents: this.#agents,
1723 spaces: this.#spaces,
1724 needInit: () => this.#needInit(),
1725 spaceNamed: (name) => this.#spaceNamed(name),
1726 checkVersion: (space, version) => this.#checkVersion(space, version),
1727 viewAt: (space, version) => this.#viewAt(space, version),
1728 agentView: (agent) => this.#agentView(agent as AgentState),
1729 spellingIn: (view, asked) => this.spellingIn(view, asked),
1730 pathsOf: (space) => this.#paths.pathsOf(space),
1731 lastChange: (space, version) => this.#paths.lastChange(space, version),
1732 atOrBefore: (list, version) => PathIndex.atOrBefore(list, version),
1733 removedIn: (space, from, to, line) => this.#paths.removedIn(space, from, to, line),
1734 };
1735 return this.#host;
1738 /** One folder at a version (history.ts). */
1739 tree(...args: Tail<Parameters<typeof historyTree>>): ReturnType<typeof historyTree> {
1740 return historyTree(this.#history, ...args);
1743 /** A path's life at a version (history.ts). */
1744 pathLife(...args: Tail<Parameters<typeof historyPathLife>>): ReturnType<typeof historyPathLife> {
1745 return historyPathLife(this.#history, ...args);
1748 /** Where lines went after a version (history.ts). */
1749 follow(...args: Tail<Parameters<typeof historyFollow>>): ReturnType<typeof historyFollow> {
1750 return historyFollow(this.#history, ...args);
1753 // The version list (log, ribbon, show), in version-log.ts behind LogHost ----------------------------
1755 #logs?: LogHost;
1756 get #logHost(): LogHost {
1757 this.#logs ??= {
1758 graph: this.#graph,
1759 paths: this.#paths,
1760 labels: this.#labels,
1761 shared: () => this.#shared,
1762 needInit: () => this.#needInit(),
1763 spaceFor: (options) => this.#spaceFor(options),
1764 checkVersion: (space, version) => this.#checkVersion(space, version),
1765 viewAt: (space, version) => this.#viewAt(space, version),
1766 view: (set) => this.#view(set),
1767 at: (space, version) => this.#at(space, version),
1768 spellingIn: (view, path) => this.spellingIn(view, path),
1769 versionChange: (space, version) =>
1770 this.#versionChange.get(`${space.name === SHARED ? "" : space.name} ${version}`),
1771 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
1772 };
1773 return this.#logs;
1776 /** The versions of shared (or of a named draft), newest first (version-log.ts). */
1777 log(...args: Tail<Parameters<typeof versionLog>>): ReturnType<typeof versionLog> {
1778 return versionLog(this.#logHost, ...args);
1781 /** Shared's versions in one small answer, for the website's version ribbon (version-log.ts). */
1782 ribbon(): ReturnType<typeof versionRibbon> {
1783 return versionRibbon(this.#logHost);
1786 /** One version of shared (or of a named draft) and the files it changed (version-log.ts). */
1787 show(...args: Tail<Parameters<typeof versionShow>>): ReturnType<typeof versionShow> {
1788 return versionShow(this.#logHost, ...args);
1791 /** A file as it was at a version of shared (or a named draft) (version-log.ts). */
1792 fileAt(...args: Tail<Parameters<typeof versionFileAt>>): ReturnType<typeof versionFileAt> {
1793 return versionFileAt(this.#logHost, ...args);
1796 /** Every file that differs between two versions of shared (or a named draft) (version-log.ts). */
1797 compare(...args: Tail<Parameters<typeof versionCompare>>): ReturnType<typeof versionCompare> {
1798 return versionCompare(this.#logHost, ...args);
1801 /** A version of shared (or of a named draft) as a ReadView (version-log.ts). */
1802 viewAt(...args: Tail<Parameters<typeof versionViewAt>>): ReturnType<typeof versionViewAt> {
1803 return versionViewAt(this.#logHost, ...args);
1806 // Whether agents' drafts would collide, in draft-collisions.ts behind DraftCollisionHost -------------
1808 #draftCollisionHost?: DraftCollisionHost;
1809 get #draftCollisions(): DraftCollisionHost {
1810 this.#draftCollisionHost ??= {
1811 graph: this.#graph,
1812 agents: this.#agents,
1813 needInit: () => this.#needInit(),
1814 shared: () => this.#shared,
1815 sharedView: () => this.#sharedView(),
1816 definitionRule: () => this.#definitionRule,
1817 draft: (agent) => this.#draft(agent as AgentState),
1818 agentView: (agent) => this.#agentView(agent as AgentState),
1819 view: (set) => this.#view(set),
1820 pairs: (draft, against, settled) => this.#pairs(draft, against, settled),
1821 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
1822 };
1823 return this.#draftCollisionHost;
1826 /** Whether agents' unpublished changes would collide, by the publish rule (draft-collisions.ts). */
1827 collisions(...args: Tail<Parameters<typeof draftCollisions>>): ReturnType<typeof draftCollisions> {
1828 return draftCollisions(this.#draftCollisions, ...args);
1831 // An agent's unpublished changes, in draft-diff.ts behind DraftDiffHost -----------------------------
1833 #draftDiffHost?: DraftDiffHost;
1834 get #draftDiff(): DraftDiffHost {
1835 this.#draftDiffHost ??= {
1836 agents: this.#agents,
1837 needInit: () => this.#needInit(),
1838 draft: (agent) => this.#draft(agent as AgentState),
1839 agentView: (agent) => this.#agentView(agent as AgentState),
1840 agentViewWithout: (agent, excluded) => {
1841 const state = agent as AgentState;
1842 return this.#agentView({ ...state, mine: state.mine.filter((id) => !excluded.has(id)) });
1843 },
1844 view: (set) => this.#view(set),
1845 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
1846 };
1847 return this.#draftDiffHost;
1850 /** What the agent's unpublished changes do, file by file (draft-diff.ts). Creates the agent if needed. */
1851 diff(agentName: string): DiffAnswer {
1852 const entries: Entry[] = [];
1853 const answer = diffOfAgent(this.#draftDiff, this.#agent(agentName, entries));
1854 this.#flush(entries);
1855 return answer;
1858 /** An agent's draft diff for a reader: never creates the agent, never writes (draft-diff.ts). */
1859 diffOf(...args: Tail<Parameters<typeof draftDiffOf>>): ReturnType<typeof draftDiffOf> {
1860 return draftDiffOf(this.#draftDiff, ...args);
1863 // Unpublished deletes-and-writes of the same text become a move (express-moves.ts) -----------------
1865 #movesHost?: ExpressMovesHost;
1866 get #expressMovesHost(): ExpressMovesHost {
1867 this.#movesHost ??= {
1868 graph: this.#graph,
1869 draft: (agent) => this.#unqueuedDraft(agent),
1870 beforeDraft: (agent, draft) => {
1871 const base = this.#at(this.#spaceOf(agent), agent.base);
1872 if (draft.some((id) => base.has(id)))
1873 return this.#view(differenceSet(this.#agentView(agent).set, new StableOverlaySet(draft)));
1874 const removed = new Set(draft),
1875 kept = agent.mine.filter((id) => !removed.has(id));
1876 return kept.length === 0
1877 ? this.#viewAt(this.#spaceOf(agent), agent.base)
1878 : this.#viewKeyed(`a ${agent.space}@${agent.base}+${kept.join(",")}`, () => unionOverlay(base, kept));
1879 },
1880 agentView: (agent) => this.#agentView(agent),
1881 view: (set) => this.#view(set),
1882 apply: (entry) => this.#apply(entry),
1883 addDraft: (agent, view, input, time, meta, entries) => this.#addDraft(agent, view, input, time, meta, entries),
1884 recordFile: (agent, view, path, text, time, meta, entries, mode) =>
1885 this.#recordFile(agent, view, path, text, time, meta, entries, mode),
1886 };
1887 return this.#movesHost;
1890 // Files kept whole, in whole-files.ts behind WholeHost ----------------------------------------------
1892 #wholes?: WholeHost;
1893 get #wholeHost(): WholeHost {
1894 this.#wholes ??= {
1895 initialized: () => this.initialized,
1896 sharedView: () => this.#sharedView(),
1897 whole: this.#whole,
1898 };
1899 return this.#wholes;
1902 // Notes list and start notes, in notes.ts behind NoteHost -------------------------------------------
1904 #news?: NewsHost;
1905 get #newsHost(): NewsHost {
1906 this.#news ??= {
1907 graph: this.#graph,
1908 agents: this.#agents,
1909 draft: (agent) => this.#draft(agent),
1910 newerFor: (agent) => this.#newerFor(agent),
1911 spaceOf: (agent) => this.#spaceOf(agent),
1912 setOf: (space) => this.#setOf(space),
1913 viewAt: (space, version) => this.#viewAt(space, version),
1914 origin: (atom, spaceName) => this.#origin(atom, spaceName),
1915 collision: (agent, pair) => this.#collision(agent, pair),
1916 definitionCollisions: (agent, newer) => this.#definitionCollisions(agent, newer),
1917 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
1918 };
1919 return this.#news;
1922 #collisions?: CollisionHost;
1923 get #collisionHost(): CollisionHost {
1924 this.#collisions ??= {
1925 graph: this.#graph,
1926 spaces: this.#spaces,
1927 version: () => this.version,
1928 spaceOf: (agent) => this.#spaceOf(agent),
1929 agentSet: (agent) => unionOverlay(this.#at(this.#spaceOf(agent), agent.base), agent.mine),
1930 draft: (agent) => this.#draft(agent),
1931 agentView: (agent) => this.#agentView(agent),
1932 at: (space, version) => this.#at(space, version),
1933 shared: () => this.#shared,
1934 };
1935 return this.#collisions;
1938 #markers?: MarkerHost;
1939 get #markerHost(): MarkerHost {
1940 this.#markers ??= {
1941 graph: this.#graph,
1942 agentView: (agent) => this.#agentView(agent),
1943 draft: (agent) => this.#draft(agent),
1944 draftFiles: (agent) => this.#draftFiles(agent),
1945 };
1946 return this.#markers;
1949 #noteWrites?: NoteWriteHost;
1950 get #noteWriteHost(): NoteWriteHost {
1951 this.#noteWrites ??= {
1952 notes: this.#notes,
1953 agents: this.#agents,
1954 changes: this.#changes,
1955 graph: this.#graph,
1956 lastNote: () => this.#lastNote,
1957 agentView: (agent) => this.#agentView(agent),
1958 viewAtVersion: (version) => this.viewAt(version),
1959 sharedView: () => this.#sharedView(),
1960 changeOfLines: (lines) => this.#changeOfLines(lines),
1961 apply: (entry) => this.#apply(entry),
1962 flush: (entries) => this.#flush(entries),
1963 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
1964 noteAnswer: (n) => this.#noteAnswer(n),
1965 };
1966 return this.#noteWrites;
1969 #noteHost?: NoteHost;
1970 get #notesHost(): NoteHost {
1971 this.#noteHost ??= {
1972 graph: this.#graph,
1973 agents: this.#agents,
1974 spaces: this.#spaces,
1975 notes: this.#notes,
1976 initialized: () => this.initialized,
1977 shared: () => this.#shared,
1978 sharedView: () => this.#sharedView(),
1979 spellingIn: (view, path) => this.spellingIn(view, path),
1980 viewAt: (space, version) => this.#viewAt(space, version),
1981 agentView: (agent) => this.#agentView(agent),
1982 view: (set) => this.#view(set),
1983 at: (space, version) => this.#at(space, version),
1984 liveNote: (agent) => this.#liveNote(agent),
1985 };
1986 return this.#noteHost;
1989 #merges?: MergeHost;
1990 get #mergeHost(): MergeHost {
1991 this.#merges ??= {
1992 graph: this.#graph,
1993 openPairs: (agent) => this.#openPairs(agent),
1994 draft: (agent) => this.#unqueuedDraft(agent),
1995 origin: (atom, spaceName) => this.#origin(atom, spaceName),
1996 view: (set) => this.#view(set),
1997 viewAt: (space, version) => this.#viewAt(space, version),
1998 spaceOf: (agent) => this.#spaceOf(agent),
1999 apply: (entry) => this.#apply(entry),
2000 agentView: (agent) => this.#agentView(agent),
2001 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
2002 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
2003 };
2004 return this.#merges;
2007 #edits?: EditHost;
2008 get #editHost(): EditHost {
2009 this.#edits ??= {
2010 agents: this.#agents,
2011 whole: this.#whole,
2012 initialized: () => this.initialized,
2013 agentView: (agent) => this.#agentView(agent),
2014 sharedView: () => this.#sharedView(),
2015 isWhole: (path, length, view, rules) => this.#isWhole(path, length, view, rules),
2016 wholeRules: (config) => this.#wholeRules(config),
2017 record: (agentName, files, time, modes, blobs, meta) => this.record(agentName, files, time, modes, blobs, meta),
2018 agent: (name, entries) => this.#agent(name, entries),
2019 draftFiles: (agent) => this.#draftFiles(agent),
2020 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
2021 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
2022 addDraft: (agent, view, input, time, meta, entries) => this.#addDraft(agent, view, input, time, meta, entries),
2023 overlapNews: (agent, before, entries) => this.#overlapNews(agent, before, entries),
2024 markedNews: (agent, files, entries) => this.#markedNews(agent, files, entries),
2025 newsAboutOwnDraft: (agent, entries) => this.#newsAboutOwnDraft(agent, entries),
2026 takeNews: (agent, entries) => this.#takeNews(agent, entries),
2027 flush: (entries) => this.#flush(entries),
2028 };
2029 return this.#edits;
2032 #announces?: AnnounceHost;
2033 get #announceHost(): AnnounceHost {
2034 this.#announces ??= {
2035 agents: this.#agents,
2036 announced: () => this.#announced,
2037 setAnnounced: (n) => {
2038 this.#announced = n;
2039 },
2040 agent: (name, entries) => this.#agent(name, entries),
2041 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
2042 apply: (entry) => this.#apply(entry),
2043 flush: (entries) => this.#flush(entries),
2044 needInit: () => this.#needInit(),
2045 };
2046 return this.#announces;
2049 #publishers?: PublishHost;
2050 get #publishHost(): PublishHost {
2051 this.#publishers ??= {
2052 agents: this.#agents,
2053 nextAt: () => this.#nextAt,
2054 checkClash: (changes, ahead) => this.#checkClash(changes, ahead),
2055 queueOn: () => this.#queueOn(),
2056 queuedAtoms: (except) => this.#queuedAtoms(except),
2057 agent: (name, entries) => this.#agent(name, entries),
2058 draft: (agent) => this.#draft(agent),
2059 spaceOf: (agent) => this.#spaceOf(agent),
2060 strandedFiles: (draft, set) => this.#strandedFiles(draft, set),
2061 setOf: (space) => this.#setOf(space),
2062 markedFiles: (agent) => this.#markedFiles(agent),
2063 agentView: (agent) => this.#agentView(agent),
2064 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
2065 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
2066 expressMoves: (agent, time, entries) => this.#expressMoves(agent, time, entries),
2067 pairs: (draft, against, settled) => this.#pairs(draft, against, settled),
2068 collision: (agent, pair) => this.#collision(agent, pair),
2069 definitionCollisions: (agent, newer) => this.#definitionCollisions(agent, newer),
2070 duplicates: (agent) => this.#duplicates(agent),
2071 refuse: (agent, space, via, time, collisions, entries, message) =>
2072 this.#refuse(agent, space, via, time, collisions, entries, message),
2073 markerCollisions: (agent) => this.#markerCollisions(agent),
2074 enqueue: (agent, message, time, draft, resolves, entries) =>
2075 this.#enqueue(agent, message, time, draft, resolves, entries),
2076 view: (set) => this.#view(set),
2077 requireClosed: (tie, union) => this.#requireClosed(tie, union),
2078 spaceOverlay: (space, atoms) =>
2079 this.#viewKeyed(`a ${space.name}@${last(space)}+${atoms.join(",")}`, () =>
2080 unionOverlay(this.#setOf(space), atoms),
2081 ),
2082 newerFor: (agent) => this.#newerFor(agent),
2083 currentChange: (agent, time) => this.#currentChange(agent, time),
2084 apply: (entry) => this.#apply(entry),
2085 newsForOthers: (publisher, space, version, entries) => this.#newsForOthers(publisher, space, version, entries),
2086 settledNews: (agent, version, settled, entries) => this.#settledNews(agent, version, settled, entries),
2087 addressedNews: (agent, version, entries) => this.#addressedNews(agent, version, entries),
2088 reviewNews: (agent, version, entries) => this.#reviewNews(agent, version, entries),
2089 flush: (entries) => this.#flush(entries),
2090 };
2091 return this.#publishers;
2094 #queues?: QueueHost;
2095 get #queueHost(): QueueHost {
2096 this.#queues ??= {
2097 graph: this.#graph,
2098 checkerReady: () => this.checkerReady,
2099 sharedView: () => this.#sharedView(),
2100 sharedOverlay: (atoms) =>
2101 this.#viewKeyed(`a @${last(this.#shared)}+${atoms.join(",")}`, () =>
2102 unionOverlay(this.#setOf(this.#shared), atoms),
2103 ),
2104 sharedAgentOverlay: (agent, atoms) => {
2105 const current = this.#setOf(this.#shared);
2106 const added = new Set([...atoms, ...agent.mine]);
2107 // Retain old-base atoms absent from current shared, without copying shared history.
2108 if (agent.base !== last(this.#shared))
2109 for (const id of this.#at(this.#spaceOf(agent), agent.base)) if (!current.has(id)) added.add(id);
2110 return this.#viewKeyed(`a @${last(this.#shared)}+${[...added].join(",")}`, () => unionOverlay(current, added));
2111 },
2112 queued: () => this.#queue,
2113 queuedId: () => this.#queuedId,
2114 checkingHas: (id) => this.#checking.has(id),
2115 replaceChecking: (ids) => {
2116 this.#checking = new Set(ids);
2117 },
2118 uncheck: (id) => {
2119 this.#checking.delete(id);
2120 },
2121 needInit: () => this.#needInit(),
2122 shared: () => this.#shared,
2123 setOf: (space) => this.#setOf(space),
2124 view: (set) => this.#view(set),
2125 agentSet: (agent) => this.#agentSet(agent),
2126 agentView: (agent) => this.#agentView(agent),
2127 pairs: (draft, against, settled) => this.#pairs(draft, against, settled),
2128 describe: (pair, yoursView, theirsView, spaceName) => this.#describe(pair, yoursView, theirsView, spaceName),
2129 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
2130 refuse: (agent, space, via, time, collisions, entries, message) =>
2131 this.#refuse(agent, space, via, time, collisions, entries, message),
2132 currentChange: (agent, time) => this.#currentChange(agent, time),
2133 nextAt: () => this.#nextAt,
2134 apply: (entry) => this.#apply(entry),
2135 agentOf: (name) => this.#agentOf(name),
2136 requireClosed: (tie, union) => this.#requireClosed(tie, union),
2137 newsForOthers: (publisher, space, version, entries) => this.#newsForOthers(publisher, space, version, entries),
2138 settledNews: (agent, version, settled, entries) => this.#settledNews(agent, version, settled, entries),
2139 addressedNews: (agent, version, entries) => this.#addressedNews(agent, version, entries),
2140 reviewNews: (agent, version, entries) => this.#reviewNews(agent, version, entries),
2141 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
2142 flush: (entries) => this.#flush(entries),
2143 };
2144 return this.#queues;
2147 #applyEntries?: ApplyEntryHost;
2148 get #applyEntryHost(): ApplyEntryHost {
2149 this.#applyEntries ??= {
2150 graph: this.#graph,
2151 agents: this.#agents,
2152 atomAt: this.#atomAt,
2153 mods: this.#mods,
2154 notes: this.#notes,
2155 changes: this.#changes,
2156 labels: this.#labels,
2157 refusals: this.#refusals,
2158 tells: this.#tells,
2159 uncheck: (id) => {
2160 this.#checking.delete(id);
2161 },
2162 stamp: (t) => {
2163 if (typeof t === "number" && t > this.#lastTime) this.#lastTime = t;
2164 },
2165 applyMembership: (entry, at) => this.#membership.apply(entry, at),
2166 agentOf: (name) => this.#agentOf(name),
2167 active: (agent, time) => this.#active(agent, time),
2168 joinChange: (agent, entry, at, draft, landed) => this.#joinChange(agent, entry, at, draft, landed),
2169 space: (name) => this.#spaces.get(name)!,
2170 queued: () => this.#queue,
2171 setQueued: (items) => {
2172 this.#queue = items;
2173 },
2174 setQueuedId: (id) => {
2175 this.#queuedId = id;
2176 },
2177 queuedId: () => this.#queuedId,
2178 setLastNote: (id) => {
2179 this.#lastNote = id;
2180 },
2181 lastNote: () => this.#lastNote,
2182 setAnnounced: (n) => {
2183 this.#announced = n;
2184 },
2185 announced: () => this.#announced,
2186 at: (space, version) => this.#at(space, version),
2187 spaceOf: (agent) => this.#spaceOf(agent),
2188 draft: (agent) => this.#draft(agent),
2189 currentChange: (agent, time) => this.#currentChange(agent, time),
2190 changeRecord: (id, agent, time) => this.#changeRecord(id, agent, time),
2191 };
2192 return this.#applyEntries;
2195 #landers?: LandHost;
2196 get #landHost(): LandHost {
2197 this.#landers ??= {
2198 viewAt: (space, version, changes) =>
2199 changes?.length
2200 ? this.#viewKeyed(`a ${space.name}@${version}+${changes.join(",")}`, () =>
2201 unionOverlay(this.#at(space, version), changes),
2203 : this.#viewAt(space, version),
2204 agents: this.#agents,
2205 graph: this.#graph,
2206 spaces: this.#spaces,
2207 version: () => this.version,
2208 nextAt: () => this.#nextAt,
2209 notQueuedYet: (what) => this.#notQueuedYet(what),
2210 checkClash: (changes) => this.#checkClash(changes),
2211 agent: (name, entries) => this.#agent(name, entries),
2212 namedSpaceOf: (agent) => this.#namedSpaceOf(agent),
2213 shared: () => this.#shared,
2214 setOf: (space) => this.#setOf(space),
2215 at: (space, version) => this.#at(space, version),
2216 view: (set) => this.#view(set),
2217 sharedView: () => this.#sharedView(),
2218 pairs: (draft, against, settled) => this.#pairs(draft, against, settled),
2219 describe: (pair, yoursView, theirsView, spaceName) => this.#describe(pair, yoursView, theirsView, spaceName),
2220 definitionRule: () => this.#definitionRule,
2221 refuse: (agent, space, via, time, collisions, entries) =>
2222 this.#refuse(agent, space, via, time, collisions, entries),
2223 requireClosed: (tie, union) => this.#requireClosed(tie, union),
2224 apply: (entry) => this.#apply(entry),
2225 newsForOthers: (publisher, space, version, entries) => this.#newsForOthers(publisher, space, version, entries),
2226 addressedNews: (agent, version, entries) => this.#addressedNews(agent, version, entries),
2227 reviewNews: (agent, version, entries) => this.#reviewNews(agent, version, entries),
2228 flush: (entries) => this.#flush(entries),
2229 };
2230 return this.#landers;
2233 #records?: RecordHost;
2234 get #recordHost(): RecordHost {
2235 this.#records ??= {
2236 agents: this.#agents,
2237 whole: this.#whole,
2238 initialized: () => this.initialized,
2239 agentView: (agent) => this.#agentView(agent),
2240 sharedView: () => this.#sharedView(),
2241 wholeOut: (files, blobs, view, config) => this.#wholeOut(files, blobs, view, config),
2242 checkBlobs: (blobs, files) => this.#checkBlobs(blobs, files),
2243 agent: (name, entries) => this.#agent(name, entries),
2244 draftFiles: (agent) => this.#draftFiles(agent),
2245 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
2246 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
2247 overlapNews: (agent, before, entries) => this.#overlapNews(agent, before, entries),
2248 markedNews: (agent, files, entries) => this.#markedNews(agent, files, entries),
2249 newsAboutOwnDraft: (agent, entries) => this.#newsAboutOwnDraft(agent, entries),
2250 takeNews: (agent, entries) => this.#takeNews(agent, entries),
2251 flush: (entries) => this.#flush(entries),
2252 };
2253 return this.#records;
2256 #restores?: RestoreHost;
2257 get #restoreHost(): RestoreHost {
2258 this.#restores ??= {
2259 graph: this.#graph,
2260 agent: (name, entries) => this.#agent(name, entries),
2261 draft: (agent) => this.#unqueuedDraft(agent),
2262 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
2263 apply: (entry) => this.#apply(entry),
2264 view: (set) => this.#view(set),
2265 agentSet: (agent) => this.#agentSet(agent),
2266 agentView: (agent) => this.#agentView(agent),
2267 agentViewWithout: (agent, excluded) =>
2268 this.#agentView({ ...agent, mine: agent.mine.filter((id) => !excluded.has(id)) }),
2269 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
2270 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
2271 flush: (entries) => this.#flush(entries),
2272 };
2273 return this.#restores;
2276 #startings?: StartingHost;
2277 get #startingHost(): StartingHost {
2278 this.#startings ??= {
2279 agents: this.#agents,
2280 changes: this.#changes,
2281 agent: (name, entries) => this.#agent(name, entries),
2282 liveNote: (agent) => this.#liveNote(agent),
2283 apply: (entry) => this.#apply(entry),
2284 overlaps: (agent, patterns) => this.#overlaps(agent, patterns),
2285 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
2286 flush: (entries) => this.#flush(entries),
2287 };
2288 return this.#startings;
2291 #syncs?: SyncHost;
2292 get #syncHost(): SyncHost {
2293 this.#syncs ??= {
2294 graph: this.#graph,
2295 labels: this.#labels,
2296 agent: (name, entries) => this.#agent(name, entries),
2297 spaceOf: (agent) => this.#spaceOf(agent),
2298 agentView: (agent) => this.#agentView(agent),
2299 captureAgentView: (agent) => {
2300 const key = this.#agentViewKey(agent);
2301 const original = this.#agentView(agent);
2302 // Projected readers reopen the immutable key; only the in-memory fallback uses the original set.
2303 return () => this.#viewKeyed(key, () => original.set);
2304 },
2305 at: (space, version) => this.#at(space, version),
2306 draft: (agent) => this.#draft(agent),
2307 strandedFiles: (draft, set) => this.#strandedFiles(draft, set),
2308 apply: (entry) => this.#apply(entry),
2309 flush: (entries) => this.#flush(entries),
2310 mergeIdentical: (agent, before, oldBase, oldVersion, time, entries) =>
2311 this.#mergeIdentical(agent, before, oldBase, oldVersion, time, entries),
2312 changesSince: (agent, before) => this.#changesSince(agent, before),
2313 };
2314 return this.#syncs;
2317 #moves?: MoveHost;
2318 get #moveHost(): MoveHost {
2319 this.#moves ??= {
2320 needInit: () => this.#needInit(),
2321 agents: this.#agents,
2322 agentView: (agent) => this.#agentView(agent),
2323 sharedView: () => this.#sharedView(),
2324 agent: (name, entries) => this.#agent(name, entries),
2325 addDraft: (agent, view, input, time, meta, entries) => this.#addDraft(agent, view, input, time, meta, entries),
2326 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
2327 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
2328 newsAboutOwnDraft: (agent, entries) => this.#newsAboutOwnDraft(agent, entries),
2329 takeNews: (agent, entries) => this.#takeNews(agent, entries),
2330 flush: (entries) => this.#flush(entries),
2331 };
2332 return this.#moves;
2335 #switches?: SwitchHost;
2336 get #switchHost(): SwitchHost {
2337 this.#switches ??= {
2338 agent: (name, entries) => this.#agent(name, entries),
2339 flush: (entries) => this.#flush(entries),
2340 spaces: this.#spaces,
2341 agentView: (agent) => this.#agentView(agent),
2342 graph: this.#graph,
2343 version: () => this.version,
2344 apply: (entry) => this.#apply(entry),
2345 draft: (agent) => this.#draft(agent),
2346 setOf: (space) => this.#setOf(space),
2347 changesSince: (agent, before) => this.#changesSince(agent, before),
2348 };
2349 return this.#switches;
2352 #draftStates?: DraftStateHost;
2353 get #draftStateHost(): DraftStateHost {
2354 this.#draftStates ??= {
2355 needInit: () => this.#needInit(),
2356 spaceNamed: (name) => this.#spaceNamed(name),
2357 shared: () => this.#shared,
2358 graph: this.#graph,
2359 agents: this.#agents,
2360 draft: (agent) => this.#draft(agent),
2361 checkClash: (changes) => this.#checkClash(changes),
2362 landCollisions: (space, changes, pick) => this.#landCollisions(space, changes, pick),
2363 };
2364 return this.#draftStates;
2367 #checkClashes?: CheckClashHost;
2368 get #checkClashHost(): CheckClashHost {
2369 this.#checkClashes ??= {
2370 shared: () => this.#shared,
2371 setOf: (space) => this.#setOf(space),
2372 view: (set) => this.#view(set),
2373 sharedView: () => this.#sharedView(),
2374 sharedOverlay: (atoms) =>
2375 this.#viewKeyed(`a @${last(this.#shared)}+${atoms.join(",")}`, () =>
2376 unionOverlay(this.#setOf(this.#shared), atoms),
2377 ),
2378 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
2379 };
2380 return this.#checkClashes;
2383 #changesSinces?: ChangesSinceHost;
2384 get #changesSinceHost(): ChangesSinceHost {
2385 this.#changesSinces ??= {
2386 agentView: (agent) => this.#agentView(agent),
2387 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
2388 openPairs: (agent) => this.#openPairs(agent),
2389 collision: (agent, pair) => this.#collision(agent, pair),
2390 duplicates: (agent) => this.#duplicates(agent),
2391 markedCollisions: (agent) => this.#markedCollisions(agent),
2392 };
2393 return this.#changesSinces;
2396 #inits?: InitHost;
2397 get #initHost(): InitHost {
2398 this.#inits ??= {
2399 initialized: () => this.initialized,
2400 whole: this.#whole,
2401 wholeOut: (files, blobs, view, config) => this.#wholeOut(files, blobs, view, config),
2402 checkBlobs: (blobs, files) => this.#checkBlobs(blobs, files),
2403 commit: (entries) => this.#commit(entries),
2404 };
2405 return this.#inits;
2408 #amends?: AmendHost;
2409 get #amendHost(): AmendHost {
2410 this.#amends ??= {
2411 agent: (name, entries) => this.#agent(name, entries),
2412 spaceOf: (agent) => this.#spaceOf(agent),
2413 apply: (entry) => this.#apply(entry),
2414 flush: (entries) => this.#flush(entries),
2415 };
2416 return this.#amends;
2419 #labelHosts?: LabelHost;
2420 get #labelHost(): LabelHost {
2421 this.#labelHosts ??= {
2422 agent: (name, entries) => this.#agent(name, entries),
2423 version: () => this.version,
2424 labels: this.#labels,
2425 apply: (entry) => this.#apply(entry),
2426 flush: (entries) => this.#flush(entries),
2427 };
2428 return this.#labelHosts;
2431 #publishOfs?: PublishOfHost;
2432 get #publishOfHost(): PublishOfHost {
2433 this.#publishOfs ??= {
2434 shared: () => this.#shared,
2435 spaces: this.#spaces,
2436 };
2437 return this.#publishOfs;
2440 #versionMetas?: VersionMetaHost;
2441 get #versionMetaHost(): VersionMetaHost {
2442 this.#versionMetas ??= {
2443 needInit: () => this.#needInit(),
2444 spaceNamed: (name) => this.#spaceNamed(name),
2445 };
2446 return this.#versionMetas;
2449 #refuses?: RefuseHost;
2450 get #refuseHost(): RefuseHost {
2451 this.#refuses ??= {
2452 apply: (entry) => this.#apply(entry),
2453 refusals: this.#refusals,
2454 };
2455 return this.#refuses;
2458 #overlapsHost?: OverlapHost;
2459 get #overlapHost(): OverlapHost {
2460 this.#overlapsHost ??= {
2461 graph: this.#graph,
2462 agents: this.#agents,
2463 agentView: (agent) => this.#agentView(agent),
2464 draft: (agent) => this.#draft(agent),
2465 draftFiles: (agent) => this.#draftFiles(agent),
2466 liveNote: (agent) => this.#liveNote(agent),
2467 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
2468 };
2469 return this.#overlapsHost;
2472 #recordFiles?: RecordFileHost;
2473 get #recordFileHost(): RecordFileHost {
2474 this.#recordFiles ??= {
2475 addDraft: (agent, view, input, time, meta, entries) => this.#addDraft(agent, view, input, time, meta, entries),
2476 };
2477 return this.#recordFiles;
2480 #addDrafts?: AddDraftHost;
2481 get #addDraftHost(): AddDraftHost {
2482 this.#addDrafts ??= {
2483 graph: this.#graph,
2484 openPairs: (agent) => this.#openPairs(agent),
2485 markersSettled: (agent, view, atom) => this.#markersSettled(agent, view, atom),
2486 apply: (entry) => this.#apply(entry),
2487 };
2488 return this.#addDrafts;
2491 #ingests?: IngestHost;
2492 get #ingestHost(): IngestHost {
2493 this.#ingests ??= {
2494 agents: this.#agents,
2495 spaces: this.#spaces,
2496 needInit: () => this.#needInit(),
2497 version: () => this.version,
2498 checkBlobs: (blobs, files) => this.#checkBlobs(blobs, files),
2499 apply: (entry) => this.#apply(entry),
2500 flush: (entries) => this.#flush(entries),
2501 wholeOut: (files, blobs, view, config) => this.#wholeOut(files, blobs, view, config),
2502 agentView: (agent) => this.#agentView(agent),
2503 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
2504 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
2505 publish: (agent, message, time, entries, asIs, direct) =>
2506 this.#publish(agent, message, time, entries, asIs, direct),
2507 land: (agent, message, time, entries, pick) => this.#land(agent, message, time, entries, pick),
2508 };
2509 return this.#ingests;
2512 #plucks?: PluckHost;
2513 get #pluckHost(): PluckHost {
2514 this.#plucks ??= {
2515 graph: this.#graph,
2516 spaces: this.#spaces,
2517 agent: (name, entries) => this.#agent(name, entries),
2518 shared: () => this.#shared,
2519 notQueuedYet: (what) => this.#notQueuedYet(what),
2520 strandedFiles: (draft, set) => this.#strandedFiles(draft, set),
2521 checkClash: (changes) => this.#checkClash(changes),
2522 land: (agent, message, time, entries, pick) => this.#land(agent, message, time, entries, pick),
2523 flush: (entries) => this.#flush(entries),
2524 };
2525 return this.#plucks;
2528 #drops?: DropHost;
2529 get #dropHost(): DropHost {
2530 this.#drops ??= {
2531 graph: this.#graph,
2532 agents: this.#agents,
2533 spaces: this.#spaces,
2534 agent: (name, entries) => this.#agent(name, entries),
2535 shared: () => this.#shared,
2536 flush: (entries) => this.#flush(entries),
2537 apply: (entry) => this.#apply(entry),
2538 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
2539 addressedNews: (agent, version, entries) => this.#addressedNews(agent, version, entries),
2540 };
2541 return this.#drops;
2544 // Changes (#44), in change-records.ts behind ChangeHost ---------------------------------------------
2546 #changeRecords?: ChangeHost;
2547 get #changeHost(): ChangeHost {
2548 this.#changeRecords ??= {
2549 changes: this.#changes,
2550 agents: this.#agents,
2551 spaces: this.#spaces,
2552 notes: this.#notes,
2553 versionChange: this.#versionChange,
2554 paths: this.#paths,
2555 graph: this.#graph,
2556 stored: () => this.#stored,
2557 shared: () => this.#shared,
2558 queue: () => this.#queue,
2559 active: (agent, time) => this.#active(agent, time),
2560 currentChange: (agent, time) => this.#currentChange(agent, time),
2561 liveNote: (agent) => this.#liveNote(agent),
2562 noteAnswer: (n) => this.#noteAnswer(n),
2563 reviewersOf: (files, id) => this.#reviewersOf(files, id),
2564 };
2565 return this.#changeRecords;
2568 // What the project looks like now, in project-status.ts behind SnapshotHost -------------------------
2570 #snapshotHost?: SnapshotHost;
2571 get #snapshot(): SnapshotHost {
2572 this.#snapshotHost ??= {
2573 agents: this.#agents,
2574 spaces: this.#spaces,
2575 queue: () => this.#queue,
2576 refusals: this.#refusals,
2577 labels: this.#labels,
2578 tells: this.#tells,
2579 needInit: () => this.#needInit(),
2580 shared: () => this.#shared,
2581 draft: (agent) => this.#draft(agent),
2582 draftFiles: (agent) => this.#draftFiles(agent),
2583 liveNote: (agent) => this.#liveNote(agent),
2584 openCollisions: (agent) => this.#openCollisions(agent),
2585 editsOf: (agent) => this.#editsOf(agent),
2586 setOf: (space) => this.#setOf(space),
2587 spaceNamed: (name) => this.#spaceNamed(name),
2588 checkVersion: (space, version) => this.#checkVersion(space, version),
2589 viewAt: (space, version) => this.#viewAt(space, version),
2590 agentView: (agent) => this.#agentView(agent),
2591 version: () => this.version,
2592 projectFile: () => (this.initialized ? projectFileIn(this.#sharedView()) : undefined),
2593 };
2594 return this.#snapshotHost;
2597 /** The paths in an agent's view now (project-status.ts). */
2598 agentPaths(...args: Tail<Parameters<typeof snapshotAgentPaths>>): ReturnType<typeof snapshotAgentPaths> {
2599 return snapshotAgentPaths(this.#snapshot, ...args);
2602 /** The paths in shared, or a named draft, at a version (project-status.ts). */
2603 pathsAt(...args: Tail<Parameters<typeof snapshotPathsAt>>): ReturnType<typeof snapshotPathsAt> {
2604 return snapshotPathsAt(this.#snapshot, ...args);
2607 /** The paths in an agent's view now, for a reader (project-status.ts). */
2608 pathsOf(...args: Tail<Parameters<typeof snapshotPathsOf>>): ReturnType<typeof snapshotPathsOf> {
2609 return snapshotPathsOf(this.#snapshot, ...args);
2612 /** Every label, with the versions it marks, newest first (project-status.ts). */
2613 labels(): ReturnType<typeof snapshotLabels> {
2614 return snapshotLabels(this.#snapshot);
2617 /** Agents, drafts, refusals and waiting announcements (project-status.ts). */
2618 status(): ReturnType<typeof snapshotStatus> {
2619 return snapshotStatus(this.#snapshot);
2622 /** The operation fence needs one actor's heads, not every agent's file projection. */
2623 actorHead(name: string): { base: number; draftChanges: number; draft: string | null } | undefined {
2624 const agent = this.#agents.get(name);
2625 if (!agent) return undefined;
2626 const published = this.#setOf(this.#spaceOf(agent));
2627 let draftChanges = 0;
2628 for (const id of agent.mine) if (!published.has(id)) draftChanges++;
2629 return { base: agent.base, draftChanges, draft: agent.space === SHARED ? null : agent.space };
2632 /** A space's contents at one of its versions. */
2633 #at(space: Space, version: number): ReadonlySet<AtomId> {
2634 return this.#membership.at(space, version);
2637 /** A space's contents now. */
2638 #setOf(space: Space): ReadonlySet<AtomId> {
2639 return this.#at(space, last(space));
2642 #draft(agent: AgentState): AtomId[] {
2643 const set = this.#setOf(this.#spaceOf(agent));
2644 return agent.mine.filter((id) => !set.has(id));
2647 /**
2648 * The draft without the agent's publishes waiting in the queue (#39): what
2649 * moves, restore and sync's merge may drop and make again. A queued item's
2650 * atoms are no longer the draft's to remake; dropping them let the queue
2651 * land a tie that depends on discarded atoms (abso issue 135, item 4).
2652 * Undoing a queued publish is abso unqueue.
2653 */
2654 #unqueuedDraft(agent: AgentState): AtomId[] {
2655 const draft = this.#draft(agent);
2656 const held = this.#queuedAtoms();
2657 return held.size === 0 ? draft : draft.filter((id) => !held.has(id));
2660 #agentSet(agent: AgentState): Set<AtomId> {
2661 return new Set([...this.#at(this.#spaceOf(agent), agent.base), ...agent.mine]);
2664 #agentView(agent: AgentState): ReadView {
2665 return this.#viewKeyed(this.#agentViewKey(agent), () => {
2666 const base = this.#at(this.#spaceOf(agent), agent.base);
2667 return base instanceof StableSet
2668 ? new StableUnionSet(base, new StableOverlaySet(agent.mine))
2669 : new Set([...base, ...agent.mine]);
2670 });
2673 /** An agent's view, keyed by what the set is made of, not by sorting every atom in it (#46): that cost more than the work. */
2674 #agentViewKey(agent: AgentState): string {
2675 // An empty draft is exactly its published base. Share its projection
2676 // with version readers instead of walking the same history twice.
2677 if (agent.mine.length === 0) return `v ${agent.space}@${agent.base}`;
2678 return `a ${agent.space}@${agent.base}+${agent.mine.join(",")}`;
2681 /** A space at a version: published versions never change, so the key is just their names (#46). */
2682 #viewAt(space: Space, version: number): ReadView {
2683 return this.#viewKeyed(`v ${space.name}@${version}`, () => this.#at(space, version));
2686 #sharedView(): ReadView {
2687 return this.#viewAt(this.#shared, last(this.#shared));
2690 /** A view of a set, cached by the set's exact contents (views.ts). */
2691 #view(set: ReadonlySet<AtomId>): ReadView {
2692 this.#views.assertUnkeyedAllowed();
2693 return this.#views.view(this.#closed(set));
2696 /** A view cached under `key` (views.ts). */
2697 #viewKeyed(key: string, set: () => ReadonlySet<AtomId>): ReadView {
2698 return this.#views.keyed(key, () => this.#closed(set()));
2701 /**
2702 * A discarded atom that a later publish still depends on stays in the view
2703 * (abso issue 80). A closed set is unchanged.
2704 */
2705 #closed(set: Iterable<AtomId>): ReadonlySet<AtomId> {
2706 if (set instanceof StableSet) {
2707 // Keep indexed membership external. Only dependencies absent from
2708 // that snapshot belong in the operation's closure overlay.
2709 const missing = new Set<AtomId>();
2710 const visit = (id: AtomId) => {
2711 const stack = [id];
2712 while (stack.length) {
2713 for (const dependency of this.#graph.atom(stack.pop()!).deps) {
2714 if (!set.has(dependency) && !missing.has(dependency)) {
2715 missing.add(dependency);
2716 stack.push(dependency);
2720 };
2721 for (const id of set) visit(id);
2722 return missing.size ? new StableUnionSet(set, new StableOverlaySet(missing)) : set;
2724 return this.#graph.closureOf(set);
2727 /** A new publish or land must not depend on an atom outside the set (abso issue 80). */
2728 #requireClosed(tie: { deps: readonly AtomId[] }, union: ReadonlySet<AtomId>): void {
2729 const missing = tie.deps.filter((id) => !union.has(id));
2730 if (missing.length > 0)
2731 throw new ProjectError(
2732 "conflict",
2733 `this change depends on ${missing.join(", ")}, which is not in the set being pushed`,
2734 );
2737 /** The space's atoms published after the agent's base, by others. */
2738 #newerFor(agent: AgentState): ReadonlySet<AtomId> {
2739 const space = this.#spaceOf(agent);
2740 const base = this.#at(space, agent.base);
2741 const current = this.#setOf(space);
2742 const newer =
2743 space.name === SHARED && space.membershipVersion
2744 ? new SharedAdditions(space, agent.base, base, current)
2745 : differenceSet(current, base);
2746 return differenceSet(newer, new StableOverlaySet(agent.mine));
2749 /** The files whose text in the agent's view differs from `before`, and its open collisions. */
2750 #changesSince(...args: Tail<Parameters<typeof hostedChangesSince>>): ReturnType<typeof hostedChangesSince> {
2751 return hostedChangesSince(this.#changesSinceHost, ...args);
2754 /** Who published an atom, looking in the given space first and then in shared. */
2755 #origin(atom: AtomId, spaceName: string): Origin {
2756 return originOf(this.#collisionHost, atom, spaceName);
2759 // Drafting ----------------------------------------------------------------------
2761 /** Check a {path: sha256} map: hex hashes, no path also given as text, and bytes already uploaded. */
2762 #checkBlobs(blobs: unknown, files: object): Record<string, string> {
2763 if (typeof blobs !== "object" || blobs === null || Array.isArray(blobs))
2764 throw new ProjectError("bad-request", "blobs must be {path: sha256}");
2765 for (const [path, sha] of Object.entries(blobs as Record<string, unknown>)) {
2766 checkPath(path);
2767 if (typeof sha !== "string" || !/^[0-9a-f]{64}$/.test(sha))
2768 throw new ProjectError("bad-request", `${path}: a blob is the SHA-256 of the bytes, in lowercase hex`);
2769 if (Object.hasOwn(files, path)) throw new ProjectError("bad-request", `${path} is given as both text and a blob`);
2770 if (!this.#hasBlob(sha))
2771 throw new ProjectError("bad-request", `${path}: upload blob ${sha} first (PUT /p/:project/blobs/${sha})`);
2773 return blobs as Record<string, string>;
2776 /**
2777 * Make one file in the agent's view what the folder has, as one draft
2778 * change: `text` (null: the file is gone; "": an empty file; undefined:
2779 * leave its lines alone) and `mode` (only the fields given). Returns
2780 * whether anything changed.
2781 */
2782 #recordFile(...args: Tail<Parameters<typeof hostedRecordFile>>): ReturnType<typeof hostedRecordFile> {
2783 return hostedRecordFile(this.#recordFileHost, ...args);
2786 /**
2787 * Moves (#28). Within one agent's unpublished draft, a line that leaves one
2788 * place and the same text that arrives somewhere else is the same line, in
2789 * either order (deleted then written, or written then deleted). Before a
2790 * publish, the draft's changes to the files involved are dropped (a discard
2791 * entry) and made again: one move per matched block, which keeps the
2792 * lines' ids, then a change per file to the draft's final text. The files
2793 * end up exactly as the draft had them. A matched block needs a line with
2794 * real content: blank lines and lone brackets only travel next to one.
2795 */
2796 #expressMoves(agent: AgentState, time: number, entries: Entry[]): void {
2797 hostedExpressMoves(this.#expressMovesHost, agent, time, entries);
2800 /**
2801 * Build a draft change against the agent's view. If it touches lines on
2802 * either side of a collision the agent has already seen, it settles that
2803 * collision (the engine's `resolves`).
2804 */
2805 #addDraft(...args: Tail<Parameters<typeof hostedAddDraft>>): ReturnType<typeof hostedAddDraft> {
2806 return hostedAddDraft(this.#addDraftHost, ...args);
2809 // Collisions and news -------------------------------------------------------------
2811 #pairs(draft: readonly AtomId[], against: ReadonlySet<AtomId>, settled: ReadonlySet<AtomId>): Pair[] {
2812 return pairsIn(this.#graph, draft, against, settled);
2815 /**
2816 * Collisions the agent has synced into and not settled: its draft against
2817 * its space at its base. In a named draft, also the draft's own changes
2818 * against shared work the draft was moved onto.
2819 */
2820 #openPairs(agent: AgentState): Pair[] {
2821 return hostedOpenPairs(this.#collisionHost, agent);
2824 /** After the agent's own change: news when its draft now collides with work published after its base. */
2825 #newsAboutOwnDraft(agent: AgentState, entries: Entry[]): void {
2826 hostedNewsAboutOwnDraft(this.#newsHost, agent, entries);
2829 /** After a publish or a landing: news for every other agent in that space whose draft collides with what just arrived. */
2830 #newsForOthers(publisher: AgentState, space: Space, version: number, entries: Entry[]): void {
2831 hostedNewsForOthers(this.#newsHost, publisher, space, version, entries);
2834 #queueNews(agent: AgentState, items: readonly { key: string; text: string }[], entries: Entry[]): void {
2835 const fresh = items.filter((p) => !agent.told.has(p.key));
2836 if (fresh.length === 0) return;
2837 const text = [...new Set(fresh.map((p) => p.text))];
2838 const entry: Entry = { type: "news", agent: agent.name, pairs: [...new Set(fresh.map((p) => p.key))], text };
2839 entries.push(entry);
2840 this.#apply(entry);
2843 #takeNews(agent: AgentState, entries: Entry[]): string[] {
2844 if (agent.news.length === 0) return [];
2845 const news = [...agent.news];
2846 const entry: Entry = { type: "heard", agent: agent.name };
2847 entries.push(entry);
2848 this.#apply(entry);
2849 return news;
2852 /** Describe a pair for the agent: its side in its own view, theirs in its space now. */
2853 #collision(agent: AgentState, pair: Pair): Collision {
2854 return this.#describe(
2855 pair,
2856 this.#agentView(agent),
2857 this.#viewAt(this.#spaceOf(agent), last(this.#spaceOf(agent))),
2858 agent.space,
2859 );
2862 #describe(pair: Pair, yoursView: ReadView, theirsView: ReadView, spaceName: string): Collision {
2863 return describePair(
2864 this.#graph,
2865 (atom, space) => this.#origin(atom, space),
2866 pair,
2867 yoursView,
2868 theirsView,
2869 spaceName,
2870 );
2873 #touchedFiles(ids: Iterable<AtomId>, views: readonly ReadView[]): Set<string> {
2874 return touchedFiles(this.#graph, ids, views);
2877 // The changed-definition rule (#11) -------------------------------------------
2879 /** The rule for an agent's draft in its space. */
2880 #definitionCollisions(agent: AgentState, newer: ReadonlySet<AtomId>): DefinitionCollision[] {
2881 const draft = new Set(this.#draft(agent));
2882 if (draft.size === 0 || newer.size === 0) return [];
2883 const space = this.#spaceOf(agent);
2884 const at = this.#at(space, agent.base);
2885 const base = agent.mine.some((id) => at.has(id))
2886 ? this.#view(differenceSet(at, new StableOverlaySet(agent.mine)))
2887 : this.#viewAt(space, agent.base);
2888 return this.#definitionRule.collisions(
2889 draft,
2890 this.#agentView(agent),
2891 base,
2892 this.#viewAt(space, last(space)),
2893 newer,
2894 space.name,
2895 );
2899export { EngineError };