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