Skip to content

abso-core

Public

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

Check passed
MCP
code on this site's /mcp
CLI
none: the JSON below is the answer
JSON
/christopher/abso-core/files/worker/project/project.ts?version=261&format=json
3,109 linesFirst import 75% · codex-capacity-chair 16% · capacity 7% · engine 1% · speed 1% · candidates 1% · Last change capacity in version 260, 45 versions changed it

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

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