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