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