Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed
MCP
code on this site's /mcp
CLI
none: the JSON below is the answer
JSON
/christopher/abso-core/files/worker/project/project.ts?version=147&format=json
2,731 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 143, 19 versions changed it

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

1// The project a Durable Object holds: shared (the published set), named
2// drafts, each agent's draft, publish, sync and news. Pure TypeScript with no
3// Node or Workers imports; the object passes the time in and stores what
4// `append` hands it. The contract is docs/v2-slice1.md.
5//
6// Every change goes through an entry. A call works out its entries, applies
7// them, and hands them to the store in one `append`. Loading applies the same
8// entries again, so a reloaded project is the same project.
9//
10// A space is somewhere agents publish to. Shared is one. A named draft (#10)
11// is another: a small shared that builds on a version of shared, that its
12// agents publish into under the same rules, and that lands in shared as one
13// unit. Every agent works in one space at a time.
15import { type Atom, type AtomId, EngineError, Graph, type LineId, type ReadView } from "../../src/engine/index.ts";
16import {
17 CachedStateStorage,
18 differenceSet,
19 type GraphStateStorage,
20 StableOverlaySet,
21 StableSet,
22 StableUnionSet,
23 StoredMap,
24 storedArray,
25 unionOverlay,
26} from "../../src/engine/state-source.ts";
27import { type AddDraftHost, addDraft as hostedAddDraft } from "./add-draft.ts";
28import { type AmendHost, amend as hostedAmend } from "./amend.ts";
29import { type AnnounceHost, announce as hostedAnnounce, announcePerson as hostedAnnouncePerson } from "./announce.ts";
30import { type ApplyEntryHost, applyEntry as hostedApplyEntry } from "./apply-entry.ts";
31import {
32 type ChangeHost,
33 change as hostedChange,
34 changeRecord as hostedChangeRecord,
35 changes as hostedChanges,
36 joinChange as hostedJoinChange,
37 namedFiles as hostedNamedFiles,
38} from "./change-records.ts";
39import { type ChangesSinceHost, changesSince as hostedChangesSince } from "./changes-since.ts";
40import { type CheckClashHost, checkClash as hostedCheckClash } from "./check-clash.ts";
41import {
42 type CollisionHost,
43 describePair,
44 duplicateCollisions,
45 openPairs as hostedOpenPairs,
46 type Origin,
47 originOf,
48 type Pair,
49 pairsIn,
50 strandedFiles,
51 touchedFiles,
52} from "./collisions.ts";
53import { type DefinitionCollision, DefinitionRule } from "./definition-rule.ts";
54import { type DraftCollisionHost, draftCollisions } from "./draft-collisions.ts";
55import { type DraftDiffHost, diffOfAgent, diffOf as draftDiffOf } from "./draft-diff.ts";
56import { type DraftStateHost, draftState as hostedDraftState } from "./draft-state.ts";
57import { type DropHost, drop as hostedDrop } from "./drop.ts";
58import { type EditHost, edit as hostedEdit } from "./edit.ts";
59import { type ExpressMovesHost, expressMoves as hostedExpressMoves } from "./express-moves.ts";
60import {
61 type HistoryHost,
62 follow as historyFollow,
63 pathLife as historyPathLife,
64 tree as historyTree,
65} from "./history.ts";
66import { ingest as hostedIngest, type IngestHost } from "./ingest.ts";
67import { init as hostedInit, type InitHost } from "./init.ts";
68import { label as hostedLabel, type LabelHost } from "./label.ts";
69import {
70 land as hostedLand,
71 landCollisions as hostedLandCollisions,
72 landDraft as hostedLandDraft,
73 type LandHost,
74} from "./land.ts";
75import {
76 blocksIn,
77 markedCollisions as hostedMarkedCollisions,
78 markedFiles as hostedMarkedFiles,
79 markerCollisions as hostedMarkerCollisions,
80 markersSettled as hostedMarkersSettled,
81 openCollisions as hostedOpenCollisions,
82 type MarkerHost,
83} from "./markers.ts";
84import { MemoryStore } from "./memory-store.ts";
85import { mergeIdentical as hostedMergeIdentical, type MergeHost } from "./merge-identical.ts";
86import { move as hostedMove, type MoveHost } from "./move.ts";
87import {
88 addressedItem,
89 newsAboutOwnDraft as hostedNewsAboutOwnDraft,
90 newsForOthers as hostedNewsForOthers,
91 markedItem,
92 type NewsHost,
93 type NewsItem,
94 reviewItem,
95 settledItem,
96} from "./news.ts";
97import {
98 closeNote as hostedCloseNote,
99 noteAnswer as hostedNoteAnswer,
100 notes as hostedNotes,
101 startingNotes as hostedStartingNotes,
102 writeNote as hostedWriteNote,
103 type NoteHost,
104 type NoteWriteHost,
105 type ReviewRule,
106 reviewersOf,
107 reviewRulesIn,
108} from "./notes.ts";
109import {
110 draftFiles as hostedDraftFiles,
111 overlapNews as hostedOverlapNews,
112 overlaps as hostedOverlaps,
113 type OverlapHost,
114} from "./overlaps.ts";
115import { checkPath } from "./path-rules.ts";
116import { PathIndex } from "./pathindex.ts";
117import { pathKey } from "./pathkey.ts";
118import { pluck as hostedPluck, type PluckHost } from "./pluck.ts";
119import { ProjectError } from "./project-error.ts";
120import { checkDraftName, checkPerson, NAME, projectFileIn } from "./project-helpers.ts";
121import {
122 type SnapshotHost,
123 agentPaths as snapshotAgentPaths,
124 labels as snapshotLabels,
125 pathsAt as snapshotPathsAt,
126 pathsOf as snapshotPathsOf,
127 status as snapshotStatus,
128} from "./project-status.ts";
129import type {
130 AgentState,
131 AgentStatus,
132 ChangeAnswer,
133 ChangeRecord,
134 Collision,
135 DiffAnswer,
136 DraftSyncAnswer,
137 DropAnswer,
138 EditsVia,
139 Entry,
140 LandAnswer,
141 MergedLine,
142 Modes,
143 NoteAnswer,
144 NoteBody,
145 NoteRecord,
146 PersonSender,
147 PluckAnswer,
148 ProjectOptions,
149 ProjectStore,
150 PublishAnswer,
151 QueuedPublish,
152 Refusal,
153 Settled,
154 Starting,
155 Tail,
156 TellRecord,
157} from "./project-types.ts";
158import { publish as hostedPublish, publishDraft as hostedPublishDraft, type PublishHost } from "./publish.ts";
159import { publishOf as hostedPublishOf, type PublishOfHost } from "./publish-of.ts";
160import {
161 enqueue as hostedEnqueue,
162 notQueuedYet as hostedNotQueuedYet,
163 queue as hostedQueue,
164 queueCandidate as hostedQueueCandidate,
165 queueChecking as hostedQueueChecking,
166 queuedAtoms as hostedQueuedAtoms,
167 queueLand as hostedQueueLand,
168 queueOn as hostedQueueOn,
169 queuePull as hostedQueuePull,
170 unqueue as hostedUnqueue,
171 type QueueHost,
172} from "./queue.ts";
173import { record as hostedRecord, type RecordHost } from "./record.ts";
174import { recordFile as hostedRecordFile, type RecordFileHost } from "./record-file.ts";
175import { refusals as hostedRefusals, refuse as hostedRefuse, type RefuseHost } from "./refuse.ts";
176import { restore as hostedRestore, type RestoreHost } from "./restore.ts";
177import { last, Membership, SHARED, SharedAdditions, type Space, sharedBaseOf } from "./spaces.ts";
178import { starting as hostedStarting, type StartingHost } from "./start.ts";
179import { switchTo as hostedSwitchTo, type SwitchHost } from "./switch-to.ts";
180import { sync as hostedSync, type SyncHost } from "./sync.ts";
181import { treeHash } from "./tree.ts";
182import {
183 type LogHost,
184 compare as versionCompare,
185 fileAt as versionFileAt,
186 log as versionLog,
187 ribbon as versionRibbon,
188 show as versionShow,
189 viewAt as versionViewAt,
190} from "./version-log.ts";
191import {
192 checkVersion as hostedCheckVersion,
193 lastVersion as hostedLastVersion,
194 versionMeta as hostedVersionMeta,
195 type VersionMetaHost,
196} from "./version-meta.ts";
197import { modesOf } from "./view-changes.ts";
198import { ViewCache } from "./views.ts";
199import {
200 isWhole as hostedIsWhole,
201 wholeOut as hostedWholeOut,
202 wholeRules as hostedWholeRules,
203 type WholeHost,
204} from "./whole-files.ts";
205import { WriterAgents } from "./writer-agents.ts";
207export { MemoryStore } from "./memory-store.ts";
208export { checkReadPath, pathProblem } from "./path-rules.ts";
209export { ProjectError } from "./project-error.ts";
210export { shapeStamp, utf8Bytes } from "./project-helpers.ts";
211export type * from "./project-types.ts";
212export { differs } from "./view-changes.ts";
214/** Entry kinds that had no time before #41; new ones get one. */
215const UNTIMED = new Set<Entry["type"]>(["join", "sync", "news", "heard", "discard", "switch"]);
217/** A start note lasts this long after the agent's last activity (#44). */
218const NOTE_IDLE = 2 * 60 * 60 * 1000;
219const WRITER_REOPEN = Symbol("verified writer checkpoint");
220export interface WriterSource {
221 readonly generation: number;
222 readonly logLength: number;
223 readonly sharedVersion: number;
225interface WriterAdoption {
226 source: WriterSource;
227 next: number;
228 ready: boolean;
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 this.#store = store;
352 this.#writerStorage = options.writerStorage ? new CachedStateStorage(options.writerStorage) : undefined;
353 if (this.#writerStorage) {
354 const storage = this.#writerStorage;
355 // A stored Graph cannot be replayed over itself. Check before any
356 // constructor writes so an accidental reopen preserves the namespace.
357 if (
358 checkpoint !== WRITER_REOPEN &&
359 ((storage.read("atoms:meta", "length") as number | undefined) ||
360 (storage.read('membership:"":versions:meta', "length") as number | undefined))
361 )
362 throw new Error("writer indexes already contain history; Project checkpoint reopen is required");
363 this.#membership = new Membership(storage);
364 this.#atomAt = storedArray(storage, "project:atom-at");
365 this.#timeAt = storedArray(storage, "project:time-at");
366 this.#versionAt = storedArray(storage, "project:version-at");
367 this.#notes = new StoredMap(storage, "project:notes");
368 this.#changes = new StoredMap(storage, "project:changes");
369 this.#labels = new StoredMap(storage, "project:labels");
370 this.#versionChange = new StoredMap(storage, "project:version-change");
371 this.#refusals = storedArray(storage, "project:refusals");
372 this.#agents = new WriterAgents(storage);
373 if (checkpoint === WRITER_REOPEN) {
374 this.#mods = storage.read("project:meta", "mods") as string[];
375 this.#queue = storage.read("project:meta", "queue") as QueuedPublish[];
376 const tells = storage.read("project:meta", "tells") as [
377 number,
378 Omit<TellRecord, "heard"> & { heard: [string, { at: number | undefined } | null][] },
379 ][];
380 this.#tells = new Map(tells.map(([id, tell]) => [id, { ...tell, heard: new Map(tell.heard) }]));
381 }
382 }
383 this.#hasBlob = options.hasBlob ?? (() => false);
384 this.#now = options.now;
385 this.#whole = options.whole;
386 this.#shapes = options.shapes;
387 // For tests (#46): AVCS_TEXT_FROM_LOG=1 runs a project on a MemoryStore with its text read back from the store.
388 const testing =
389 (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env?.AVCS_TEXT_FROM_LOG ===
390 "1";
391 const entryAt =
392 options.entryAt ??
393 (testing && store instanceof MemoryStore ? (at: number) => (store as MemoryStore).entries[at]! : undefined);
394 // An atom as its log entry stores it. Not stored yet: still in this call's pending entries; while loading, every entry is stored.
395 const stored = (seq: number): Atom => {
396 const at = this.#atomAt[seq]!;
397 const entry = !this.#loading && at >= this.#stored ? this.#pending[at - this.#stored]! : entryAt!(at);
398 if (entry?.type === "init" || entry?.type === "draft") return entry.atom;
399 // A publish's or land's tie atom (#46: its lists are read back too).
400 if (entry?.type === "publish" || entry?.type === "land") return entry.tie;
401 throw new Error(`log entry ${at} holds no atom ${seq}`);
402 };
403 // Line text and each atom's deletes and claim keys stay in the log (#46), read back when asked for.
404 this.#graph = this.#writerStorage
405 ? new Graph({ storage: this.#writerStorage })
406 : entryAt
407 ? new Graph({ texts: (seq) => stored(seq).inserts.map((r) => r.lines), lists: (seq) => stored(seq) })
408 : new Graph();
409 this.#views = new ViewCache(this.#graph, options.readViewProvider);
410 this.#paths = new PathIndex({
411 graph: this.#graph,
412 at: (space, version) => this.#at(space, version),
413 viewAt: (space, version) => this.#viewAt(space, version),
414 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
415 shapes: this.#shapes,
416 });
417 }
419 /** Rebuild a project from its stored entries. New entries go to `store`. */
420 static load(entries: Iterable<Entry>, store: ProjectStore, options: ProjectOptions = {}): Project {
421 const testing =
422 (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env?.AVCS_TEXT_FROM_LOG ===
423 "1";
424 if (testing && !options.entryAt && Array.isArray(entries)) {
425 // Loaded from someone else's entries: its text is read back from them (and from the new store after them).
426 const from = entries as Entry[];
427 const after = store instanceof MemoryStore ? store : undefined;
428 options = { ...options, entryAt: (at) => (at < from.length ? from[at]! : after!.entries[at - from.length]!) };
429 }
430 const project = new Project(store, options);
431 project.#loading = true;
432 for (const entry of entries) {
433 project.#apply(entry);
434 project.#stored++;
435 project.#persistMutable();
436 }
437 project.#loading = false;
438 project.#writeCheckpoint();
439 return project;
440 }
442 /** Reopen committed writer indexes. The host supplies the authoritative canonical log length. */
443 static openWriter(
444 store: ProjectStore,
445 storage: GraphStateStorage,
446 logLength: number,
447 options: Omit<ProjectOptions, "writerStorage"> = {},
448 ): Project {
449 const adoption = storage.read("project:meta", "adoption") as WriterAdoption | undefined;
450 if (adoption && !adoption.ready) throw new Error("writer adoption is incomplete");
451 return Project.#openWriter(store, storage, logLength, options);
452 }
454 static #openWriter(
455 store: ProjectStore,
456 storage: GraphStateStorage,
457 logLength: number,
458 options: Omit<ProjectOptions, "writerStorage">,
459 ): Project {
460 const checkpoint = storage.read("project:meta", "checkpoint") as
461 | { format: number; logLength: number; atoms: number; version: number }
462 | undefined;
463 const length = (name: string) => (storage.read(`${name}:meta`, "length") as number | undefined) ?? 0;
464 if (
465 !Number.isSafeInteger(logLength) ||
466 logLength < 1 ||
467 checkpoint?.format !== 1 ||
468 checkpoint.logLength !== logLength ||
469 storage.read("project:meta", "stored") !== logLength ||
470 length("project:time-at") !== logLength ||
471 length("atoms") !== checkpoint.atoms ||
472 length("project:atom-at") !== checkpoint.atoms ||
473 length('membership:"":versions') !== checkpoint.version + 1 ||
474 length("project:version-at") !== checkpoint.version + 1 ||
475 !["mods", "queue", "tells"].every((key) => Array.isArray(storage.read("project:meta", key)))
476 )
477 throw new Error("writer checkpoint does not match the canonical log and indexes");
478 return new Project(store, { ...options, writerStorage: storage }, WRITER_REOPEN);
479 }
481 /**
482 * Derive one bounded page from the host's canonical frames. The host reads
483 * those frames from its own log and revalidates the source inside this same
484 * transaction. Partial adoption cannot be opened for normal operations.
485 */
486 static adoptWriterPage(
487 storage: GraphStateStorage,
488 input: {
489 source: WriterSource;
490 from: number;
491 frames: Iterable<{ seq: number; json: string }>;
492 maxEntries: number;
493 maxBytes: number;
494 currentSource(): WriterSource;
495 },
496 options: Omit<ProjectOptions, "writerStorage"> = {},
497 ): { next: number; ready: boolean; entries: number; bytes: number } {
498 const same = (a: WriterSource, b: WriterSource) =>
499 a.generation === b.generation && a.logLength === b.logLength && a.sharedVersion === b.sharedVersion;
500 if (
501 ![input.source.generation, input.source.logLength, input.source.sharedVersion, input.from].every(
502 (n) => Number.isSafeInteger(n) && n >= 0,
503 ) ||
504 input.source.logLength < 1 ||
505 !Number.isSafeInteger(input.maxEntries) ||
506 input.maxEntries < 1 ||
507 input.maxEntries > 256 ||
508 !Number.isSafeInteger(input.maxBytes) ||
509 input.maxBytes < 1 ||
510 input.maxBytes > 8_000_000
511 )
512 throw new Error("invalid writer adoption bounds or source");
513 return storage.transaction(() => {
514 if (!same(input.currentSource(), input.source))
515 throw new Error("canonical source changed before writer adoption");
516 const previous = storage.read("project:meta", "adoption") as WriterAdoption | undefined;
517 if (
518 (previous && (!same(previous.source, input.source) || previous.ready || previous.next !== input.from)) ||
519 (!previous && input.from !== 0)
520 )
521 throw new Error("writer adoption source or cursor does not match");
522 const noAppend: ProjectStore = {
523 append: () => {
524 throw new Error("adoption must never append canonical history");
525 },
526 };
527 const project = previous
528 ? Project.#openWriter(noAppend, storage, input.from, options)
529 : new Project(noAppend, { ...options, writerStorage: storage });
530 project.#loading = true;
531 let count = 0;
532 let bytes = 0;
533 for (const frame of input.frames) {
534 if (
535 count >= input.maxEntries ||
536 frame.seq !== input.from + count ||
537 frame.seq >= input.source.logLength ||
538 typeof frame.json !== "string" ||
539 frame.json.length > input.maxBytes - bytes
540 )
541 throw new Error("writer adoption page exceeds bounds or has a noncontiguous frame");
542 bytes += new TextEncoder().encode(frame.json).byteLength;
543 if (bytes > input.maxBytes) throw new Error("writer adoption page exceeds byte bound");
544 project.#apply(JSON.parse(frame.json) as Entry);
545 project.#stored++;
546 project.#persistMutable();
547 count++;
548 }
549 if (count === 0) throw new Error("writer adoption page must advance");
550 project.#loading = false;
551 const next = input.from + count;
552 const ready = next === input.source.logLength;
553 if (!same(input.currentSource(), input.source))
554 throw new Error("canonical source changed during writer adoption");
555 if (ready && project.version !== input.source.sharedVersion)
556 throw new Error("adopted shared version differs from canonical source");
557 project.#writeCheckpoint();
558 storage.write("project:meta", "adoption", { source: input.source, next, ready } satisfies WriterAdoption);
559 return { next, ready, entries: count, bytes };
560 });
561 }
563 /**
564 * Apply more stored entries to a copy loaded for reading (#41, replay):
565 * scrubbing forward applies only what's new. Never for the live project.
566 */
567 catchUp(entries: Iterable<Entry>): void {
568 this.#loading = true;
569 try {
570 for (const entry of entries) {
571 this.#apply(entry);
572 this.#stored++;
573 }
574 } finally {
575 this.#loading = false;
576 }
577 }
579 /** The log position of the next entry: how many entries the log holds (#41). */
580 get logLength(): number {
581 return this.#stored;
582 }
584 get initialized(): boolean {
585 return this.#shared.versions.length > 0;
586 }
588 /** The current shared version. */
589 get version(): number {
590 this.#needInit();
591 return this.#shared.versions.length - 1;
592 }
594 /** Shared's files, for the push out to Artifacts. */
595 files(): Record<string, string> {
596 return this.#sharedView().files();
597 }
599 /** Shared's binary files, for the push out to Artifacts: path -> the SHA-256 of its bytes. Not in `files()`. */
600 blobs(): Record<string, string> {
601 return this.#sharedView().blobs();
602 }
604 /** Shared's executable files and links, for the push out to Artifacts: path -> mode. Other files are plain. */
605 modes(): Modes {
606 return modesOf(this.#sharedView());
607 }
609 /** Shared as a ReadView, for reading lines (blame, why). Don't hold on to it across calls. */
610 sharedView(): ReadView {
611 return this.#sharedView();
612 }
614 /** The agents the project knows, by name. */
615 agents(): string[] {
616 return [...this.#agents.keys()].sort();
617 }
619 /**
620 * An agent's unpublished changes, oldest first, and its view (its space at its base plus its changes). Read only.
621 * The view is laid out on first use: where asks every agent, most have no changes, and a big project has more
622 * agents than the view cache holds, so building every view cost each call about 0.7 s.
623 */
624 draftOf(agentName: string): { atoms: AtomId[]; readonly view: ReadView } | undefined {
625 const agent = this.#agents.get(agentName);
626 if (!agent) return undefined;
627 const view = () => this.#agentView(agent);
628 return {
629 atoms: this.#draft(agent),
630 get view() {
631 return view();
632 },
633 };
634 }
636 /** The shared version an atom was published in, or undefined while it's only in a draft. */
637 versionOf(atom: AtomId): number | undefined {
638 return this.#shared.publishedIn.get(atom);
639 }
641 /**
642 * Where an atom was published: shared if it's there, else the named draft
643 * that has it (by name), else undefined (it's only in a draft so far).
644 */
645 publishOf(...args: Tail<Parameters<typeof hostedPublishOf>>): ReturnType<typeof hostedPublishOf> {
646 return hostedPublishOf(this.#publishOfHost, ...args);
647 }
649 /** The newest version of shared, or of a named draft. */
650 lastVersion(...args: Tail<Parameters<typeof hostedLastVersion>>): ReturnType<typeof hostedLastVersion> {
651 return hostedLastVersion(this.#versionMetaHost, ...args);
652 }
654 /** Shared (null), then each named draft by name: every space with versions (abso issue 80). */
655 spaceNames(): (string | null)[] {
656 return [null, ...[...this.#spaces.keys()].filter((n) => n !== SHARED).sort()];
657 }
659 /** Who made a version of shared or a named draft, why and when, and a draft's shared base (abso issue 80). */
660 versionMeta(...args: Tail<Parameters<typeof hostedVersionMeta>>): ReturnType<typeof hostedVersionMeta> {
661 return hostedVersionMeta(this.#versionMetaHost, ...args);
662 }
664 /** Who published a version of shared, and why. */
665 published(version: number): { agent: string; message: string; time: number } | undefined {
666 const p = this.#shared.versions[version];
667 return p && { agent: p.agent, message: p.message, time: p.time };
668 }
670 /** The graph, for reading (blame, history). Don't add to it. */
671 get graph(): Graph {
672 return this.#graph;
673 }
675 // Calls -------------------------------------------------------------------
677 /** Create the project from a folder's text files. Empty files are skipped (the engine can't hold them). */
678 init(...args: Tail<Parameters<typeof hostedInit>>): ReturnType<typeof hostedInit> {
679 return hostedInit(this.#initHost, ...args);
680 }
682 /** An Edit, Write or MultiEdit from the hook, against the agent's view. */
683 edit(...args: Tail<Parameters<typeof hostedEdit>>): ReturnType<typeof hostedEdit> {
684 return hostedEdit(this.#editHost, ...args);
685 }
687 /** Whole files as the agent's folder has them; each is diffed against its view. */
688 record(...args: Tail<Parameters<typeof hostedRecord>>): ReturnType<typeof hostedRecord> {
689 return hostedRecord(this.#recordHost, ...args);
690 }
692 /** Add the agent's draft to its space (publish.ts). */
693 publish(...args: Tail<Parameters<typeof hostedPublish>>): ReturnType<typeof hostedPublish> {
694 return hostedPublish(this.#publishHost, ...args);
695 }
697 #publish(
698 agent: AgentState,
699 message: string,
700 time: number,
701 entries: Entry[],
702 asIs = false,
703 direct = false,
704 ): PublishAnswer {
705 return hostedPublishDraft(this.#publishHost, agent, message, time, entries, asIs, direct);
706 }
708 /**
709 * How the agent's newest edit arrived (#41). The mod sends X-Abso-Client
710 * avcs-mod/<stamp>; the hook sends abso-cli/<version> (avcs-cli/ before #59) with the chat's
711 * session; abso record and git pushes send no session. Edits stored before
712 * the client was recorded have only the session: those count as the mod
713 * (the hook stands down where the mod is installed), with modCurrent null.
714 */
715 #editsOf(agent: AgentState): {
716 edits: EditsVia;
717 modCurrent: boolean | null;
718 lastEdit: number | null;
719 joined: number | null;
720 } {
721 const last = agent.lastEdit;
722 const joined = agent.joined ?? null;
723 if (!last) return { edits: "none", modCurrent: null, lastEdit: null, joined };
724 const { client, session } = last;
725 if (client?.startsWith("avcs-mod/"))
726 return { edits: "mod", modCurrent: client === this.#mods[this.#mods.length - 1], lastEdit: last.time, joined };
727 if (client === undefined && session) return { edits: "mod", modCurrent: null, lastEdit: last.time, joined };
728 return { edits: session ? "hook" : "commands", modCurrent: null, lastEdit: last.time, joined };
729 }
731 // Spellings and moves (#49) --------------------------------------------------------
733 /** Refuse work whose paths would clash in shared (#49), before anything of it is written. */
734 #checkClash(...args: Tail<Parameters<typeof hostedCheckClash>>): ReturnType<typeof hostedCheckClash> {
735 return hostedCheckClash(this.#checkClashHost, ...args);
736 }
738 /**
739 * Move a file in the agent's draft (#49): its lines keep their ids, as with
740 * git mv, so blame and why follow it. The only way to change a file's case.
741 * Refused when `to` is another existing file, ignoring case.
742 */
743 move(...args: Tail<Parameters<typeof hostedMove>>): ReturnType<typeof hostedMove> {
744 return hostedMove(this.#moveHost, ...args);
745 }
747 // Files kept whole (#46) ----------------------------------------------------------
749 /** avcs.json's `"whole": [globs]`: paths kept whole. From `config` when given (init), else shared's. */
750 #wholeRules(config?: string): string[] {
751 return hostedWholeRules(this.#wholeHost, config);
752 }
754 /**
755 * Whether a file is kept whole: its path matches avcs.json's "whole", its
756 * text passes WHOLE_LIMIT, or it is already a blob where it's going. The
757 * last makes it one-way: a file kept whole stays whole while it exists,
758 * even if it shrinks or the rule changes, so it never flips back and forth.
759 */
760 #isWhole(path: string, length: number, view: ReadView | undefined, rules: readonly string[]): boolean {
761 return hostedIsWhole(this.#wholeHost, path, length, view, rules);
762 }
764 /** Files and blobs with every whole file's text moved into the blob store. */
765 #wholeOut(
766 files: Readonly<Record<string, string | null>>,
767 blobs: Readonly<Record<string, string>>,
768 view: ReadView | undefined,
769 config?: string,
770 ): { files: Record<string, string | null>; blobs: Record<string, string> } {
771 return hostedWholeOut(this.#wholeHost, files, blobs, view, config);
772 }
774 // Changes (#44) -------------------------------------------------------------------
776 /** The agent did something at `time`: its start note ends first if it had been idle over 2 hours. */
777 #active(agent: AgentState, time: number): void {
778 if (agent.starting && agent.lastActive !== undefined && time - agent.lastActive > NOTE_IDLE) {
779 delete agent.starting;
780 delete agent.noteAt;
781 }
782 if (agent.lastActive === undefined || time > agent.lastActive) agent.lastActive = time;
783 }
785 /** The agent's start note, unless it has been idle over 2 hours. */
786 #liveNote(agent: AgentState): Starting | undefined {
787 if (!agent.starting) return undefined;
788 const now = this.#now?.() ?? this.#lastTime;
789 return agent.lastActive !== undefined && now - agent.lastActive > NOTE_IDLE ? undefined : agent.starting;
790 }
792 /** The change the agent is working on at `time`: its named draft's, or its start note's; none for a lone publish. */
793 #currentChange(agent: AgentState, time: number): number | undefined {
794 if (agent.space !== SHARED) return this.#spaces.get(agent.space)?.startedAt;
795 if (!agent.starting || agent.noteAt === undefined) return undefined;
796 return agent.lastActive !== undefined && time - agent.lastActive > NOTE_IDLE ? undefined : agent.noteAt;
797 }
799 /** The position the next entry written will have. */
800 get #nextAt(): number {
801 return this.#stored + this.#pending.length;
802 }
804 #changeRecord(id: number, agent: AgentState, time: number, queuedNote?: Starting): ChangeRecord {
805 return hostedChangeRecord(this.#changeHost, id, agent, time, queuedNote);
806 }
808 /** A publish or land joins its change. Entries from before changes: the start note named it, and the publish ended the note. */
809 #joinChange(
810 agent: AgentState,
811 entry: Extract<Entry, { type: "publish" | "land" }>,
812 at: number,
813 draft: string | null,
814 landed?: string,
815 ): void {
816 hostedJoinChange(this.#changeHost, agent, entry, at, draft, landed);
817 }
819 /**
820 * One change (#44): the start note, named draft or publish that began it,
821 * each of its versions and the files they changed, what it settled, and its
822 * refusals. `id` is the log position of the entry that began it.
823 */
824 change(id: number): ChangeAnswer {
825 return hostedChange(this.#changeHost, id);
826 }
828 /** The files a version's changes name: cheap, for lists (the change page works out the net changes). */
829 #namedFiles(space: Space, version: number): string[] {
830 return hostedNamedFiles(this.#graph, space, version);
831 }
833 /**
834 * "Since you last looked" (#44): the changes with anything new at or after
835 * log position `since`, newest first, at most `limit`. Their files are the
836 * ones their changes name; the change page has the net changes.
837 */
838 changes(
839 since = 0,
840 limit = 50,
841 before?: number,
842 issue?: number,
843 ): { since: number; next: number; changes: ChangeAnswer[]; older?: number } {
844 return hostedChanges(this.#changeHost, since, limit, before, issue);
845 }
847 // Notes on lines (#44) --------------------------------------------------------------
849 /**
850 * Leave a note on lines of a file (#44): lines `from` to `to` (1-based) as
851 * shared shows them now, as `of`'s draft shows them (to note work before
852 * it's published), or at `version`. Or answer a note with `reply`. The
853 * lines' authors, the change's agent and the thread hear it as news.
854 */
855 note(
856 agentName: string,
857 body: NoteBody,
858 time: number,
859 ): { id: number; change: number | null; lines: [number, number] } {
860 this.#needInit();
861 const entries: Entry[] = [];
862 return this.#note(entries, () => ({ name: this.#agent(agentName, entries).name }), body, time);
863 }
865 /**
866 * A signed-in person's note from the website (#41). The Worker has checked
867 * who it is. The writer is recorded as "person:<id>" with `person`, never
868 * as an agent, and the news quotes the text.
869 */
870 notePerson(
871 person: { id: unknown; name: unknown },
872 body: NoteBody,
873 time: number,
874 ): { id: number; change: number | null; lines: [number, number] } {
875 this.#needInit();
876 const from = checkPerson(person);
877 return this.#note([], () => ({ name: `person:${from.person.id}`, person: from }), body, time);
878 }
880 /** Close a person's own note (#41): only the person who wrote it can. */
881 closeNotePerson(person: { id: unknown; name: unknown }, id: number, how: unknown, time: number): NoteAnswer {
882 const from = checkPerson(person);
883 return this.#closeNote(`person:${from.person.id}`, id, how, time, from);
884 }
886 #note(
887 entries: Entry[],
888 writerOf: () => { name: string; person?: PersonSender },
889 body: NoteBody,
890 time: number,
891 ): { id: number; change: number | null; lines: [number, number] } {
892 return hostedWriteNote(this.#noteWriteHost, entries, writerOf, body, time);
893 }
895 /** The project's reviewers per area (#44): avcs.json's `"review": [{"paths": [...], "reviewer": "..."}]` in shared. */
896 #reviewRules(): ReviewRule[] {
897 return reviewRulesIn(projectFileIn(this.#sharedView())?.text);
898 }
900 /** Each reviewer whose area these files fall in, the files that do, and whether it has noted change `id`. */
901 #reviewersOf(files: readonly string[], id: number): { agent: string; files: string[]; read: boolean }[] {
902 return reviewersOf(this.#reviewRules(), files, (agent) =>
903 [...this.#notes.values()].some((n) => n.change === id && n.agent === agent),
904 );
905 }
907 /** After a version of shared: the reviewers whose areas it touches hear of its change, once per change (#44). */
908 #reviewNews(agent: AgentState, version: number, entries: Entry[]): void {
909 const id = this.#versionChange.get(` ${version}`);
910 if (id === undefined) return;
911 const rec = this.#changes.get(id);
912 const files = this.#namedFiles(this.#shared, version);
913 for (const r of this.#reviewersOf(files, id)) {
914 if (r.agent === agent.name) continue;
915 const reviewer = this.#agents.get(r.agent);
916 if (!reviewer) continue;
917 const title =
918 rec?.note?.text ?? (rec?.kind === "draft" ? `draft ${rec.draft}` : (rec?.versions[0]?.message ?? ""));
919 this.#queueNews(reviewer, [reviewItem(agent.name, id, title, r.files, version)], entries);
920 }
921 }
923 /** After a version of shared: each open objection whose lines it took out tells its writer (#44). */
924 #addressedNews(agent: AgentState, version: number, entries: Entry[]): void {
925 for (const n of this.#notes.values()) {
926 if (n.kind !== "objection" || n.closed || n.reply !== undefined || n.agent === agent.name) continue;
927 if (this.#noteAnswer(n).state !== "addressed") continue;
928 const writer = this.#agents.get(n.agent);
929 if (writer) this.#queueNews(writer, [addressedItem(agent.name, version, n)], entries);
930 }
931 }
933 /** Close a note: only its writer can (#44). */
934 closeNote(agentName: string, id: number, how: unknown, time: number): NoteAnswer {
935 return this.#closeNote(agentName, id, how, time);
936 }
938 #closeNote(agentName: string, id: number, how: unknown, time: number, person?: PersonSender): NoteAnswer {
939 return hostedCloseNote(this.#noteWriteHost, agentName, id, how, time, person);
940 }
942 /** Notes, oldest first: on a file, on a change, or only the ones still open. */
943 notes(...args: Tail<Parameters<typeof hostedNotes>>): ReturnType<typeof hostedNotes> {
944 return hostedNotes(this.#notesHost, ...args);
945 }
947 /** The change the newest of these lines was written in: its version's, or its author's current one if unpublished. */
948 #changeOfLines(lines: readonly LineId[]): number | undefined {
949 let newest: Atom | undefined;
950 for (const l of lines) {
951 const info = this.#graph.line(l);
952 const atom = info && this.#graph.atom(info.atom);
953 if (atom && (!newest || atom.seq > newest.seq)) newest = atom;
954 }
955 if (!newest) return undefined;
956 for (const space of [this.#shared, ...[...this.#spaces.values()].filter((s) => s.name !== SHARED)]) {
957 const v = space.publishedIn.get(newest.id);
958 if (v !== undefined) return this.#versionChange.get(`${space.name === SHARED ? "" : space.name} ${v}`);
959 }
960 const author = this.#agents.get(newest.author);
961 return author ? this.#currentChange(author, this.#now?.() ?? this.#lastTime) : undefined;
962 }
964 #noteAnswer(n: NoteRecord): NoteAnswer {
965 return hostedNoteAnswer(this.#notesHost, n);
966 }
968 // The merge queue (#39) ------------------------------------------------------------
970 /** Whether shared's avcs.json turns the merge queue on (`"queue": true`). */
971 #queueOn(): boolean {
972 return hostedQueueOn(this.#queueHost);
973 }
975 /** With the queue on, nothing lands in shared unchecked; land and pluck don't go through the queue yet. */
976 #notQueuedYet(what: string): void {
977 hostedNotQueuedYet(this.#queueHost, what);
978 }
980 /** Atoms of every queued publish, or only other agents' with `except`. */
981 #queuedAtoms(except?: string): Set<AtomId> {
982 return hostedQueuedAtoms(this.#queueHost, except);
983 }
985 /** Queue the agent's publish (#39). */
986 #enqueue(
987 agent: AgentState,
988 message: string,
989 time: number,
990 draft: readonly AtomId[],
991 resolves: readonly AtomId[],
992 entries: Entry[],
993 ): PublishAnswer {
994 return hostedEnqueue(this.#queueHost, agent, message, time, draft, resolves, entries);
995 }
997 /** The merge queue now (#39): waiting publishes in order, and which are in the batch being checked. */
998 queue(...args: Tail<Parameters<typeof hostedQueue>>): ReturnType<typeof hostedQueue> {
999 return hostedQueue(this.#queueHost, ...args);
1002 /** Mark the first `n` queued publishes as the batch being checked (0 ends it). Not logged. */
1003 queueChecking(...args: Tail<Parameters<typeof hostedQueueChecking>>): ReturnType<typeof hostedQueueChecking> {
1004 return hostedQueueChecking(this.#queueHost, ...args);
1007 /** Shared with the first `n` queued publishes on top (#39): the files a batch's check runs on, and their tree hash. */
1008 queueCandidate(...args: Tail<Parameters<typeof hostedQueueCandidate>>): ReturnType<typeof hostedQueueCandidate> {
1009 return hostedQueueCandidate(this.#queueHost, ...args);
1012 /** The tree hash of a version of shared (#39): it equals a candidate's when that's what landed. */
1013 treeAt(version: number): string {
1014 const view = this.viewAt(version);
1015 return treeHash({ files: view.files(), modes: modesOf(view), blobs: view.blobs() });
1018 /**
1019 * Land the first `n` queued publishes (#39), in order, each as its own
1020 * version, after their batch passed. Each tells others what arrived, its
1021 * author that it landed, and the authors of what it settled what it kept.
1022 */
1023 queueLand(...args: Tail<Parameters<typeof hostedQueueLand>>): ReturnType<typeof hostedQueueLand> {
1024 return hostedQueueLand(this.#queueHost, ...args);
1027 /**
1028 * Take a queued publish out (#39): its check failed, or its author withdrew
1029 * it. Its changes are simply still in its author's draft. Later queued
1030 * publishes that build on its changes come out with it.
1031 */
1032 queuePull(...args: Tail<Parameters<typeof hostedQueuePull>>): ReturnType<typeof hostedQueuePull> {
1033 return hostedQueuePull(this.#queueHost, ...args);
1036 /** The agent withdraws its queued publishes (#39): refused while one is in the batch being checked. */
1037 unqueue(...args: Tail<Parameters<typeof hostedUnqueue>>): ReturnType<typeof hostedUnqueue> {
1038 return hostedUnqueue(this.#queueHost, ...args);
1041 /**
1042 * Correct the message of the agent's newest publish in its space (#27).
1043 * Only the message changes: shared only grows, so a version's changes are
1044 * fixed by publishing again (or dropping it). The log keeps the original.
1045 */
1046 amend(...args: Tail<Parameters<typeof hostedAmend>>): ReturnType<typeof hostedAmend> {
1047 return hostedAmend(this.#amendHost, ...args);
1050 /**
1051 * Put a label on a version of shared (the newest by default), or take it
1052 * off with `remove`. A label can mark many versions ("passed-ci"); a folder
1053 * follows the newest with `sync {label}`.
1054 */
1055 label(...args: Tail<Parameters<typeof hostedLabel>>): ReturnType<typeof hostedLabel> {
1056 return hostedLabel(this.#labelHost, ...args);
1059 /**
1060 * Drop published versions of shared (#10): a new shared version whose set
1061 * leaves out their changes. Later work that doesn't depend on them stays;
1062 * history keeps them. When later published work built on them, they are
1063 * refused with that work listed, unless `withDependents`, which drops it
1064 * too. Unpublished work that builds on them (an agent's draft, a named
1065 * draft not yet landed) always refuses it: drop never touches it.
1066 */
1067 drop(
1068 agentName: string,
1069 versions: readonly number[],
1070 message: string,
1071 time: number,
1072 options: { withDependents?: boolean } = {},
1073 ): DropAnswer {
1074 return hostedDrop(this.#dropHost, agentName, versions, message, time, options);
1077 /**
1078 * After a sync, merge files where the agent's draft and the newer work
1079 * collide, the way git merges a file (#25, Fuzzer): from the agent's old
1080 * base, its draft's text and the newer text. Changes both made identically
1081 * are kept once; changes on one side are kept. Only when every file
1082 * involved merges with no conflict are the draft's changes to them dropped
1083 * (a discard entry) and made again as the merged text. Otherwise nothing
1084 * changes, and the collision stands with both sides' lines in the file.
1085 */
1086 #mergeIdentical(
1087 agent: AgentState,
1088 before: ReadView,
1089 oldBase: ReadonlySet<AtomId>,
1090 oldVersion: number,
1091 time: number,
1092 entries: Entry[],
1093 ): MergedLine[] {
1094 return hostedMergeIdentical(this.#mergeHost, agent, before, oldBase, oldVersion, time, entries);
1097 /**
1098 * Names the agent's draft defines at the top level of a file where other
1099 * work defines them too, so they are defined twice there (#25, Fuzzer).
1100 */
1101 #duplicates(agent: AgentState): Collision[] {
1102 return duplicateCollisions(this.#collisionHost, agent);
1105 /**
1106 * Draft changes that build on atoms a set doesn't have (a drop took them
1107 * out): the files they touch. Those changes can't move onto that set.
1108 */
1109 #strandedFiles(draft: readonly AtomId[], set: ReadonlySet<AtomId>): string[] {
1110 return strandedFiles(this.#graph, draft, set);
1113 /** Answer a refusal, and log it (an entry that changes nothing but the counts). */
1114 #refuse(...args: Tail<Parameters<typeof hostedRefuse>>): ReturnType<typeof hostedRefuse> {
1115 return hostedRefuse(this.#refuseHost, ...args);
1118 /**
1119 * Tell other agents something, as news: "Announcement from <agent>:
1120 * <text>". It reaches each one with its next edit, record or news call.
1121 * `to` names agents; without it, every other agent the project has now.
1122 */
1123 announce(...args: Tail<Parameters<typeof hostedAnnounce>>): ReturnType<typeof hostedAnnounce> {
1124 return hostedAnnounce(this.#announceHost, ...args);
1127 /**
1128 * A signed-in person's announcement from the website (#41). The Worker has
1129 * checked who sent it; the engine records it on each recipient's news with
1130 * `from`, and never makes the person an agent. The text is JSON-quoted, so
1131 * a line break in it can't pass for another item.
1132 */
1133 announcePerson(...args: Tail<Parameters<typeof hostedAnnouncePerson>>): ReturnType<typeof hostedAnnouncePerson> {
1134 return hostedAnnouncePerson(this.#announceHost, ...args);
1137 /**
1138 * Say what the agent is starting on (#37, #13), before any edit lands:
1139 * `text`, and the files it expects to change if it knows them. Nothing is
1140 * locked or refused. where and status show it until the agent publishes,
1141 * lands, or sends null. The answer names who already has unpublished
1142 * changes in, or a starting note on, those files; they hear of it too.
1143 */
1144 starting(...args: Tail<Parameters<typeof hostedStarting>>): ReturnType<typeof hostedStarting> {
1145 return hostedStarting(this.#startingHost, ...args);
1148 /** Every agent's starting note, by agent name. */
1149 startingNotes(): ReturnType<typeof hostedStartingNotes> {
1150 return hostedStartingNotes(this.#notesHost);
1153 #openCollisions(agent: AgentState): { collisions?: AgentStatus["collisions"] } {
1154 return hostedOpenCollisions(this.#markerHost, agent);
1157 /**
1158 * News when an edit leaves a file holding blocks of collision markers
1159 * (#11): how many, and how to settle them. Again whenever the count changes.
1160 */
1161 #markedNews(agent: AgentState, files: readonly string[], entries: Entry[]): void {
1162 const marked = new Set(this.#markedFiles(agent));
1163 const view = this.#agentView(agent);
1164 const items: NewsItem[] = [];
1165 for (const file of [...new Set(files)].sort()) {
1166 if (!marked.has(file) || !view.hasFile(file)) continue;
1167 const n = blocksIn(view.lines(file).map((l) => l.text)).length;
1168 if (n === 0) continue;
1169 items.push(markedItem(this.#draft(agent)[0] ?? "", file, n));
1171 this.#queueNews(agent, items, entries);
1174 /** The collided changes behind each block whose marker lines `atom` deletes (#11). */
1175 #markersSettled(agent: AgentState, view: ReadView, atom: Atom): AtomId[] {
1176 return hostedMarkersSettled(this.#markerHost, agent, view, atom);
1179 /** Files where a sync wrote the agent collision markers in its current space (#11). */
1180 #markedFiles(agent: AgentState): string[] {
1181 return hostedMarkedFiles(agent);
1184 /** The blocks of markers still in the agent's files, as collisions (#11): listed by sync and status. */
1185 #markedCollisions(agent: AgentState): Collision[] {
1186 return hostedMarkedCollisions(this.#markerHost, agent);
1189 /**
1190 * Marker lines the agent's draft adds (#11), as collisions: each
1191 * well-formed block, and any marker line left outside one. Only the labeled
1192 * lines the engine writes count, so a document that shows markers can be
1193 * published.
1194 */
1195 #markerCollisions(agent: AgentState): Collision[] {
1196 return hostedMarkerCollisions(this.#markerHost, agent);
1199 /** One line of news for each other author whose marked collision a publish settled (#11): what was kept, and any lines lost. */
1200 #settledNews(agent: AgentState, version: number, settled: readonly Settled[], entries: Entry[]): void {
1201 for (const s of settled) {
1202 const other = this.#agents.get(s.theirs.agent);
1203 if (!other || other === agent) continue;
1204 this.#queueNews(other, [settledItem(agent.name, version, s)], entries);
1208 /**
1209 * The files the agent's unpublished changes touch, in its own view. Kept per agent under what they're
1210 * made of: its view's key and its draft. Most agents haven't moved since the last
1211 * status, and the view cache holds fewer views than a big project has agents, so working them out again
1212 * on every call cost about 0.5 s on abso. A copy goes out, so no caller can change what's kept.
1213 */
1214 #draftFiles(agent: AgentState): Set<string> {
1215 const key = `${this.#agentViewKey(agent)}|${this.#draft(agent).join(",")}`;
1216 let kept = this.#draftFilesKept.get(agent.name);
1217 if (kept?.key !== key) {
1218 kept = { key, files: hostedDraftFiles(this.#overlapHost, agent) };
1219 this.#draftFilesKept.set(agent.name, kept);
1221 return new Set(kept.files);
1224 /** Other agents in the agent's space whose unpublished changes or starting note meet `patterns`. */
1225 #overlaps(...args: Tail<Parameters<typeof hostedOverlaps>>): ReturnType<typeof hostedOverlaps> {
1226 return hostedOverlaps(this.#overlapHost, ...args);
1229 /**
1230 * News the first time a draft touches a file someone else in its space has
1231 * unpublished changes in, or a starting note on (#37): one line per file and agent, once per draft. It tells; it never stops
1232 * the edit.
1233 */
1234 #overlapNews(...args: Tail<Parameters<typeof hostedOverlapNews>>): ReturnType<typeof hostedOverlapNews> {
1235 return hostedOverlapNews(this.#overlapHost, ...args);
1238 /** Hand over the news waiting for an agent (collisions, definitions, moves, announcements), once. */
1239 news(agentName: string): { news: string[]; items: { text: string; at: number | null }[] } {
1240 const entries: Entry[] = [];
1241 const agent = this.#agent(agentName, entries);
1242 const items = agent.news.map((text, i) => ({ text, at: agent.newsAt[i] ?? null }));
1243 const news = this.#takeNews(agent, entries);
1244 this.#flush(entries);
1245 return { news, items };
1248 /** Refused publishes and lands, newest first (`limit` defaults to 50), with counts over all of them. */
1249 refusals(...args: Tail<Parameters<typeof hostedRefusals>>): ReturnType<typeof hostedRefusals> {
1250 return hostedRefusals(this.#refuseHost, ...args);
1253 /**
1254 * Move the agent's base to its space's newest version. Returns every file
1255 * whose text in its view changes (null when it's gone), and the collisions
1256 * it now has to settle. A first sync returns every file (that's how a
1257 * folder joins).
1258 */
1259 sync(...args: Tail<Parameters<typeof hostedSync>>): ReturnType<typeof hostedSync> {
1260 return hostedSync(this.#syncHost, ...args);
1263 /**
1264 * Move the agent to a named draft, or back to shared with null. Its
1265 * unpublished changes stay parked on the server in the space it leaves,
1266 * and what it parked in the space it moves to comes back. Nothing is lost
1267 * and nothing has to be published or stashed first. A new named draft
1268 * starts on shared's newest version; with `carry`, the agent's current
1269 * unpublished changes move into it instead of being parked. Answers like a
1270 * sync: the files that change in its folder.
1271 */
1272 switchTo(...args: Tail<Parameters<typeof hostedSwitchTo>>): ReturnType<typeof hostedSwitchTo> {
1273 return hostedSwitchTo(this.#switchHost, ...args);
1276 /**
1277 * Move the agent's named draft onto shared's newest version. The draft's
1278 * agents see it when they next sync; anything it collides with is theirs
1279 * to settle before the draft lands.
1280 */
1281 syncDraft(agentName: string, time: number): DraftSyncAnswer {
1282 const entries: Entry[] = [];
1283 const agent = this.#agent(agentName, entries);
1284 const space = this.#namedSpaceOf(agent);
1285 const ownOnly = [...space.own].filter((id) => !this.#shared.own.has(id) && !this.#shared.droppedIn.has(id));
1286 const stranded = this.#strandedFiles(ownOnly, this.#shared.own);
1287 if (stranded.length > 0) {
1288 throw new ProjectError(
1289 "conflict",
1290 `draft ${space.name} has changes to ${stranded.join(", ")} that build on lines a drop took out of shared`,
1291 );
1293 if (sharedBaseOf(space) !== this.version) {
1294 entries.push({
1295 type: "space-sync",
1296 space: space.name,
1297 agent: agent.name,
1298 time,
1299 version: last(space) + 1,
1300 sharedBase: this.version,
1301 });
1302 this.#apply(entries[entries.length - 1]!);
1304 this.#flush(entries);
1305 return { draft: space.name, version: last(space), sharedBase: sharedBaseOf(space) };
1308 /**
1309 * Land the agent's named draft in shared as one unit: every change
1310 * published into it that shared doesn't have yet. Refused, like a publish,
1311 * when those changes collide with work that landed in shared after the
1312 * draft's base; sync the draft, settle, and land again.
1313 */
1314 land(...args: Tail<Parameters<typeof hostedLand>>): ReturnType<typeof hostedLand> {
1315 return hostedLand(this.#landHost, ...args);
1318 /**
1319 * What landing `changes` of a named draft would collide with in shared now (#41, the Drafts page reads it
1320 * too): the same pairs and definitions land refuses on.
1321 */
1322 #landCollisions(
1323 space: Space,
1324 changes: AtomId[],
1325 pick: boolean,
1326 ): { collisions: Collision[]; newer: Set<AtomId>; union: Set<AtomId> } {
1327 return hostedLandCollisions(this.#landHost, space, changes, pick);
1330 /**
1331 * A named draft's state in one read (#41, the Drafts page, D3 and D16): the shared version it builds on and
1332 * how far behind shared that is, its versions, when its first edit was, who works in it, and what landing it
1333 * now would collide with (the same check land makes, so nothing is written).
1334 */
1335 draftState(...args: Tail<Parameters<typeof hostedDraftState>>): ReturnType<typeof hostedDraftState> {
1336 return hostedDraftState(this.#draftStateHost, ...args);
1339 #land(
1340 agent: AgentState,
1341 message: string,
1342 time: number,
1343 entries: Entry[],
1344 pick?: { space: Space; changes: AtomId[] },
1345 ): LandAnswer {
1346 return hostedLandDraft(this.#landHost, agent, message, time, entries, pick);
1349 /**
1350 * Take part of a named draft into shared (#27): the changes of some of its
1351 * versions, as one new version of shared, checked for collisions like a
1352 * land. When they build on other versions of the draft, those are listed
1353 * and it is refused, unless `withDependencies` takes them too. The draft
1354 * stays as it is; landing it later brings in only what's left.
1355 */
1356 pluck(
1357 agentName: string,
1358 draftName: string,
1359 versions: readonly number[],
1360 message: string,
1361 time: number,
1362 options: { withDependencies?: boolean } = {},
1363 ): PluckAnswer {
1364 return hostedPluck(this.#pluckHost, agentName, draftName, versions, message, time, options);
1367 /**
1368 * Take in commits a person pushed with plain git (demo moment 5, #5, #8).
1369 * `base` is the shared version their first commit builds on (the
1370 * `avcs-version` of the commit they cloned). Each commit gives its whole
1371 * tree as text; a file of the view missing from it is deleted. The commits
1372 * go into a named draft `git-<sha>` on that version, one publish each, and
1373 * the draft lands in shared at once if nothing collides. The push already
1374 * happened, so a collision isn't refused: the draft waits, with its
1375 * collisions listed, for someone to switch to it, settle and land it.
1376 */
1377 ingest(...args: Tail<Parameters<typeof hostedIngest>>): ReturnType<typeof hostedIngest> {
1378 return hostedIngest(this.#ingestHost, ...args);
1381 // Reading history, and discarding -------------------------------------------
1383 #checkVersion(space: Space, version: number): void {
1384 hostedCheckVersion(space, version);
1387 /**
1388 * Discard the agent's unpublished changes to some files (all of them with
1389 * `files` null), like git restore. Changes that touch only those files and
1390 * that no kept change builds on leave the draft; anything left over is
1391 * undone by a new change that puts the files back. Answers with each
1392 * file's text now, for the folder.
1393 */
1394 restore(...args: Tail<Parameters<typeof hostedRestore>>): ReturnType<typeof hostedRestore> {
1395 return hostedRestore(this.#restoreHost, ...args);
1398 /** The space options name: an agent's current space with `agent`, else the named draft, else shared. */
1399 #spaceFor(options: { draft?: string | null; agent?: string }): Space {
1400 if (options.agent !== undefined) {
1401 const agent = this.#agents.get(options.agent);
1402 if (!agent) throw new ProjectError("bad-request", `there is no agent ${JSON.stringify(options.agent)}`);
1403 return this.#spaceOf(agent);
1405 return this.#spaceNamed(options.draft ?? null);
1408 #spaceNamed(name: string | null): Space {
1409 const key = name === null ? SHARED : checkDraftName(name);
1410 const space = this.#spaces.get(key);
1411 if (!space) throw new ProjectError("bad-request", `there is no draft ${String(name)}`);
1412 return space;
1415 /**
1416 * The stored spelling a read means (#41, F7, the rule #49 set for writes):
1417 * the path itself, else the one file it matches by pathKey; failing that,
1418 * the one file ever in the view it matches, for a file since taken out.
1419 * A path that matches two files is answered exactly.
1420 */
1421 spellingIn(view: ReadView, path: string): string {
1422 if (view.hasFile(path)) return path;
1423 const key = pathKey(path);
1424 const live = view.knownPaths().filter((p) => pathKey(p) === key && view.hasFile(p));
1425 if (live.length > 0) return live.length === 1 ? live[0]! : path;
1426 const known = view.knownPaths();
1427 if (known.includes(path)) return path;
1428 const gone = known.filter((p) => pathKey(p) === key);
1429 return gone.length === 1 ? gone[0]! : path;
1432 // Applying entries ------------------------------------------------------------
1434 #apply(entry: Entry): void {
1435 // Entries written before #41 have no time on these kinds; new ones do, so replay can place them.
1436 const kept =
1437 this.#loading || !UNTIMED.has(entry.type) || "time" in entry ? entry : ({ ...entry, time: Date.now() } as Entry);
1438 if (!this.#loading) this.#pending.push(kept);
1439 const at = this.#loading ? this.#stored : this.#stored + this.#pending.length - 1;
1440 // Positions by time (#41, the website): the newest time up to each position, as the log holds it.
1441 const keptTime =
1442 kept.type === "draft" ? kept.atom.time : "time" in kept && typeof kept.time === "number" ? kept.time : undefined;
1443 const prior = at > 0 ? this.#timeAt[at - 1]! : 0;
1444 this.#timeAt[at] = keptTime !== undefined && keptTime > prior ? keptTime : prior;
1445 const versionsBefore = this.#spaces.get(SHARED)?.versions.length ?? 0;
1446 try {
1447 this.#applyEntry(entry, at, keptTime);
1448 } finally {
1449 // Positions by version: where each version of shared was made.
1450 const versionsAfter = this.#spaces.get(SHARED)?.versions.length ?? 0;
1451 for (let v = versionsBefore; v < versionsAfter; v++) this.#versionAt[v] = at;
1455 /**
1456 * The log position for a time or a version of shared (#41, the website):
1457 * for `time`, the position just after the last entry no later than it
1458 * (entries with no time take their predecessor's); for `version`, the
1459 * position just after the entry that made it. `end` is the log's length.
1460 */
1461 position(q: { time?: number; version?: number }): { position: number; end: number } {
1462 const end = this.#timeAt.length;
1463 if (q.version !== undefined) {
1464 if (!Number.isInteger(q.version) || q.version < 0 || q.version >= this.#versionAt.length)
1465 throw new ProjectError("not-found", `there is no version ${String(q.version)}`);
1466 return { position: this.#versionAt[q.version]! + 1, end };
1468 if (typeof q.time !== "number" || !Number.isFinite(q.time))
1469 throw new ProjectError("bad-request", "position needs ?time= or ?version=");
1470 // The newest time up to each position never goes down, so halve.
1471 let lo = 0;
1472 let hi = end;
1473 while (lo < hi) {
1474 const mid = (lo + hi) >> 1;
1475 if (this.#timeAt[mid]! <= q.time) lo = mid + 1;
1476 else hi = mid;
1478 return { position: lo, end };
1481 #applyEntry(entry: Entry, at: number, time: number | undefined): void {
1482 hostedApplyEntry(this.#applyEntryHost, entry, at, time);
1485 /** Apply entries and store them. */
1486 #commit(entries: Entry[]): void {
1487 for (const e of entries) this.#apply(e);
1488 this.#flush(entries);
1491 /** Store entries that are already applied. */
1492 #flush(_entries: readonly Entry[]): void {
1493 if (this.#pending.length === 0) return;
1494 const out = this.#pending;
1495 this.#store.append(out);
1496 this.#persistMutable();
1497 this.#pending = [];
1498 this.#stored += out.length;
1499 this.#writeCheckpoint();
1502 #writeCheckpoint(): void {
1503 this.#writerStorage?.write("project:meta", "checkpoint", {
1504 format: 1,
1505 logLength: this.#stored,
1506 atoms: this.#graph.size,
1507 version: this.version,
1508 });
1511 #persistMutable(): void {
1512 if (!this.#writerStorage) return;
1513 if (this.#agents instanceof WriterAgents) this.#agents.flush();
1514 this.#writerStorage.write("project:meta", "mods", this.#mods);
1515 this.#writerStorage.write("project:meta", "queue", this.#queue);
1516 this.#writerStorage.write(
1517 "project:meta",
1518 "tells",
1519 [...this.#tells].map(([id, tell]) => [id, { ...tell, heard: [...tell.heard] }]),
1520 );
1523 /**
1524 * The agent an entry names. Before every applied entry was stored, a call
1525 * that joined an agent and then threw could leave the join out of the log
1526 * while later entries named the agent. The lost join had the version the
1527 * project was at then, which is the version now, during replay.
1528 */
1529 #agentOf(name: string): AgentState {
1530 let agent = this.#agents.get(name);
1531 if (!agent) {
1532 this.#apply({ type: "join", agent: name, version: this.#shared.versions.length - 1 });
1533 agent = this.#agents.get(name)!;
1535 return agent;
1538 // Agents, spaces and views ----------------------------------------------------
1540 get #shared(): Space {
1541 return this.#spaces.get(SHARED)!;
1544 #needInit(): void {
1545 if (!this.initialized) throw new ProjectError("not-initialized", "the project has no files yet; init it first");
1548 #agent(name: string, entries: Entry[]): AgentState {
1549 this.#needInit();
1550 if (typeof name !== "string" || !NAME.test(name) || name === "init") {
1551 throw new ProjectError(
1552 "bad-agent",
1553 `bad agent name ${JSON.stringify(name)}: letters, digits, '.', '_' and '-', up to 64`,
1554 );
1556 let agent = this.#agents.get(name);
1557 if (!agent) {
1558 const join: Entry = { type: "join", agent: name, version: this.version };
1559 entries.push(join);
1560 this.#apply(join);
1561 agent = this.#agents.get(name)!;
1563 return agent;
1566 #spaceOf(agent: AgentState): Space {
1567 return this.#spaces.get(agent.space)!;
1570 #namedSpaceOf(agent: AgentState): Space {
1571 if (agent.space === SHARED) {
1572 throw new ProjectError("bad-request", `${agent.name} works in shared, not a named draft; switch to one first`);
1574 return this.#spaceOf(agent);
1577 // History reads (#41), in history.ts behind HistoryHost (#46, disk-first 1) ------------------------
1579 #host?: HistoryHost;
1580 /** The project as the history reads see it: the seam the derived tables plug into (abso issues 48, 79). */
1581 get #history(): HistoryHost {
1582 this.#host ??= {
1583 graph: this.#graph,
1584 agents: this.#agents,
1585 spaces: this.#spaces,
1586 needInit: () => this.#needInit(),
1587 spaceNamed: (name) => this.#spaceNamed(name),
1588 checkVersion: (space, version) => this.#checkVersion(space, version),
1589 viewAt: (space, version) => this.#viewAt(space, version),
1590 agentView: (agent) => this.#agentView(agent as AgentState),
1591 spellingIn: (view, asked) => this.spellingIn(view, asked),
1592 pathsOf: (space) => this.#paths.pathsOf(space),
1593 lastChange: (space, version) => this.#paths.lastChange(space, version),
1594 atOrBefore: (list, version) => PathIndex.atOrBefore(list, version),
1595 removedIn: (space, from, to, line) => this.#paths.removedIn(space, from, to, line),
1596 };
1597 return this.#host;
1600 /** One folder at a version (history.ts). */
1601 tree(...args: Tail<Parameters<typeof historyTree>>): ReturnType<typeof historyTree> {
1602 return historyTree(this.#history, ...args);
1605 /** A path's life at a version (history.ts). */
1606 pathLife(...args: Tail<Parameters<typeof historyPathLife>>): ReturnType<typeof historyPathLife> {
1607 return historyPathLife(this.#history, ...args);
1610 /** Where lines went after a version (history.ts). */
1611 follow(...args: Tail<Parameters<typeof historyFollow>>): ReturnType<typeof historyFollow> {
1612 return historyFollow(this.#history, ...args);
1615 // The version list (log, ribbon, show), in version-log.ts behind LogHost ----------------------------
1617 #logs?: LogHost;
1618 get #logHost(): LogHost {
1619 this.#logs ??= {
1620 graph: this.#graph,
1621 paths: this.#paths,
1622 labels: this.#labels,
1623 shared: () => this.#shared,
1624 needInit: () => this.#needInit(),
1625 spaceFor: (options) => this.#spaceFor(options),
1626 checkVersion: (space, version) => this.#checkVersion(space, version),
1627 viewAt: (space, version) => this.#viewAt(space, version),
1628 view: (set) => this.#view(set),
1629 at: (space, version) => this.#at(space, version),
1630 spellingIn: (view, path) => this.spellingIn(view, path),
1631 versionChange: (space, version) =>
1632 this.#versionChange.get(`${space.name === SHARED ? "" : space.name} ${version}`),
1633 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
1634 };
1635 return this.#logs;
1638 /** The versions of shared (or of a named draft), newest first (version-log.ts). */
1639 log(...args: Tail<Parameters<typeof versionLog>>): ReturnType<typeof versionLog> {
1640 return versionLog(this.#logHost, ...args);
1643 /** Shared's versions in one small answer, for the website's version ribbon (version-log.ts). */
1644 ribbon(): ReturnType<typeof versionRibbon> {
1645 return versionRibbon(this.#logHost);
1648 /** One version of shared (or of a named draft) and the files it changed (version-log.ts). */
1649 show(...args: Tail<Parameters<typeof versionShow>>): ReturnType<typeof versionShow> {
1650 return versionShow(this.#logHost, ...args);
1653 /** A file as it was at a version of shared (or a named draft) (version-log.ts). */
1654 fileAt(...args: Tail<Parameters<typeof versionFileAt>>): ReturnType<typeof versionFileAt> {
1655 return versionFileAt(this.#logHost, ...args);
1658 /** Every file that differs between two versions of shared (or a named draft) (version-log.ts). */
1659 compare(...args: Tail<Parameters<typeof versionCompare>>): ReturnType<typeof versionCompare> {
1660 return versionCompare(this.#logHost, ...args);
1663 /** A version of shared (or of a named draft) as a ReadView (version-log.ts). */
1664 viewAt(...args: Tail<Parameters<typeof versionViewAt>>): ReturnType<typeof versionViewAt> {
1665 return versionViewAt(this.#logHost, ...args);
1668 // Whether agents' drafts would collide, in draft-collisions.ts behind DraftCollisionHost -------------
1670 #draftCollisionHost?: DraftCollisionHost;
1671 get #draftCollisions(): DraftCollisionHost {
1672 this.#draftCollisionHost ??= {
1673 graph: this.#graph,
1674 agents: this.#agents,
1675 needInit: () => this.#needInit(),
1676 shared: () => this.#shared,
1677 sharedView: () => this.#sharedView(),
1678 definitionRule: () => this.#definitionRule,
1679 draft: (agent) => this.#draft(agent as AgentState),
1680 agentView: (agent) => this.#agentView(agent as AgentState),
1681 view: (set) => this.#view(set),
1682 pairs: (draft, against, settled) => this.#pairs(draft, against, settled),
1683 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
1684 };
1685 return this.#draftCollisionHost;
1688 /** Whether agents' unpublished changes would collide, by the publish rule (draft-collisions.ts). */
1689 collisions(...args: Tail<Parameters<typeof draftCollisions>>): ReturnType<typeof draftCollisions> {
1690 return draftCollisions(this.#draftCollisions, ...args);
1693 // An agent's unpublished changes, in draft-diff.ts behind DraftDiffHost -----------------------------
1695 #draftDiffHost?: DraftDiffHost;
1696 get #draftDiff(): DraftDiffHost {
1697 this.#draftDiffHost ??= {
1698 agents: this.#agents,
1699 needInit: () => this.#needInit(),
1700 draft: (agent) => this.#draft(agent as AgentState),
1701 agentView: (agent) => this.#agentView(agent as AgentState),
1702 view: (set) => this.#view(set),
1703 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
1704 };
1705 return this.#draftDiffHost;
1708 /** What the agent's unpublished changes do, file by file (draft-diff.ts). Creates the agent if needed. */
1709 diff(agentName: string): DiffAnswer {
1710 const entries: Entry[] = [];
1711 const answer = diffOfAgent(this.#draftDiff, this.#agent(agentName, entries));
1712 this.#flush(entries);
1713 return answer;
1716 /** An agent's draft diff for a reader: never creates the agent, never writes (draft-diff.ts). */
1717 diffOf(...args: Tail<Parameters<typeof draftDiffOf>>): ReturnType<typeof draftDiffOf> {
1718 return draftDiffOf(this.#draftDiff, ...args);
1721 // Unpublished deletes-and-writes of the same text become a move (express-moves.ts) -----------------
1723 #movesHost?: ExpressMovesHost;
1724 get #expressMovesHost(): ExpressMovesHost {
1725 this.#movesHost ??= {
1726 graph: this.#graph,
1727 draft: (agent) => this.#unqueuedDraft(agent),
1728 beforeDraft: (agent, draft) => {
1729 const base = this.#at(this.#spaceOf(agent), agent.base);
1730 if (draft.some((id) => base.has(id)))
1731 return this.#view(differenceSet(this.#agentView(agent).set, new StableOverlaySet(draft)));
1732 const removed = new Set(draft),
1733 kept = agent.mine.filter((id) => !removed.has(id));
1734 return kept.length === 0
1735 ? this.#viewAt(this.#spaceOf(agent), agent.base)
1736 : this.#viewKeyed(`a ${agent.space}@${agent.base}+${kept.join(",")}`, () => unionOverlay(base, kept));
1737 },
1738 agentView: (agent) => this.#agentView(agent),
1739 view: (set) => this.#view(set),
1740 apply: (entry) => this.#apply(entry),
1741 addDraft: (agent, view, input, time, meta, entries) => this.#addDraft(agent, view, input, time, meta, entries),
1742 recordFile: (agent, view, path, text, time, meta, entries, mode) =>
1743 this.#recordFile(agent, view, path, text, time, meta, entries, mode),
1744 };
1745 return this.#movesHost;
1748 // Files kept whole, in whole-files.ts behind WholeHost ----------------------------------------------
1750 #wholes?: WholeHost;
1751 get #wholeHost(): WholeHost {
1752 this.#wholes ??= {
1753 initialized: () => this.initialized,
1754 sharedView: () => this.#sharedView(),
1755 whole: this.#whole,
1756 };
1757 return this.#wholes;
1760 // Notes list and start notes, in notes.ts behind NoteHost -------------------------------------------
1762 #news?: NewsHost;
1763 get #newsHost(): NewsHost {
1764 this.#news ??= {
1765 graph: this.#graph,
1766 agents: this.#agents,
1767 draft: (agent) => this.#draft(agent),
1768 newerFor: (agent) => this.#newerFor(agent),
1769 spaceOf: (agent) => this.#spaceOf(agent),
1770 setOf: (space) => this.#setOf(space),
1771 viewAt: (space, version) => this.#viewAt(space, version),
1772 origin: (atom, spaceName) => this.#origin(atom, spaceName),
1773 collision: (agent, pair) => this.#collision(agent, pair),
1774 definitionCollisions: (agent, newer) => this.#definitionCollisions(agent, newer),
1775 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
1776 };
1777 return this.#news;
1780 #collisions?: CollisionHost;
1781 get #collisionHost(): CollisionHost {
1782 this.#collisions ??= {
1783 graph: this.#graph,
1784 spaces: this.#spaces,
1785 version: () => this.version,
1786 spaceOf: (agent) => this.#spaceOf(agent),
1787 agentSet: (agent) => unionOverlay(this.#at(this.#spaceOf(agent), agent.base), agent.mine),
1788 draft: (agent) => this.#draft(agent),
1789 agentView: (agent) => this.#agentView(agent),
1790 at: (space, version) => this.#at(space, version),
1791 shared: () => this.#shared,
1792 };
1793 return this.#collisions;
1796 #markers?: MarkerHost;
1797 get #markerHost(): MarkerHost {
1798 this.#markers ??= {
1799 graph: this.#graph,
1800 agentView: (agent) => this.#agentView(agent),
1801 draft: (agent) => this.#draft(agent),
1802 draftFiles: (agent) => this.#draftFiles(agent),
1803 };
1804 return this.#markers;
1807 #noteWrites?: NoteWriteHost;
1808 get #noteWriteHost(): NoteWriteHost {
1809 this.#noteWrites ??= {
1810 notes: this.#notes,
1811 agents: this.#agents,
1812 changes: this.#changes,
1813 graph: this.#graph,
1814 lastNote: () => this.#lastNote,
1815 agentView: (agent) => this.#agentView(agent),
1816 viewAtVersion: (version) => this.viewAt(version),
1817 sharedView: () => this.#sharedView(),
1818 changeOfLines: (lines) => this.#changeOfLines(lines),
1819 apply: (entry) => this.#apply(entry),
1820 flush: (entries) => this.#flush(entries),
1821 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
1822 noteAnswer: (n) => this.#noteAnswer(n),
1823 };
1824 return this.#noteWrites;
1827 #noteHost?: NoteHost;
1828 get #notesHost(): NoteHost {
1829 this.#noteHost ??= {
1830 graph: this.#graph,
1831 agents: this.#agents,
1832 spaces: this.#spaces,
1833 notes: this.#notes,
1834 initialized: () => this.initialized,
1835 shared: () => this.#shared,
1836 sharedView: () => this.#sharedView(),
1837 spellingIn: (view, path) => this.spellingIn(view, path),
1838 viewAt: (space, version) => this.#viewAt(space, version),
1839 agentView: (agent) => this.#agentView(agent),
1840 view: (set) => this.#view(set),
1841 at: (space, version) => this.#at(space, version),
1842 liveNote: (agent) => this.#liveNote(agent),
1843 };
1844 return this.#noteHost;
1847 #merges?: MergeHost;
1848 get #mergeHost(): MergeHost {
1849 this.#merges ??= {
1850 graph: this.#graph,
1851 openPairs: (agent) => this.#openPairs(agent),
1852 draft: (agent) => this.#unqueuedDraft(agent),
1853 origin: (atom, spaceName) => this.#origin(atom, spaceName),
1854 view: (set) => this.#view(set),
1855 viewAt: (space, version) => this.#viewAt(space, version),
1856 spaceOf: (agent) => this.#spaceOf(agent),
1857 apply: (entry) => this.#apply(entry),
1858 agentView: (agent) => this.#agentView(agent),
1859 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
1860 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
1861 };
1862 return this.#merges;
1865 #edits?: EditHost;
1866 get #editHost(): EditHost {
1867 this.#edits ??= {
1868 agents: this.#agents,
1869 whole: this.#whole,
1870 initialized: () => this.initialized,
1871 agentView: (agent) => this.#agentView(agent),
1872 sharedView: () => this.#sharedView(),
1873 isWhole: (path, length, view, rules) => this.#isWhole(path, length, view, rules),
1874 wholeRules: (config) => this.#wholeRules(config),
1875 record: (agentName, files, time, modes, blobs, meta) => this.record(agentName, files, time, modes, blobs, meta),
1876 agent: (name, entries) => this.#agent(name, entries),
1877 draftFiles: (agent) => this.#draftFiles(agent),
1878 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
1879 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
1880 addDraft: (agent, view, input, time, meta, entries) => this.#addDraft(agent, view, input, time, meta, entries),
1881 overlapNews: (agent, before, entries) => this.#overlapNews(agent, before, entries),
1882 markedNews: (agent, files, entries) => this.#markedNews(agent, files, entries),
1883 newsAboutOwnDraft: (agent, entries) => this.#newsAboutOwnDraft(agent, entries),
1884 takeNews: (agent, entries) => this.#takeNews(agent, entries),
1885 flush: (entries) => this.#flush(entries),
1886 };
1887 return this.#edits;
1890 #announces?: AnnounceHost;
1891 get #announceHost(): AnnounceHost {
1892 this.#announces ??= {
1893 agents: this.#agents,
1894 announced: () => this.#announced,
1895 setAnnounced: (n) => {
1896 this.#announced = n;
1897 },
1898 agent: (name, entries) => this.#agent(name, entries),
1899 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
1900 apply: (entry) => this.#apply(entry),
1901 flush: (entries) => this.#flush(entries),
1902 needInit: () => this.#needInit(),
1903 };
1904 return this.#announces;
1907 #publishers?: PublishHost;
1908 get #publishHost(): PublishHost {
1909 this.#publishers ??= {
1910 agents: this.#agents,
1911 nextAt: () => this.#nextAt,
1912 checkClash: (changes, ahead) => this.#checkClash(changes, ahead),
1913 queueOn: () => this.#queueOn(),
1914 queuedAtoms: (except) => this.#queuedAtoms(except),
1915 agent: (name, entries) => this.#agent(name, entries),
1916 draft: (agent) => this.#draft(agent),
1917 spaceOf: (agent) => this.#spaceOf(agent),
1918 strandedFiles: (draft, set) => this.#strandedFiles(draft, set),
1919 setOf: (space) => this.#setOf(space),
1920 markedFiles: (agent) => this.#markedFiles(agent),
1921 agentView: (agent) => this.#agentView(agent),
1922 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
1923 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
1924 expressMoves: (agent, time, entries) => this.#expressMoves(agent, time, entries),
1925 pairs: (draft, against, settled) => this.#pairs(draft, against, settled),
1926 collision: (agent, pair) => this.#collision(agent, pair),
1927 definitionCollisions: (agent, newer) => this.#definitionCollisions(agent, newer),
1928 duplicates: (agent) => this.#duplicates(agent),
1929 refuse: (agent, space, via, time, collisions, entries) =>
1930 this.#refuse(agent, space, via, time, collisions, entries),
1931 markerCollisions: (agent) => this.#markerCollisions(agent),
1932 enqueue: (agent, message, time, draft, resolves, entries) =>
1933 this.#enqueue(agent, message, time, draft, resolves, entries),
1934 view: (set) => this.#view(set),
1935 requireClosed: (tie, union) => this.#requireClosed(tie, union),
1936 spaceOverlay: (space, atoms) =>
1937 this.#viewKeyed(`a ${space.name}@${last(space)}+${atoms.join(",")}`, () =>
1938 unionOverlay(this.#setOf(space), atoms),
1939 ),
1940 newerFor: (agent) => this.#newerFor(agent),
1941 currentChange: (agent, time) => this.#currentChange(agent, time),
1942 apply: (entry) => this.#apply(entry),
1943 newsForOthers: (publisher, space, version, entries) => this.#newsForOthers(publisher, space, version, entries),
1944 settledNews: (agent, version, settled, entries) => this.#settledNews(agent, version, settled, entries),
1945 addressedNews: (agent, version, entries) => this.#addressedNews(agent, version, entries),
1946 reviewNews: (agent, version, entries) => this.#reviewNews(agent, version, entries),
1947 flush: (entries) => this.#flush(entries),
1948 };
1949 return this.#publishers;
1952 #queues?: QueueHost;
1953 get #queueHost(): QueueHost {
1954 this.#queues ??= {
1955 graph: this.#graph,
1956 checkerReady: () => this.checkerReady,
1957 sharedView: () => this.#sharedView(),
1958 queued: () => this.#queue,
1959 queuedId: () => this.#queuedId,
1960 checkingHas: (id) => this.#checking.has(id),
1961 replaceChecking: (ids) => {
1962 this.#checking = new Set(ids);
1963 },
1964 uncheck: (id) => {
1965 this.#checking.delete(id);
1966 },
1967 needInit: () => this.#needInit(),
1968 shared: () => this.#shared,
1969 setOf: (space) => this.#setOf(space),
1970 view: (set) => this.#view(set),
1971 agentSet: (agent) => this.#agentSet(agent),
1972 agentView: (agent) => this.#agentView(agent),
1973 pairs: (draft, against, settled) => this.#pairs(draft, against, settled),
1974 describe: (pair, yoursView, theirsView, spaceName) => this.#describe(pair, yoursView, theirsView, spaceName),
1975 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
1976 refuse: (agent, space, via, time, collisions, entries) =>
1977 this.#refuse(agent, space, via, time, collisions, entries),
1978 currentChange: (agent, time) => this.#currentChange(agent, time),
1979 nextAt: () => this.#nextAt,
1980 apply: (entry) => this.#apply(entry),
1981 agentOf: (name) => this.#agentOf(name),
1982 requireClosed: (tie, union) => this.#requireClosed(tie, union),
1983 newsForOthers: (publisher, space, version, entries) => this.#newsForOthers(publisher, space, version, entries),
1984 settledNews: (agent, version, settled, entries) => this.#settledNews(agent, version, settled, entries),
1985 addressedNews: (agent, version, entries) => this.#addressedNews(agent, version, entries),
1986 reviewNews: (agent, version, entries) => this.#reviewNews(agent, version, entries),
1987 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
1988 flush: (entries) => this.#flush(entries),
1989 };
1990 return this.#queues;
1993 #applyEntries?: ApplyEntryHost;
1994 get #applyEntryHost(): ApplyEntryHost {
1995 this.#applyEntries ??= {
1996 graph: this.#graph,
1997 agents: this.#agents,
1998 atomAt: this.#atomAt,
1999 mods: this.#mods,
2000 notes: this.#notes,
2001 changes: this.#changes,
2002 labels: this.#labels,
2003 refusals: this.#refusals,
2004 tells: this.#tells,
2005 uncheck: (id) => {
2006 this.#checking.delete(id);
2007 },
2008 stamp: (t) => {
2009 if (typeof t === "number" && t > this.#lastTime) this.#lastTime = t;
2010 },
2011 applyMembership: (entry, at) => this.#membership.apply(entry, at),
2012 agentOf: (name) => this.#agentOf(name),
2013 active: (agent, time) => this.#active(agent, time),
2014 joinChange: (agent, entry, at, draft, landed) => this.#joinChange(agent, entry, at, draft, landed),
2015 space: (name) => this.#spaces.get(name)!,
2016 queued: () => this.#queue,
2017 setQueued: (items) => {
2018 this.#queue = items;
2019 },
2020 setQueuedId: (id) => {
2021 this.#queuedId = id;
2022 },
2023 queuedId: () => this.#queuedId,
2024 setLastNote: (id) => {
2025 this.#lastNote = id;
2026 },
2027 lastNote: () => this.#lastNote,
2028 setAnnounced: (n) => {
2029 this.#announced = n;
2030 },
2031 announced: () => this.#announced,
2032 at: (space, version) => this.#at(space, version),
2033 spaceOf: (agent) => this.#spaceOf(agent),
2034 draft: (agent) => this.#draft(agent),
2035 currentChange: (agent, time) => this.#currentChange(agent, time),
2036 changeRecord: (id, agent, time) => this.#changeRecord(id, agent, time),
2037 };
2038 return this.#applyEntries;
2041 #landers?: LandHost;
2042 get #landHost(): LandHost {
2043 this.#landers ??= {
2044 agents: this.#agents,
2045 graph: this.#graph,
2046 spaces: this.#spaces,
2047 version: () => this.version,
2048 nextAt: () => this.#nextAt,
2049 notQueuedYet: (what) => this.#notQueuedYet(what),
2050 checkClash: (changes) => this.#checkClash(changes),
2051 agent: (name, entries) => this.#agent(name, entries),
2052 namedSpaceOf: (agent) => this.#namedSpaceOf(agent),
2053 shared: () => this.#shared,
2054 setOf: (space) => this.#setOf(space),
2055 at: (space, version) => this.#at(space, version),
2056 view: (set) => this.#view(set),
2057 sharedView: () => this.#sharedView(),
2058 pairs: (draft, against, settled) => this.#pairs(draft, against, settled),
2059 describe: (pair, yoursView, theirsView, spaceName) => this.#describe(pair, yoursView, theirsView, spaceName),
2060 definitionRule: () => this.#definitionRule,
2061 refuse: (agent, space, via, time, collisions, entries) =>
2062 this.#refuse(agent, space, via, time, collisions, entries),
2063 requireClosed: (tie, union) => this.#requireClosed(tie, union),
2064 apply: (entry) => this.#apply(entry),
2065 newsForOthers: (publisher, space, version, entries) => this.#newsForOthers(publisher, space, version, entries),
2066 addressedNews: (agent, version, entries) => this.#addressedNews(agent, version, entries),
2067 reviewNews: (agent, version, entries) => this.#reviewNews(agent, version, entries),
2068 flush: (entries) => this.#flush(entries),
2069 };
2070 return this.#landers;
2073 #records?: RecordHost;
2074 get #recordHost(): RecordHost {
2075 this.#records ??= {
2076 agents: this.#agents,
2077 whole: this.#whole,
2078 initialized: () => this.initialized,
2079 agentView: (agent) => this.#agentView(agent),
2080 sharedView: () => this.#sharedView(),
2081 wholeOut: (files, blobs, view, config) => this.#wholeOut(files, blobs, view, config),
2082 checkBlobs: (blobs, files) => this.#checkBlobs(blobs, files),
2083 agent: (name, entries) => this.#agent(name, entries),
2084 draftFiles: (agent) => this.#draftFiles(agent),
2085 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
2086 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
2087 overlapNews: (agent, before, entries) => this.#overlapNews(agent, before, entries),
2088 markedNews: (agent, files, entries) => this.#markedNews(agent, files, entries),
2089 newsAboutOwnDraft: (agent, entries) => this.#newsAboutOwnDraft(agent, entries),
2090 takeNews: (agent, entries) => this.#takeNews(agent, entries),
2091 flush: (entries) => this.#flush(entries),
2092 };
2093 return this.#records;
2096 #restores?: RestoreHost;
2097 get #restoreHost(): RestoreHost {
2098 this.#restores ??= {
2099 graph: this.#graph,
2100 agent: (name, entries) => this.#agent(name, entries),
2101 draft: (agent) => this.#unqueuedDraft(agent),
2102 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
2103 apply: (entry) => this.#apply(entry),
2104 view: (set) => this.#view(set),
2105 agentSet: (agent) => this.#agentSet(agent),
2106 agentView: (agent) => this.#agentView(agent),
2107 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
2108 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
2109 flush: (entries) => this.#flush(entries),
2110 };
2111 return this.#restores;
2114 #startings?: StartingHost;
2115 get #startingHost(): StartingHost {
2116 this.#startings ??= {
2117 agents: this.#agents,
2118 changes: this.#changes,
2119 agent: (name, entries) => this.#agent(name, entries),
2120 liveNote: (agent) => this.#liveNote(agent),
2121 apply: (entry) => this.#apply(entry),
2122 overlaps: (agent, patterns) => this.#overlaps(agent, patterns),
2123 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
2124 flush: (entries) => this.#flush(entries),
2125 };
2126 return this.#startings;
2129 #syncs?: SyncHost;
2130 get #syncHost(): SyncHost {
2131 this.#syncs ??= {
2132 graph: this.#graph,
2133 labels: this.#labels,
2134 agent: (name, entries) => this.#agent(name, entries),
2135 spaceOf: (agent) => this.#spaceOf(agent),
2136 agentView: (agent) => this.#agentView(agent),
2137 at: (space, version) => this.#at(space, version),
2138 draft: (agent) => this.#draft(agent),
2139 strandedFiles: (draft, set) => this.#strandedFiles(draft, set),
2140 apply: (entry) => this.#apply(entry),
2141 flush: (entries) => this.#flush(entries),
2142 mergeIdentical: (agent, before, oldBase, oldVersion, time, entries) =>
2143 this.#mergeIdentical(agent, before, oldBase, oldVersion, time, entries),
2144 changesSince: (agent, before) => this.#changesSince(agent, before),
2145 };
2146 return this.#syncs;
2149 #moves?: MoveHost;
2150 get #moveHost(): MoveHost {
2151 this.#moves ??= {
2152 needInit: () => this.#needInit(),
2153 agents: this.#agents,
2154 agentView: (agent) => this.#agentView(agent),
2155 sharedView: () => this.#sharedView(),
2156 agent: (name, entries) => this.#agent(name, entries),
2157 addDraft: (agent, view, input, time, meta, entries) => this.#addDraft(agent, view, input, time, meta, entries),
2158 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
2159 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
2160 newsAboutOwnDraft: (agent, entries) => this.#newsAboutOwnDraft(agent, entries),
2161 takeNews: (agent, entries) => this.#takeNews(agent, entries),
2162 flush: (entries) => this.#flush(entries),
2163 };
2164 return this.#moves;
2167 #switches?: SwitchHost;
2168 get #switchHost(): SwitchHost {
2169 this.#switches ??= {
2170 agent: (name, entries) => this.#agent(name, entries),
2171 flush: (entries) => this.#flush(entries),
2172 spaces: this.#spaces,
2173 agentView: (agent) => this.#agentView(agent),
2174 graph: this.#graph,
2175 version: () => this.version,
2176 apply: (entry) => this.#apply(entry),
2177 draft: (agent) => this.#draft(agent),
2178 setOf: (space) => this.#setOf(space),
2179 changesSince: (agent, before) => this.#changesSince(agent, before),
2180 };
2181 return this.#switches;
2184 #draftStates?: DraftStateHost;
2185 get #draftStateHost(): DraftStateHost {
2186 this.#draftStates ??= {
2187 needInit: () => this.#needInit(),
2188 spaceNamed: (name) => this.#spaceNamed(name),
2189 shared: () => this.#shared,
2190 graph: this.#graph,
2191 agents: this.#agents,
2192 draft: (agent) => this.#draft(agent),
2193 checkClash: (changes) => this.#checkClash(changes),
2194 landCollisions: (space, changes, pick) => this.#landCollisions(space, changes, pick),
2195 };
2196 return this.#draftStates;
2199 #checkClashes?: CheckClashHost;
2200 get #checkClashHost(): CheckClashHost {
2201 this.#checkClashes ??= {
2202 shared: () => this.#shared,
2203 setOf: (space) => this.#setOf(space),
2204 view: (set) => this.#view(set),
2205 sharedView: () => this.#sharedView(),
2206 sharedOverlay: (atoms) =>
2207 this.#viewKeyed(`a @${last(this.#shared)}+${atoms.join(",")}`, () =>
2208 unionOverlay(this.#setOf(this.#shared), atoms),
2209 ),
2210 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
2211 };
2212 return this.#checkClashes;
2215 #changesSinces?: ChangesSinceHost;
2216 get #changesSinceHost(): ChangesSinceHost {
2217 this.#changesSinces ??= {
2218 agentView: (agent) => this.#agentView(agent),
2219 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
2220 openPairs: (agent) => this.#openPairs(agent),
2221 collision: (agent, pair) => this.#collision(agent, pair),
2222 duplicates: (agent) => this.#duplicates(agent),
2223 markedCollisions: (agent) => this.#markedCollisions(agent),
2224 };
2225 return this.#changesSinces;
2228 #inits?: InitHost;
2229 get #initHost(): InitHost {
2230 this.#inits ??= {
2231 initialized: () => this.initialized,
2232 whole: this.#whole,
2233 wholeOut: (files, blobs, view, config) => this.#wholeOut(files, blobs, view, config),
2234 checkBlobs: (blobs, files) => this.#checkBlobs(blobs, files),
2235 commit: (entries) => this.#commit(entries),
2236 };
2237 return this.#inits;
2240 #amends?: AmendHost;
2241 get #amendHost(): AmendHost {
2242 this.#amends ??= {
2243 agent: (name, entries) => this.#agent(name, entries),
2244 spaceOf: (agent) => this.#spaceOf(agent),
2245 apply: (entry) => this.#apply(entry),
2246 flush: (entries) => this.#flush(entries),
2247 };
2248 return this.#amends;
2251 #labelHosts?: LabelHost;
2252 get #labelHost(): LabelHost {
2253 this.#labelHosts ??= {
2254 agent: (name, entries) => this.#agent(name, entries),
2255 version: () => this.version,
2256 labels: this.#labels,
2257 apply: (entry) => this.#apply(entry),
2258 flush: (entries) => this.#flush(entries),
2259 };
2260 return this.#labelHosts;
2263 #publishOfs?: PublishOfHost;
2264 get #publishOfHost(): PublishOfHost {
2265 this.#publishOfs ??= {
2266 shared: () => this.#shared,
2267 spaces: this.#spaces,
2268 };
2269 return this.#publishOfs;
2272 #versionMetas?: VersionMetaHost;
2273 get #versionMetaHost(): VersionMetaHost {
2274 this.#versionMetas ??= {
2275 needInit: () => this.#needInit(),
2276 spaceNamed: (name) => this.#spaceNamed(name),
2277 };
2278 return this.#versionMetas;
2281 #refuses?: RefuseHost;
2282 get #refuseHost(): RefuseHost {
2283 this.#refuses ??= {
2284 apply: (entry) => this.#apply(entry),
2285 refusals: this.#refusals,
2286 };
2287 return this.#refuses;
2290 #overlapsHost?: OverlapHost;
2291 get #overlapHost(): OverlapHost {
2292 this.#overlapsHost ??= {
2293 graph: this.#graph,
2294 agents: this.#agents,
2295 agentView: (agent) => this.#agentView(agent),
2296 draft: (agent) => this.#draft(agent),
2297 draftFiles: (agent) => this.#draftFiles(agent),
2298 liveNote: (agent) => this.#liveNote(agent),
2299 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
2300 };
2301 return this.#overlapsHost;
2304 #recordFiles?: RecordFileHost;
2305 get #recordFileHost(): RecordFileHost {
2306 this.#recordFiles ??= {
2307 addDraft: (agent, view, input, time, meta, entries) => this.#addDraft(agent, view, input, time, meta, entries),
2308 };
2309 return this.#recordFiles;
2312 #addDrafts?: AddDraftHost;
2313 get #addDraftHost(): AddDraftHost {
2314 this.#addDrafts ??= {
2315 graph: this.#graph,
2316 openPairs: (agent) => this.#openPairs(agent),
2317 markersSettled: (agent, view, atom) => this.#markersSettled(agent, view, atom),
2318 apply: (entry) => this.#apply(entry),
2319 };
2320 return this.#addDrafts;
2323 #ingests?: IngestHost;
2324 get #ingestHost(): IngestHost {
2325 this.#ingests ??= {
2326 agents: this.#agents,
2327 spaces: this.#spaces,
2328 needInit: () => this.#needInit(),
2329 version: () => this.version,
2330 checkBlobs: (blobs, files) => this.#checkBlobs(blobs, files),
2331 apply: (entry) => this.#apply(entry),
2332 flush: (entries) => this.#flush(entries),
2333 wholeOut: (files, blobs, view, config) => this.#wholeOut(files, blobs, view, config),
2334 agentView: (agent) => this.#agentView(agent),
2335 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
2336 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
2337 publish: (agent, message, time, entries, asIs, direct) =>
2338 this.#publish(agent, message, time, entries, asIs, direct),
2339 land: (agent, message, time, entries, pick) => this.#land(agent, message, time, entries, pick),
2340 };
2341 return this.#ingests;
2344 #plucks?: PluckHost;
2345 get #pluckHost(): PluckHost {
2346 this.#plucks ??= {
2347 graph: this.#graph,
2348 spaces: this.#spaces,
2349 agent: (name, entries) => this.#agent(name, entries),
2350 shared: () => this.#shared,
2351 notQueuedYet: (what) => this.#notQueuedYet(what),
2352 strandedFiles: (draft, set) => this.#strandedFiles(draft, set),
2353 checkClash: (changes) => this.#checkClash(changes),
2354 land: (agent, message, time, entries, pick) => this.#land(agent, message, time, entries, pick),
2355 flush: (entries) => this.#flush(entries),
2356 };
2357 return this.#plucks;
2360 #drops?: DropHost;
2361 get #dropHost(): DropHost {
2362 this.#drops ??= {
2363 graph: this.#graph,
2364 agents: this.#agents,
2365 spaces: this.#spaces,
2366 agent: (name, entries) => this.#agent(name, entries),
2367 shared: () => this.#shared,
2368 flush: (entries) => this.#flush(entries),
2369 apply: (entry) => this.#apply(entry),
2370 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
2371 addressedNews: (agent, version, entries) => this.#addressedNews(agent, version, entries),
2372 };
2373 return this.#drops;
2376 // Changes (#44), in change-records.ts behind ChangeHost ---------------------------------------------
2378 #changeRecords?: ChangeHost;
2379 get #changeHost(): ChangeHost {
2380 this.#changeRecords ??= {
2381 changes: this.#changes,
2382 agents: this.#agents,
2383 spaces: this.#spaces,
2384 notes: this.#notes,
2385 versionChange: this.#versionChange,
2386 paths: this.#paths,
2387 graph: this.#graph,
2388 stored: () => this.#stored,
2389 shared: () => this.#shared,
2390 queue: () => this.#queue,
2391 active: (agent, time) => this.#active(agent, time),
2392 currentChange: (agent, time) => this.#currentChange(agent, time),
2393 liveNote: (agent) => this.#liveNote(agent),
2394 noteAnswer: (n) => this.#noteAnswer(n),
2395 reviewersOf: (files, id) => this.#reviewersOf(files, id),
2396 };
2397 return this.#changeRecords;
2400 // What the project looks like now, in project-status.ts behind SnapshotHost -------------------------
2402 #snapshotHost?: SnapshotHost;
2403 get #snapshot(): SnapshotHost {
2404 this.#snapshotHost ??= {
2405 agents: this.#agents,
2406 spaces: this.#spaces,
2407 queue: () => this.#queue,
2408 refusals: this.#refusals,
2409 labels: this.#labels,
2410 tells: this.#tells,
2411 needInit: () => this.#needInit(),
2412 shared: () => this.#shared,
2413 draft: (agent) => this.#draft(agent),
2414 draftFiles: (agent) => this.#draftFiles(agent),
2415 liveNote: (agent) => this.#liveNote(agent),
2416 openCollisions: (agent) => this.#openCollisions(agent),
2417 editsOf: (agent) => this.#editsOf(agent),
2418 setOf: (space) => this.#setOf(space),
2419 spaceNamed: (name) => this.#spaceNamed(name),
2420 checkVersion: (space, version) => this.#checkVersion(space, version),
2421 viewAt: (space, version) => this.#viewAt(space, version),
2422 agentView: (agent) => this.#agentView(agent),
2423 version: () => this.version,
2424 projectFile: () => (this.initialized ? projectFileIn(this.#sharedView()) : undefined),
2425 };
2426 return this.#snapshotHost;
2429 /** The paths in an agent's view now (project-status.ts). */
2430 agentPaths(...args: Tail<Parameters<typeof snapshotAgentPaths>>): ReturnType<typeof snapshotAgentPaths> {
2431 return snapshotAgentPaths(this.#snapshot, ...args);
2434 /** The paths in shared, or a named draft, at a version (project-status.ts). */
2435 pathsAt(...args: Tail<Parameters<typeof snapshotPathsAt>>): ReturnType<typeof snapshotPathsAt> {
2436 return snapshotPathsAt(this.#snapshot, ...args);
2439 /** The paths in an agent's view now, for a reader (project-status.ts). */
2440 pathsOf(...args: Tail<Parameters<typeof snapshotPathsOf>>): ReturnType<typeof snapshotPathsOf> {
2441 return snapshotPathsOf(this.#snapshot, ...args);
2444 /** Every label, with the versions it marks, newest first (project-status.ts). */
2445 labels(): ReturnType<typeof snapshotLabels> {
2446 return snapshotLabels(this.#snapshot);
2449 /** Agents, drafts, refusals and waiting announcements (project-status.ts). */
2450 status(): ReturnType<typeof snapshotStatus> {
2451 return snapshotStatus(this.#snapshot);
2454 /** The operation fence needs one actor's heads, not every agent's file projection. */
2455 actorHead(name: string): { base: number; draftChanges: number; draft: string | null } | undefined {
2456 const agent = this.#agents.get(name);
2457 if (!agent) return undefined;
2458 const published = this.#setOf(this.#spaceOf(agent));
2459 let draftChanges = 0;
2460 for (const id of agent.mine) if (!published.has(id)) draftChanges++;
2461 return { base: agent.base, draftChanges, draft: agent.space === SHARED ? null : agent.space };
2464 /** A space's contents at one of its versions. */
2465 #at(space: Space, version: number): ReadonlySet<AtomId> {
2466 return this.#membership.at(space, version);
2469 /** A space's contents now. */
2470 #setOf(space: Space): ReadonlySet<AtomId> {
2471 return this.#at(space, last(space));
2474 #draft(agent: AgentState): AtomId[] {
2475 const set = this.#setOf(this.#spaceOf(agent));
2476 return agent.mine.filter((id) => !set.has(id));
2479 /**
2480 * The draft without the agent's publishes waiting in the queue (#39): what
2481 * moves, restore and sync's merge may drop and make again. A queued item's
2482 * atoms are no longer the draft's to remake; dropping them let the queue
2483 * land a tie that depends on discarded atoms (abso issue 135, item 4).
2484 * Undoing a queued publish is abso unqueue.
2485 */
2486 #unqueuedDraft(agent: AgentState): AtomId[] {
2487 const draft = this.#draft(agent);
2488 const held = this.#queuedAtoms();
2489 return held.size === 0 ? draft : draft.filter((id) => !held.has(id));
2492 #agentSet(agent: AgentState): Set<AtomId> {
2493 return new Set([...this.#at(this.#spaceOf(agent), agent.base), ...agent.mine]);
2496 #agentView(agent: AgentState): ReadView {
2497 return this.#viewKeyed(this.#agentViewKey(agent), () => {
2498 const base = this.#at(this.#spaceOf(agent), agent.base);
2499 return base instanceof StableSet
2500 ? new StableUnionSet(base, new StableOverlaySet(agent.mine))
2501 : new Set([...base, ...agent.mine]);
2502 });
2505 /** 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. */
2506 #agentViewKey(agent: AgentState): string {
2507 // An empty draft is exactly its published base. Share its projection
2508 // with version readers instead of walking the same history twice.
2509 if (agent.mine.length === 0) return `v ${agent.space}@${agent.base}`;
2510 return `a ${agent.space}@${agent.base}+${agent.mine.join(",")}`;
2513 /** A space at a version: published versions never change, so the key is just their names (#46). */
2514 #viewAt(space: Space, version: number): ReadView {
2515 return this.#viewKeyed(`v ${space.name}@${version}`, () => this.#at(space, version));
2518 #sharedView(): ReadView {
2519 return this.#viewAt(this.#shared, last(this.#shared));
2522 /** A view of a set, cached by the set's exact contents (views.ts). */
2523 #view(set: ReadonlySet<AtomId>): ReadView {
2524 this.#views.assertUnkeyedAllowed();
2525 return this.#views.view(this.#closed(set));
2528 /** A view cached under `key` (views.ts). */
2529 #viewKeyed(key: string, set: () => ReadonlySet<AtomId>): ReadView {
2530 return this.#views.keyed(key, () => this.#closed(set()));
2533 /**
2534 * A discarded atom that a later publish still depends on stays in the view
2535 * (abso issue 80). A closed set is unchanged.
2536 */
2537 #closed(set: Iterable<AtomId>): ReadonlySet<AtomId> {
2538 if (set instanceof StableSet) {
2539 // Keep indexed membership external. Only dependencies absent from
2540 // that snapshot belong in the operation's closure overlay.
2541 const missing = new Set<AtomId>();
2542 const visit = (id: AtomId) => {
2543 const stack = [id];
2544 while (stack.length) {
2545 for (const dependency of this.#graph.atom(stack.pop()!).deps) {
2546 if (!set.has(dependency) && !missing.has(dependency)) {
2547 missing.add(dependency);
2548 stack.push(dependency);
2552 };
2553 for (const id of set) visit(id);
2554 return missing.size ? new StableUnionSet(set, new StableOverlaySet(missing)) : set;
2556 return this.#graph.closureOf(set);
2559 /** A new publish or land must not depend on an atom outside the set (abso issue 80). */
2560 #requireClosed(tie: { deps: readonly AtomId[] }, union: ReadonlySet<AtomId>): void {
2561 const missing = tie.deps.filter((id) => !union.has(id));
2562 if (missing.length > 0)
2563 throw new ProjectError(
2564 "conflict",
2565 `this change depends on ${missing.join(", ")}, which is not in the set being pushed`,
2566 );
2569 /** The space's atoms published after the agent's base, by others. */
2570 #newerFor(agent: AgentState): ReadonlySet<AtomId> {
2571 const space = this.#spaceOf(agent);
2572 const base = this.#at(space, agent.base);
2573 const current = this.#setOf(space);
2574 const newer =
2575 space.name === SHARED && space.membershipVersion
2576 ? new SharedAdditions(space, agent.base, base, current)
2577 : differenceSet(current, base);
2578 return differenceSet(newer, new StableOverlaySet(agent.mine));
2581 /** The files whose text in the agent's view differs from `before`, and its open collisions. */
2582 #changesSince(...args: Tail<Parameters<typeof hostedChangesSince>>): ReturnType<typeof hostedChangesSince> {
2583 return hostedChangesSince(this.#changesSinceHost, ...args);
2586 /** Who published an atom, looking in the given space first and then in shared. */
2587 #origin(atom: AtomId, spaceName: string): Origin {
2588 return originOf(this.#collisionHost, atom, spaceName);
2591 // Drafting ----------------------------------------------------------------------
2593 /** Check a {path: sha256} map: hex hashes, no path also given as text, and bytes already uploaded. */
2594 #checkBlobs(blobs: unknown, files: object): Record<string, string> {
2595 if (typeof blobs !== "object" || blobs === null || Array.isArray(blobs))
2596 throw new ProjectError("bad-request", "blobs must be {path: sha256}");
2597 for (const [path, sha] of Object.entries(blobs as Record<string, unknown>)) {
2598 checkPath(path);
2599 if (typeof sha !== "string" || !/^[0-9a-f]{64}$/.test(sha))
2600 throw new ProjectError("bad-request", `${path}: a blob is the SHA-256 of the bytes, in lowercase hex`);
2601 if (Object.hasOwn(files, path)) throw new ProjectError("bad-request", `${path} is given as both text and a blob`);
2602 if (!this.#hasBlob(sha))
2603 throw new ProjectError("bad-request", `${path}: upload blob ${sha} first (PUT /p/:project/blobs/${sha})`);
2605 return blobs as Record<string, string>;
2608 /**
2609 * Make one file in the agent's view what the folder has, as one draft
2610 * change: `text` (null: the file is gone; "": an empty file; undefined:
2611 * leave its lines alone) and `mode` (only the fields given). Returns
2612 * whether anything changed.
2613 */
2614 #recordFile(...args: Tail<Parameters<typeof hostedRecordFile>>): ReturnType<typeof hostedRecordFile> {
2615 return hostedRecordFile(this.#recordFileHost, ...args);
2618 /**
2619 * Moves (#28). Within one agent's unpublished draft, a line that leaves one
2620 * place and the same text that arrives somewhere else is the same line, in
2621 * either order (deleted then written, or written then deleted). Before a
2622 * publish, the draft's changes to the files involved are dropped (a discard
2623 * entry) and made again: one move per matched block, which keeps the
2624 * lines' ids, then a change per file to the draft's final text. The files
2625 * end up exactly as the draft had them. A matched block needs a line with
2626 * real content: blank lines and lone brackets only travel next to one.
2627 */
2628 #expressMoves(agent: AgentState, time: number, entries: Entry[]): void {
2629 hostedExpressMoves(this.#expressMovesHost, agent, time, entries);
2632 /**
2633 * Build a draft change against the agent's view. If it touches lines on
2634 * either side of a collision the agent has already seen, it settles that
2635 * collision (the engine's `resolves`).
2636 */
2637 #addDraft(...args: Tail<Parameters<typeof hostedAddDraft>>): ReturnType<typeof hostedAddDraft> {
2638 return hostedAddDraft(this.#addDraftHost, ...args);
2641 // Collisions and news -------------------------------------------------------------
2643 #pairs(draft: readonly AtomId[], against: ReadonlySet<AtomId>, settled: ReadonlySet<AtomId>): Pair[] {
2644 return pairsIn(this.#graph, draft, against, settled);
2647 /**
2648 * Collisions the agent has synced into and not settled: its draft against
2649 * its space at its base. In a named draft, also the draft's own changes
2650 * against shared work the draft was moved onto.
2651 */
2652 #openPairs(agent: AgentState): Pair[] {
2653 return hostedOpenPairs(this.#collisionHost, agent);
2656 /** After the agent's own change: news when its draft now collides with work published after its base. */
2657 #newsAboutOwnDraft(agent: AgentState, entries: Entry[]): void {
2658 hostedNewsAboutOwnDraft(this.#newsHost, agent, entries);
2661 /** After a publish or a landing: news for every other agent in that space whose draft collides with what just arrived. */
2662 #newsForOthers(publisher: AgentState, space: Space, version: number, entries: Entry[]): void {
2663 hostedNewsForOthers(this.#newsHost, publisher, space, version, entries);
2666 #queueNews(agent: AgentState, items: readonly { key: string; text: string }[], entries: Entry[]): void {
2667 const fresh = items.filter((p) => !agent.told.has(p.key));
2668 if (fresh.length === 0) return;
2669 const text = [...new Set(fresh.map((p) => p.text))];
2670 const entry: Entry = { type: "news", agent: agent.name, pairs: [...new Set(fresh.map((p) => p.key))], text };
2671 entries.push(entry);
2672 this.#apply(entry);
2675 #takeNews(agent: AgentState, entries: Entry[]): string[] {
2676 if (agent.news.length === 0) return [];
2677 const news = [...agent.news];
2678 const entry: Entry = { type: "heard", agent: agent.name };
2679 entries.push(entry);
2680 this.#apply(entry);
2681 return news;
2684 /** Describe a pair for the agent: its side in its own view, theirs in its space now. */
2685 #collision(agent: AgentState, pair: Pair): Collision {
2686 return this.#describe(
2687 pair,
2688 this.#agentView(agent),
2689 this.#viewAt(this.#spaceOf(agent), last(this.#spaceOf(agent))),
2690 agent.space,
2691 );
2694 #describe(pair: Pair, yoursView: ReadView, theirsView: ReadView, spaceName: string): Collision {
2695 return describePair(
2696 this.#graph,
2697 (atom, space) => this.#origin(atom, space),
2698 pair,
2699 yoursView,
2700 theirsView,
2701 spaceName,
2702 );
2705 #touchedFiles(ids: Iterable<AtomId>, views: readonly ReadView[]): Set<string> {
2706 return touchedFiles(this.#graph, ids, views);
2709 // The changed-definition rule (#11) -------------------------------------------
2711 /** The rule for an agent's draft in its space. */
2712 #definitionCollisions(agent: AgentState, newer: ReadonlySet<AtomId>): DefinitionCollision[] {
2713 const draft = new Set(this.#draft(agent));
2714 if (draft.size === 0 || newer.size === 0) return [];
2715 const space = this.#spaceOf(agent);
2716 const at = this.#at(space, agent.base);
2717 const base = agent.mine.some((id) => at.has(id))
2718 ? this.#view(differenceSet(at, new StableOverlaySet(agent.mine)))
2719 : this.#viewAt(space, agent.base);
2720 return this.#definitionRule.collisions(
2721 draft,
2722 this.#agentView(agent),
2723 base,
2724 this.#viewAt(space, last(space)),
2725 newer,
2726 space.name,
2727 );
2731export { EngineError };