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?format=json
3,238 linesFirst import 72% · codex-capacity-chair 16% · capacity 9% · engine 1% · readspeed 1% · speed 1% · Last change capacity in version 318, 58 versions changed it
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 {
16 type Atom,
17 type AtomId,
18 EngineError,
19 Graph,
20 type LineId,
21 type ReadView,
22 View,
23} from "../../src/engine/index.ts";
24import {
25 CachedStateStorage,
26 differenceSet,
27 type GraphStateStorage,
28 isClosedSet,
29 markClosed,
30 StableOverlaySet,
31 StableSet,
32 StableUnionSet,
33 StoredMap,
34 storedArray,
35 unionOverlay,
36} from "../../src/engine/state-source.ts";
37import { type AddDraftHost, addDraft as hostedAddDraft } from "./add-draft.ts";
38import { type AmendHost, amend as hostedAmend } from "./amend.ts";
39import {
40 type AnnounceHost,
41 announce as hostedAnnounce,
42 announcePerson as hostedAnnouncePerson,
43 seatNotice as hostedSeatNotice,
44} from "./announce.ts";
45import { type ApplyEntryHost, applyEntry as hostedApplyEntry } from "./apply-entry.ts";
46import {
47 type ChangeHost,
48 change as hostedChange,
49 changeRecord as hostedChangeRecord,
50 changes as hostedChanges,
51 joinChange as hostedJoinChange,
52 namedFiles as hostedNamedFiles,
53} from "./change-records.ts";
54import { type ChangesSinceHost, changesSince as hostedChangesSince } from "./changes-since.ts";
55import { type CheckClashHost, checkClash as hostedCheckClash } from "./check-clash.ts";
56import {
57 type CollisionHost,
58 describePair,
59 duplicateCollisions,
60 openPairs as hostedOpenPairs,
61 type Origin,
62 originOf,
63 type Pair,
64 pairsIn,
65 strandedFiles,
66 touchedBeyond,
67 touchedFiles,
68} from "./collisions.ts";
69import { type DefinitionCollision, DefinitionRule } from "./definition-rule.ts";
70import { type DraftCollisionHost, draftCollisions } from "./draft-collisions.ts";
71import { type DraftDiffHost, diffOfAgent, diffOf as draftDiffOf } from "./draft-diff.ts";
72import { type DraftStateHost, draftState as hostedDraftState } from "./draft-state.ts";
73import { type DropHost, drop as hostedDrop } from "./drop.ts";
74import { type EditHost, edit as hostedEdit } from "./edit.ts";
75import { type ExpressMovesHost, expressMoves as hostedExpressMoves } from "./express-moves.ts";
76import {
77 type HistoryHost,
78 follow as historyFollow,
79 pathLife as historyPathLife,
80 tree as historyTree,
81} from "./history.ts";
82import { ingest as hostedIngest, type IngestHost } from "./ingest.ts";
83import { init as hostedInit, type InitHost } from "./init.ts";
84import { KeptParts } from "./kept-parts.ts";
85import { label as hostedLabel, type LabelHost } from "./label.ts";
86import {
87 land as hostedLand,
88 landCollisions as hostedLandCollisions,
89 landDraft as hostedLandDraft,
90 type LandHost,
91} from "./land.ts";
92import {
93 blocksIn,
94 markedCollisions as hostedMarkedCollisions,
95 markedFiles as hostedMarkedFiles,
96 markerCollisions as hostedMarkerCollisions,
97 markersSettled as hostedMarkersSettled,
98 openCollisions as hostedOpenCollisions,
99 type MarkerHost,
100} from "./markers.ts";
101import { MemoryStore } from "./memory-store.ts";
102import { mergeIdentical as hostedMergeIdentical, type MergeHost } from "./merge-identical.ts";
103import { move as hostedMove, type MoveHost } from "./move.ts";
104import {
105 addressedItem,
106 newsAboutOwnDraft as hostedNewsAboutOwnDraft,
107 newsForOthers as hostedNewsForOthers,
108 newsOwed as hostedNewsOwed,
109 owedAgents as hostedOwedAgents,
110 owedNewsNames as hostedOwedNewsNames,
111 markedItem,
112 type NewsHost,
113 type NewsItem,
114 type OwedDefinitionNews,
115 reviewItem,
116 settledItem,
117} from "./news.ts";
118import {
119 closeNote as hostedCloseNote,
120 noteAnswer as hostedNoteAnswer,
121 notes as hostedNotes,
122 startingNotes as hostedStartingNotes,
123 writeNote as hostedWriteNote,
124 type NoteHost,
125 type NoteWriteHost,
126 type ReviewRule,
127 reviewersOf,
128 reviewRulesIn,
129} from "./notes.ts";
130import {
131 draftFiles as hostedDraftFiles,
132 overlapNews as hostedOverlapNews,
133 overlaps as hostedOverlaps,
134 type OverlapHost,
135} from "./overlaps.ts";
136import { checkPath } from "./path-rules.ts";
137import { PathIndex } from "./pathindex.ts";
138import { pathKey } from "./pathkey.ts";
139import { pluck as hostedPluck, type PluckHost } from "./pluck.ts";
140import { ProjectError } from "./project-error.ts";
141import { checkDraftName, checkPerson, NAME, projectFileIn } from "./project-helpers.ts";
142import {
143 type SnapshotHost,
144 agentPaths as snapshotAgentPaths,
145 labels as snapshotLabels,
146 pathsAt as snapshotPathsAt,
147 pathsOf as snapshotPathsOf,
148 status as snapshotStatus,
149} from "./project-status.ts";
150import type {
151 AgentState,
152 AgentStatus,
153 ChangeAnswer,
154 ChangeRecord,
155 Collision,
156 DiffAnswer,
157 DraftSyncAnswer,
158 DropAnswer,
159 EditsVia,
160 Entry,
161 LandAnswer,
162 MergedLine,
163 Modes,
164 NewsWritten,
165 NoteAnswer,
166 NoteBody,
167 NoteRecord,
168 PersonSender,
169 PluckAnswer,
170 ProjectOptions,
171 ProjectStore,
172 PublishAnswer,
173 QueuedPublish,
174 Refusal,
175 Settled,
176 Starting,
177 Tail,
178 TellRecord,
179} from "./project-types.ts";
180import { publish as hostedPublish, publishDraft as hostedPublishDraft, type PublishHost } from "./publish.ts";
181import { publishOf as hostedPublishOf, type PublishOfHost } from "./publish-of.ts";
182import {
183 enqueue as hostedEnqueue,
184 notQueuedYet as hostedNotQueuedYet,
185 queue as hostedQueue,
186 queueCandidate as hostedQueueCandidate,
187 queueChecking as hostedQueueChecking,
188 queuedAtoms as hostedQueuedAtoms,
189 queueLand as hostedQueueLand,
190 queueOn as hostedQueueOn,
191 queuePull as hostedQueuePull,
192 unqueue as hostedUnqueue,
193 type QueueHost,
194} from "./queue.ts";
195import { record as hostedRecord, type RecordHost } from "./record.ts";
196import { recordFile as hostedRecordFile, type RecordFileHost } from "./record-file.ts";
197import { refusals as hostedRefusals, refuse as hostedRefuse, type RefuseHost } from "./refuse.ts";
198import { restore as hostedRestore, type RestoreHost } from "./restore.ts";
199import {
200 closureChangedAt,
201 indexClosure,
202 last,
203 Membership,
204 SHARED,
205 SharedAdditions,
206 type Space,
207 sharedBaseOf,
208} from "./spaces.ts";
209import { starting as hostedStarting, type StartingHost } from "./start.ts";
210import { switchTo as hostedSwitchTo, type SwitchHost } from "./switch-to.ts";
211import { sync as hostedSync, type SyncHost } from "./sync.ts";
212import { treeHash } from "./tree.ts";
213import {
214 authoredVersion,
215 authorTotalsAt,
216 type FileTotals,
217 versionFiles as keptVersionFiles,
218 type VersionFilesHost,
219} from "./version-files.ts";
220import {
221 type LogHost,
222 compare as versionCompare,
223 compareSummary as versionCompareSummary,
224 fileAt as versionFileAt,
225 fileExactAt as versionFileExactAt,
226 log as versionLog,
227 ribbon as versionRibbon,
228 show as versionShow,
229 viewAt as versionViewAt,
230} from "./version-log.ts";
231import {
232 checkVersion as hostedCheckVersion,
233 lastVersion as hostedLastVersion,
234 versionMeta as hostedVersionMeta,
235 type VersionMetaHost,
236} from "./version-meta.ts";
237import { modesOf } from "./view-changes.ts";
238import { ViewCache } from "./views.ts";
239import {
240 isWhole as hostedIsWhole,
241 wholeOut as hostedWholeOut,
242 wholeRules as hostedWholeRules,
243 type WholeHost,
244} from "./whole-files.ts";
245import { without as hostedWithout, type WithoutHost } from "./without.ts";
246import { WriterAgents } from "./writer-agents.ts";
248export { MemoryStore } from "./memory-store.ts";
249export { checkReadPath, pathProblem } from "./path-rules.ts";
250export { ProjectError } from "./project-error.ts";
251export { shapeStamp, utf8Bytes } from "./project-helpers.ts";
252export type * from "./project-types.ts";
253export { differs } from "./view-changes.ts";
255/** Entry kinds that had no time before #41; new ones get one. */
256const UNTIMED = new Set<Entry["type"]>(["join", "sync", "news", "heard", "discard", "switch"]);
258/** A start note lasts this long after the agent's last activity (#44). */
259const NOTE_IDLE = 2 * 60 * 60 * 1000;
260const WRITER_REOPEN = Symbol("verified writer checkpoint");
261/**
262 * The stored writer's read cache (abso Capacity). An agent's diff on typescript-rs touches more rows than the old
263 * 4,096 held, so it read many of them again: 59,000 reads cold, against 22,000 at this size.
264 */
265const WRITER_CACHE_BYTES = 4 * 1_048_576;
266const WRITER_CACHE_ROWS = 16_384;
267/** The biggest row the writer cache keeps (abso Capacity): an agent and all the news it was told can be 100 KB. */
268const WRITER_CACHE_ROW_BYTES = 16_384;
269/** Old-form agent rows moved to told buckets at each write (abso Capacity): abso's 109 take about 28 writes. */
270const OLD_TOLD_PER_WRITE = 4;
271export interface WriterSource {
272 readonly generation: number;
273 readonly logLength: number;
274 readonly sharedVersion: number;
276interface WriterAdoption {
277 source: WriterSource;
278 next: number;
279 ready: boolean;
282/** A decoded entry is supplied by a host that binds its bytes to canonical authority. */
283export type WriterAdoptionFrame = { seq: number; json: string } | { seq: number; bytes: number; entry: Entry };
284function adoptionFrameBytes(frame: WriterAdoptionFrame): number {
285 return "json" in frame
286 ? typeof frame.json === "string"
287 ? new TextEncoder().encode(frame.json).byteLength
288 : NaN
289 : frame.bytes;
291function adoptionFrameEntry(frame: WriterAdoptionFrame): Entry {
292 return "json" in frame ? (JSON.parse(frame.json) as Entry) : frame.entry;
295/** Where a view and its base place moved lines differently (View.placedDifferently), when both are Views. */
296function placedBetween(view: ReadView, base: ReadView): ReadonlySet<string> | undefined {
297 return view instanceof View && base instanceof View ? view.placedDifferently(base) : undefined;
300export class Project {
301 readonly #store: ProjectStore;
302 readonly #writerStorage?: GraphStateStorage;
303 readonly #graph: Graph;
304 /** Views laid out from atom sets, cached under a byte budget (views.ts). */
305 readonly #views: ViewCache;
306 /** What draft collisions keep between calls, under its own byte budget (kept-parts.ts). */
307 #keptParts: KeptParts | undefined;
308 /** Each agent's draft files, under the key they were worked out for (#draftFiles). */
309 readonly #draftFilesKept = new Map<string, { key: string; files: Set<string> }>();
310 /** Each version's files and each path's history (pathindex.ts). */
311 readonly #paths: PathIndex;
312 /** For each atom (by seq) that wrote lines, the log position of the entry that recorded it (#46). */
313 readonly #atomAt: number[] = [];
314 /** Which atoms are in which space at which version (#46, disk-first 1): the rules live in spaces.ts. */
315 readonly #membership = new Membership();
316 get #spaces(): Map<string, Space> {
317 return this.#membership.spaces;
318 }
319 readonly #agents = new Map<string, AgentState>();
320 readonly #refusals: Refusal[] = [];
321 /** Labels on shared's versions: name -> versions, ascending. */
322 readonly #labels = new Map<string, number[]>();
323 /** The newest tells and who has heard each (apply-entry.ts). */
324 readonly #tells = new Map<number, TellRecord>();
325 /**
326 * Entries applied but not stored yet, in order. Every applied entry is
327 * stored at the next flush, even when the call that applied it threw
328 * afterwards; otherwise the log could miss a join that later entries rely on.
329 */
330 #pending: Entry[] = [];
331 /**
332 * Whether something runs the merge queue's check (#39). Until the Worker has
333 * a checker it stays false, and `"queue": true` in avcs.json does nothing:
334 * publishes would otherwise wait for a check that never comes. Replay
335 * doesn't depend on it.
336 */
337 checkerReady = false;
338 /**
339 * Owed news (abso Capacity, 2026-10-15): a publish's definition news for other agents is left for after its write
340 * (takeOwedDefinitionNews, definitionNewsOwed, deliverOwedNews). The disk route sets it; the replay engine doesn't.
341 */
342 owesDefinitionNews = false;
343 #owed: OwedDefinitionNews[] = [];
344 readonly #now: (() => number) | undefined;
345 readonly #newsWritten: ((items: readonly NewsWritten[]) => void) | undefined;
346 readonly #whole: ProjectOptions["whole"];
347 readonly #shapes: ProjectOptions["shapes"];
348 readonly #logLine: ProjectOptions["logLine"];
349 /** For each log position, the newest time up to it (#41): time to position in one search. */
350 readonly #timeAt: number[] = [];
351 /** For each version of shared, the log position of the entry that made it (#41). */
352 readonly #versionAt: number[] = [];
353 /** The newest time any applied entry carries: the clock when none was given. */
354 #lastTimeMemory = 0;
355 get #lastTime(): number {
356 return this.#writerStorage
357 ? ((this.#writerStorage.read("project:meta", "lastTime") as number | undefined) ?? 0)
358 : this.#lastTimeMemory;
359 }
360 set #lastTime(value: number) {
361 if (this.#writerStorage) this.#writerStorage.write("project:meta", "lastTime", value);
362 else this.#lastTimeMemory = value;
363 }
364 /** Every change (#44), by id. */
365 readonly #changes = new Map<number, ChangeRecord>();
366 /** Each version's change, by "<draft or ''> <version>" (#44): what a note on its lines belongs to. */
367 readonly #versionChange = new Map<string, number>();
368 /** Every note (#44), by id. */
369 readonly #notes = new Map<number, NoteRecord>();
370 /** Mod versions (X-Abso-Client) in the order they first sent an edit (#41): the last is taken as the installed one. */
371 #mods: string[] = [];
372 /** The merge queue (#39), in order: publishes to shared waiting for their batch's check. */
373 #queue: QueuedPublish[] = [];
374 /** The newest note's id (#44). */
375 #lastNoteMemory = 0;
376 get #lastNote(): number {
377 return this.#writerStorage
378 ? ((this.#writerStorage.read("project:meta", "lastNote") as number | undefined) ?? 0)
379 : this.#lastNoteMemory;
380 }
381 set #lastNote(value: number) {
382 if (this.#writerStorage) this.#writerStorage.write("project:meta", "lastNote", value);
383 else this.#lastNoteMemory = value;
384 }
385 #queuedIdMemory = 0;
386 get #queuedId(): number {
387 return this.#writerStorage
388 ? ((this.#writerStorage.read("project:meta", "queuedId") as number | undefined) ?? 0)
389 : this.#queuedIdMemory;
390 }
391 set #queuedId(value: number) {
392 if (this.#writerStorage) this.#writerStorage.write("project:meta", "queuedId", value);
393 else this.#queuedIdMemory = value;
394 }
395 /** Queued ids in the batch being checked now: not in the log, only for refusing an unqueue mid-check. */
396 #checking = new Set<number>();
397 /** How many entries the store holds: the log position of the next one (#41, the website's feed and replay). */
398 #storedMemory = 0;
399 get #stored(): number {
400 return this.#writerStorage
401 ? ((this.#writerStorage.read("project:meta", "stored") as number | undefined) ?? 0)
402 : this.#storedMemory;
403 }
404 set #stored(value: number) {
405 if (this.#writerStorage) this.#writerStorage.write("project:meta", "stored", value);
406 else this.#storedMemory = value;
407 }
408 /** Names on the lines a change replaced, by "<atom> <last replaced line>" (atoms never change). */
409 #rule?: DefinitionRule;
410 get #definitionRule(): DefinitionRule {
411 this.#rule ??= new DefinitionRule(this.#graph, (atom, space) => this.#origin(atom, space));
412 return this.#rule;
413 }
414 /** The newest announcement's id (announcements are news entries keyed "announce <id>"). */
415 #announcedMemory = 0;
416 get #announced(): number {
417 return this.#writerStorage
418 ? ((this.#writerStorage.read("project:meta", "announced") as number | undefined) ?? 0)
419 : this.#announcedMemory;
420 }
421 set #announced(value: number) {
422 if (this.#writerStorage) this.#writerStorage.write("project:meta", "announced", value);
423 else this.#announcedMemory = value;
424 }
425 #loading = false;
427 readonly #hasBlob: (sha256: string) => boolean;
429 constructor(store: ProjectStore, options: ProjectOptions = {}, checkpoint?: typeof WRITER_REOPEN) {
430 if (options.indexAcceptedAtom && !options.writerStorage)
431 throw Error("accepted atom indexing requires writer storage");
432 this.#store = store;
433 this.#writerStorage = options.writerStorage
434 ? new CachedStateStorage(options.writerStorage, WRITER_CACHE_BYTES, WRITER_CACHE_ROWS, WRITER_CACHE_ROW_BYTES)
435 : undefined;
436 if (this.#writerStorage) {
437 const storage = this.#writerStorage;
438 // A stored Graph cannot be replayed over itself. Check before any
439 // constructor writes so an accidental reopen preserves the namespace.
440 if (
441 checkpoint !== WRITER_REOPEN &&
442 ((storage.read("atoms:meta", "length") as number | undefined) ||
443 (storage.read('membership:"":versions:meta', "length") as number | undefined))
444 )
445 throw new Error("writer indexes already contain history; Project checkpoint reopen is required");
446 this.#membership = new Membership(storage);
447 this.#atomAt = storedArray(storage, "project:atom-at");
448 this.#timeAt = storedArray(storage, "project:time-at");
449 this.#versionAt = storedArray(storage, "project:version-at");
450 this.#notes = new StoredMap(storage, "project:notes");
451 this.#changes = new StoredMap(storage, "project:changes");
452 this.#labels = new StoredMap(storage, "project:labels");
453 this.#versionChange = new StoredMap(storage, "project:version-change");
454 this.#refusals = storedArray(storage, "project:refusals");
455 this.#agents = new WriterAgents(storage);
456 if (checkpoint === WRITER_REOPEN) {
457 this.#mods = storage.read("project:meta", "mods") as string[];
458 this.#queue = storage.read("project:meta", "queue") as QueuedPublish[];
459 const tells = storage.read("project:meta", "tells") as [
460 number,
461 Omit<TellRecord, "heard"> & { heard: [string, { at: number | undefined } | null][] },
462 ][];
463 this.#tells = new Map(tells.map(([id, tell]) => [id, { ...tell, heard: new Map(tell.heard) }]));
464 }
465 }
466 this.#hasBlob = options.hasBlob ?? (() => false);
467 this.#now = options.now;
468 this.#newsWritten = options.newsWritten;
469 this.#whole = options.whole;
470 this.#shapes = options.shapes;
471 this.#logLine = options.logLine;
472 // For tests (#46): AVCS_TEXT_FROM_LOG=1 runs a project on a MemoryStore with its text read back from the store.
473 const testing =
474 (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env?.AVCS_TEXT_FROM_LOG ===
475 "1";
476 const entryAt =
477 options.entryAt ??
478 (testing && store instanceof MemoryStore ? (at: number) => (store as MemoryStore).entries[at]! : undefined);
479 // An atom as its log entry stores it. Not stored yet: still in this call's pending entries; while loading, every entry is stored.
480 const stored = (seq: number): Atom => {
481 const at = this.#atomAt[seq]!;
482 const entry = !this.#loading && at >= this.#stored ? this.#pending[at - this.#stored]! : entryAt!(at);
483 if (entry?.type === "init" || entry?.type === "draft") return entry.atom;
484 // A publish's or land's tie atom (#46: its lists are read back too).
485 if (entry?.type === "publish" || entry?.type === "land") return entry.tie;
486 throw new Error(`log entry ${at} holds no atom ${seq}`);
487 };
488 // Line text and each atom's deletes and claim keys stay in the log (#46), read back when asked for.
489 this.#graph = this.#writerStorage
490 ? new Graph({ storage: this.#writerStorage, indexAcceptedAtom: options.indexAcceptedAtom })
491 : entryAt
492 ? new Graph({ texts: (seq) => stored(seq).inserts.map((r) => r.lines), lists: (seq) => stored(seq) })
493 : new Graph();
494 this.#views = new ViewCache(this.#graph, options.readViewProvider);
495 this.#paths = new PathIndex({
496 graph: this.#graph,
497 at: (space, version) => this.#at(space, version),
498 viewAt: (space, version) => this.#viewAt(space, version),
499 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
500 shapes: this.#shapes,
501 });
502 }
504 /** Rebuild a project from its stored entries. New entries go to `store`. */
505 static load(entries: Iterable<Entry>, store: ProjectStore, options: ProjectOptions = {}): Project {
506 const testing =
507 (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env?.AVCS_TEXT_FROM_LOG ===
508 "1";
509 if (testing && !options.entryAt && Array.isArray(entries)) {
510 // Loaded from someone else's entries: its text is read back from them (and from the new store after them).
511 const from = entries as Entry[];
512 const after = store instanceof MemoryStore ? store : undefined;
513 options = { ...options, entryAt: (at) => (at < from.length ? from[at]! : after!.entries[at - from.length]!) };
514 }
515 const project = new Project(store, options);
516 project.#loading = true;
517 for (const entry of entries) {
518 project.#apply(entry);
519 project.#stored++;
520 project.#persistMutable();
521 }
522 project.#loading = false;
523 project.#writeCheckpoint();
524 return project;
525 }
527 /** Reopen committed writer indexes. The host supplies the authoritative canonical log length. */
528 static openWriter(
529 store: ProjectStore,
530 storage: GraphStateStorage,
531 logLength: number,
532 options: Omit<ProjectOptions, "writerStorage"> = {},
533 ): Project {
534 const adoption = storage.read("project:meta", "adoption") as WriterAdoption | undefined;
535 if (adoption && !adoption.ready) throw new Error("writer adoption is incomplete");
536 return Project.#openWriter(store, storage, logLength, options);
537 }
539 static #openWriter(
540 store: ProjectStore,
541 storage: GraphStateStorage,
542 logLength: number,
543 options: Omit<ProjectOptions, "writerStorage">,
544 ): Project {
545 const checkpoint = storage.read("project:meta", "checkpoint") as
546 | { format: number; logLength: number; atoms: number; version: number }
547 | undefined;
548 const length = (name: string) => (storage.read(`${name}:meta`, "length") as number | undefined) ?? 0;
549 if (
550 !Number.isSafeInteger(logLength) ||
551 logLength < 1 ||
552 checkpoint?.format !== 1 ||
553 checkpoint.logLength !== logLength ||
554 storage.read("project:meta", "stored") !== logLength ||
555 length("project:time-at") !== logLength ||
556 length("atoms") !== checkpoint.atoms ||
557 length("project:atom-at") !== checkpoint.atoms ||
558 length('membership:"":versions') !== checkpoint.version + 1 ||
559 length("project:version-at") !== checkpoint.version + 1 ||
560 !["mods", "queue", "tells"].every((key) => Array.isArray(storage.read("project:meta", key)))
561 )
562 throw new Error("writer checkpoint does not match the canonical log and indexes");
563 return new Project(store, { ...options, writerStorage: storage }, WRITER_REOPEN);
564 }
566 /** Open a host-verified historical prefix. Its state must be immutable and
567 * scoped to canonical authority; adoption readiness describes the live writer,
568 * not whether this individual prefix has a complete checkpoint. */
569 static openHistorical(
570 storage: GraphStateStorage,
571 logLength: number,
572 scratch: GraphStateStorage,
573 assertScope: () => void = () => {
574 storage.read("project:meta", "checkpoint");
575 },
576 readViewProvider?: ProjectOptions["readViewProvider"],
577 ): Project {
578 const refuse = (): never => {
579 throw new Error("historical project is read-only");
580 };
581 const selected = (collection: string) => {
582 // Revalidate the historical scope even when accessing derived scratch.
583 assertScope();
584 return collection.startsWith("projection-scratch:") ? scratch : storage;
585 };
586 return Project.#openWriter(
587 { append: refuse },
588 {
589 read: (collection, key) => selected(collection).read(collection, key),
590 entries: (collection) => selected(collection).entries(collection),
591 write: (collection, key, value) => {
592 if (selected(collection) !== scratch) refuse();
593 scratch.write(collection, key, value);
594 },
595 remove: (collection, key) => {
596 if (selected(collection) !== scratch) refuse();
597 scratch.remove(collection, key);
598 },
599 transaction: (body) => storage.transaction(() => scratch.transaction(body)),
600 },
601 logLength,
602 { readViewProvider },
603 );
604 }
606 /**
607 * Derive one bounded page from the host's canonical frames. The host reads
608 * those frames from its own log and revalidates the source inside this same
609 * transaction. Partial adoption cannot be opened for normal operations.
610 */
611 static adoptWriterPage(
612 storage: GraphStateStorage,
613 input: {
614 source: WriterSource;
615 from: number;
616 frames: Iterable<WriterAdoptionFrame>;
617 maxEntries: number;
618 maxBytes: number;
619 /** The host supplies disk-backed decoded entries and verified byte counts. */
620 decodedFrames?: boolean;
621 currentSource(): WriterSource;
622 /** Select the host's derived historical revision before applying a frame.
623 * Each selected revision receives a complete Project checkpoint. */
624 beginRevision?(logLength: number): void;
625 },
626 options: Omit<ProjectOptions, "writerStorage"> = {},
627 ): { next: number; ready: boolean; entries: number; bytes: number } {
628 const same = (a: WriterSource, b: WriterSource) =>
629 a.generation === b.generation && a.logLength === b.logLength && a.sharedVersion === b.sharedVersion;
630 if (
631 ![input.source.generation, input.source.logLength, input.source.sharedVersion, input.from].every(
632 (n) => Number.isSafeInteger(n) && n >= 0,
633 ) ||
634 input.source.logLength < 1 ||
635 !Number.isSafeInteger(input.maxEntries) ||
636 input.maxEntries < 1 ||
637 input.maxEntries > 256 ||
638 !Number.isSafeInteger(input.maxBytes) ||
639 input.maxBytes < 1 ||
640 (input.maxBytes > 8_000_000 && input.decodedFrames !== true)
641 )
642 throw new Error("invalid writer adoption bounds or source");
643 return storage.transaction(() => {
644 if (!same(input.currentSource(), input.source))
645 throw new Error("canonical source changed before writer adoption");
646 const previous = storage.read("project:meta", "adoption") as WriterAdoption | undefined;
647 if (
648 (previous && (!same(previous.source, input.source) || previous.ready || previous.next !== input.from)) ||
649 (!previous && input.from !== 0)
650 )
651 throw new Error("writer adoption source or cursor does not match");
652 const noAppend: ProjectStore = {
653 append: () => {
654 throw new Error("adoption must never append canonical history");
655 },
656 };
657 const project = previous
658 ? Project.#openWriter(noAppend, storage, input.from, options)
659 : new Project(noAppend, { ...options, writerStorage: storage });
660 project.#loading = true;
661 let count = 0;
662 let bytes = 0;
663 for (const frame of input.frames) {
664 if (input.decodedFrames && "json" in frame) throw new Error("decoded adoption requires decoded frames");
665 const size = adoptionFrameBytes(frame);
666 if (
667 count >= input.maxEntries ||
668 frame.seq !== input.from + count ||
669 frame.seq >= input.source.logLength ||
670 !Number.isSafeInteger(size) ||
671 size < 1 ||
672 size > input.maxBytes - bytes
673 )
674 throw new Error("writer adoption page exceeds bounds or has a noncontiguous frame");
675 bytes += size;
676 if (bytes > input.maxBytes) throw new Error("writer adoption page exceeds byte bound");
677 input.beginRevision?.(frame.seq + 1);
678 project.#apply(adoptionFrameEntry(frame));
679 project.#stored++;
680 project.#persistMutable();
681 if (input.beginRevision) project.#writeCheckpoint();
682 count++;
683 }
684 if (count === 0) throw new Error("writer adoption page must advance");
685 project.#loading = false;
686 const next = input.from + count;
687 const ready = next === input.source.logLength;
688 if (!same(input.currentSource(), input.source))
689 throw new Error("canonical source changed during writer adoption");
690 if (ready && project.version !== input.source.sharedVersion)
691 throw new Error("adopted shared version differs from canonical source");
692 project.#writeCheckpoint();
693 storage.write("project:meta", "adoption", { source: input.source, next, ready } satisfies WriterAdoption);
694 return { next, ready, entries: count, bytes };
695 });
696 }
698 /**
699 * Extend derived historical indexes from an already checkpointed prefix.
700 * The host supplies only new canonical frames inside its commit transaction.
701 */
702 static extendHistoricalPage(
703 storage: GraphStateStorage,
704 input: {
705 from: number;
706 frames: Iterable<WriterAdoptionFrame>;
707 maxEntries: number;
708 maxBytes: number;
709 /** The host supplies disk-backed decoded entries and verified byte counts. */
710 decodedFrames?: boolean;
711 beginRevision(logLength: number): void;
712 /** Verify both the saved prefix and the new frames against canonical authority. */
713 validateAuthority(): void;
714 },
715 ): { next: number; entries: number; bytes: number } {
716 if (
717 !Number.isSafeInteger(input.from) ||
718 input.from < 1 ||
719 !Number.isSafeInteger(input.maxEntries) ||
720 input.maxEntries < 1 ||
721 input.maxEntries > 256 ||
722 !Number.isSafeInteger(input.maxBytes) ||
723 input.maxBytes < 1 ||
724 (input.maxBytes > 8_000_000 && input.decodedFrames !== true)
725 )
726 throw new Error("invalid historical extension bounds");
727 const validate = () => {
728 const result: unknown = input.validateAuthority();
729 if (result && (typeof result === "object" || typeof result === "function") && "then" in result)
730 throw new Error("historical authority must be synchronous");
731 };
732 return storage.transaction(() => {
733 validate();
734 const project = Project.#openWriter(
735 {
736 append: () => {
737 throw new Error("history derivation cannot append canonical entries");
738 },
739 },
740 storage,
741 input.from,
742 {},
743 );
744 project.#loading = true;
745 let entries = 0,
746 bytes = 0;
747 for (const frame of input.frames) {
748 if (input.decodedFrames && "json" in frame) throw new Error("decoded adoption requires decoded frames");
749 const size = adoptionFrameBytes(frame);
750 if (
751 entries >= input.maxEntries ||
752 frame.seq !== input.from + entries ||
753 !Number.isSafeInteger(size) ||
754 size < 1 ||
755 size > input.maxBytes - bytes
756 )
757 throw new Error("historical extension exceeds bounds or is not contiguous");
758 bytes += size;
759 if (bytes > input.maxBytes) throw new Error("historical extension exceeds byte bound");
760 input.beginRevision(frame.seq + 1);
761 project.#apply(adoptionFrameEntry(frame));
762 project.#stored++;
763 project.#persistMutable();
764 project.#writeCheckpoint();
765 entries++;
766 }
767 if (!entries) throw new Error("historical extension must advance");
768 validate();
769 return { next: input.from + entries, entries, bytes };
770 });
771 }
773 /** Apply more entries to a replay copy. Never for the live project. */
774 catchUp(entries: Iterable<Entry>): void {
775 this.#loading = true;
776 try {
777 for (const entry of entries) {
778 this.#apply(entry);
779 this.#stored++;
780 }
781 } finally {
782 this.#loading = false;
783 }
784 }
786 /** The log position of the next entry: how many entries the log holds (#41). */
787 get logLength(): number {
788 return this.#stored;
789 }
791 get initialized(): boolean {
792 return this.#shared.versions.length > 0;
793 }
795 /** The current shared version. */
796 get version(): number {
797 this.#needInit();
798 return this.#shared.versions.length - 1;
799 }
801 /** Shared's files, for the push out to Artifacts. */
802 files(): Record<string, string> {
803 return this.#sharedView().files();
804 }
806 /** Shared's binary files, for the push out to Artifacts: path -> the SHA-256 of its bytes. Not in `files()`. */
807 blobs(): Record<string, string> {
808 return this.#sharedView().blobs();
809 }
811 /** Shared's executable files and links, for the push out to Artifacts: path -> mode. Other files are plain. */
812 modes(): Modes {
813 return modesOf(this.#sharedView());
814 }
816 /** Shared as a ReadView, for reading lines (blame, why). Don't hold on to it across calls. */
817 sharedView(): ReadView {
818 return this.#sharedView();
819 }
821 /** The agents the project knows, by name. */
822 agents(): string[] {
823 return [...this.#agents.keys()].sort();
824 }
826 /**
827 * An agent's unpublished changes, oldest first, and its view (its space at its base plus its changes). Read only.
828 * The view is laid out on first use: where asks every agent, most have no changes, and a big project has more
829 * agents than the view cache holds, so building every view cost each call about 0.7 s.
830 */
831 draftOf(agentName: string): { atoms: AtomId[]; readonly view: ReadView } | undefined {
832 const agent = this.#agents.get(agentName);
833 if (!agent) return undefined;
834 const view = () => this.#agentView(agent);
835 return {
836 atoms: this.#draft(agent),
837 get view() {
838 return view();
839 },
840 };
841 }
843 /** The shared version an atom was published in, or undefined while it's only in a draft. */
844 versionOf(atom: AtomId): number | undefined {
845 return this.#shared.publishedIn.get(atom);
846 }
848 /**
849 * Where an atom was published: shared if it's there, else the named draft
850 * that has it (by name), else undefined (it's only in a draft so far).
851 */
852 publishOf(...args: Tail<Parameters<typeof hostedPublishOf>>): ReturnType<typeof hostedPublishOf> {
853 return hostedPublishOf(this.#publishOfHost, ...args);
854 }
856 /** The newest version of shared, or of a named draft. */
857 lastVersion(...args: Tail<Parameters<typeof hostedLastVersion>>): ReturnType<typeof hostedLastVersion> {
858 return hostedLastVersion(this.#versionMetaHost, ...args);
859 }
861 /** Shared (null), then each named draft by name: every space with versions (abso issue 80). */
862 spaceNames(): (string | null)[] {
863 return [null, ...[...this.#spaces.keys()].filter((n) => n !== SHARED).sort()];
864 }
866 /** Who made a version of shared or a named draft, why and when, and a draft's shared base (abso issue 80). */
867 versionMeta(...args: Tail<Parameters<typeof hostedVersionMeta>>): ReturnType<typeof hostedVersionMeta> {
868 return hostedVersionMeta(this.#versionMetaHost, ...args);
869 }
871 /** Who published a version of shared, and why. */
872 published(version: number): { agent: string; message: string; time: number } | undefined {
873 const p = this.#shared.versions[version];
874 return p && { agent: p.agent, message: p.message, time: p.time };
875 }
877 /** The atoms a version of shared, or of a named draft, added to its space: what was pushed together (blame's trail). */
878 versionAtoms(version: number, draft: string | null = null): readonly AtomId[] {
879 const space = draft === null ? this.#shared : this.#spaces.get(draft);
880 return space?.versions[version]?.atoms ?? [];
881 }
883 /** The graph, for reading (blame, history). Don't add to it. */
884 get graph(): Graph {
885 return this.#graph;
886 }
888 // Calls -------------------------------------------------------------------
890 /** Create the project from a folder's text files. Empty files are skipped (the engine can't hold them). */
891 init(...args: Tail<Parameters<typeof hostedInit>>): ReturnType<typeof hostedInit> {
892 return hostedInit(this.#initHost, ...args);
893 }
895 /** An Edit, Write or MultiEdit from the hook, against the agent's view. */
896 edit(...args: Tail<Parameters<typeof hostedEdit>>): ReturnType<typeof hostedEdit> {
897 return hostedEdit(this.#editHost, ...args);
898 }
900 /** Whole files as the agent's folder has them; each is diffed against its view. */
901 record(...args: Tail<Parameters<typeof hostedRecord>>): ReturnType<typeof hostedRecord> {
902 return hostedRecord(this.#recordHost, ...args);
903 }
905 /** Add the agent's draft to its space (publish.ts). */
906 publish(...args: Tail<Parameters<typeof hostedPublish>>): ReturnType<typeof hostedPublish> {
907 return hostedPublish(this.#publishHost, ...args);
908 }
910 #publish(
911 agent: AgentState,
912 message: string,
913 time: number,
914 entries: Entry[],
915 asIs = false,
916 direct = false,
917 ): PublishAnswer {
918 return hostedPublishDraft(this.#publishHost, agent, message, time, entries, asIs, direct);
919 }
921 /**
922 * How the agent's newest edit arrived (#41). The mod sends X-Abso-Client
923 * avcs-mod/<stamp>; the hook sends abso-cli/<version> (avcs-cli/ before #59) with the chat's
924 * session; abso record and git pushes send no session. Edits stored before
925 * the client was recorded have only the session: those count as the mod
926 * (the hook stands down where the mod is installed), with modCurrent null.
927 */
928 #editsOf(agent: AgentState): {
929 edits: EditsVia;
930 modCurrent: boolean | null;
931 lastEdit: number | null;
932 joined: number | null;
933 } {
934 const last = agent.lastEdit;
935 const joined = agent.joined ?? null;
936 if (!last) return { edits: "none", modCurrent: null, lastEdit: null, joined };
937 const { client, session } = last;
938 if (client?.startsWith("avcs-mod/"))
939 return { edits: "mod", modCurrent: client === this.#mods[this.#mods.length - 1], lastEdit: last.time, joined };
940 if (client === undefined && session) return { edits: "mod", modCurrent: null, lastEdit: last.time, joined };
941 return { edits: session ? "hook" : "commands", modCurrent: null, lastEdit: last.time, joined };
942 }
944 // Spellings and moves (#49) --------------------------------------------------------
946 /** Refuse work whose paths would clash in shared (#49), before anything of it is written. */
947 #checkClash(...args: Tail<Parameters<typeof hostedCheckClash>>): ReturnType<typeof hostedCheckClash> {
948 return hostedCheckClash(this.#checkClashHost, ...args);
949 }
951 /**
952 * Move a file in the agent's draft (#49): its lines keep their ids, as with
953 * git mv, so blame and why follow it. The only way to change a file's case.
954 * Refused when `to` is another existing file, ignoring case.
955 */
956 move(...args: Tail<Parameters<typeof hostedMove>>): ReturnType<typeof hostedMove> {
957 return hostedMove(this.#moveHost, ...args);
958 }
960 // Files kept whole (#46) ----------------------------------------------------------
962 /** avcs.json's `"whole": [globs]`: paths kept whole. From `config` when given (init), else shared's. */
963 #wholeRules(config?: string): string[] {
964 return hostedWholeRules(this.#wholeHost, config);
965 }
967 /**
968 * Whether a file is kept whole: its path matches avcs.json's "whole", its
969 * text passes WHOLE_LIMIT, or it is already a blob where it's going. The
970 * last makes it one-way: a file kept whole stays whole while it exists,
971 * even if it shrinks or the rule changes, so it never flips back and forth.
972 */
973 #isWhole(path: string, length: number, view: ReadView | undefined, rules: readonly string[]): boolean {
974 return hostedIsWhole(this.#wholeHost, path, length, view, rules);
975 }
977 /** Files and blobs with every whole file's text moved into the blob store. */
978 #wholeOut(
979 files: Readonly<Record<string, string | null>>,
980 blobs: Readonly<Record<string, string>>,
981 view: ReadView | undefined,
982 config?: string,
983 ): { files: Record<string, string | null>; blobs: Record<string, string> } {
984 return hostedWholeOut(this.#wholeHost, files, blobs, view, config);
985 }
987 // Changes (#44) -------------------------------------------------------------------
989 /** The agent did something at `time`: its start note ends first if it had been idle over 2 hours. */
990 #active(agent: AgentState, time: number): void {
991 if (agent.starting && agent.lastActive !== undefined && time - agent.lastActive > NOTE_IDLE) {
992 delete agent.starting;
993 delete agent.noteAt;
994 }
995 if (agent.lastActive === undefined || time > agent.lastActive) agent.lastActive = time;
996 }
998 /** The agent's start note, unless it has been idle over 2 hours. */
999 #liveNote(agent: AgentState): Starting | undefined {
1000 if (!agent.starting) return undefined;
1001 const now = this.#now?.() ?? this.#lastTime;
1002 return agent.lastActive !== undefined && now - agent.lastActive > NOTE_IDLE ? undefined : agent.starting;
1005 /** The change the agent is working on at `time`: its named draft's, or its start note's; none for a lone publish. */
1006 #currentChange(agent: AgentState, time: number): number | undefined {
1007 if (agent.space !== SHARED) return this.#spaces.get(agent.space)?.startedAt;
1008 if (!agent.starting || agent.noteAt === undefined) return undefined;
1009 return agent.lastActive !== undefined && time - agent.lastActive > NOTE_IDLE ? undefined : agent.noteAt;
1012 /** The position the next entry written will have. */
1013 get #nextAt(): number {
1014 return this.#stored + this.#pending.length;
1017 #changeRecord(id: number, agent: AgentState, time: number, queuedNote?: Starting): ChangeRecord {
1018 return hostedChangeRecord(this.#changeHost, id, agent, time, queuedNote);
1021 /** A publish or land joins its change. Entries from before changes: the start note named it, and the publish ended the note. */
1022 #joinChange(
1023 agent: AgentState,
1024 entry: Extract<Entry, { type: "publish" | "land" }>,
1025 at: number,
1026 draft: string | null,
1027 landed?: string,
1028 ): void {
1029 hostedJoinChange(this.#changeHost, agent, entry, at, draft, landed);
1032 /**
1033 * One change (#44): the start note, named draft or publish that began it,
1034 * each of its versions and the files they changed, what it settled, and its
1035 * refusals. `id` is the log position of the entry that began it.
1036 */
1037 change(id: number): ChangeAnswer {
1038 return hostedChange(this.#changeHost, id);
1041 /** The files a version's changes name: cheap, for lists (the change page works out the net changes). */
1042 #namedFiles(space: Space, version: number): string[] {
1043 return hostedNamedFiles(this.#graph, space, version);
1046 /**
1047 * "Since you last looked" (#44): the changes with anything new at or after
1048 * log position `since`, newest first, at most `limit`. Their files are the
1049 * ones their changes name; the change page has the net changes.
1050 */
1051 changes(
1052 since = 0,
1053 limit = 50,
1054 before?: number,
1055 issue?: number,
1056 ): { since: number; next: number; changes: ChangeAnswer[]; older?: number } {
1057 return hostedChanges(this.#changeHost, since, limit, before, issue);
1060 // Notes on lines (#44) --------------------------------------------------------------
1062 /**
1063 * Leave a note on lines of a file (#44): lines `from` to `to` (1-based) as
1064 * shared shows them now, as `of`'s draft shows them (to note work before
1065 * it's published), or at `version`. Or answer a note with `reply`. The
1066 * lines' authors, the change's agent and the thread hear it as news.
1067 */
1068 note(
1069 agentName: string,
1070 body: NoteBody,
1071 time: number,
1072 ): { id: number; change: number | null; lines: [number, number] } {
1073 this.#needInit();
1074 const entries: Entry[] = [];
1075 return this.#note(entries, () => ({ name: this.#agent(agentName, entries).name }), body, time);
1078 /**
1079 * A signed-in person's note from the website (#41). The Worker has checked
1080 * who it is. The writer is recorded as "person:<id>" with `person`, never
1081 * as an agent, and the news quotes the text.
1082 */
1083 notePerson(
1084 person: { id: unknown; name: unknown },
1085 body: NoteBody,
1086 time: number,
1087 ): { id: number; change: number | null; lines: [number, number] } {
1088 this.#needInit();
1089 const from = checkPerson(person);
1090 return this.#note([], () => ({ name: `person:${from.person.id}`, person: from }), body, time);
1093 /** Close a person's own note (#41): only the person who wrote it can. */
1094 closeNotePerson(person: { id: unknown; name: unknown }, id: number, how: unknown, time: number): NoteAnswer {
1095 const from = checkPerson(person);
1096 return this.#closeNote(`person:${from.person.id}`, id, how, time, from);
1099 #note(
1100 entries: Entry[],
1101 writerOf: () => { name: string; person?: PersonSender },
1102 body: NoteBody,
1103 time: number,
1104 ): { id: number; change: number | null; lines: [number, number] } {
1105 return hostedWriteNote(this.#noteWriteHost, entries, writerOf, body, time);
1108 /** The project's reviewers per area (#44): avcs.json's `"review": [{"paths": [...], "reviewer": "..."}]` in shared. */
1109 #reviewRules(): ReviewRule[] {
1110 if (["abso.json", "avcs.json"].every((path) => this.#graph.startCodeOf(path) === undefined)) return [];
1111 return reviewRulesIn(projectFileIn(this.#sharedView())?.text);
1114 /** Each reviewer whose area these files fall in, the files that do, and whether it has noted change `id`. */
1115 #reviewersOf(files: readonly string[], id: number): { agent: string; files: string[]; read: boolean }[] {
1116 return reviewersOf(this.#reviewRules(), files, (agent) =>
1117 [...this.#notes.values()].some((n) => n.change === id && n.agent === agent),
1118 );
1121 /** After a version of shared: the reviewers whose areas it touches hear of its change, once per change (#44). */
1122 #reviewNews(agent: AgentState, version: number, entries: Entry[]): void {
1123 const id = this.#versionChange.get(` ${version}`);
1124 if (id === undefined) return;
1125 const rec = this.#changes.get(id);
1126 const files = this.#namedFiles(this.#shared, version);
1127 for (const r of this.#reviewersOf(files, id)) {
1128 if (r.agent === agent.name) continue;
1129 const reviewer = this.#agents.get(r.agent);
1130 if (!reviewer) continue;
1131 const title =
1132 rec?.note?.text ?? (rec?.kind === "draft" ? `draft ${rec.draft}` : (rec?.versions[0]?.message ?? ""));
1133 this.#queueNews(reviewer, [reviewItem(agent.name, id, title, r.files, version)], entries);
1137 /** After a version of shared: each open objection whose lines it took out tells its writer (#44). */
1138 #addressedNews(agent: AgentState, version: number, entries: Entry[]): void {
1139 for (const n of this.#notes.values()) {
1140 if (n.kind !== "objection" || n.closed || n.reply !== undefined || n.agent === agent.name) continue;
1141 if (this.#noteAnswer(n).state !== "addressed") continue;
1142 const writer = this.#agents.get(n.agent);
1143 if (writer) this.#queueNews(writer, [addressedItem(agent.name, version, n)], entries);
1147 /** Close a note: only its writer can (#44). */
1148 closeNote(agentName: string, id: number, how: unknown, time: number): NoteAnswer {
1149 return this.#closeNote(agentName, id, how, time);
1152 #closeNote(agentName: string, id: number, how: unknown, time: number, person?: PersonSender): NoteAnswer {
1153 return hostedCloseNote(this.#noteWriteHost, agentName, id, how, time, person);
1156 /** Notes, oldest first: on a file, on a change, or only the ones still open. */
1157 notes(...args: Tail<Parameters<typeof hostedNotes>>): ReturnType<typeof hostedNotes> {
1158 return hostedNotes(this.#notesHost, ...args);
1161 /** The change the newest of these lines was written in: its version's, or its author's current one if unpublished. */
1162 #changeOfLines(lines: readonly LineId[]): number | undefined {
1163 let newest: Atom | undefined;
1164 for (const l of lines) {
1165 const info = this.#graph.line(l);
1166 const atom = info && this.#graph.atom(info.atom);
1167 if (atom && (!newest || atom.seq > newest.seq)) newest = atom;
1169 if (!newest) return undefined;
1170 for (const space of [this.#shared, ...[...this.#spaces.values()].filter((s) => s.name !== SHARED)]) {
1171 const v = space.publishedIn.get(newest.id);
1172 if (v !== undefined) return this.#versionChange.get(`${space.name === SHARED ? "" : space.name} ${v}`);
1174 const author = this.#agents.get(newest.author);
1175 return author ? this.#currentChange(author, this.#now?.() ?? this.#lastTime) : undefined;
1178 #noteAnswer(n: NoteRecord): NoteAnswer {
1179 return hostedNoteAnswer(this.#notesHost, n);
1182 // The merge queue (#39) ------------------------------------------------------------
1184 /** Whether shared's avcs.json turns the merge queue on (`"queue": true`). */
1185 #queueOn(): boolean {
1186 return hostedQueueOn(this.#queueHost);
1189 /** With the queue on, nothing lands in shared unchecked; land and pluck don't go through the queue yet. */
1190 #notQueuedYet(what: string): void {
1191 hostedNotQueuedYet(this.#queueHost, what);
1194 /** Atoms of every queued publish, or only other agents' with `except`. */
1195 #queuedAtoms(except?: string): Set<AtomId> {
1196 return hostedQueuedAtoms(this.#queueHost, except);
1199 /** Queue the agent's publish (#39). */
1200 #enqueue(
1201 agent: AgentState,
1202 message: string,
1203 time: number,
1204 draft: readonly AtomId[],
1205 resolves: readonly AtomId[],
1206 entries: Entry[],
1207 ): PublishAnswer {
1208 return hostedEnqueue(this.#queueHost, agent, message, time, draft, resolves, entries);
1211 /** The merge queue now (#39): waiting publishes in order, and which are in the batch being checked. */
1212 queue(...args: Tail<Parameters<typeof hostedQueue>>): ReturnType<typeof hostedQueue> {
1213 return hostedQueue(this.#queueHost, ...args);
1216 /** Mark the first `n` queued publishes as the batch being checked (0 ends it). Not logged. */
1217 queueChecking(...args: Tail<Parameters<typeof hostedQueueChecking>>): ReturnType<typeof hostedQueueChecking> {
1218 return hostedQueueChecking(this.#queueHost, ...args);
1221 /** Shared with the first `n` queued publishes on top (#39): the files a batch's check runs on, and their tree hash. */
1222 queueCandidate(...args: Tail<Parameters<typeof hostedQueueCandidate>>): ReturnType<typeof hostedQueueCandidate> {
1223 return hostedQueueCandidate(this.#queueHost, ...args);
1226 /** The tree hash of a version of shared (#39): it equals a candidate's when that's what landed. */
1227 treeAt(version: number): string {
1228 const view = this.viewAt(version);
1229 return treeHash({ files: view.files(), modes: modesOf(view), blobs: view.blobs() });
1232 /**
1233 * Land the first `n` queued publishes (#39), in order, each as its own
1234 * version, after their batch passed. Each tells others what arrived, its
1235 * author that it landed, and the authors of what it settled what it kept.
1236 */
1237 queueLand(...args: Tail<Parameters<typeof hostedQueueLand>>): ReturnType<typeof hostedQueueLand> {
1238 return hostedQueueLand(this.#queueHost, ...args);
1241 /**
1242 * Take a queued publish out (#39): its check failed, or its author withdrew
1243 * it. Its changes are simply still in its author's draft. Later queued
1244 * publishes that build on its changes come out with it.
1245 */
1246 queuePull(...args: Tail<Parameters<typeof hostedQueuePull>>): ReturnType<typeof hostedQueuePull> {
1247 return hostedQueuePull(this.#queueHost, ...args);
1250 /** The agent withdraws its queued publishes (#39): refused while one is in the batch being checked. */
1251 unqueue(...args: Tail<Parameters<typeof hostedUnqueue>>): ReturnType<typeof hostedUnqueue> {
1252 return hostedUnqueue(this.#queueHost, ...args);
1255 /**
1256 * Correct the message of the agent's newest publish in its space (#27).
1257 * Only the message changes: shared only grows, so a version's changes are
1258 * fixed by publishing again (or dropping it). The log keeps the original.
1259 */
1260 amend(...args: Tail<Parameters<typeof hostedAmend>>): ReturnType<typeof hostedAmend> {
1261 return hostedAmend(this.#amendHost, ...args);
1264 /**
1265 * Put a label on a version of shared (the newest by default), or take it
1266 * off with `remove`. A label can mark many versions ("passed-ci"); a folder
1267 * follows the newest with `sync {label}`.
1268 */
1269 label(...args: Tail<Parameters<typeof hostedLabel>>): ReturnType<typeof hostedLabel> {
1270 return hostedLabel(this.#labelHost, ...args);
1273 /**
1274 * Drop published versions of shared (#10): a new shared version whose set
1275 * leaves out their changes. Later work that doesn't depend on them stays;
1276 * history keeps them. When later published work built on them, they are
1277 * refused with that work listed, unless `withDependents`, which drops it
1278 * too. Unpublished work that builds on them (an agent's draft, a named
1279 * draft not yet landed) always refuses it: drop never touches it.
1280 */
1281 drop(
1282 agentName: string,
1283 versions: readonly number[],
1284 message: string,
1285 time: number,
1286 options: { withDependents?: boolean } = {},
1287 ): DropAnswer {
1288 return hostedDrop(this.#dropHost, agentName, versions, message, time, options);
1291 /**
1292 * After a sync, merge files where the agent's draft and the newer work
1293 * collide, the way git merges a file (#25, Fuzzer): from the agent's old
1294 * base, its draft's text and the newer text. Changes both made identically
1295 * are kept once; changes on one side are kept. Only when every file
1296 * involved merges with no conflict are the draft's changes to them dropped
1297 * (a discard entry) and made again as the merged text. Otherwise nothing
1298 * changes, and the collision stands with both sides' lines in the file.
1299 */
1300 #mergeIdentical(
1301 agent: AgentState,
1302 before: ReadView,
1303 oldBase: ReadonlySet<AtomId>,
1304 oldVersion: number,
1305 time: number,
1306 entries: Entry[],
1307 ): MergedLine[] {
1308 return hostedMergeIdentical(this.#mergeHost, agent, before, oldBase, oldVersion, time, entries);
1311 /**
1312 * Names the agent's draft defines at the top level of a file where other
1313 * work defines them too, so they are defined twice there (#25, Fuzzer).
1314 */
1315 #duplicates(agent: AgentState): Collision[] {
1316 return duplicateCollisions(this.#collisionHost, agent);
1319 /**
1320 * Draft changes that build on atoms a set doesn't have (a drop took them
1321 * out): the files they touch. Those changes can't move onto that set.
1322 */
1323 #strandedFiles(draft: readonly AtomId[], set: ReadonlySet<AtomId>): string[] {
1324 return strandedFiles(this.#graph, draft, set);
1327 /** Answer a refusal, and log it (an entry that changes nothing but the counts). */
1328 #refuse(...args: Tail<Parameters<typeof hostedRefuse>>): ReturnType<typeof hostedRefuse> {
1329 return hostedRefuse(this.#refuseHost, ...args);
1332 /**
1333 * Tell other agents something, as news: "Announcement from <agent>:
1334 * <text>". It reaches each one with its next edit, record or news call.
1335 * `to` names agents; without it, every other agent the project has now.
1336 */
1337 announce(...args: Tail<Parameters<typeof hostedAnnounce>>): ReturnType<typeof hostedAnnounce> {
1338 return hostedAnnounce(this.#announceHost, ...args);
1341 /**
1342 * A signed-in person's announcement from the website (#41). The Worker has
1343 * checked who sent it; the engine records it on each recipient's news with
1344 * `from`, and never makes the person an agent. The text is JSON-quoted, so
1345 * a line break in it can't pass for another item.
1346 */
1347 announcePerson(...args: Tail<Parameters<typeof hostedAnnouncePerson>>): ReturnType<typeof hostedAnnouncePerson> {
1348 return hostedAnnouncePerson(this.#announceHost, ...args);
1351 /** The definition news the writes since the last call owe other agents, handed over once (news.ts). */
1352 takeOwedDefinitionNews(): OwedDefinitionNews[] {
1353 const owed = this.#owed;
1354 this.#owed = [];
1355 return owed;
1358 /** What a publish owes, worked out against its version (news.ts newsOwed), for `only` these agents if given. Reads only. */
1359 newsOwed(owed: OwedDefinitionNews, only?: readonly string[]): { agent: string; items: NewsItem[] }[] {
1360 return hostedNewsOwed(this.#newsHost, owed, only);
1363 /** newsOwed, under the name owed definition news had before abso 714. */
1364 definitionNewsOwed(owed: OwedDefinitionNews, only?: readonly string[]): { agent: string; items: NewsItem[] }[] {
1365 return this.newsOwed(owed, only);
1368 /** The names a publish's definitions changed (news.ts owedNewsNames), worked out once for its owed news. Reads only. */
1369 owedNewsNames(owed: OwedDefinitionNews): string[] {
1370 return hostedOwedNewsNames(this.#newsHost, owed);
1373 /** The agents a publish's owed news may be for (news.ts owedAgents). Reads only. */
1374 owedAgents(owed: OwedDefinitionNews): string[] {
1375 return hostedOwedAgents(this.#newsHost, owed);
1378 /** Tells each agent its owed items, as queueNews does: what an agent was already told adds nothing. */
1379 deliverOwedNews(found: readonly { agent: string; items: readonly NewsItem[] }[]): number {
1380 const entries: Entry[] = [];
1381 for (const { agent: name, items } of found) {
1382 const agent = this.#agents.get(name);
1383 if (agent) this.#queueNews(agent, items, entries);
1385 this.#flush(entries);
1386 return entries.length;
1389 /** A seat's earlier chat hears that another chat just used the seat (announce.ts seatNotice). */
1390 seatNotice(...args: Tail<Parameters<typeof hostedSeatNotice>>): ReturnType<typeof hostedSeatNotice> {
1391 return hostedSeatNotice(this.#announceHost, ...args);
1394 /**
1395 * Say what the agent is starting on (#37, #13), before any edit lands:
1396 * `text`, and the files it expects to change if it knows them. Nothing is
1397 * locked or refused. where and status show it until the agent publishes,
1398 * lands, or sends null. The answer names who already has unpublished
1399 * changes in, or a starting note on, those files; they hear of it too.
1400 */
1401 starting(...args: Tail<Parameters<typeof hostedStarting>>): ReturnType<typeof hostedStarting> {
1402 return hostedStarting(this.#startingHost, ...args);
1405 /** Every agent's starting note, by agent name. */
1406 startingNotes(): ReturnType<typeof hostedStartingNotes> {
1407 return hostedStartingNotes(this.#notesHost);
1410 #openCollisions(agent: AgentState): { collisions?: AgentStatus["collisions"] } {
1411 return hostedOpenCollisions(this.#markerHost, agent);
1414 /**
1415 * News when an edit leaves a file holding blocks of collision markers
1416 * (#11): how many, and how to settle them. Again whenever the count changes.
1417 */
1418 #markedNews(agent: AgentState, files: readonly string[], entries: Entry[]): void {
1419 const marked = new Set(this.#markedFiles(agent));
1420 const view = this.#agentView(agent);
1421 const items: NewsItem[] = [];
1422 for (const file of [...new Set(files)].sort()) {
1423 if (!marked.has(file) || !view.hasFile(file)) continue;
1424 const n = blocksIn(view.lines(file).map((l) => l.text)).length;
1425 if (n === 0) continue;
1426 items.push(markedItem(this.#draft(agent)[0] ?? "", file, n));
1428 this.#queueNews(agent, items, entries);
1431 /** The collided changes behind each block whose marker lines `atom` deletes (#11). */
1432 #markersSettled(agent: AgentState, view: ReadView, atom: Atom): AtomId[] {
1433 return hostedMarkersSettled(this.#markerHost, agent, view, atom);
1436 /** Files where a sync wrote the agent collision markers in its current space (#11). */
1437 #markedFiles(agent: AgentState): string[] {
1438 return hostedMarkedFiles(agent);
1441 /** The blocks of markers still in the agent's files, as collisions (#11): listed by sync and status. */
1442 #markedCollisions(agent: AgentState): Collision[] {
1443 return hostedMarkedCollisions(this.#markerHost, agent);
1446 /**
1447 * Marker lines the agent's draft adds (#11), as collisions: each
1448 * well-formed block, and any marker line left outside one. Only the labeled
1449 * lines the engine writes count, so a document that shows markers can be
1450 * published.
1451 */
1452 #markerCollisions(agent: AgentState): Collision[] {
1453 return hostedMarkerCollisions(this.#markerHost, agent);
1456 /** One line of news for each other author whose marked collision a publish settled (#11): what was kept, and any lines lost. */
1457 #settledNews(agent: AgentState, version: number, settled: readonly Settled[], entries: Entry[]): void {
1458 for (const s of settled) {
1459 const other = this.#agents.get(s.theirs.agent);
1460 if (!other || other === agent) continue;
1461 this.#queueNews(other, [settledItem(agent.name, version, s)], entries);
1465 /**
1466 * The files the agent's unpublished changes touch, in its own view. Kept per agent under what they're
1467 * made of: its view's key and its draft. Most agents haven't moved since the last
1468 * status, and the view cache holds fewer views than a big project has agents, so working them out again
1469 * on every call cost about 0.5 s on abso. A copy goes out, so no caller can change what's kept.
1470 */
1471 #draftFiles(agent: AgentState): Set<string> {
1472 const key = `${this.#agentViewKey(agent)}|${this.#draft(agent).join(",")}`;
1473 let kept = this.#draftFilesKept.get(agent.name);
1474 if (kept?.key !== key) {
1475 kept = { key, files: hostedDraftFiles(this.#overlapHost, agent) };
1476 this.#draftFilesKept.set(agent.name, kept);
1478 return new Set(kept.files);
1481 /** Other agents in the agent's space whose unpublished changes or starting note meet `patterns`. */
1482 #overlaps(...args: Tail<Parameters<typeof hostedOverlaps>>): ReturnType<typeof hostedOverlaps> {
1483 return hostedOverlaps(this.#overlapHost, ...args);
1486 /**
1487 * News the first time a draft touches a file someone else in its space has
1488 * unpublished changes in, or a starting note on (#37): one line per file and agent, once per draft. It tells; it never stops
1489 * the edit.
1490 */
1491 #overlapNews(...args: Tail<Parameters<typeof hostedOverlapNews>>): ReturnType<typeof hostedOverlapNews> {
1492 return hostedOverlapNews(this.#overlapHost, ...args);
1495 /** The news waiting for an agent, read only: nothing is taken, heard or written. None for an agent it hasn't got. */
1496 peekNews(agentName: string): { text: string; at: number | null }[] {
1497 const agent = typeof agentName === "string" ? this.#agents.get(agentName) : undefined;
1498 return agent ? agent.news.map((text, i) => ({ text, at: agent.newsAt[i] ?? null })) : [];
1501 /** Whether the project has this agent. Read only. */
1502 hasAgent(agentName: string): boolean {
1503 return typeof agentName === "string" && this.#agents.get(agentName) !== undefined;
1506 /** Hand over the news waiting for an agent (collisions, definitions, moves, announcements), once. */
1507 news(agentName: string): { news: string[]; items: { text: string; at: number | null }[] } {
1508 const entries: Entry[] = [];
1509 const agent = this.#agent(agentName, entries);
1510 const items = agent.news.map((text, i) => ({ text, at: agent.newsAt[i] ?? null }));
1511 const news = this.#takeNews(agent, entries);
1512 this.#flush(entries);
1513 return { news, items };
1516 /** Refused publishes and lands, newest first (`limit` defaults to 50), with counts over all of them. */
1517 refusals(...args: Tail<Parameters<typeof hostedRefusals>>): ReturnType<typeof hostedRefusals> {
1518 return hostedRefusals(this.#refuseHost, ...args);
1521 /**
1522 * Move the agent's base to its space's newest version. Returns every file
1523 * whose text in its view changes (null when it's gone), and the collisions
1524 * it now has to settle. A first sync returns every file (that's how a
1525 * folder joins).
1526 */
1527 sync(...args: Tail<Parameters<typeof hostedSync>>): ReturnType<typeof hostedSync> {
1528 return hostedSync(this.#syncHost, ...args);
1531 /**
1532 * Move the agent to a named draft, or back to shared with null. Its
1533 * unpublished changes stay parked on the server in the space it leaves,
1534 * and what it parked in the space it moves to comes back. Nothing is lost
1535 * and nothing has to be published or stashed first. A new named draft
1536 * starts on shared's newest version; with `carry`, the agent's current
1537 * unpublished changes move into it instead of being parked. Answers like a
1538 * sync: the files that change in its folder.
1539 */
1540 switchTo(...args: Tail<Parameters<typeof hostedSwitchTo>>): ReturnType<typeof hostedSwitchTo> {
1541 return hostedSwitchTo(this.#switchHost, ...args);
1544 /**
1545 * Move the agent's named draft onto shared's newest version. The draft's
1546 * agents see it when they next sync; anything it collides with is theirs
1547 * to settle before the draft lands.
1548 */
1549 syncDraft(agentName: string, time: number): DraftSyncAnswer {
1550 const entries: Entry[] = [];
1551 const agent = this.#agent(agentName, entries);
1552 const space = this.#namedSpaceOf(agent);
1553 const ownOnly = [...space.own].filter((id) => !this.#shared.own.has(id) && !this.#shared.droppedIn.has(id));
1554 const stranded = this.#strandedFiles(ownOnly, this.#shared.own);
1555 if (stranded.length > 0) {
1556 throw new ProjectError(
1557 "conflict",
1558 `draft ${space.name} has changes to ${stranded.join(", ")} that build on lines a drop took out of shared`,
1559 );
1561 if (sharedBaseOf(space) !== this.version) {
1562 entries.push({
1563 type: "space-sync",
1564 space: space.name,
1565 agent: agent.name,
1566 time,
1567 version: last(space) + 1,
1568 sharedBase: this.version,
1569 });
1570 this.#apply(entries[entries.length - 1]!);
1572 this.#flush(entries);
1573 return { draft: space.name, version: last(space), sharedBase: sharedBaseOf(space) };
1576 /**
1577 * Land the agent's named draft in shared as one unit: every change
1578 * published into it that shared doesn't have yet. Refused, like a publish,
1579 * when those changes collide with work that landed in shared after the
1580 * draft's base; sync the draft, settle, and land again.
1581 */
1582 land(...args: Tail<Parameters<typeof hostedLand>>): ReturnType<typeof hostedLand> {
1583 return hostedLand(this.#landHost, ...args);
1586 /**
1587 * What landing `changes` of a named draft would collide with in shared now (#41, the Drafts page reads it
1588 * too): the same pairs and definitions land refuses on.
1589 */
1590 #landCollisions(
1591 space: Space,
1592 changes: AtomId[],
1593 pick: boolean,
1594 ): { collisions: Collision[]; newer: ReadonlySet<AtomId>; union: ReadonlySet<AtomId> } {
1595 return hostedLandCollisions(this.#landHost, space, changes, pick);
1598 /**
1599 * A named draft's state in one read (#41, the Drafts page, D3 and D16): the shared version it builds on and
1600 * how far behind shared that is, its versions, when its first edit was, who works in it, and what landing it
1601 * now would collide with (the same check land makes, so nothing is written).
1602 */
1603 draftState(...args: Tail<Parameters<typeof hostedDraftState>>): ReturnType<typeof hostedDraftState> {
1604 return hostedDraftState(this.#draftStateHost, ...args);
1607 #land(
1608 agent: AgentState,
1609 message: string,
1610 time: number,
1611 entries: Entry[],
1612 pick?: { space: Space; changes: AtomId[] },
1613 ): LandAnswer {
1614 return hostedLandDraft(this.#landHost, agent, message, time, entries, pick);
1617 /**
1618 * Take part of a named draft into shared (#27): the changes of some of its
1619 * versions, as one new version of shared, checked for collisions like a
1620 * land. When they build on other versions of the draft, those are listed
1621 * and it is refused, unless `withDependencies` takes them too. The draft
1622 * stays as it is; landing it later brings in only what's left.
1623 */
1624 pluck(
1625 agentName: string,
1626 draftName: string,
1627 versions: readonly number[],
1628 message: string,
1629 time: number,
1630 options: { withDependencies?: boolean } = {},
1631 ): PluckAnswer {
1632 return hostedPluck(this.#pluckHost, agentName, draftName, versions, message, time, options);
1635 /**
1636 * Take in commits a person pushed with plain git (demo moment 5, #5, #8).
1637 * `base` is the shared version their first commit builds on (the
1638 * `avcs-version` of the commit they cloned). Each commit gives its whole
1639 * tree as text; a file of the view missing from it is deleted. The commits
1640 * go into a named draft `git-<sha>` on that version, one publish each, and
1641 * the draft lands in shared at once if nothing collides. The push already
1642 * happened, so a collision isn't refused: the draft waits, with its
1643 * collisions listed, for someone to switch to it, settle and land it.
1644 */
1645 ingest(...args: Tail<Parameters<typeof hostedIngest>>): ReturnType<typeof hostedIngest> {
1646 return hostedIngest(this.#ingestHost, ...args);
1649 // Reading history, and discarding -------------------------------------------
1651 #checkVersion(space: Space, version: number): void {
1652 hostedCheckVersion(space, version);
1655 /**
1656 * Discard the agent's unpublished changes to some files (all of them with
1657 * `files` null), like git restore. Changes that touch only those files and
1658 * that no kept change builds on leave the draft; anything left over is
1659 * undone by a new change that puts the files back. Answers with each
1660 * file's text now, for the folder.
1661 */
1662 restore(...args: Tail<Parameters<typeof hostedRestore>>): ReturnType<typeof hostedRestore> {
1663 return hostedRestore(this.#restoreHost, ...args);
1666 /** The space options name: an agent's current space with `agent`, else the named draft, else shared. */
1667 #spaceFor(options: { draft?: string | null; agent?: string }): Space {
1668 if (options.agent !== undefined) {
1669 const agent = this.#agents.get(options.agent);
1670 if (!agent) throw new ProjectError("bad-request", `there is no agent ${JSON.stringify(options.agent)}`);
1671 return this.#spaceOf(agent);
1673 return this.#spaceNamed(options.draft ?? null);
1676 #spaceNamed(name: string | null): Space {
1677 const key = name === null ? SHARED : checkDraftName(name);
1678 const space = this.#spaces.get(key);
1679 if (!space) throw new ProjectError("bad-request", `there is no draft ${String(name)}`);
1680 return space;
1683 /**
1684 * The stored spelling a read means (#41, F7, the rule #49 set for writes):
1685 * the path itself, else the one file it matches by pathKey; failing that,
1686 * the one file ever in the view it matches, for a file since taken out.
1687 * A path that matches two files is answered exactly.
1688 */
1689 spellingIn(view: ReadView, path: string): string {
1690 if (view.hasFile(path)) return path;
1691 const key = pathKey(path);
1692 const live = view.knownPaths().filter((p) => pathKey(p) === key && view.hasFile(p));
1693 if (live.length > 0) return live.length === 1 ? live[0]! : path;
1694 const known = view.knownPaths();
1695 if (known.includes(path)) return path;
1696 const gone = known.filter((p) => pathKey(p) === key);
1697 return gone.length === 1 ? gone[0]! : path;
1700 // Applying entries ------------------------------------------------------------
1702 #apply(entry: Entry): void {
1703 // Entries written before #41 have no time on these kinds; new ones do, so replay can place them.
1704 const kept =
1705 this.#loading || !UNTIMED.has(entry.type) || "time" in entry ? entry : ({ ...entry, time: Date.now() } as Entry);
1706 if (!this.#loading) this.#pending.push(kept);
1707 const at = this.#loading ? this.#stored : this.#stored + this.#pending.length - 1;
1708 // Positions by time (#41, the website): the newest time up to each position, as the log holds it.
1709 const keptTime =
1710 kept.type === "draft" ? kept.atom.time : "time" in kept && typeof kept.time === "number" ? kept.time : undefined;
1711 const prior = at > 0 ? this.#timeAt[at - 1]! : 0;
1712 this.#timeAt[at] = keptTime !== undefined && keptTime > prior ? keptTime : prior;
1713 const versionsBefore = this.#spaces.get(SHARED)?.versions.length ?? 0;
1714 try {
1715 this.#applyEntry(entry, at, keptTime);
1716 // Shared's closure, kept per version on disk (abso Capacity): after the entry, since its atoms join the graph after
1717 // its membership.
1718 if (this.#writerStorage && (this.#spaces.get(SHARED)?.versions.length ?? 0) > versionsBefore) {
1719 const shared = this.#spaces.get(SHARED)!;
1720 const storage = this.#writerStorage;
1721 indexClosure(storage, shared, this.#graph);
1722 // Each new version's changed files, from what it touched (version-files.ts): kept in the shapes table when
1723 // the host gives one, so the log, a path's history and the tree never lay versions out to find them.
1724 const host: VersionFilesHost = {
1725 storage,
1726 graph: this.#graph,
1727 at: (v) => this.#at(shared, v),
1728 viewAt: (v) => this.#viewAt(shared, v),
1729 empty: () => new View(this.#graph, []),
1730 closureChangedAt: (v) => closureChangedAt(storage, v),
1731 };
1732 for (let v = versionsBefore; v < shared.versions.length; v++) {
1733 const { files, exists } = keptVersionFiles(host, shared.versions[v]!);
1734 this.#paths.keep(shared, v, files, v === 0 ? host.empty() : host.viewAt(v - 1), host.viewAt(v), exists);
1737 } finally {
1738 // Positions by version: where each version of shared was made.
1739 const versionsAfter = this.#spaces.get(SHARED)?.versions.length ?? 0;
1740 for (let v = versionsBefore; v < versionsAfter; v++) this.#versionAt[v] = at;
1744 /**
1745 * The log position for a time or a version of shared (#41, the website):
1746 * for `time`, the position just after the last entry no later than it
1747 * (entries with no time take their predecessor's); for `version`, the
1748 * position just after the entry that made it. `end` is the log's length.
1749 */
1750 position(q: { time?: number; version?: number }): { position: number; end: number } {
1751 const end = this.#timeAt.length;
1752 if (q.version !== undefined) {
1753 if (!Number.isInteger(q.version) || q.version < 0 || q.version >= this.#versionAt.length)
1754 throw new ProjectError("not-found", `there is no version ${String(q.version)}`);
1755 return { position: this.#versionAt[q.version]! + 1, end };
1757 if (typeof q.time !== "number" || !Number.isFinite(q.time))
1758 throw new ProjectError("bad-request", "position needs ?time= or ?version=");
1759 // The newest time up to each position never goes down, so halve.
1760 let lo = 0;
1761 let hi = end;
1762 while (lo < hi) {
1763 const mid = (lo + hi) >> 1;
1764 if (this.#timeAt[mid]! <= q.time) lo = mid + 1;
1765 else hi = mid;
1767 return { position: lo, end };
1770 #applyEntry(entry: Entry, at: number, time: number | undefined): void {
1771 hostedApplyEntry(this.#applyEntryHost, entry, at, time);
1774 /** Apply entries and store them. */
1775 #commit(entries: Entry[]): void {
1776 for (const e of entries) this.#apply(e);
1777 this.#flush(entries);
1780 /** Store entries that are already applied. */
1781 #flush(_entries: readonly Entry[]): void {
1782 if (this.#pending.length === 0) return;
1783 const out = this.#pending;
1784 this.#store.append(out);
1785 if (this.#newsWritten) {
1786 const items: NewsWritten[] = [];
1787 out.forEach((entry, i) => {
1788 if (entry.type !== "news") return;
1789 for (const text of entry.text)
1790 items.push({ agent: entry.agent, text, at: entry.time ?? null, seq: this.#stored + i });
1791 });
1792 if (items.length > 0) this.#newsWritten(items);
1794 this.#persistMutable();
1795 // A few more agents' old told lists into their buckets at each write, until every row has moved (writer-agents.ts).
1796 if (this.#agents instanceof WriterAgents) this.#agents.moveOldTold(OLD_TOLD_PER_WRITE);
1797 this.#pending = [];
1798 this.#stored += out.length;
1799 this.#writeCheckpoint();
1802 #writeCheckpoint(): void {
1803 this.#writerStorage?.write("project:meta", "checkpoint", {
1804 format: 1,
1805 logLength: this.#stored,
1806 atoms: this.#graph.size,
1807 version: this.version,
1808 });
1811 #persistMutable(): void {
1812 if (!this.#writerStorage) return;
1813 if (this.#agents instanceof WriterAgents) this.#agents.flush();
1814 this.#writerStorage.write("project:meta", "mods", this.#mods);
1815 this.#writerStorage.write("project:meta", "queue", this.#queue);
1816 this.#writerStorage.write(
1817 "project:meta",
1818 "tells",
1819 [...this.#tells].map(([id, tell]) => [id, { ...tell, heard: [...tell.heard] }]),
1820 );
1823 /**
1824 * The agent an entry names. Before every applied entry was stored, a call
1825 * that joined an agent and then threw could leave the join out of the log
1826 * while later entries named the agent. The lost join had the version the
1827 * project was at then, which is the version now, during replay.
1828 */
1829 #agentOf(name: string): AgentState {
1830 let agent = this.#agents.get(name);
1831 if (!agent) {
1832 this.#apply({ type: "join", agent: name, version: this.#shared.versions.length - 1 });
1833 agent = this.#agents.get(name)!;
1835 return agent;
1838 // Agents, spaces and views ----------------------------------------------------
1840 get #shared(): Space {
1841 return this.#spaces.get(SHARED)!;
1844 #needInit(): void {
1845 if (!this.initialized) throw new ProjectError("not-initialized", "the project has no files yet; init it first");
1848 #agent(name: string, entries: Entry[]): AgentState {
1849 this.#needInit();
1850 if (typeof name !== "string" || !NAME.test(name) || name === "init") {
1851 throw new ProjectError(
1852 "bad-agent",
1853 `bad agent name ${JSON.stringify(name)}: letters, digits, '.', '_' and '-', up to 64`,
1854 );
1856 let agent = this.#agents.get(name);
1857 if (!agent) {
1858 const join: Entry = { type: "join", agent: name, version: this.version };
1859 entries.push(join);
1860 this.#apply(join);
1861 agent = this.#agents.get(name)!;
1863 return agent;
1866 #spaceOf(agent: AgentState): Space {
1867 return this.#spaces.get(agent.space)!;
1870 #namedSpaceOf(agent: AgentState): Space {
1871 if (agent.space === SHARED) {
1872 throw new ProjectError("bad-request", `${agent.name} works in shared, not a named draft; switch to one first`);
1874 return this.#spaceOf(agent);
1877 // History reads (#41), in history.ts behind HistoryHost (#46, disk-first 1) ------------------------
1879 #host?: HistoryHost;
1880 /** The project as the history reads see it: the seam the derived tables plug into (abso issues 48, 79). */
1881 get #history(): HistoryHost {
1882 this.#host ??= {
1883 graph: this.#graph,
1884 agents: this.#agents,
1885 spaces: this.#spaces,
1886 needInit: () => this.#needInit(),
1887 spaceNamed: (name) => this.#spaceNamed(name),
1888 checkVersion: (space, version) => this.#checkVersion(space, version),
1889 viewAt: (space, version) => this.#viewAt(space, version),
1890 keptPaths: (space, version) => this.#keptPaths(space, version),
1891 authorTotals: (space, version, agent) => this.#authorTotals(space, version, agent as AgentState | undefined),
1892 agentTouched: (agent) => this.#agentTouched(agent as AgentState),
1893 agentView: (agent) => this.#agentView(agent as AgentState),
1894 spellingIn: (view, asked) => this.spellingIn(view, asked),
1895 pathsOf: (space) => this.#paths.pathsOf(space),
1896 lastChange: (space, version) => this.#paths.lastChange(space, version),
1897 atOrBefore: (list, version) => PathIndex.atOrBefore(list, version),
1898 removedIn: (space, from, to, line) => this.#paths.removedIn(space, from, to, line),
1899 };
1900 return this.#host;
1903 /** Shared's file list from kept shapes on a stored writer, where a version's layout reads its files from disk. */
1904 #keptPaths(space: Space, version: number): string[] | undefined {
1905 return this.#writerStorage && space.name === SHARED ? this.#paths.keptPaths(space, version) : undefined;
1908 /**
1909 * Each file's kept author totals for tree with authors (version-files.ts), on a stored writer and for shared only. An
1910 * agent's view takes its base's totals for every file its draft doesn't touch, as its layout does (touchedBeyond),
1911 * and lays out the rest; a draft that moves lines lays out everything.
1912 */
1913 #authorTotals(
1914 space: Space,
1915 version: number,
1916 agent?: AgentState,
1917 ): ((path: string) => FileTotals | undefined) | undefined {
1918 const storage = this.#writerStorage;
1919 if (!storage || space.name !== SHARED || authoredVersion(storage) === undefined) return undefined;
1920 if (!agent) return (path) => authorTotalsAt(storage, path, version);
1921 const except = this.#agentTouched(agent);
1922 if (!except) return undefined;
1923 return (path) => (except.has(path) ? undefined : authorTotalsAt(storage, path, version));
1926 /**
1927 * The files an agent's draft, and whatever it depends on beyond its base, can make differ from its base
1928 * (touchedBeyond); every other file is the same in both. Undefined when the draft moves lines.
1929 */
1930 #agentTouched(agent: AgentState): ReadonlySet<string> | undefined {
1931 if (agent.mine.length === 0) return new Set();
1932 const base = this.#viewAt(this.#spaceOf(agent), agent.base);
1933 const view = this.#agentView(agent);
1934 return touchedBeyond(this.#graph, base.set, agent.mine, [base, view], () => placedBetween(view, base));
1937 /**
1938 * Kept author totals for a folder's blame (blame.ts), where blame reads: shared at a version (the newest by default) or
1939 * an agent's view. A named draft has none. Undefined when none are kept.
1940 */
1941 authorTotalsFor(where: {
1942 version?: number;
1943 draft?: string;
1944 agent?: string;
1945 }): ((path: string) => FileTotals | undefined) | undefined {
1946 if (where.draft !== undefined) return undefined;
1947 if (where.agent !== undefined) {
1948 const agent = this.#agents.get(where.agent);
1949 return agent ? this.#authorTotals(this.#spaceOf(agent), agent.base, agent) : undefined;
1951 return this.#authorTotals(this.#shared, where.version ?? last(this.#shared));
1954 /** One folder at a version (history.ts). */
1955 tree(...args: Tail<Parameters<typeof historyTree>>): ReturnType<typeof historyTree> {
1956 return historyTree(this.#history, ...args);
1959 /** A path's life at a version (history.ts). */
1960 pathLife(...args: Tail<Parameters<typeof historyPathLife>>): ReturnType<typeof historyPathLife> {
1961 return historyPathLife(this.#history, ...args);
1964 /** Where lines went after a version (history.ts). */
1965 follow(...args: Tail<Parameters<typeof historyFollow>>): ReturnType<typeof historyFollow> {
1966 return historyFollow(this.#history, ...args);
1969 // The version list (log, ribbon, show), in version-log.ts behind LogHost ----------------------------
1971 #logs?: LogHost;
1972 get #logHost(): LogHost {
1973 this.#logs ??= {
1974 graph: this.#graph,
1975 paths: this.#paths,
1976 labels: this.#labels,
1977 shared: () => this.#shared,
1978 needInit: () => this.#needInit(),
1979 spaceFor: (options) => this.#spaceFor(options),
1980 checkVersion: (space, version) => this.#checkVersion(space, version),
1981 viewAt: (space, version) => this.#viewAt(space, version),
1982 view: (set) => this.#view(set),
1983 at: (space, version) => this.#at(space, version),
1984 spellingIn: (view, path) => this.spellingIn(view, path),
1985 versionChange: (space, version) =>
1986 this.#versionChange.get(`${space.name === SHARED ? "" : space.name} ${version}`),
1987 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
1988 };
1989 return this.#logs;
1992 /** The versions of shared (or of a named draft), newest first (version-log.ts). */
1993 log(...args: Tail<Parameters<typeof versionLog>>): ReturnType<typeof versionLog> {
1994 return versionLog(this.#logHost, ...args);
1997 /** Shared's versions in one small answer, for the website's version ribbon (version-log.ts). */
1998 ribbon(): ReturnType<typeof versionRibbon> {
1999 return versionRibbon(this.#logHost);
2002 /** One version of shared (or of a named draft) and the files it changed (version-log.ts). */
2003 show(...args: Tail<Parameters<typeof versionShow>>): ReturnType<typeof versionShow> {
2004 return versionShow(this.#logHost, ...args);
2007 /** A file as it was at a version of shared (or a named draft) (version-log.ts). */
2008 fileAt(...args: Tail<Parameters<typeof versionFileAt>>): ReturnType<typeof versionFileAt> {
2009 return versionFileAt(this.#logHost, ...args);
2012 /** fileAt for exactly this spelling, from the file's own lines: no list of the version's files (version-log.ts). */
2013 fileExactAt(...args: Tail<Parameters<typeof versionFileExactAt>>): ReturnType<typeof versionFileExactAt> {
2014 return versionFileExactAt(this.#logHost, ...args);
2017 /** Every file that differs between two versions of shared (or a named draft) (version-log.ts). */
2018 compare(...args: Tail<Parameters<typeof versionCompare>>): ReturnType<typeof versionCompare> {
2019 return versionCompare(this.#logHost, ...args);
2022 /** compare as each file's size and SHA-256, not its texts (version-log.ts, abso issue 680). */
2023 compareSummary(...args: Tail<Parameters<typeof versionCompareSummary>>): ReturnType<typeof versionCompareSummary> {
2024 return versionCompareSummary(this.#logHost, ...args);
2027 /** A version of shared without some earlier versions, or the refusal naming what builds on them (without.ts). */
2028 without(version: number, versions: readonly number[]): ReturnType<typeof hostedWithout> {
2029 const host: WithoutHost = {
2030 graph: this.#graph,
2031 shared: () => this.#shared,
2032 needInit: () => this.#needInit(),
2033 checkVersion: (space, v) => this.#checkVersion(space, v),
2034 viewAt: (space, v) => this.#viewAt(space, v),
2035 at: (space, v) => this.#at(space, v),
2036 closed: (set) => this.#closed(set),
2037 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
2038 };
2039 return hostedWithout(host, version, versions);
2042 /** A version of shared (or of a named draft) as a ReadView (version-log.ts). */
2043 viewAt(...args: Tail<Parameters<typeof versionViewAt>>): ReturnType<typeof versionViewAt> {
2044 return versionViewAt(this.#logHost, ...args);
2047 // Whether agents' drafts would collide, in draft-collisions.ts behind DraftCollisionHost -------------
2049 #draftCollisionHost?: DraftCollisionHost;
2050 get #draftCollisions(): DraftCollisionHost {
2051 this.#draftCollisionHost ??= {
2052 graph: this.#graph,
2053 agents: this.#agents,
2054 needInit: () => this.#needInit(),
2055 shared: () => this.#shared,
2056 sharedView: () => this.#sharedView(),
2057 definitionRule: () => this.#definitionRule,
2058 draft: (agent) => this.#draft(agent as AgentState),
2059 agentView: (agent) => this.#agentView(agent as AgentState),
2060 draftsView: (agents) => this.#draftsView(agents as readonly AgentState[]),
2061 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
2062 // On a stored writer only, as a reader kept between calls is (abso Capacity).
2063 keptParts: () => (this.#writerStorage ? (this.#keptParts ??= new KeptParts()) : undefined),
2064 draftKey: (agent) => {
2065 const a = agent as AgentState;
2066 return `${last(this.#shared)} ${a.space}@${a.base} ${this.#draft(a).join(",")}`;
2067 },
2068 };
2069 return this.#draftCollisionHost;
2072 /**
2073 * Shared now with some agents' drafts on top, for draft collisions (abso Capacity). Kept under the drafts' atoms and
2074 * shared's version, so a second ask with nothing changed lays nothing out again, and laid out as shared is for every
2075 * file the drafts don't touch, as an agent's view is. One agent based on shared's newest version is its own view.
2076 */
2077 #draftsView(agents: readonly AgentState[]): ReadView {
2078 const shared = this.#shared;
2079 const version = last(shared);
2080 const only = agents.length === 1 ? agents[0]! : undefined;
2081 if (only && only.space === SHARED && only.base === version) return this.#agentView(only);
2082 const drafts = agents.map((agent) => this.#draft(agent));
2083 const mine = drafts.flat();
2084 const base = this.#sharedView();
2085 const view = this.#viewKeyed(`d ${SHARED}@${version}+${drafts.map((d) => d.join(",")).join("+")}`, () =>
2086 unionOverlay(base.set, mine),
2087 );
2088 if (this.#writerStorage && mine.length > 0 && view instanceof View && base instanceof View) {
2089 view.shareMoves(base);
2090 view.shareFiles(base, () =>
2091 touchedBeyond(this.#graph, base.set, mine, [base, view], () => placedBetween(view, base)),
2092 );
2094 return view;
2097 /** Whether agents' unpublished changes would collide, by the publish rule (draft-collisions.ts). */
2098 collisions(...args: Tail<Parameters<typeof draftCollisions>>): ReturnType<typeof draftCollisions> {
2099 return draftCollisions(this.#draftCollisions, ...args);
2102 // An agent's unpublished changes, in draft-diff.ts behind DraftDiffHost -----------------------------
2104 #draftDiffHost?: DraftDiffHost;
2105 get #draftDiff(): DraftDiffHost {
2106 this.#draftDiffHost ??= {
2107 agents: this.#agents,
2108 needInit: () => this.#needInit(),
2109 draft: (agent) => this.#draft(agent as AgentState),
2110 agentView: (agent) => this.#agentView(agent as AgentState),
2111 agentViewWithout: (agent, excluded) => {
2112 const state = agent as AgentState;
2113 return this.#agentView({ ...state, mine: state.mine.filter((id) => !excluded.has(id)) });
2114 },
2115 view: (set) => this.#view(set),
2116 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
2117 };
2118 return this.#draftDiffHost;
2121 /** What the agent's unpublished changes do, file by file (draft-diff.ts). Creates the agent if needed. */
2122 diff(agentName: string): DiffAnswer {
2123 const entries: Entry[] = [];
2124 const answer = diffOfAgent(this.#draftDiff, this.#agent(agentName, entries));
2125 this.#flush(entries);
2126 return answer;
2129 /** An agent's draft diff for a reader: never creates the agent, never writes (draft-diff.ts). */
2130 diffOf(...args: Tail<Parameters<typeof draftDiffOf>>): ReturnType<typeof draftDiffOf> {
2131 return draftDiffOf(this.#draftDiff, ...args);
2134 // Unpublished deletes-and-writes of the same text become a move (express-moves.ts) -----------------
2136 #movesHost?: ExpressMovesHost;
2137 get #expressMovesHost(): ExpressMovesHost {
2138 this.#movesHost ??= {
2139 graph: this.#graph,
2140 draft: (agent) => this.#unqueuedDraft(agent),
2141 beforeDraft: (agent, draft) => {
2142 const base = this.#at(this.#spaceOf(agent), agent.base);
2143 if (draft.some((id) => base.has(id)))
2144 return this.#view(differenceSet(this.#agentView(agent).set, new StableOverlaySet(draft)));
2145 const removed = new Set(draft),
2146 kept = agent.mine.filter((id) => !removed.has(id));
2147 return kept.length === 0
2148 ? this.#viewAt(this.#spaceOf(agent), agent.base)
2149 : this.#viewKeyed(`a ${agent.space}@${agent.base}+${kept.join(",")}`, () => unionOverlay(base, kept));
2150 },
2151 agentView: (agent) => this.#agentView(agent),
2152 view: (set) => this.#view(set),
2153 apply: (entry) => this.#apply(entry),
2154 addDraft: (agent, view, input, time, meta, entries) => this.#addDraft(agent, view, input, time, meta, entries),
2155 recordFile: (agent, view, path, text, time, meta, entries, mode) =>
2156 this.#recordFile(agent, view, path, text, time, meta, entries, mode),
2157 };
2158 return this.#movesHost;
2161 // Files kept whole, in whole-files.ts behind WholeHost ----------------------------------------------
2163 #wholes?: WholeHost;
2164 get #wholeHost(): WholeHost {
2165 this.#wholes ??= {
2166 initialized: () => this.initialized,
2167 sharedView: () => this.#sharedView(),
2168 whole: this.#whole,
2169 };
2170 return this.#wholes;
2173 // Notes list and start notes, in notes.ts behind NoteHost -------------------------------------------
2175 #news?: NewsHost;
2176 get #newsHost(): NewsHost {
2177 this.#news ??= {
2178 graph: this.#graph,
2179 agents: this.#agents,
2180 draft: (agent) => this.#draft(agent),
2181 newerFor: (agent) => this.#newerFor(agent),
2182 spaceOf: (agent) => this.#spaceOf(agent),
2183 setOf: (space) => this.#setOf(space),
2184 viewAt: (space, version) => this.#viewAt(space, version),
2185 origin: (atom, spaceName) => this.#origin(atom, spaceName),
2186 collision: (agent, pair) => this.#collision(agent, pair),
2187 definitionCollisions: (agent, newer, names) => this.#definitionCollisions(agent, newer, names),
2188 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
2189 logLine: (line) => this.#logLine?.(line),
2190 owesDefinitionNews: () => this.owesDefinitionNews,
2191 owe: (owed) => void this.#owed.push(owed),
2192 spaceNamed: (name) => (name === SHARED ? this.#shared : this.#spaces.get(name)),
2193 newerAt: (agent, version) => this.#newerFor(agent, version),
2194 definitionCollisionsAt: (agent, newer, names, version) =>
2195 this.#definitionCollisions(agent, newer, names, version),
2196 setAt: (space, version) => this.#at(space, version),
2197 collisionAt: (agent, pair, version) =>
2198 this.#describe(pair, this.#agentView(agent), this.#viewAt(this.#spaceOf(agent), version), agent.space),
2199 };
2200 return this.#news;
2203 #collisions?: CollisionHost;
2204 get #collisionHost(): CollisionHost {
2205 this.#collisions ??= {
2206 graph: this.#graph,
2207 spaces: this.#spaces,
2208 version: () => this.version,
2209 spaceOf: (agent) => this.#spaceOf(agent),
2210 agentSet: (agent) => unionOverlay(this.#at(this.#spaceOf(agent), agent.base), agent.mine),
2211 draft: (agent) => this.#draft(agent),
2212 agentView: (agent) => this.#agentView(agent),
2213 at: (space, version) => this.#at(space, version),
2214 shared: () => this.#shared,
2215 };
2216 return this.#collisions;
2219 #markers?: MarkerHost;
2220 get #markerHost(): MarkerHost {
2221 this.#markers ??= {
2222 graph: this.#graph,
2223 agentView: (agent) => this.#agentView(agent),
2224 draft: (agent) => this.#draft(agent),
2225 draftFiles: (agent) => this.#draftFiles(agent),
2226 };
2227 return this.#markers;
2230 #noteWrites?: NoteWriteHost;
2231 get #noteWriteHost(): NoteWriteHost {
2232 this.#noteWrites ??= {
2233 notes: this.#notes,
2234 agents: this.#agents,
2235 changes: this.#changes,
2236 graph: this.#graph,
2237 lastNote: () => this.#lastNote,
2238 agentView: (agent) => this.#agentView(agent),
2239 viewAtVersion: (version) => this.viewAt(version),
2240 sharedView: () => this.#sharedView(),
2241 changeOfLines: (lines) => this.#changeOfLines(lines),
2242 apply: (entry) => this.#apply(entry),
2243 flush: (entries) => this.#flush(entries),
2244 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
2245 noteAnswer: (n) => this.#noteAnswer(n),
2246 };
2247 return this.#noteWrites;
2250 #noteHost?: NoteHost;
2251 get #notesHost(): NoteHost {
2252 this.#noteHost ??= {
2253 graph: this.#graph,
2254 agents: this.#agents,
2255 spaces: this.#spaces,
2256 notes: this.#notes,
2257 initialized: () => this.initialized,
2258 shared: () => this.#shared,
2259 sharedView: () => this.#sharedView(),
2260 spellingIn: (view, path) => this.spellingIn(view, path),
2261 viewAt: (space, version) => this.#viewAt(space, version),
2262 agentView: (agent) => this.#agentView(agent),
2263 view: (set) => this.#view(set),
2264 at: (space, version) => this.#at(space, version),
2265 liveNote: (agent) => this.#liveNote(agent),
2266 };
2267 return this.#noteHost;
2270 #merges?: MergeHost;
2271 get #mergeHost(): MergeHost {
2272 this.#merges ??= {
2273 graph: this.#graph,
2274 openPairs: (agent) => this.#openPairs(agent),
2275 draft: (agent) => this.#unqueuedDraft(agent),
2276 origin: (atom, spaceName) => this.#origin(atom, spaceName),
2277 view: (set) => this.#view(set),
2278 viewAt: (space, version) => this.#viewAt(space, version),
2279 spaceOf: (agent) => this.#spaceOf(agent),
2280 apply: (entry) => this.#apply(entry),
2281 agentView: (agent) => this.#agentView(agent),
2282 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
2283 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
2284 };
2285 return this.#merges;
2288 #edits?: EditHost;
2289 get #editHost(): EditHost {
2290 this.#edits ??= {
2291 agents: this.#agents,
2292 whole: this.#whole,
2293 initialized: () => this.initialized,
2294 agentView: (agent) => this.#agentView(agent),
2295 sharedView: () => this.#sharedView(),
2296 isWhole: (path, length, view, rules) => this.#isWhole(path, length, view, rules),
2297 wholeRules: (config) => this.#wholeRules(config),
2298 record: (agentName, files, time, modes, blobs, meta) => this.record(agentName, files, time, modes, blobs, meta),
2299 agent: (name, entries) => this.#agent(name, entries),
2300 draftFiles: (agent) => this.#draftFiles(agent),
2301 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
2302 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
2303 addDraft: (agent, view, input, time, meta, entries) => this.#addDraft(agent, view, input, time, meta, entries),
2304 overlapNews: (agent, before, entries) => this.#overlapNews(agent, before, entries),
2305 markedNews: (agent, files, entries) => this.#markedNews(agent, files, entries),
2306 newsAboutOwnDraft: (agent, entries) => this.#newsAboutOwnDraft(agent, entries),
2307 takeNews: (agent, entries) => this.#takeNews(agent, entries),
2308 flush: (entries) => this.#flush(entries),
2309 };
2310 return this.#edits;
2313 #announces?: AnnounceHost;
2314 get #announceHost(): AnnounceHost {
2315 this.#announces ??= {
2316 agents: this.#agents,
2317 announced: () => this.#announced,
2318 setAnnounced: (n) => {
2319 this.#announced = n;
2320 },
2321 agent: (name, entries) => this.#agent(name, entries),
2322 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
2323 apply: (entry) => this.#apply(entry),
2324 flush: (entries) => this.#flush(entries),
2325 needInit: () => this.#needInit(),
2326 };
2327 return this.#announces;
2330 #publishers?: PublishHost;
2331 get #publishHost(): PublishHost {
2332 this.#publishers ??= {
2333 agents: this.#agents,
2334 nextAt: () => this.#nextAt,
2335 checkClash: (changes, ahead) => this.#checkClash(changes, ahead),
2336 queueOn: () => this.#queueOn(),
2337 queuedAtoms: (except) => this.#queuedAtoms(except),
2338 agent: (name, entries) => this.#agent(name, entries),
2339 draft: (agent) => this.#draft(agent),
2340 spaceOf: (agent) => this.#spaceOf(agent),
2341 strandedFiles: (draft, set) => this.#strandedFiles(draft, set),
2342 setOf: (space) => this.#setOf(space),
2343 markedFiles: (agent) => this.#markedFiles(agent),
2344 agentView: (agent) => this.#agentView(agent),
2345 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
2346 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
2347 expressMoves: (agent, time, entries) => this.#expressMoves(agent, time, entries),
2348 pairs: (draft, against, settled) => this.#pairs(draft, against, settled),
2349 collision: (agent, pair) => this.#collision(agent, pair),
2350 definitionCollisions: (agent, newer) => this.#definitionCollisions(agent, newer),
2351 duplicates: (agent) => this.#duplicates(agent),
2352 refuse: (agent, space, via, time, collisions, entries, message) =>
2353 this.#refuse(agent, space, via, time, collisions, entries, message),
2354 markerCollisions: (agent) => this.#markerCollisions(agent),
2355 enqueue: (agent, message, time, draft, resolves, entries) =>
2356 this.#enqueue(agent, message, time, draft, resolves, entries),
2357 view: (set) => this.#view(set),
2358 requireClosed: (tie, union) => this.#requireClosed(tie, union),
2359 spaceOverlay: (space, atoms) =>
2360 this.#viewKeyed(`a ${space.name}@${last(space)}+${atoms.join(",")}`, () =>
2361 unionOverlay(this.#setOf(space), atoms),
2362 ),
2363 newerFor: (agent) => this.#newerFor(agent),
2364 currentChange: (agent, time) => this.#currentChange(agent, time),
2365 apply: (entry) => this.#apply(entry),
2366 newsForOthers: (publisher, space, version, entries) => this.#newsForOthers(publisher, space, version, entries),
2367 settledNews: (agent, version, settled, entries) => this.#settledNews(agent, version, settled, entries),
2368 addressedNews: (agent, version, entries) => this.#addressedNews(agent, version, entries),
2369 reviewNews: (agent, version, entries) => this.#reviewNews(agent, version, entries),
2370 flush: (entries) => this.#flush(entries),
2371 };
2372 return this.#publishers;
2375 #queues?: QueueHost;
2376 get #queueHost(): QueueHost {
2377 this.#queues ??= {
2378 graph: this.#graph,
2379 checkerReady: () => this.checkerReady,
2380 sharedView: () => this.#sharedView(),
2381 sharedOverlay: (atoms) =>
2382 this.#viewKeyed(`a @${last(this.#shared)}+${atoms.join(",")}`, () =>
2383 unionOverlay(this.#setOf(this.#shared), atoms),
2384 ),
2385 sharedAgentOverlay: (agent, atoms) => {
2386 const current = this.#setOf(this.#shared);
2387 const added = new Set([...atoms, ...agent.mine]);
2388 // Retain old-base atoms absent from current shared, without copying shared history.
2389 if (agent.base !== last(this.#shared))
2390 for (const id of this.#at(this.#spaceOf(agent), agent.base)) if (!current.has(id)) added.add(id);
2391 return this.#viewKeyed(`a @${last(this.#shared)}+${[...added].join(",")}`, () => unionOverlay(current, added));
2392 },
2393 queued: () => this.#queue,
2394 queuedId: () => this.#queuedId,
2395 checkingHas: (id) => this.#checking.has(id),
2396 replaceChecking: (ids) => {
2397 this.#checking = new Set(ids);
2398 },
2399 uncheck: (id) => {
2400 this.#checking.delete(id);
2401 },
2402 needInit: () => this.#needInit(),
2403 shared: () => this.#shared,
2404 setOf: (space) => this.#setOf(space),
2405 view: (set) => this.#view(set),
2406 agentSet: (agent) => this.#agentSet(agent),
2407 agentView: (agent) => this.#agentView(agent),
2408 pairs: (draft, against, settled) => this.#pairs(draft, against, settled),
2409 describe: (pair, yoursView, theirsView, spaceName) => this.#describe(pair, yoursView, theirsView, spaceName),
2410 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
2411 refuse: (agent, space, via, time, collisions, entries, message) =>
2412 this.#refuse(agent, space, via, time, collisions, entries, message),
2413 currentChange: (agent, time) => this.#currentChange(agent, time),
2414 nextAt: () => this.#nextAt,
2415 apply: (entry) => this.#apply(entry),
2416 agentOf: (name) => this.#agentOf(name),
2417 requireClosed: (tie, union) => this.#requireClosed(tie, union),
2418 newsForOthers: (publisher, space, version, entries) => this.#newsForOthers(publisher, space, version, entries),
2419 settledNews: (agent, version, settled, entries) => this.#settledNews(agent, version, settled, entries),
2420 addressedNews: (agent, version, entries) => this.#addressedNews(agent, version, entries),
2421 reviewNews: (agent, version, entries) => this.#reviewNews(agent, version, entries),
2422 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
2423 flush: (entries) => this.#flush(entries),
2424 };
2425 return this.#queues;
2428 #applyEntries?: ApplyEntryHost;
2429 get #applyEntryHost(): ApplyEntryHost {
2430 this.#applyEntries ??= {
2431 graph: this.#graph,
2432 agents: this.#agents,
2433 atomAt: this.#atomAt,
2434 mods: this.#mods,
2435 notes: this.#notes,
2436 changes: this.#changes,
2437 labels: this.#labels,
2438 refusals: this.#refusals,
2439 tells: this.#tells,
2440 uncheck: (id) => {
2441 this.#checking.delete(id);
2442 },
2443 stamp: (t) => {
2444 if (typeof t === "number" && t > this.#lastTime) this.#lastTime = t;
2445 },
2446 applyMembership: (entry, at) => this.#membership.apply(entry, at),
2447 agentOf: (name) => this.#agentOf(name),
2448 active: (agent, time) => this.#active(agent, time),
2449 joinChange: (agent, entry, at, draft, landed) => this.#joinChange(agent, entry, at, draft, landed),
2450 space: (name) => this.#spaces.get(name)!,
2451 queued: () => this.#queue,
2452 setQueued: (items) => {
2453 this.#queue = items;
2454 },
2455 setQueuedId: (id) => {
2456 this.#queuedId = id;
2457 },
2458 queuedId: () => this.#queuedId,
2459 setLastNote: (id) => {
2460 this.#lastNote = id;
2461 },
2462 lastNote: () => this.#lastNote,
2463 setAnnounced: (n) => {
2464 this.#announced = n;
2465 },
2466 announced: () => this.#announced,
2467 at: (space, version) => this.#at(space, version),
2468 spaceOf: (agent) => this.#spaceOf(agent),
2469 draft: (agent) => this.#draft(agent),
2470 currentChange: (agent, time) => this.#currentChange(agent, time),
2471 changeRecord: (id, agent, time) => this.#changeRecord(id, agent, time),
2472 };
2473 return this.#applyEntries;
2476 #landers?: LandHost;
2477 get #landHost(): LandHost {
2478 this.#landers ??= {
2479 viewAt: (space, version, changes) =>
2480 changes?.length
2481 ? this.#viewKeyed(`a ${space.name}@${version}+${changes.join(",")}`, () =>
2482 unionOverlay(this.#at(space, version), changes),
2484 : this.#viewAt(space, version),
2485 agents: this.#agents,
2486 graph: this.#graph,
2487 spaces: this.#spaces,
2488 version: () => this.version,
2489 nextAt: () => this.#nextAt,
2490 notQueuedYet: (what) => this.#notQueuedYet(what),
2491 checkClash: (changes) => this.#checkClash(changes),
2492 agent: (name, entries) => this.#agent(name, entries),
2493 namedSpaceOf: (agent) => this.#namedSpaceOf(agent),
2494 shared: () => this.#shared,
2495 setOf: (space) => this.#setOf(space),
2496 at: (space, version) => this.#at(space, version),
2497 view: (set) => this.#view(set),
2498 sharedView: () => this.#sharedView(),
2499 pairs: (draft, against, settled) => this.#pairs(draft, against, settled),
2500 describe: (pair, yoursView, theirsView, spaceName) => this.#describe(pair, yoursView, theirsView, spaceName),
2501 definitionRule: () => this.#definitionRule,
2502 // Only from a stored writer's kept rows, as keptPaths: a project in memory keeps none, and works them out.
2503 changedSince: (space, from, to) =>
2504 this.#writerStorage ? this.#paths.keptChangesSince(space, from, to) : undefined,
2505 refuse: (agent, space, via, time, collisions, entries) =>
2506 this.#refuse(agent, space, via, time, collisions, entries),
2507 requireClosed: (tie, union) => this.#requireClosed(tie, union),
2508 apply: (entry) => this.#apply(entry),
2509 newsForOthers: (publisher, space, version, entries) => this.#newsForOthers(publisher, space, version, entries),
2510 addressedNews: (agent, version, entries) => this.#addressedNews(agent, version, entries),
2511 reviewNews: (agent, version, entries) => this.#reviewNews(agent, version, entries),
2512 flush: (entries) => this.#flush(entries),
2513 };
2514 return this.#landers;
2517 #records?: RecordHost;
2518 get #recordHost(): RecordHost {
2519 this.#records ??= {
2520 agents: this.#agents,
2521 whole: this.#whole,
2522 initialized: () => this.initialized,
2523 agentView: (agent) => this.#agentView(agent),
2524 sharedView: () => this.#sharedView(),
2525 wholeOut: (files, blobs, view, config) => this.#wholeOut(files, blobs, view, config),
2526 checkBlobs: (blobs, files) => this.#checkBlobs(blobs, files),
2527 agent: (name, entries) => this.#agent(name, entries),
2528 draftFiles: (agent) => this.#draftFiles(agent),
2529 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
2530 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
2531 overlapNews: (agent, before, entries) => this.#overlapNews(agent, before, entries),
2532 markedNews: (agent, files, entries) => this.#markedNews(agent, files, entries),
2533 newsAboutOwnDraft: (agent, entries) => this.#newsAboutOwnDraft(agent, entries),
2534 takeNews: (agent, entries) => this.#takeNews(agent, entries),
2535 flush: (entries) => this.#flush(entries),
2536 };
2537 return this.#records;
2540 #restores?: RestoreHost;
2541 get #restoreHost(): RestoreHost {
2542 this.#restores ??= {
2543 graph: this.#graph,
2544 agent: (name, entries) => this.#agent(name, entries),
2545 draft: (agent) => this.#unqueuedDraft(agent),
2546 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
2547 apply: (entry) => this.#apply(entry),
2548 view: (set) => this.#view(set),
2549 agentSet: (agent) => this.#agentSet(agent),
2550 agentView: (agent) => this.#agentView(agent),
2551 agentViewWithout: (agent, excluded) =>
2552 this.#agentView({ ...agent, mine: agent.mine.filter((id) => !excluded.has(id)) }),
2553 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
2554 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
2555 flush: (entries) => this.#flush(entries),
2556 };
2557 return this.#restores;
2560 #startings?: StartingHost;
2561 get #startingHost(): StartingHost {
2562 this.#startings ??= {
2563 agents: this.#agents,
2564 changes: this.#changes,
2565 agent: (name, entries) => this.#agent(name, entries),
2566 liveNote: (agent) => this.#liveNote(agent),
2567 apply: (entry) => this.#apply(entry),
2568 overlaps: (agent, patterns) => this.#overlaps(agent, patterns),
2569 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
2570 flush: (entries) => this.#flush(entries),
2571 };
2572 return this.#startings;
2575 #syncs?: SyncHost;
2576 get #syncHost(): SyncHost {
2577 this.#syncs ??= {
2578 graph: this.#graph,
2579 labels: this.#labels,
2580 agent: (name, entries) => this.#agent(name, entries),
2581 spaceOf: (agent) => this.#spaceOf(agent),
2582 agentView: (agent) => this.#agentView(agent),
2583 captureAgentView: (agent) => {
2584 const key = this.#agentViewKey(agent);
2585 const original = this.#agentView(agent);
2586 // Projected readers reopen the immutable key; only the in-memory fallback uses the original set.
2587 return () => this.#viewKeyed(key, () => original.set);
2588 },
2589 at: (space, version) => this.#at(space, version),
2590 draft: (agent) => this.#draft(agent),
2591 strandedFiles: (draft, set) => this.#strandedFiles(draft, set),
2592 apply: (entry) => this.#apply(entry),
2593 flush: (entries) => this.#flush(entries),
2594 mergeIdentical: (agent, before, oldBase, oldVersion, time, entries) =>
2595 this.#mergeIdentical(agent, before, oldBase, oldVersion, time, entries),
2596 changesSince: (agent, before) => this.#changesSince(agent, before),
2597 };
2598 return this.#syncs;
2601 #moves?: MoveHost;
2602 get #moveHost(): MoveHost {
2603 this.#moves ??= {
2604 needInit: () => this.#needInit(),
2605 agents: this.#agents,
2606 agentView: (agent) => this.#agentView(agent),
2607 sharedView: () => this.#sharedView(),
2608 agent: (name, entries) => this.#agent(name, entries),
2609 addDraft: (agent, view, input, time, meta, entries) => this.#addDraft(agent, view, input, time, meta, entries),
2610 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
2611 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
2612 newsAboutOwnDraft: (agent, entries) => this.#newsAboutOwnDraft(agent, entries),
2613 takeNews: (agent, entries) => this.#takeNews(agent, entries),
2614 flush: (entries) => this.#flush(entries),
2615 };
2616 return this.#moves;
2619 #switches?: SwitchHost;
2620 get #switchHost(): SwitchHost {
2621 this.#switches ??= {
2622 agent: (name, entries) => this.#agent(name, entries),
2623 flush: (entries) => this.#flush(entries),
2624 spaces: this.#spaces,
2625 agentView: (agent) => this.#agentView(agent),
2626 graph: this.#graph,
2627 version: () => this.version,
2628 apply: (entry) => this.#apply(entry),
2629 draft: (agent) => this.#draft(agent),
2630 setOf: (space) => this.#setOf(space),
2631 changesSince: (agent, before) => this.#changesSince(agent, before),
2632 };
2633 return this.#switches;
2636 #draftStates?: DraftStateHost;
2637 get #draftStateHost(): DraftStateHost {
2638 this.#draftStates ??= {
2639 needInit: () => this.#needInit(),
2640 spaceNamed: (name) => this.#spaceNamed(name),
2641 shared: () => this.#shared,
2642 graph: this.#graph,
2643 agents: this.#agents,
2644 draft: (agent) => this.#draft(agent),
2645 checkClash: (changes) => this.#checkClash(changes),
2646 landCollisions: (space, changes, pick) => this.#landCollisions(space, changes, pick),
2647 };
2648 return this.#draftStates;
2651 #checkClashes?: CheckClashHost;
2652 get #checkClashHost(): CheckClashHost {
2653 this.#checkClashes ??= {
2654 shared: () => this.#shared,
2655 setOf: (space) => this.#setOf(space),
2656 view: (set) => this.#view(set),
2657 sharedView: () => this.#sharedView(),
2658 sharedOverlay: (atoms) =>
2659 this.#viewKeyed(`a @${last(this.#shared)}+${atoms.join(",")}`, () =>
2660 unionOverlay(this.#setOf(this.#shared), atoms),
2661 ),
2662 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
2663 };
2664 return this.#checkClashes;
2667 #changesSinces?: ChangesSinceHost;
2668 get #changesSinceHost(): ChangesSinceHost {
2669 this.#changesSinces ??= {
2670 agentView: (agent) => this.#agentView(agent),
2671 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
2672 openPairs: (agent) => this.#openPairs(agent),
2673 collision: (agent, pair) => this.#collision(agent, pair),
2674 duplicates: (agent) => this.#duplicates(agent),
2675 markedCollisions: (agent) => this.#markedCollisions(agent),
2676 };
2677 return this.#changesSinces;
2680 #inits?: InitHost;
2681 get #initHost(): InitHost {
2682 this.#inits ??= {
2683 initialized: () => this.initialized,
2684 whole: this.#whole,
2685 wholeOut: (files, blobs, view, config) => this.#wholeOut(files, blobs, view, config),
2686 checkBlobs: (blobs, files) => this.#checkBlobs(blobs, files),
2687 commit: (entries) => this.#commit(entries),
2688 };
2689 return this.#inits;
2692 #amends?: AmendHost;
2693 get #amendHost(): AmendHost {
2694 this.#amends ??= {
2695 agent: (name, entries) => this.#agent(name, entries),
2696 spaceOf: (agent) => this.#spaceOf(agent),
2697 apply: (entry) => this.#apply(entry),
2698 flush: (entries) => this.#flush(entries),
2699 };
2700 return this.#amends;
2703 #labelHosts?: LabelHost;
2704 get #labelHost(): LabelHost {
2705 this.#labelHosts ??= {
2706 agent: (name, entries) => this.#agent(name, entries),
2707 version: () => this.version,
2708 labels: this.#labels,
2709 apply: (entry) => this.#apply(entry),
2710 flush: (entries) => this.#flush(entries),
2711 };
2712 return this.#labelHosts;
2715 #publishOfs?: PublishOfHost;
2716 get #publishOfHost(): PublishOfHost {
2717 this.#publishOfs ??= {
2718 shared: () => this.#shared,
2719 spaces: this.#spaces,
2720 };
2721 return this.#publishOfs;
2724 #versionMetas?: VersionMetaHost;
2725 get #versionMetaHost(): VersionMetaHost {
2726 this.#versionMetas ??= {
2727 needInit: () => this.#needInit(),
2728 spaceNamed: (name) => this.#spaceNamed(name),
2729 };
2730 return this.#versionMetas;
2733 #refuses?: RefuseHost;
2734 get #refuseHost(): RefuseHost {
2735 this.#refuses ??= {
2736 apply: (entry) => this.#apply(entry),
2737 refusals: this.#refusals,
2738 };
2739 return this.#refuses;
2742 #overlapsHost?: OverlapHost;
2743 get #overlapHost(): OverlapHost {
2744 this.#overlapsHost ??= {
2745 graph: this.#graph,
2746 agents: this.#agents,
2747 agentView: (agent) => this.#agentView(agent),
2748 draft: (agent) => this.#draft(agent),
2749 draftFiles: (agent) => this.#draftFiles(agent),
2750 liveNote: (agent) => this.#liveNote(agent),
2751 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
2752 };
2753 return this.#overlapsHost;
2756 #recordFiles?: RecordFileHost;
2757 get #recordFileHost(): RecordFileHost {
2758 this.#recordFiles ??= {
2759 addDraft: (agent, view, input, time, meta, entries) => this.#addDraft(agent, view, input, time, meta, entries),
2760 };
2761 return this.#recordFiles;
2764 #addDrafts?: AddDraftHost;
2765 get #addDraftHost(): AddDraftHost {
2766 this.#addDrafts ??= {
2767 graph: this.#graph,
2768 openPairs: (agent) => this.#openPairs(agent),
2769 markersSettled: (agent, view, atom) => this.#markersSettled(agent, view, atom),
2770 apply: (entry) => this.#apply(entry),
2771 };
2772 return this.#addDrafts;
2775 #ingests?: IngestHost;
2776 get #ingestHost(): IngestHost {
2777 this.#ingests ??= {
2778 agents: this.#agents,
2779 spaces: this.#spaces,
2780 needInit: () => this.#needInit(),
2781 version: () => this.version,
2782 checkBlobs: (blobs, files) => this.#checkBlobs(blobs, files),
2783 apply: (entry) => this.#apply(entry),
2784 flush: (entries) => this.#flush(entries),
2785 wholeOut: (files, blobs, view, config) => this.#wholeOut(files, blobs, view, config),
2786 agentView: (agent) => this.#agentView(agent),
2787 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
2788 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
2789 publish: (agent, message, time, entries, asIs, direct) =>
2790 this.#publish(agent, message, time, entries, asIs, direct),
2791 land: (agent, message, time, entries, pick) => this.#land(agent, message, time, entries, pick),
2792 };
2793 return this.#ingests;
2796 #plucks?: PluckHost;
2797 get #pluckHost(): PluckHost {
2798 this.#plucks ??= {
2799 graph: this.#graph,
2800 spaces: this.#spaces,
2801 agent: (name, entries) => this.#agent(name, entries),
2802 shared: () => this.#shared,
2803 notQueuedYet: (what) => this.#notQueuedYet(what),
2804 strandedFiles: (draft, set) => this.#strandedFiles(draft, set),
2805 checkClash: (changes) => this.#checkClash(changes),
2806 land: (agent, message, time, entries, pick) => this.#land(agent, message, time, entries, pick),
2807 flush: (entries) => this.#flush(entries),
2808 };
2809 return this.#plucks;
2812 #drops?: DropHost;
2813 get #dropHost(): DropHost {
2814 this.#drops ??= {
2815 graph: this.#graph,
2816 agents: this.#agents,
2817 spaces: this.#spaces,
2818 agent: (name, entries) => this.#agent(name, entries),
2819 shared: () => this.#shared,
2820 flush: (entries) => this.#flush(entries),
2821 apply: (entry) => this.#apply(entry),
2822 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
2823 addressedNews: (agent, version, entries) => this.#addressedNews(agent, version, entries),
2824 };
2825 return this.#drops;
2828 // Changes (#44), in change-records.ts behind ChangeHost ---------------------------------------------
2830 #changeRecords?: ChangeHost;
2831 get #changeHost(): ChangeHost {
2832 this.#changeRecords ??= {
2833 changes: this.#changes,
2834 agents: this.#agents,
2835 spaces: this.#spaces,
2836 notes: this.#notes,
2837 versionChange: this.#versionChange,
2838 paths: this.#paths,
2839 graph: this.#graph,
2840 stored: () => this.#stored,
2841 shared: () => this.#shared,
2842 queue: () => this.#queue,
2843 active: (agent, time) => this.#active(agent, time),
2844 currentChange: (agent, time) => this.#currentChange(agent, time),
2845 liveNote: (agent) => this.#liveNote(agent),
2846 noteAnswer: (n) => this.#noteAnswer(n),
2847 reviewersOf: (files, id) => this.#reviewersOf(files, id),
2848 };
2849 return this.#changeRecords;
2852 // What the project looks like now, in project-status.ts behind SnapshotHost -------------------------
2854 #snapshotHost?: SnapshotHost;
2855 get #snapshot(): SnapshotHost {
2856 this.#snapshotHost ??= {
2857 agents: this.#agents,
2858 spaces: this.#spaces,
2859 queue: () => this.#queue,
2860 refusals: this.#refusals,
2861 labels: this.#labels,
2862 tells: this.#tells,
2863 needInit: () => this.#needInit(),
2864 shared: () => this.#shared,
2865 draft: (agent) => this.#draft(agent),
2866 draftFiles: (agent) => this.#draftFiles(agent),
2867 liveNote: (agent) => this.#liveNote(agent),
2868 openCollisions: (agent) => this.#openCollisions(agent),
2869 editsOf: (agent) => this.#editsOf(agent),
2870 setOf: (space) => this.#setOf(space),
2871 spaceNamed: (name) => this.#spaceNamed(name),
2872 checkVersion: (space, version) => this.#checkVersion(space, version),
2873 viewAt: (space, version) => this.#viewAt(space, version),
2874 keptPaths: (space, version) => this.#keptPaths(space, version),
2875 agentView: (agent) => this.#agentView(agent),
2876 version: () => this.version,
2877 projectFile: () => (this.initialized ? projectFileIn(this.#sharedView()) : undefined),
2878 };
2879 return this.#snapshotHost;
2882 /** The paths in an agent's view now (project-status.ts). */
2883 agentPaths(...args: Tail<Parameters<typeof snapshotAgentPaths>>): ReturnType<typeof snapshotAgentPaths> {
2884 return snapshotAgentPaths(this.#snapshot, ...args);
2887 /** The paths in shared, or a named draft, at a version (project-status.ts). */
2888 pathsAt(...args: Tail<Parameters<typeof snapshotPathsAt>>): ReturnType<typeof snapshotPathsAt> {
2889 return snapshotPathsAt(this.#snapshot, ...args);
2892 /** The paths in an agent's view now, for a reader (project-status.ts). */
2893 pathsOf(...args: Tail<Parameters<typeof snapshotPathsOf>>): ReturnType<typeof snapshotPathsOf> {
2894 return snapshotPathsOf(this.#snapshot, ...args);
2897 /** Every label, with the versions it marks, newest first (project-status.ts). */
2898 labels(): ReturnType<typeof snapshotLabels> {
2899 return snapshotLabels(this.#snapshot);
2902 /** Agents, drafts, refusals and waiting announcements (project-status.ts). */
2903 status(): ReturnType<typeof snapshotStatus> {
2904 return snapshotStatus(this.#snapshot);
2907 /** The operation fence needs one actor's heads, not every agent's file projection. */
2908 actorHead(name: string): { base: number; draftChanges: number; draft: string | null } | undefined {
2909 const agent = this.#agents.get(name);
2910 if (!agent) return undefined;
2911 const published = this.#setOf(this.#spaceOf(agent));
2912 let draftChanges = 0;
2913 for (const id of agent.mine) if (!published.has(id)) draftChanges++;
2914 return { base: agent.base, draftChanges, draft: agent.space === SHARED ? null : agent.space };
2917 /** A space's contents at one of its versions. */
2918 #at(space: Space, version: number): ReadonlySet<AtomId> {
2919 return this.#membership.at(space, version);
2922 /** A space's contents now. */
2923 #setOf(space: Space): ReadonlySet<AtomId> {
2924 return this.#at(space, last(space));
2927 #draft(agent: AgentState): AtomId[] {
2928 const set = this.#setOf(this.#spaceOf(agent));
2929 return agent.mine.filter((id) => !set.has(id));
2932 /**
2933 * The draft without the agent's publishes waiting in the queue (#39): what
2934 * moves, restore and sync's merge may drop and make again. A queued item's
2935 * atoms are no longer the draft's to remake; dropping them let the queue
2936 * land a tie that depends on discarded atoms (abso issue 135, item 4).
2937 * Undoing a queued publish is abso unqueue.
2938 */
2939 #unqueuedDraft(agent: AgentState): AtomId[] {
2940 const draft = this.#draft(agent);
2941 const held = this.#queuedAtoms();
2942 return held.size === 0 ? draft : draft.filter((id) => !held.has(id));
2945 #agentSet(agent: AgentState): Set<AtomId> {
2946 return new Set([...this.#at(this.#spaceOf(agent), agent.base), ...agent.mine]);
2949 #agentView(agent: AgentState): ReadView {
2950 const view = this.#viewKeyed(this.#agentViewKey(agent), () => {
2951 const base = this.#at(this.#spaceOf(agent), agent.base);
2952 return base instanceof StableSet
2953 ? new StableUnionSet(base, new StableOverlaySet(agent.mine))
2954 : new Set([...base, ...agent.mine]);
2955 });
2956 // A draft that moves nothing resolves its moves as its base does (abso Capacity): take them from the base's view.
2957 if (this.#writerStorage && agent.mine.length > 0 && view instanceof View) {
2958 const base = this.#viewAt(this.#spaceOf(agent), agent.base);
2959 if (base instanceof View) {
2960 view.shareMoves(base);
2961 // And its layout of every file the draft doesn't touch, when the draft moves nothing (abso Capacity). What the
2962 // view holds beyond its base is the draft and whatever the draft depends on that the base lacks (the view's
2963 // set is closed): each of those can change a file, so all of them count.
2964 const mine = agent.mine;
2965 view.shareFiles(base, () =>
2966 touchedBeyond(this.#graph, base.set, mine, [base, view], () => placedBetween(view, base)),
2967 );
2970 return view;
2973 /** 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. */
2974 #agentViewKey(agent: AgentState): string {
2975 // An empty draft is exactly its published base. Share its projection
2976 // with version readers instead of walking the same history twice.
2977 if (agent.mine.length === 0) return `v ${agent.space}@${agent.base}`;
2978 return `a ${agent.space}@${agent.base}+${agent.mine.join(",")}`;
2981 /** A space at a version: published versions never change, so the key is just their names (#46). */
2982 #viewAt(space: Space, version: number): ReadView {
2983 const view = this.#viewKeyed(`v ${space.name}@${version}`, () => this.#at(space, version));
2984 // Which files it has from the kept path list (abso Capacity, View.knowPaths), as pathsAt answers.
2985 if (view instanceof View && this.#writerStorage && space.name === SHARED)
2986 view.knowPaths(() => this.#paths.keptPathSet(space, version));
2987 return view;
2990 #sharedView(): ReadView {
2991 return this.#viewAt(this.#shared, last(this.#shared));
2994 /**
2995 * After each read of a reader kept between calls, one that changed nothing (abso Capacity): the cached views back
2996 * under their budget, since views grow while a call lays files out and the cache weighs them only when they are
2997 * asked for again (on abso, a tree with authors left 38 MB of views held against the 24 MB budget), and the agents
2998 * the read decoded let go, read again from storage by the next call (7 MB on abso, every agent's news told).
2999 */
3000 afterRead(): void {
3001 this.#views.trim();
3002 if (this.#agents instanceof WriterAgents) this.#agents.release();
3005 /** A view of a set, cached by the set's exact contents (views.ts). */
3006 #view(set: ReadonlySet<AtomId>): ReadView {
3007 this.#views.assertUnkeyedAllowed();
3008 return this.#views.view(this.#closed(set));
3011 /** A view cached under `key` (views.ts). */
3012 #viewKeyed(key: string, set: () => ReadonlySet<AtomId>): ReadView {
3013 return this.#views.keyed(key, () => this.#closed(set()));
3016 /**
3017 * A discarded atom that a later publish still depends on stays in the view
3018 * (abso issue 80). A closed set is unchanged.
3019 */
3020 #closed(set: Iterable<AtomId>): ReadonlySet<AtomId> {
3021 if (isClosedSet(set)) return set as ReadonlySet<AtomId>;
3022 if (set instanceof StableSet) {
3023 // Keep indexed membership external. Only dependencies absent from
3024 // that snapshot belong in the operation's closure overlay. Over a stored closed base (abso Capacity),
3025 // only the atoms outside it can reach outside it: unions are opened down to their closed parts.
3026 const walk: Iterable<AtomId>[] = [];
3027 const open = (part: ReadonlySet<AtomId>): void => {
3028 if (isClosedSet(part)) return;
3029 if (part instanceof StableUnionSet) {
3030 open(part.left);
3031 open(part.right);
3032 } else walk.push(part);
3033 };
3034 open(set);
3035 const missing = new Set<AtomId>();
3036 const visit = (id: AtomId) => {
3037 const stack = [id];
3038 while (stack.length) {
3039 for (const dependency of this.#graph.atom(stack.pop()!).deps) {
3040 if (!set.has(dependency) && !missing.has(dependency)) {
3041 missing.add(dependency);
3042 stack.push(dependency);
3046 };
3047 for (const part of walk) for (const id of part) visit(id);
3048 return markClosed(missing.size ? new StableUnionSet(set, new StableOverlaySet(missing)) : set);
3050 return this.#graph.closureOf(set);
3053 /** A new publish or land must not depend on an atom outside the set (abso issue 80). */
3054 #requireClosed(tie: { deps: readonly AtomId[] }, union: ReadonlySet<AtomId>): void {
3055 const missing = tie.deps.filter((id) => !union.has(id));
3056 if (missing.length > 0)
3057 throw new ProjectError(
3058 "conflict",
3059 `this change depends on ${missing.join(", ")}, which is not in the set being pushed`,
3060 );
3063 /** The space's atoms published after the agent's base, by others. */
3064 /** `upTo`: the work published after the agent's base up to that version only (owed news, news.ts). */
3065 #newerFor(agent: AgentState, upTo?: number): ReadonlySet<AtomId> {
3066 const space = this.#spaceOf(agent);
3067 const base = this.#at(space, agent.base);
3068 const current = upTo === undefined ? this.#setOf(space) : this.#at(space, upTo);
3069 const newer =
3070 space.name === SHARED && space.membershipVersion
3071 ? new SharedAdditions(space, agent.base, base, current, upTo ?? last(space))
3072 : differenceSet(current, base);
3073 return differenceSet(newer, new StableOverlaySet(agent.mine));
3076 /** The files whose text in the agent's view differs from `before`, and its open collisions. */
3077 #changesSince(...args: Tail<Parameters<typeof hostedChangesSince>>): ReturnType<typeof hostedChangesSince> {
3078 return hostedChangesSince(this.#changesSinceHost, ...args);
3081 /** Who published an atom, looking in the given space first and then in shared. */
3082 #origin(atom: AtomId, spaceName: string): Origin {
3083 return originOf(this.#collisionHost, atom, spaceName);
3086 // Drafting ----------------------------------------------------------------------
3088 /** Check a {path: sha256} map: hex hashes, no path also given as text, and bytes already uploaded. */
3089 #checkBlobs(blobs: unknown, files: object): Record<string, string> {
3090 if (typeof blobs !== "object" || blobs === null || Array.isArray(blobs))
3091 throw new ProjectError("bad-request", "blobs must be {path: sha256}");
3092 for (const [path, sha] of Object.entries(blobs as Record<string, unknown>)) {
3093 checkPath(path);
3094 if (typeof sha !== "string" || !/^[0-9a-f]{64}$/.test(sha))
3095 throw new ProjectError("bad-request", `${path}: a blob is the SHA-256 of the bytes, in lowercase hex`);
3096 if (Object.hasOwn(files, path)) throw new ProjectError("bad-request", `${path} is given as both text and a blob`);
3097 if (!this.#hasBlob(sha))
3098 throw new ProjectError("bad-request", `${path}: upload blob ${sha} first (PUT /p/:project/blobs/${sha})`);
3100 return blobs as Record<string, string>;
3103 /**
3104 * Make one file in the agent's view what the folder has, as one draft
3105 * change: `text` (null: the file is gone; "": an empty file; undefined:
3106 * leave its lines alone) and `mode` (only the fields given). Returns
3107 * whether anything changed.
3108 */
3109 #recordFile(...args: Tail<Parameters<typeof hostedRecordFile>>): ReturnType<typeof hostedRecordFile> {
3110 return hostedRecordFile(this.#recordFileHost, ...args);
3113 /**
3114 * Moves (#28). Within one agent's unpublished draft, a line that leaves one
3115 * place and the same text that arrives somewhere else is the same line, in
3116 * either order (deleted then written, or written then deleted). Before a
3117 * publish, the draft's changes to the files involved are dropped (a discard
3118 * entry) and made again: one move per matched block, which keeps the
3119 * lines' ids, then a change per file to the draft's final text. The files
3120 * end up exactly as the draft had them. A matched block needs a line with
3121 * real content: blank lines and lone brackets only travel next to one.
3122 */
3123 #expressMoves(agent: AgentState, time: number, entries: Entry[]): void {
3124 hostedExpressMoves(this.#expressMovesHost, agent, time, entries);
3127 /**
3128 * Build a draft change against the agent's view. If it touches lines on
3129 * either side of a collision the agent has already seen, it settles that
3130 * collision (the engine's `resolves`).
3131 */
3132 #addDraft(...args: Tail<Parameters<typeof hostedAddDraft>>): ReturnType<typeof hostedAddDraft> {
3133 return hostedAddDraft(this.#addDraftHost, ...args);
3136 // Collisions and news -------------------------------------------------------------
3138 #pairs(draft: readonly AtomId[], against: ReadonlySet<AtomId>, settled: ReadonlySet<AtomId>): Pair[] {
3139 return pairsIn(this.#graph, draft, against, settled);
3142 /**
3143 * Collisions the agent has synced into and not settled: its draft against
3144 * its space at its base. In a named draft, also the draft's own changes
3145 * against shared work the draft was moved onto.
3146 */
3147 #openPairs(agent: AgentState): Pair[] {
3148 return hostedOpenPairs(this.#collisionHost, agent);
3151 /** After the agent's own change: news when its draft now collides with work published after its base. */
3152 #newsAboutOwnDraft(agent: AgentState, entries: Entry[]): void {
3153 hostedNewsAboutOwnDraft(this.#newsHost, agent, entries);
3156 /** After a publish or a landing: news for every other agent in that space whose draft collides with what just arrived. */
3157 #newsForOthers(publisher: AgentState, space: Space, version: number, entries: Entry[]): void {
3158 hostedNewsForOthers(this.#newsHost, publisher, space, version, entries);
3161 #queueNews(agent: AgentState, items: readonly { key: string; text: string }[], entries: Entry[]): void {
3162 const fresh = items.filter((p) => !agent.told.has(p.key));
3163 if (fresh.length === 0) return;
3164 const text = [...new Set(fresh.map((p) => p.text))];
3165 const entry: Entry = { type: "news", agent: agent.name, pairs: [...new Set(fresh.map((p) => p.key))], text };
3166 entries.push(entry);
3167 this.#apply(entry);
3170 #takeNews(agent: AgentState, entries: Entry[]): string[] {
3171 if (agent.news.length === 0) return [];
3172 const news = [...agent.news];
3173 const entry: Entry = { type: "heard", agent: agent.name };
3174 entries.push(entry);
3175 this.#apply(entry);
3176 return news;
3179 /** Describe a pair for the agent: its side in its own view, theirs in its space now. */
3180 #collision(agent: AgentState, pair: Pair): Collision {
3181 return this.#describe(
3182 pair,
3183 this.#agentView(agent),
3184 this.#viewAt(this.#spaceOf(agent), last(this.#spaceOf(agent))),
3185 agent.space,
3186 );
3189 #describe(pair: Pair, yoursView: ReadView, theirsView: ReadView, spaceName: string): Collision {
3190 return describePair(
3191 this.#graph,
3192 (atom, space) => this.#origin(atom, space),
3193 pair,
3194 yoursView,
3195 theirsView,
3196 spaceName,
3197 );
3200 #touchedFiles(ids: Iterable<AtomId>, views: readonly ReadView[]): Set<string> {
3201 return touchedFiles(this.#graph, ids, views);
3204 // The changed-definition rule (#11) -------------------------------------------
3206 /** The rule for an agent's draft in its space. */
3207 #definitionCollisions(
3208 agent: AgentState,
3209 newer: ReadonlySet<AtomId>,
3210 names?: ReadonlySet<string>,
3211 /** The space's version to compare against: its newest, or an owed publish's (news.ts). */
3212 version?: number,
3213 ): DefinitionCollision[] {
3214 const draft = new Set(this.#draft(agent));
3215 if (draft.size === 0 || newer.size === 0) return [];
3216 const space = this.#spaceOf(agent);
3217 const at = this.#at(space, agent.base);
3218 const base = agent.mine.some((id) => at.has(id))
3219 ? this.#view(differenceSet(at, new StableOverlaySet(agent.mine)))
3220 : this.#viewAt(space, agent.base);
3221 const to = version ?? last(space);
3222 return this.#definitionRule.collisions(
3223 draft,
3224 this.#agentView(agent),
3225 base,
3226 this.#viewAt(space, to),
3227 newer,
3228 space.name,
3229 undefined,
3230 names,
3231 // Where the space changed since the agent's base, from each version's kept files on a stored writer, as land's
3232 // (abso 714): walking every newer atom for them was 6.5 s of a publish 770 versions behind on abso.
3233 () => (this.#writerStorage ? this.#paths.keptChangesSince(space, agent.base, to) : undefined),
3234 );
3238export { EngineError };