- 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=45&format=json
2,417 linesFirst import 100% · pinch 1% · engine 1% · infra-split 1%Last change infra-split in version 37, 4 versions changed it
You're reading version 45. The newest is 318, and 54 versions since then changed this file.
1// The project a Durable Object holds: shared (the published set), named
2// drafts, each agent's draft, publish, sync and news. Pure TypeScript with no
3// Node or Workers imports; the object passes the time in and stores what
4// `append` hands it. The contract is docs/v2-slice1.md.
5//
6// Every change goes through an entry. A call works out its entries, applies
7// them, and hands them to the store in one `append`. Loading applies the same
8// entries again, so a reloaded project is the same project.
9//
10// A space is somewhere agents publish to. Shared is one. A named draft (#10)
11// is another: a small shared that builds on a version of shared, that its
12// agents publish into under the same rules, and that lands in shared as one
13// unit. Every agent works in one space at a time.
15import {
16 type Atom,
17 type AtomId,
18 type ConflictKey,
19 conflictKeys,
20 type EditInput,
21 EngineError,
22 Graph,
23 type LineId,
24 type MoveInput,
25 type View,
26} from "../../src/engine/index.ts";
27import { type AddDraftHost, addDraft as hostedAddDraft } from "./add-draft.ts";
28import { type AmendHost, amend as hostedAmend } from "./amend.ts";
29import { type AnnounceHost, announce as hostedAnnounce, announcePerson as hostedAnnouncePerson } from "./announce.ts";
30import { type ApplyEntryHost, applyEntry as hostedApplyEntry } from "./apply-entry.ts";
31import {
32 type ChangeHost,
33 change as hostedChange,
34 changeRecord as hostedChangeRecord,
35 changes as hostedChanges,
36 joinChange as hostedJoinChange,
37 namedFiles as hostedNamedFiles,
38} from "./change-records.ts";
39import { type ChangesSinceHost, changesSince as hostedChangesSince } from "./changes-since.ts";
40import { type CheckClashHost, checkClash as hostedCheckClash } from "./check-clash.ts";
41import {
42 type CollisionHost,
43 describePair,
44 duplicateCollisions,
45 openPairs as hostedOpenPairs,
46 type Origin,
47 originOf,
48 type Pair,
49 pairsIn,
50 strandedFiles,
51 touchedFiles,
52} from "./collisions.ts";
53import { type DefinitionCollision, DefinitionRule } from "./definition-rule.ts";
54import { type DraftCollisionHost, draftCollisions } from "./draft-collisions.ts";
55import { type DraftDiffHost, diffOfAgent, diffOf as draftDiffOf } from "./draft-diff.ts";
56import { type DraftStateHost, draftState as hostedDraftState } from "./draft-state.ts";
57import { type DropHost, drop as hostedDrop } from "./drop.ts";
58import { type EditHost, edit as hostedEdit } from "./edit.ts";
59import { type ExpressMovesHost, expressMoves as hostedExpressMoves } from "./express-moves.ts";
60import {
61 type HistoryHost,
62 follow as historyFollow,
63 pathLife as historyPathLife,
64 tree as historyTree,
65} from "./history.ts";
66import { ingest as hostedIngest, type IngestHost } from "./ingest.ts";
67import { init as hostedInit, type InitHost } from "./init.ts";
68import { label as hostedLabel, type LabelHost } from "./label.ts";
69import {
70 land as hostedLand,
71 landCollisions as hostedLandCollisions,
72 landDraft as hostedLandDraft,
73 type LandHost,
74} from "./land.ts";
75import {
76 blocksIn,
77 markedCollisions as hostedMarkedCollisions,
78 markedFiles as hostedMarkedFiles,
79 markerCollisions as hostedMarkerCollisions,
80 markersSettled as hostedMarkersSettled,
81 openCollisions as hostedOpenCollisions,
82 type MarkerHost,
83} from "./markers.ts";
84import { MemoryStore } from "./memory-store.ts";
85import { mergeIdentical as hostedMergeIdentical, type MergeHost } from "./merge-identical.ts";
86import { move as hostedMove, type MoveHost } from "./move.ts";
87import {
88 addressedItem,
89 newsAboutOwnDraft as hostedNewsAboutOwnDraft,
90 newsForOthers as hostedNewsForOthers,
91 markedItem,
92 type NewsHost,
93 type NewsItem,
94 reviewItem,
95 settledItem,
96} from "./news.ts";
97import {
98 closeNote as hostedCloseNote,
99 noteAnswer as hostedNoteAnswer,
100 notes as hostedNotes,
101 noteView as hostedNoteView,
102 startingNotes as hostedStartingNotes,
103 writeNote as hostedWriteNote,
104 type NoteHost,
105 type NoteWriteHost,
106 type ReviewRule,
107 reviewersOf,
108 reviewRulesIn,
109} from "./notes.ts";
110import {
111 draftFiles as hostedDraftFiles,
112 overlapNews as hostedOverlapNews,
113 overlaps as hostedOverlaps,
114 type OverlapHost,
115} from "./overlaps.ts";
116import { checkPath } from "./path-rules.ts";
117import { PathIndex } from "./pathindex.ts";
118import { pathKey } from "./pathkey.ts";
119import { pluck as hostedPluck, type PluckHost } from "./pluck.ts";
120import { ProjectError } from "./project-error.ts";
121import { checkDraftName, checkPerson, NAME, projectFileIn } from "./project-helpers.ts";
122import {
123 type SnapshotHost,
124 agentPaths as snapshotAgentPaths,
125 labels as snapshotLabels,
126 pathsAt as snapshotPathsAt,
127 pathsOf as snapshotPathsOf,
128 status as snapshotStatus,
129} from "./project-status.ts";
130import type {
131 AgentState,
132 AgentStatus,
133 ChangeAnswer,
134 ChangeRecord,
135 Collision,
136 DiffAnswer,
137 DraftSyncAnswer,
138 DropAnswer,
139 EditsVia,
140 Entry,
141 LandAnswer,
142 MergedLine,
143 Meta,
144 Mode,
145 Modes,
146 NoteAnswer,
147 NoteBody,
148 NoteRecord,
149 PersonSender,
150 PluckAnswer,
151 ProjectOptions,
152 ProjectStore,
153 PublishAnswer,
154 QueuedPublish,
155 Refusal,
156 Settled,
157 Starting,
158 SwitchAnswer,
159 Tail,
160 TellRecord,
161} from "./project-types.ts";
162import { publish as hostedPublish, publishDraft as hostedPublishDraft, type PublishHost } from "./publish.ts";
163import { publishOf as hostedPublishOf, type PublishOfHost } from "./publish-of.ts";
164import {
165 enqueue as hostedEnqueue,
166 notQueuedYet as hostedNotQueuedYet,
167 queue as hostedQueue,
168 queueCandidate as hostedQueueCandidate,
169 queueChecking as hostedQueueChecking,
170 queuedAtoms as hostedQueuedAtoms,
171 queueLand as hostedQueueLand,
172 queueOn as hostedQueueOn,
173 queuePull as hostedQueuePull,
174 unqueue as hostedUnqueue,
175 type QueueHost,
176} from "./queue.ts";
177import { record as hostedRecord, type RecordHost } from "./record.ts";
178import { recordFile as hostedRecordFile, type RecordFileHost } from "./record-file.ts";
179import { refusals as hostedRefusals, refuse as hostedRefuse, type RefuseHost } from "./refuse.ts";
180import { restore as hostedRestore, type RestoreHost } from "./restore.ts";
181import { addVersion, last, Membership, newSpace, type Published, SHARED, type Space, sharedBaseOf } from "./spaces.ts";
182import { starting as hostedStarting, type StartingHost } from "./start.ts";
183import { switchTo as hostedSwitchTo, type SwitchHost } from "./switch-to.ts";
184import { sync as hostedSync, type SyncHost } from "./sync.ts";
185import { treeHash } from "./tree.ts";
186import {
187 type LogHost,
188 compare as versionCompare,
189 fileAt as versionFileAt,
190 log as versionLog,
191 ribbon as versionRibbon,
192 show as versionShow,
193 viewAt as versionViewAt,
194} from "./version-log.ts";
195import {
196 checkVersion as hostedCheckVersion,
197 lastVersion as hostedLastVersion,
198 versionMeta as hostedVersionMeta,
199 type VersionMetaHost,
200} from "./version-meta.ts";
201import { modesOf } from "./view-changes.ts";
202import { ViewCache } from "./views.ts";
203import {
204 isWhole as hostedIsWhole,
205 wholeOut as hostedWholeOut,
206 wholeRules as hostedWholeRules,
207 type WholeHost,
208} from "./whole-files.ts";
210export { MemoryStore } from "./memory-store.ts";
211export { checkReadPath, pathProblem } from "./path-rules.ts";
212export { ProjectError } from "./project-error.ts";
213export { shapeStamp, utf8Bytes } from "./project-helpers.ts";
214export type * from "./project-types.ts";
215export { differs } from "./view-changes.ts";
217/** Entry kinds that had no time before #41; new ones get one. */
218const UNTIMED = new Set<Entry["type"]>(["join", "sync", "news", "heard", "discard", "switch"]);
220/** A start note lasts this long after the agent's last activity (#44). */
221const NOTE_IDLE = 2 * 60 * 60 * 1000;
223export class Project {
224 readonly #store: ProjectStore;
225 readonly #graph: Graph;
226 /** Views laid out from atom sets, cached under a byte budget (views.ts). */
227 readonly #views: ViewCache;
228 /** Each version's files and each path's history (pathindex.ts). */
229 readonly #paths: PathIndex;
230 /** For each atom (by seq) that wrote lines, the log position of the entry that recorded it (#46). */
231 readonly #atomAt: number[] = [];
232 /** Which atoms are in which space at which version (#46, disk-first 1): the rules live in spaces.ts. */
233 readonly #membership = new Membership();
234 get #spaces(): Map<string, Space> {
235 return this.#membership.spaces;
236 }
237 readonly #agents = new Map<string, AgentState>();
238 readonly #refusals: Refusal[] = [];
239 /** Labels on shared's versions: name -> versions, ascending. */
240 readonly #labels = new Map<string, number[]>();
241 /** The newest tells and who has heard each (apply-entry.ts). */
242 readonly #tells = new Map<number, TellRecord>();
243 /**
244 * Entries applied but not stored yet, in order. Every applied entry is
245 * stored at the next flush, even when the call that applied it threw
246 * afterwards; otherwise the log could miss a join that later entries rely on.
247 */
248 #pending: Entry[] = [];
249 /**
250 * Whether something runs the merge queue's check (#39). Until the Worker has
251 * a checker it stays false, and `"queue": true` in avcs.json does nothing:
252 * publishes would otherwise wait for a check that never comes. Replay
253 * doesn't depend on it.
254 */
255 checkerReady = false;
256 readonly #now: (() => number) | undefined;
257 readonly #whole: ProjectOptions["whole"];
258 readonly #shapes: ProjectOptions["shapes"];
259 /** For each log position, the newest time up to it (#41): time to position in one search. */
260 readonly #timeAt: number[] = [];
261 /** For each version of shared, the log position of the entry that made it (#41). */
262 readonly #versionAt: number[] = [];
263 /** The newest time any applied entry carries: the clock when none was given. */
264 #lastTime = 0;
265 /** Every change (#44), by id. */
266 readonly #changes = new Map<number, ChangeRecord>();
267 /** Each version's change, by "<draft or ''> <version>" (#44): what a note on its lines belongs to. */
268 readonly #versionChange = new Map<string, number>();
269 /** Every note (#44), by id. */
270 readonly #notes = new Map<number, NoteRecord>();
271 /** Mod versions (X-Avcs-Client) in the order they first sent an edit (#41): the last is taken as the installed one. */
272 #mods: string[] = [];
273 /** The merge queue (#39), in order: publishes to shared waiting for their batch's check. */
274 #queue: QueuedPublish[] = [];
275 /** The newest note's id (#44). */
276 #lastNote = 0;
277 #queuedId = 0;
278 /** Queued ids in the batch being checked now: not in the log, only for refusing an unqueue mid-check. */
279 #checking = new Set<number>();
280 /** How many entries the store holds: the log position of the next one (#41, the website's feed and replay). */
281 #stored = 0;
282 /** Names on the lines a change replaced, by "<atom> <last replaced line>" (atoms never change). */
283 #rule?: DefinitionRule;
284 get #definitionRule(): DefinitionRule {
285 this.#rule ??= new DefinitionRule(this.#graph, (atom, space) => this.#origin(atom, space));
286 return this.#rule;
287 }
288 /** The newest announcement's id (announcements are news entries keyed "announce <id>"). */
289 #announced = 0;
290 #loading = false;
292 readonly #hasBlob: (sha256: string) => boolean;
294 constructor(store: ProjectStore, options: ProjectOptions = {}) {
295 this.#store = store;
296 this.#hasBlob = options.hasBlob ?? (() => false);
297 this.#now = options.now;
298 this.#whole = options.whole;
299 this.#shapes = options.shapes;
300 // For tests (#46): AVCS_TEXT_FROM_LOG=1 runs a project on a MemoryStore with its text read back from the store.
301 const testing =
302 (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env?.AVCS_TEXT_FROM_LOG ===
303 "1";
304 const entryAt =
305 options.entryAt ??
306 (testing && store instanceof MemoryStore ? (at: number) => (store as MemoryStore).entries[at]! : undefined);
307 // An atom as its log entry stores it. Not stored yet: still in this call's pending entries; while loading, every entry is stored.
308 const stored = (seq: number): Atom => {
309 const at = this.#atomAt[seq]!;
310 const entry = !this.#loading && at >= this.#stored ? this.#pending[at - this.#stored]! : entryAt!(at);
311 if (entry?.type === "init" || entry?.type === "draft") return entry.atom;
312 // A publish's or land's tie atom (#46: its lists are read back too).
313 if (entry?.type === "publish" || entry?.type === "land") return entry.tie;
314 throw new Error(`log entry ${at} holds no atom ${seq}`);
315 };
316 // Line text and each atom's deletes and claim keys stay in the log (#46), read back when asked for.
317 this.#graph = entryAt
318 ? new Graph({ texts: (seq) => stored(seq).inserts.map((r) => r.lines), lists: (seq) => stored(seq) })
319 : new Graph();
320 this.#views = new ViewCache(this.#graph);
321 this.#paths = new PathIndex({
322 graph: this.#graph,
323 at: (space, version) => this.#at(space, version),
324 viewAt: (space, version) => this.#viewAt(space, version),
325 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
326 shapes: this.#shapes,
327 });
328 }
330 /** Rebuild a project from its stored entries. New entries go to `store`. */
331 static load(entries: Iterable<Entry>, store: ProjectStore, options: ProjectOptions = {}): Project {
332 const testing =
333 (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env?.AVCS_TEXT_FROM_LOG ===
334 "1";
335 if (testing && !options.entryAt && Array.isArray(entries)) {
336 // Loaded from someone else's entries: its text is read back from them (and from the new store after them).
337 const from = entries as Entry[];
338 const after = store instanceof MemoryStore ? store : undefined;
339 options = { ...options, entryAt: (at) => (at < from.length ? from[at]! : after!.entries[at - from.length]!) };
340 }
341 const project = new Project(store, options);
342 project.#loading = true;
343 for (const entry of entries) {
344 project.#apply(entry);
345 project.#stored++;
346 }
347 project.#loading = false;
348 return project;
349 }
351 /**
352 * Apply more stored entries to a copy loaded for reading (#41, replay):
353 * scrubbing forward applies only what's new. Never for the live project.
354 */
355 catchUp(entries: Iterable<Entry>): void {
356 this.#loading = true;
357 try {
358 for (const entry of entries) {
359 this.#apply(entry);
360 this.#stored++;
361 }
362 } finally {
363 this.#loading = false;
364 }
365 }
367 /** The log position of the next entry: how many entries the log holds (#41). */
368 get logLength(): number {
369 return this.#stored;
370 }
372 get initialized(): boolean {
373 return this.#shared.versions.length > 0;
374 }
376 /** The current shared version. */
377 get version(): number {
378 this.#needInit();
379 return this.#shared.versions.length - 1;
380 }
382 /** Shared's files, for the push out to Artifacts. */
383 files(): Record<string, string> {
384 return this.#sharedView().files();
385 }
387 /** Shared's binary files, for the push out to Artifacts: path -> the SHA-256 of its bytes. Not in `files()`. */
388 blobs(): Record<string, string> {
389 return this.#sharedView().blobs();
390 }
392 /** Shared's executable files and links, for the push out to Artifacts: path -> mode. Other files are plain. */
393 modes(): Modes {
394 return modesOf(this.#sharedView());
395 }
397 /** Shared as a View, for reading lines (blame, why). Don't hold on to it across calls. */
398 sharedView(): View {
399 return this.#sharedView();
400 }
402 /** The agents the project knows, by name. */
403 agents(): string[] {
404 return [...this.#agents.keys()].sort();
405 }
407 /** An agent's unpublished changes, oldest first, and its view (its space at its base plus its changes). Read only. */
408 draftOf(agentName: string): { atoms: AtomId[]; view: View } | undefined {
409 const agent = this.#agents.get(agentName);
410 return agent && { atoms: this.#draft(agent), view: this.#agentView(agent) };
411 }
413 /** The shared version an atom was published in, or undefined while it's only in a draft. */
414 versionOf(atom: AtomId): number | undefined {
415 return this.#shared.publishedIn.get(atom);
416 }
418 /**
419 * Where an atom was published: shared if it's there, else the named draft
420 * that has it (by name), else undefined (it's only in a draft so far).
421 */
422 publishOf(...args: Tail<Parameters<typeof hostedPublishOf>>): ReturnType<typeof hostedPublishOf> {
423 return hostedPublishOf(this.#publishOfHost, ...args);
424 }
426 /** The newest version of shared, or of a named draft. */
427 lastVersion(...args: Tail<Parameters<typeof hostedLastVersion>>): ReturnType<typeof hostedLastVersion> {
428 return hostedLastVersion(this.#versionMetaHost, ...args);
429 }
431 /** Shared (null), then each named draft by name: every space with versions (abso issue 80). */
432 spaceNames(): (string | null)[] {
433 return [null, ...[...this.#spaces.keys()].filter((n) => n !== SHARED).sort()];
434 }
436 /** Who made a version of shared or a named draft, why and when, and a draft's shared base (abso issue 80). */
437 versionMeta(...args: Tail<Parameters<typeof hostedVersionMeta>>): ReturnType<typeof hostedVersionMeta> {
438 return hostedVersionMeta(this.#versionMetaHost, ...args);
439 }
441 /** Who published a version of shared, and why. */
442 published(version: number): { agent: string; message: string; time: number } | undefined {
443 const p = this.#shared.versions[version];
444 return p && { agent: p.agent, message: p.message, time: p.time };
445 }
447 /** The graph, for reading (blame, history). Don't add to it. */
448 get graph(): Graph {
449 return this.#graph;
450 }
452 // Calls -------------------------------------------------------------------
454 /** Create the project from a folder's text files. Empty files are skipped (the engine can't hold them). */
455 init(...args: Tail<Parameters<typeof hostedInit>>): ReturnType<typeof hostedInit> {
456 return hostedInit(this.#initHost, ...args);
457 }
459 /** An Edit, Write or MultiEdit from the hook, against the agent's view. */
460 edit(...args: Tail<Parameters<typeof hostedEdit>>): ReturnType<typeof hostedEdit> {
461 return hostedEdit(this.#editHost, ...args);
462 }
464 /** Whole files as the agent's folder has them; each is diffed against its view. */
465 record(...args: Tail<Parameters<typeof hostedRecord>>): ReturnType<typeof hostedRecord> {
466 return hostedRecord(this.#recordHost, ...args);
467 }
469 /** Add the agent's draft to its space (publish.ts). */
470 publish(...args: Tail<Parameters<typeof hostedPublish>>): ReturnType<typeof hostedPublish> {
471 return hostedPublish(this.#publishHost, ...args);
472 }
474 #publish(
475 agent: AgentState,
476 message: string,
477 time: number,
478 entries: Entry[],
479 asIs = false,
480 direct = false,
481 ): PublishAnswer {
482 return hostedPublishDraft(this.#publishHost, agent, message, time, entries, asIs, direct);
483 }
485 /**
486 * How the agent's newest edit arrived (#41). The mod sends X-Avcs-Client
487 * avcs-mod/<stamp>; the hook sends abso-cli/<version> (avcs-cli/ before #59) with the chat's
488 * session; abso record and git pushes send no session. Edits stored before
489 * the client was recorded have only the session: those count as the mod
490 * (the hook stands down where the mod is installed), with modCurrent null.
491 */
492 #editsOf(agent: AgentState): {
493 edits: EditsVia;
494 modCurrent: boolean | null;
495 lastEdit: number | null;
496 joined: number | null;
497 } {
498 const last = agent.lastEdit;
499 const joined = agent.joined ?? null;
500 if (!last) return { edits: "none", modCurrent: null, lastEdit: null, joined };
501 const { client, session } = last;
502 if (client?.startsWith("avcs-mod/"))
503 return { edits: "mod", modCurrent: client === this.#mods[this.#mods.length - 1], lastEdit: last.time, joined };
504 if (client === undefined && session) return { edits: "mod", modCurrent: null, lastEdit: last.time, joined };
505 return { edits: session ? "hook" : "commands", modCurrent: null, lastEdit: last.time, joined };
506 }
508 // Spellings and moves (#49) --------------------------------------------------------
510 /** Refuse work whose paths would clash in shared (#49), before anything of it is written. */
511 #checkClash(...args: Tail<Parameters<typeof hostedCheckClash>>): ReturnType<typeof hostedCheckClash> {
512 return hostedCheckClash(this.#checkClashHost, ...args);
513 }
515 /**
516 * Move a file in the agent's draft (#49): its lines keep their ids, as with
517 * git mv, so blame and why follow it. The only way to change a file's case.
518 * Refused when `to` is another existing file, ignoring case.
519 */
520 move(...args: Tail<Parameters<typeof hostedMove>>): ReturnType<typeof hostedMove> {
521 return hostedMove(this.#moveHost, ...args);
522 }
524 // Files kept whole (#46) ----------------------------------------------------------
526 /** avcs.json's `"whole": [globs]`: paths kept whole. From `config` when given (init), else shared's. */
527 #wholeRules(config?: string): string[] {
528 return hostedWholeRules(this.#wholeHost, config);
529 }
531 /**
532 * Whether a file is kept whole: its path matches avcs.json's "whole", its
533 * text passes WHOLE_LIMIT, or it is already a blob where it's going. The
534 * last makes it one-way: a file kept whole stays whole while it exists,
535 * even if it shrinks or the rule changes, so it never flips back and forth.
536 */
537 #isWhole(path: string, length: number, view: View | undefined, rules: readonly string[]): boolean {
538 return hostedIsWhole(this.#wholeHost, path, length, view, rules);
539 }
541 /** Files and blobs with every whole file's text moved into the blob store. */
542 #wholeOut(
543 files: Readonly<Record<string, string | null>>,
544 blobs: Readonly<Record<string, string>>,
545 view: View | undefined,
546 config?: string,
547 ): { files: Record<string, string | null>; blobs: Record<string, string> } {
548 return hostedWholeOut(this.#wholeHost, files, blobs, view, config);
549 }
551 // Changes (#44) -------------------------------------------------------------------
553 /** The agent did something at `time`: its start note ends first if it had been idle over 2 hours. */
554 #active(agent: AgentState, time: number): void {
555 if (agent.starting && agent.lastActive !== undefined && time - agent.lastActive > NOTE_IDLE) {
556 delete agent.starting;
557 delete agent.noteAt;
558 }
559 if (agent.lastActive === undefined || time > agent.lastActive) agent.lastActive = time;
560 }
562 /** The agent's start note, unless it has been idle over 2 hours. */
563 #liveNote(agent: AgentState): Starting | undefined {
564 if (!agent.starting) return undefined;
565 const now = this.#now?.() ?? this.#lastTime;
566 return agent.lastActive !== undefined && now - agent.lastActive > NOTE_IDLE ? undefined : agent.starting;
567 }
569 /** The change the agent is working on at `time`: its named draft's, or its start note's; none for a lone publish. */
570 #currentChange(agent: AgentState, time: number): number | undefined {
571 if (agent.space !== SHARED) return this.#spaces.get(agent.space)?.startedAt;
572 if (!agent.starting || agent.noteAt === undefined) return undefined;
573 return agent.lastActive !== undefined && time - agent.lastActive > NOTE_IDLE ? undefined : agent.noteAt;
574 }
576 /** The position the next entry written will have. */
577 get #nextAt(): number {
578 return this.#stored + this.#pending.length;
579 }
581 #changeRecord(id: number, agent: AgentState, time: number, queuedNote?: Starting): ChangeRecord {
582 return hostedChangeRecord(this.#changeHost, id, agent, time, queuedNote);
583 }
585 /** A publish or land joins its change. Entries from before changes: the start note named it, and the publish ended the note. */
586 #joinChange(
587 agent: AgentState,
588 entry: Extract<Entry, { type: "publish" | "land" }>,
589 at: number,
590 draft: string | null,
591 landed?: string,
592 ): void {
593 hostedJoinChange(this.#changeHost, agent, entry, at, draft, landed);
594 }
596 /**
597 * One change (#44): the start note, named draft or publish that began it,
598 * each of its versions and the files they changed, what it settled, and its
599 * refusals. `id` is the log position of the entry that began it.
600 */
601 change(id: number): ChangeAnswer {
602 return hostedChange(this.#changeHost, id);
603 }
605 /** The files a version's changes name: cheap, for lists (the change page works out the net changes). */
606 #namedFiles(space: Space, version: number): string[] {
607 return hostedNamedFiles(this.#graph, space, version);
608 }
610 /**
611 * "Since you last looked" (#44): the changes with anything new at or after
612 * log position `since`, newest first, at most `limit`. Their files are the
613 * ones their changes name; the change page has the net changes.
614 */
615 changes(
616 since = 0,
617 limit = 50,
618 before?: number,
619 issue?: number,
620 ): { since: number; next: number; changes: ChangeAnswer[]; older?: number } {
621 return hostedChanges(this.#changeHost, since, limit, before, issue);
622 }
624 // Notes on lines (#44) --------------------------------------------------------------
626 /**
627 * Leave a note on lines of a file (#44): lines `from` to `to` (1-based) as
628 * shared shows them now, as `of`'s draft shows them (to note work before
629 * it's published), or at `version`. Or answer a note with `reply`. The
630 * lines' authors, the change's agent and the thread hear it as news.
631 */
632 note(
633 agentName: string,
634 body: NoteBody,
635 time: number,
636 ): { id: number; change: number | null; lines: [number, number] } {
637 this.#needInit();
638 const entries: Entry[] = [];
639 return this.#note(entries, () => ({ name: this.#agent(agentName, entries).name }), body, time);
640 }
642 /**
643 * A signed-in person's note from the website (#41). The Worker has checked
644 * who it is. The writer is recorded as "person:<id>" with `person`, never
645 * as an agent, and the news quotes the text.
646 */
647 notePerson(
648 person: { id: unknown; name: unknown },
649 body: NoteBody,
650 time: number,
651 ): { id: number; change: number | null; lines: [number, number] } {
652 this.#needInit();
653 const from = checkPerson(person);
654 return this.#note([], () => ({ name: `person:${from.person.id}`, person: from }), body, time);
655 }
657 /** Close a person's own note (#41): only the person who wrote it can. */
658 closeNotePerson(person: { id: unknown; name: unknown }, id: number, how: unknown, time: number): NoteAnswer {
659 const from = checkPerson(person);
660 return this.#closeNote(`person:${from.person.id}`, id, how, time, from);
661 }
663 #note(
664 entries: Entry[],
665 writerOf: () => { name: string; person?: PersonSender },
666 body: NoteBody,
667 time: number,
668 ): { id: number; change: number | null; lines: [number, number] } {
669 return hostedWriteNote(this.#noteWriteHost, entries, writerOf, body, time);
670 }
672 /** The project's reviewers per area (#44): avcs.json's `"review": [{"paths": [...], "reviewer": "..."}]` in shared. */
673 #reviewRules(): ReviewRule[] {
674 return reviewRulesIn(projectFileIn(this.#sharedView())?.text);
675 }
677 /** Each reviewer whose area these files fall in, the files that do, and whether it has noted change `id`. */
678 #reviewersOf(files: readonly string[], id: number): { agent: string; files: string[]; read: boolean }[] {
679 return reviewersOf(this.#reviewRules(), files, (agent) =>
680 [...this.#notes.values()].some((n) => n.change === id && n.agent === agent),
681 );
682 }
684 /** After a version of shared: the reviewers whose areas it touches hear of its change, once per change (#44). */
685 #reviewNews(agent: AgentState, version: number, entries: Entry[]): void {
686 const id = this.#versionChange.get(` ${version}`);
687 if (id === undefined) return;
688 const rec = this.#changes.get(id);
689 const files = this.#namedFiles(this.#shared, version);
690 for (const r of this.#reviewersOf(files, id)) {
691 if (r.agent === agent.name) continue;
692 const reviewer = this.#agents.get(r.agent);
693 if (!reviewer) continue;
694 const title =
695 rec?.note?.text ?? (rec?.kind === "draft" ? `draft ${rec.draft}` : (rec?.versions[0]?.message ?? ""));
696 this.#queueNews(reviewer, [reviewItem(agent.name, id, title, r.files, version)], entries);
697 }
698 }
700 /** After a version of shared: each open objection whose lines it took out tells its writer (#44). */
701 #addressedNews(agent: AgentState, version: number, entries: Entry[]): void {
702 for (const n of this.#notes.values()) {
703 if (n.kind !== "objection" || n.closed || n.reply !== undefined || n.agent === agent.name) continue;
704 if (this.#noteAnswer(n).state !== "addressed") continue;
705 const writer = this.#agents.get(n.agent);
706 if (writer) this.#queueNews(writer, [addressedItem(agent.name, version, n)], entries);
707 }
708 }
710 /** Close a note: only its writer can (#44). */
711 closeNote(agentName: string, id: number, how: unknown, time: number): NoteAnswer {
712 return this.#closeNote(agentName, id, how, time);
713 }
715 #closeNote(agentName: string, id: number, how: unknown, time: number, person?: PersonSender): NoteAnswer {
716 return hostedCloseNote(this.#noteWriteHost, agentName, id, how, time, person);
717 }
719 /** Notes, oldest first: on a file, on a change, or only the ones still open. */
720 notes(...args: Tail<Parameters<typeof hostedNotes>>): ReturnType<typeof hostedNotes> {
721 return hostedNotes(this.#notesHost, ...args);
722 }
724 /** The change the newest of these lines was written in: its version's, or its author's current one if unpublished. */
725 #changeOfLines(lines: readonly LineId[]): number | undefined {
726 let newest: Atom | undefined;
727 for (const l of lines) {
728 const info = this.#graph.line(l);
729 const atom = info && this.#graph.atom(info.atom);
730 if (atom && (!newest || atom.seq > newest.seq)) newest = atom;
731 }
732 if (!newest) return undefined;
733 for (const space of [this.#shared, ...[...this.#spaces.values()].filter((s) => s.name !== SHARED)]) {
734 const v = space.publishedIn.get(newest.id);
735 if (v !== undefined) return this.#versionChange.get(`${space.name === SHARED ? "" : space.name} ${v}`);
736 }
737 const author = this.#agents.get(newest.author);
738 return author ? this.#currentChange(author, this.#now?.() ?? this.#lastTime) : undefined;
739 }
741 /**
742 * The view a note's lines live in (#44):
743 * shared once any were published there; else the named draft they were
744 * published into; else their author's draft, where it works now or where it
745 * parked it. Undefined when no space holds them any more (a discarded draft).
746 */
747 #noteView(n: NoteRecord): View | undefined {
748 return hostedNoteView(this.#notesHost, n);
749 }
751 #noteAnswer(n: NoteRecord): NoteAnswer {
752 return hostedNoteAnswer(this.#notesHost, n);
753 }
755 // The merge queue (#39) ------------------------------------------------------------
757 /** Whether shared's avcs.json turns the merge queue on (`"queue": true`). */
758 #queueOn(): boolean {
759 return hostedQueueOn(this.#queueHost);
760 }
762 /** With the queue on, nothing lands in shared unchecked; land and pluck don't go through the queue yet. */
763 #notQueuedYet(what: string): void {
764 hostedNotQueuedYet(this.#queueHost, what);
765 }
767 /** Atoms of every queued publish, or only other agents' with `except`. */
768 #queuedAtoms(except?: string): Set<AtomId> {
769 return hostedQueuedAtoms(this.#queueHost, except);
770 }
772 /** Queue the agent's publish (#39). */
773 #enqueue(
774 agent: AgentState,
775 message: string,
776 time: number,
777 draft: readonly AtomId[],
778 resolves: readonly AtomId[],
779 entries: Entry[],
780 ): PublishAnswer {
781 return hostedEnqueue(this.#queueHost, agent, message, time, draft, resolves, entries);
782 }
784 /** The merge queue now (#39): waiting publishes in order, and which are in the batch being checked. */
785 queue(...args: Tail<Parameters<typeof hostedQueue>>): ReturnType<typeof hostedQueue> {
786 return hostedQueue(this.#queueHost, ...args);
787 }
789 /** Mark the first `n` queued publishes as the batch being checked (0 ends it). Not logged. */
790 queueChecking(...args: Tail<Parameters<typeof hostedQueueChecking>>): ReturnType<typeof hostedQueueChecking> {
791 return hostedQueueChecking(this.#queueHost, ...args);
792 }
794 /** Shared with the first `n` queued publishes on top (#39): the files a batch's check runs on, and their tree hash. */
795 queueCandidate(...args: Tail<Parameters<typeof hostedQueueCandidate>>): ReturnType<typeof hostedQueueCandidate> {
796 return hostedQueueCandidate(this.#queueHost, ...args);
797 }
799 /** The tree hash of a version of shared (#39): it equals a candidate's when that's what landed. */
800 treeAt(version: number): string {
801 const view = this.viewAt(version);
802 return treeHash({ files: view.files(), modes: modesOf(view), blobs: view.blobs() });
803 }
805 /**
806 * Land the first `n` queued publishes (#39), in order, each as its own
807 * version, after their batch passed. Each tells others what arrived, its
808 * author that it landed, and the authors of what it settled what it kept.
809 */
810 queueLand(...args: Tail<Parameters<typeof hostedQueueLand>>): ReturnType<typeof hostedQueueLand> {
811 return hostedQueueLand(this.#queueHost, ...args);
812 }
814 /**
815 * Take a queued publish out (#39): its check failed, or its author withdrew
816 * it. Its changes are simply still in its author's draft. Later queued
817 * publishes that build on its changes come out with it.
818 */
819 queuePull(...args: Tail<Parameters<typeof hostedQueuePull>>): ReturnType<typeof hostedQueuePull> {
820 return hostedQueuePull(this.#queueHost, ...args);
821 }
823 /** The agent withdraws its queued publishes (#39): refused while one is in the batch being checked. */
824 unqueue(...args: Tail<Parameters<typeof hostedUnqueue>>): ReturnType<typeof hostedUnqueue> {
825 return hostedUnqueue(this.#queueHost, ...args);
826 }
828 /**
829 * Correct the message of the agent's newest publish in its space (#27).
830 * Only the message changes: shared only grows, so a version's changes are
831 * fixed by publishing again (or dropping it). The log keeps the original.
832 */
833 amend(...args: Tail<Parameters<typeof hostedAmend>>): ReturnType<typeof hostedAmend> {
834 return hostedAmend(this.#amendHost, ...args);
835 }
837 /**
838 * Put a label on a version of shared (the newest by default), or take it
839 * off with `remove`. A label can mark many versions ("passed-ci"); a folder
840 * follows the newest with `sync {label}`.
841 */
842 label(...args: Tail<Parameters<typeof hostedLabel>>): ReturnType<typeof hostedLabel> {
843 return hostedLabel(this.#labelHost, ...args);
844 }
846 /**
847 * Drop published versions of shared (#10): a new shared version whose set
848 * leaves out their changes. Later work that doesn't depend on them stays;
849 * history keeps them. When later published work built on them, they are
850 * refused with that work listed, unless `withDependents`, which drops it
851 * too. Unpublished work that builds on them (an agent's draft, a named
852 * draft not yet landed) always refuses it: drop never touches it.
853 */
854 drop(
855 agentName: string,
856 versions: readonly number[],
857 message: string,
858 time: number,
859 options: { withDependents?: boolean } = {},
860 ): DropAnswer {
861 return hostedDrop(this.#dropHost, agentName, versions, message, time, options);
862 }
864 /**
865 * After a sync, merge files where the agent's draft and the newer work
866 * collide, the way git merges a file (#25, Fuzzer): from the agent's old
867 * base, its draft's text and the newer text. Changes both made identically
868 * are kept once; changes on one side are kept. Only when every file
869 * involved merges with no conflict are the draft's changes to them dropped
870 * (a discard entry) and made again as the merged text. Otherwise nothing
871 * changes, and the collision stands with both sides' lines in the file.
872 */
873 #mergeIdentical(
874 agent: AgentState,
875 before: View,
876 oldBase: ReadonlySet<AtomId>,
877 oldVersion: number,
878 time: number,
879 entries: Entry[],
880 ): MergedLine[] {
881 return hostedMergeIdentical(this.#mergeHost, agent, before, oldBase, oldVersion, time, entries);
882 }
884 /**
885 * Names the agent's draft defines at the top level of a file where other
886 * work defines them too, so they are defined twice there (#25, Fuzzer).
887 */
888 #duplicates(agent: AgentState): Collision[] {
889 return duplicateCollisions(this.#collisionHost, agent);
890 }
892 /**
893 * Draft changes that build on atoms a set doesn't have (a drop took them
894 * out): the files they touch. Those changes can't move onto that set.
895 */
896 #strandedFiles(draft: readonly AtomId[], set: ReadonlySet<AtomId>): string[] {
897 return strandedFiles(this.#graph, draft, set);
898 }
900 /** Answer a refusal, and log it (an entry that changes nothing but the counts). */
901 #refuse(...args: Tail<Parameters<typeof hostedRefuse>>): ReturnType<typeof hostedRefuse> {
902 return hostedRefuse(this.#refuseHost, ...args);
903 }
905 /**
906 * Tell other agents something, as news: "Announcement from <agent>:
907 * <text>". It reaches each one with its next edit, record or news call.
908 * `to` names agents; without it, every other agent the project has now.
909 */
910 announce(...args: Tail<Parameters<typeof hostedAnnounce>>): ReturnType<typeof hostedAnnounce> {
911 return hostedAnnounce(this.#announceHost, ...args);
912 }
914 /**
915 * A signed-in person's announcement from the website (#41). The Worker has
916 * checked who sent it; the engine records it on each recipient's news with
917 * `from`, and never makes the person an agent. The text is JSON-quoted, so
918 * a line break in it can't pass for another item.
919 */
920 announcePerson(...args: Tail<Parameters<typeof hostedAnnouncePerson>>): ReturnType<typeof hostedAnnouncePerson> {
921 return hostedAnnouncePerson(this.#announceHost, ...args);
922 }
924 /**
925 * Say what the agent is starting on (#37, #13), before any edit lands:
926 * `text`, and the files it expects to change if it knows them. Nothing is
927 * locked or refused. where and status show it until the agent publishes,
928 * lands, or sends null. The answer names who already has unpublished
929 * changes in, or a starting note on, those files; they hear of it too.
930 */
931 starting(...args: Tail<Parameters<typeof hostedStarting>>): ReturnType<typeof hostedStarting> {
932 return hostedStarting(this.#startingHost, ...args);
933 }
935 /** Every agent's starting note, by agent name. */
936 startingNotes(): ReturnType<typeof hostedStartingNotes> {
937 return hostedStartingNotes(this.#notesHost);
938 }
940 #openCollisions(agent: AgentState): { collisions?: AgentStatus["collisions"] } {
941 return hostedOpenCollisions(this.#markerHost, agent);
942 }
944 /**
945 * News when an edit leaves a file holding blocks of collision markers
946 * (#11): how many, and how to settle them. Again whenever the count changes.
947 */
948 #markedNews(agent: AgentState, files: readonly string[], entries: Entry[]): void {
949 const marked = new Set(this.#markedFiles(agent));
950 const view = this.#agentView(agent);
951 const items: NewsItem[] = [];
952 for (const file of [...new Set(files)].sort()) {
953 if (!marked.has(file) || !view.hasFile(file)) continue;
954 const n = blocksIn(view.lines(file).map((l) => l.text)).length;
955 if (n === 0) continue;
956 items.push(markedItem(this.#draft(agent)[0] ?? "", file, n));
957 }
958 this.#queueNews(agent, items, entries);
959 }
961 /** The collided changes behind each block whose marker lines `atom` deletes (#11). */
962 #markersSettled(agent: AgentState, view: View, atom: Atom): AtomId[] {
963 return hostedMarkersSettled(this.#markerHost, agent, view, atom);
964 }
966 /** Files where a sync wrote the agent collision markers in its current space (#11). */
967 #markedFiles(agent: AgentState): string[] {
968 return hostedMarkedFiles(agent);
969 }
971 /** The blocks of markers still in the agent's files, as collisions (#11): listed by sync and status. */
972 #markedCollisions(agent: AgentState): Collision[] {
973 return hostedMarkedCollisions(this.#markerHost, agent);
974 }
976 /**
977 * Marker lines the agent's draft adds (#11), as collisions: each
978 * well-formed block, and any marker line left outside one. Only the labeled
979 * lines the engine writes count, so a document that shows markers can be
980 * published.
981 */
982 #markerCollisions(agent: AgentState): Collision[] {
983 return hostedMarkerCollisions(this.#markerHost, agent);
984 }
986 /** One line of news for each other author whose marked collision a publish settled (#11): what was kept, and any lines lost. */
987 #settledNews(agent: AgentState, version: number, settled: readonly Settled[], entries: Entry[]): void {
988 for (const s of settled) {
989 const other = this.#agents.get(s.theirs.agent);
990 if (!other || other === agent) continue;
991 this.#queueNews(other, [settledItem(agent.name, version, s)], entries);
992 }
993 }
995 /** The files the agent's unpublished changes touch, in its own view. */
996 #draftFiles(...args: Tail<Parameters<typeof hostedDraftFiles>>): ReturnType<typeof hostedDraftFiles> {
997 return hostedDraftFiles(this.#overlapHost, ...args);
998 }
1000 /** Other agents in the agent's space whose unpublished changes or starting note meet `patterns`. */
1001 #overlaps(...args: Tail<Parameters<typeof hostedOverlaps>>): ReturnType<typeof hostedOverlaps> {
1002 return hostedOverlaps(this.#overlapHost, ...args);
1003 }
1005 /**
1006 * News the first time a draft touches a file someone else in its space has
1007 * unpublished changes in, or a starting note on (#37): one line per file and agent, once per draft. It tells; it never stops
1008 * the edit.
1009 */
1010 #overlapNews(...args: Tail<Parameters<typeof hostedOverlapNews>>): ReturnType<typeof hostedOverlapNews> {
1011 return hostedOverlapNews(this.#overlapHost, ...args);
1012 }
1014 /** Hand over the news waiting for an agent (collisions, definitions, moves, announcements), once. */
1015 news(agentName: string): { news: string[]; items: { text: string; at: number | null }[] } {
1016 const entries: Entry[] = [];
1017 const agent = this.#agent(agentName, entries);
1018 const items = agent.news.map((text, i) => ({ text, at: agent.newsAt[i] ?? null }));
1019 const news = this.#takeNews(agent, entries);
1020 this.#flush(entries);
1021 return { news, items };
1022 }
1024 /** Refused publishes and lands, newest first (`limit` defaults to 50), with counts over all of them. */
1025 refusals(...args: Tail<Parameters<typeof hostedRefusals>>): ReturnType<typeof hostedRefusals> {
1026 return hostedRefusals(this.#refuseHost, ...args);
1027 }
1029 /**
1030 * Move the agent's base to its space's newest version. Returns every file
1031 * whose text in its view changes (null when it's gone), and the collisions
1032 * it now has to settle. A first sync returns every file (that's how a
1033 * folder joins).
1034 */
1035 sync(...args: Tail<Parameters<typeof hostedSync>>): ReturnType<typeof hostedSync> {
1036 return hostedSync(this.#syncHost, ...args);
1037 }
1039 /**
1040 * Move the agent to a named draft, or back to shared with null. Its
1041 * unpublished changes stay parked on the server in the space it leaves,
1042 * and what it parked in the space it moves to comes back. Nothing is lost
1043 * and nothing has to be published or stashed first. A new named draft
1044 * starts on shared's newest version; with `carry`, the agent's current
1045 * unpublished changes move into it instead of being parked. Answers like a
1046 * sync: the files that change in its folder.
1047 */
1048 switchTo(...args: Tail<Parameters<typeof hostedSwitchTo>>): ReturnType<typeof hostedSwitchTo> {
1049 return hostedSwitchTo(this.#switchHost, ...args);
1050 }
1052 /**
1053 * Move the agent's named draft onto shared's newest version. The draft's
1054 * agents see it when they next sync; anything it collides with is theirs
1055 * to settle before the draft lands.
1056 */
1057 syncDraft(agentName: string, time: number): DraftSyncAnswer {
1058 const entries: Entry[] = [];
1059 const agent = this.#agent(agentName, entries);
1060 const space = this.#namedSpaceOf(agent);
1061 const ownOnly = [...space.own].filter((id) => !this.#shared.own.has(id) && !this.#shared.droppedIn.has(id));
1062 const stranded = this.#strandedFiles(ownOnly, this.#shared.own);
1063 if (stranded.length > 0) {
1064 throw new ProjectError(
1065 "conflict",
1066 `draft ${space.name} has changes to ${stranded.join(", ")} that build on lines a drop took out of shared`,
1067 );
1068 }
1069 if (sharedBaseOf(space) !== this.version) {
1070 entries.push({
1071 type: "space-sync",
1072 space: space.name,
1073 agent: agent.name,
1074 time,
1075 version: last(space) + 1,
1076 sharedBase: this.version,
1077 });
1078 this.#apply(entries[entries.length - 1]!);
1079 }
1080 this.#flush(entries);
1081 return { draft: space.name, version: last(space), sharedBase: sharedBaseOf(space) };
1082 }
1084 /**
1085 * Land the agent's named draft in shared as one unit: every change
1086 * published into it that shared doesn't have yet. Refused, like a publish,
1087 * when those changes collide with work that landed in shared after the
1088 * draft's base; sync the draft, settle, and land again.
1089 */
1090 land(...args: Tail<Parameters<typeof hostedLand>>): ReturnType<typeof hostedLand> {
1091 return hostedLand(this.#landHost, ...args);
1092 }
1094 /**
1095 * What landing `changes` of a named draft would collide with in shared now (#41, the Drafts page reads it
1096 * too): the same pairs and definitions land refuses on.
1097 */
1098 #landCollisions(
1099 space: Space,
1100 changes: AtomId[],
1101 pick: boolean,
1102 ): { collisions: Collision[]; newer: Set<AtomId>; union: Set<AtomId> } {
1103 return hostedLandCollisions(this.#landHost, space, changes, pick);
1104 }
1106 /**
1107 * A named draft's state in one read (#41, the Drafts page, D3 and D16): the shared version it builds on and
1108 * how far behind shared that is, its versions, when its first edit was, who works in it, and what landing it
1109 * now would collide with (the same check land makes, so nothing is written).
1110 */
1111 draftState(...args: Tail<Parameters<typeof hostedDraftState>>): ReturnType<typeof hostedDraftState> {
1112 return hostedDraftState(this.#draftStateHost, ...args);
1113 }
1115 #land(
1116 agent: AgentState,
1117 message: string,
1118 time: number,
1119 entries: Entry[],
1120 pick?: { space: Space; changes: AtomId[] },
1121 ): LandAnswer {
1122 return hostedLandDraft(this.#landHost, agent, message, time, entries, pick);
1123 }
1125 /**
1126 * Take part of a named draft into shared (#27): the changes of some of its
1127 * versions, as one new version of shared, checked for collisions like a
1128 * land. When they build on other versions of the draft, those are listed
1129 * and it is refused, unless `withDependencies` takes them too. The draft
1130 * stays as it is; landing it later brings in only what's left.
1131 */
1132 pluck(
1133 agentName: string,
1134 draftName: string,
1135 versions: readonly number[],
1136 message: string,
1137 time: number,
1138 options: { withDependencies?: boolean } = {},
1139 ): PluckAnswer {
1140 return hostedPluck(this.#pluckHost, agentName, draftName, versions, message, time, options);
1141 }
1143 /**
1144 * Take in commits a person pushed with plain git (demo moment 5, #5, #8).
1145 * `base` is the shared version their first commit builds on (the
1146 * `avcs-version` of the commit they cloned). Each commit gives its whole
1147 * tree as text; a file of the view missing from it is deleted. The commits
1148 * go into a named draft `git-<sha>` on that version, one publish each, and
1149 * the draft lands in shared at once if nothing collides. The push already
1150 * happened, so a collision isn't refused: the draft waits, with its
1151 * collisions listed, for someone to switch to it, settle and land it.
1152 */
1153 ingest(...args: Tail<Parameters<typeof hostedIngest>>): ReturnType<typeof hostedIngest> {
1154 return hostedIngest(this.#ingestHost, ...args);
1155 }
1157 // Reading history, and discarding -------------------------------------------
1159 #checkVersion(space: Space, version: number): void {
1160 hostedCheckVersion(space, version);
1161 }
1163 /**
1164 * Discard the agent's unpublished changes to some files (all of them with
1165 * `files` null), like git restore. Changes that touch only those files and
1166 * that no kept change builds on leave the draft; anything left over is
1167 * undone by a new change that puts the files back. Answers with each
1168 * file's text now, for the folder.
1169 */
1170 restore(...args: Tail<Parameters<typeof hostedRestore>>): ReturnType<typeof hostedRestore> {
1171 return hostedRestore(this.#restoreHost, ...args);
1172 }
1174 /** The space options name: an agent's current space with `agent`, else the named draft, else shared. */
1175 #spaceFor(options: { draft?: string | null; agent?: string }): Space {
1176 if (options.agent !== undefined) {
1177 const agent = this.#agents.get(options.agent);
1178 if (!agent) throw new ProjectError("bad-request", `there is no agent ${JSON.stringify(options.agent)}`);
1179 return this.#spaceOf(agent);
1180 }
1181 return this.#spaceNamed(options.draft ?? null);
1182 }
1184 #spaceNamed(name: string | null): Space {
1185 const key = name === null ? SHARED : checkDraftName(name);
1186 const space = this.#spaces.get(key);
1187 if (!space) throw new ProjectError("bad-request", `there is no draft ${String(name)}`);
1188 return space;
1189 }
1191 /**
1192 * The stored spelling a read means (#41, F7, the rule #49 set for writes):
1193 * the path itself, else the one file it matches by pathKey; failing that,
1194 * the one file ever in the view it matches, for a file since taken out.
1195 * A path that matches two files is answered exactly.
1196 */
1197 spellingIn(view: View, path: string): string {
1198 if (view.hasFile(path)) return path;
1199 const key = pathKey(path);
1200 const live = view.knownPaths().filter((p) => pathKey(p) === key && view.hasFile(p));
1201 if (live.length > 0) return live.length === 1 ? live[0]! : path;
1202 const known = view.knownPaths();
1203 if (known.includes(path)) return path;
1204 const gone = known.filter((p) => pathKey(p) === key);
1205 return gone.length === 1 ? gone[0]! : path;
1206 }
1208 // Applying entries ------------------------------------------------------------
1210 #apply(entry: Entry): void {
1211 // Entries written before #41 have no time on these kinds; new ones do, so replay can place them.
1212 const kept =
1213 this.#loading || !UNTIMED.has(entry.type) || "time" in entry ? entry : ({ ...entry, time: Date.now() } as Entry);
1214 if (!this.#loading) this.#pending.push(kept);
1215 const at = this.#loading ? this.#stored : this.#stored + this.#pending.length - 1;
1216 // Positions by time (#41, the website): the newest time up to each position, as the log holds it.
1217 const keptTime =
1218 kept.type === "draft" ? kept.atom.time : "time" in kept && typeof kept.time === "number" ? kept.time : undefined;
1219 const prior = at > 0 ? this.#timeAt[at - 1]! : 0;
1220 this.#timeAt[at] = keptTime !== undefined && keptTime > prior ? keptTime : prior;
1221 const versionsBefore = this.#spaces.get(SHARED)?.versions.length ?? 0;
1222 try {
1223 this.#applyEntry(entry, at, keptTime);
1224 } finally {
1225 // Positions by version: where each version of shared was made.
1226 const versionsAfter = this.#spaces.get(SHARED)?.versions.length ?? 0;
1227 for (let v = versionsBefore; v < versionsAfter; v++) this.#versionAt[v] = at;
1228 }
1229 }
1231 /**
1232 * The log position for a time or a version of shared (#41, the website):
1233 * for `time`, the position just after the last entry no later than it
1234 * (entries with no time take their predecessor's); for `version`, the
1235 * position just after the entry that made it. `end` is the log's length.
1236 */
1237 position(q: { time?: number; version?: number }): { position: number; end: number } {
1238 const end = this.#timeAt.length;
1239 if (q.version !== undefined) {
1240 if (!Number.isInteger(q.version) || q.version < 0 || q.version >= this.#versionAt.length)
1241 throw new ProjectError("not-found", `there is no version ${String(q.version)}`);
1242 return { position: this.#versionAt[q.version]! + 1, end };
1243 }
1244 if (typeof q.time !== "number" || !Number.isFinite(q.time))
1245 throw new ProjectError("bad-request", "position needs ?time= or ?version=");
1246 // The newest time up to each position never goes down, so halve.
1247 let lo = 0;
1248 let hi = end;
1249 while (lo < hi) {
1250 const mid = (lo + hi) >> 1;
1251 if (this.#timeAt[mid]! <= q.time) lo = mid + 1;
1252 else hi = mid;
1253 }
1254 return { position: lo, end };
1255 }
1257 #applyEntry(entry: Entry, at: number, time: number | undefined): void {
1258 hostedApplyEntry(this.#applyEntryHost, entry, at, time);
1259 }
1261 /** Apply entries and store them. */
1262 #commit(entries: Entry[]): void {
1263 for (const e of entries) this.#apply(e);
1264 this.#flush(entries);
1265 }
1267 /** Store entries that are already applied. */
1268 #flush(_entries: readonly Entry[]): void {
1269 if (this.#pending.length === 0) return;
1270 const out = this.#pending;
1271 this.#pending = [];
1272 this.#store.append(out);
1273 this.#stored += out.length;
1274 }
1276 /**
1277 * The agent an entry names. Before every applied entry was stored, a call
1278 * that joined an agent and then threw could leave the join out of the log
1279 * while later entries named the agent. The lost join had the version the
1280 * project was at then, which is the version now, during replay.
1281 */
1282 #agentOf(name: string): AgentState {
1283 let agent = this.#agents.get(name);
1284 if (!agent) {
1285 this.#apply({ type: "join", agent: name, version: this.#shared.versions.length - 1 });
1286 agent = this.#agents.get(name)!;
1287 }
1288 return agent;
1289 }
1291 // Agents, spaces and views ----------------------------------------------------
1293 get #shared(): Space {
1294 return this.#spaces.get(SHARED)!;
1295 }
1297 #needInit(): void {
1298 if (!this.initialized) throw new ProjectError("not-initialized", "the project has no files yet; init it first");
1299 }
1301 #agent(name: string, entries: Entry[]): AgentState {
1302 this.#needInit();
1303 if (typeof name !== "string" || !NAME.test(name) || name === "init") {
1304 throw new ProjectError(
1305 "bad-agent",
1306 `bad agent name ${JSON.stringify(name)}: letters, digits, '.', '_' and '-', up to 64`,
1307 );
1308 }
1309 let agent = this.#agents.get(name);
1310 if (!agent) {
1311 const join: Entry = { type: "join", agent: name, version: this.version };
1312 entries.push(join);
1313 this.#apply(join);
1314 agent = this.#agents.get(name)!;
1315 }
1316 return agent;
1317 }
1319 #spaceOf(agent: AgentState): Space {
1320 return this.#spaces.get(agent.space)!;
1321 }
1323 #namedSpaceOf(agent: AgentState): Space {
1324 if (agent.space === SHARED) {
1325 throw new ProjectError("bad-request", `${agent.name} works in shared, not a named draft; switch to one first`);
1326 }
1327 return this.#spaceOf(agent);
1328 }
1330 // History reads (#41), in history.ts behind HistoryHost (#46, disk-first 1) ------------------------
1332 #host?: HistoryHost;
1333 /** The project as the history reads see it: the seam the derived tables plug into (abso issues 48, 79). */
1334 get #history(): HistoryHost {
1335 this.#host ??= {
1336 graph: this.#graph,
1337 agents: this.#agents,
1338 spaces: this.#spaces,
1339 needInit: () => this.#needInit(),
1340 spaceNamed: (name) => this.#spaceNamed(name),
1341 checkVersion: (space, version) => this.#checkVersion(space, version),
1342 viewAt: (space, version) => this.#viewAt(space, version),
1343 agentView: (agent) => this.#agentView(agent as AgentState),
1344 spellingIn: (view, asked) => this.spellingIn(view, asked),
1345 pathsOf: (space) => this.#paths.pathsOf(space),
1346 lastChange: (space, version) => this.#paths.lastChange(space, version),
1347 atOrBefore: (list, version) => PathIndex.atOrBefore(list, version),
1348 removedIn: (space, from, to, line) => this.#paths.removedIn(space, from, to, line),
1349 };
1350 return this.#host;
1351 }
1353 /** One folder at a version (history.ts). */
1354 tree(...args: Tail<Parameters<typeof historyTree>>): ReturnType<typeof historyTree> {
1355 return historyTree(this.#history, ...args);
1356 }
1358 /** A path's life at a version (history.ts). */
1359 pathLife(...args: Tail<Parameters<typeof historyPathLife>>): ReturnType<typeof historyPathLife> {
1360 return historyPathLife(this.#history, ...args);
1361 }
1363 /** Where lines went after a version (history.ts). */
1364 follow(...args: Tail<Parameters<typeof historyFollow>>): ReturnType<typeof historyFollow> {
1365 return historyFollow(this.#history, ...args);
1366 }
1368 // The version list (log, ribbon, show), in version-log.ts behind LogHost ----------------------------
1370 #logs?: LogHost;
1371 get #logHost(): LogHost {
1372 this.#logs ??= {
1373 graph: this.#graph,
1374 paths: this.#paths,
1375 labels: this.#labels,
1376 shared: () => this.#shared,
1377 needInit: () => this.#needInit(),
1378 spaceFor: (options) => this.#spaceFor(options),
1379 checkVersion: (space, version) => this.#checkVersion(space, version),
1380 viewAt: (space, version) => this.#viewAt(space, version),
1381 view: (set) => this.#view(set),
1382 at: (space, version) => this.#at(space, version),
1383 spellingIn: (view, path) => this.spellingIn(view, path),
1384 versionChange: (space, version) =>
1385 this.#versionChange.get(`${space.name === SHARED ? "" : space.name} ${version}`),
1386 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
1387 };
1388 return this.#logs;
1389 }
1391 /** The versions of shared (or of a named draft), newest first (version-log.ts). */
1392 log(...args: Tail<Parameters<typeof versionLog>>): ReturnType<typeof versionLog> {
1393 return versionLog(this.#logHost, ...args);
1394 }
1396 /** Shared's versions in one small answer, for the website's version ribbon (version-log.ts). */
1397 ribbon(): ReturnType<typeof versionRibbon> {
1398 return versionRibbon(this.#logHost);
1399 }
1401 /** One version of shared (or of a named draft) and the files it changed (version-log.ts). */
1402 show(...args: Tail<Parameters<typeof versionShow>>): ReturnType<typeof versionShow> {
1403 return versionShow(this.#logHost, ...args);
1404 }
1406 /** A file as it was at a version of shared (or a named draft) (version-log.ts). */
1407 fileAt(...args: Tail<Parameters<typeof versionFileAt>>): ReturnType<typeof versionFileAt> {
1408 return versionFileAt(this.#logHost, ...args);
1409 }
1411 /** Every file that differs between two versions of shared (or a named draft) (version-log.ts). */
1412 compare(...args: Tail<Parameters<typeof versionCompare>>): ReturnType<typeof versionCompare> {
1413 return versionCompare(this.#logHost, ...args);
1414 }
1416 /** A version of shared (or of a named draft) as a View (version-log.ts). */
1417 viewAt(...args: Tail<Parameters<typeof versionViewAt>>): ReturnType<typeof versionViewAt> {
1418 return versionViewAt(this.#logHost, ...args);
1419 }
1421 // Whether agents' drafts would collide, in draft-collisions.ts behind DraftCollisionHost -------------
1423 #draftCollisionHost?: DraftCollisionHost;
1424 get #draftCollisions(): DraftCollisionHost {
1425 this.#draftCollisionHost ??= {
1426 graph: this.#graph,
1427 agents: this.#agents,
1428 needInit: () => this.#needInit(),
1429 shared: () => this.#shared,
1430 sharedView: () => this.#sharedView(),
1431 definitionRule: () => this.#definitionRule,
1432 draft: (agent) => this.#draft(agent as AgentState),
1433 agentView: (agent) => this.#agentView(agent as AgentState),
1434 view: (set) => this.#view(set),
1435 pairs: (draft, against, settled) => this.#pairs(draft, against, settled),
1436 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
1437 };
1438 return this.#draftCollisionHost;
1439 }
1441 /** Whether agents' unpublished changes would collide, by the publish rule (draft-collisions.ts). */
1442 collisions(...args: Tail<Parameters<typeof draftCollisions>>): ReturnType<typeof draftCollisions> {
1443 return draftCollisions(this.#draftCollisions, ...args);
1444 }
1446 // An agent's unpublished changes, in draft-diff.ts behind DraftDiffHost -----------------------------
1448 #draftDiffHost?: DraftDiffHost;
1449 get #draftDiff(): DraftDiffHost {
1450 this.#draftDiffHost ??= {
1451 agents: this.#agents,
1452 needInit: () => this.#needInit(),
1453 draft: (agent) => this.#draft(agent as AgentState),
1454 agentView: (agent) => this.#agentView(agent as AgentState),
1455 view: (set) => this.#view(set),
1456 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
1457 };
1458 return this.#draftDiffHost;
1459 }
1461 /** What the agent's unpublished changes do, file by file (draft-diff.ts). Creates the agent if needed. */
1462 diff(agentName: string): DiffAnswer {
1463 const entries: Entry[] = [];
1464 const answer = diffOfAgent(this.#draftDiff, this.#agent(agentName, entries));
1465 this.#flush(entries);
1466 return answer;
1467 }
1469 /** An agent's draft diff for a reader: never creates the agent, never writes (draft-diff.ts). */
1470 diffOf(...args: Tail<Parameters<typeof draftDiffOf>>): ReturnType<typeof draftDiffOf> {
1471 return draftDiffOf(this.#draftDiff, ...args);
1472 }
1474 // Unpublished deletes-and-writes of the same text become a move (express-moves.ts) -----------------
1476 #movesHost?: ExpressMovesHost;
1477 get #expressMovesHost(): ExpressMovesHost {
1478 this.#movesHost ??= {
1479 graph: this.#graph,
1480 draft: (agent) => this.#unqueuedDraft(agent),
1481 agentView: (agent) => this.#agentView(agent),
1482 view: (set) => this.#view(set),
1483 apply: (entry) => this.#apply(entry),
1484 addDraft: (agent, view, input, time, meta, entries) => this.#addDraft(agent, view, input, time, meta, entries),
1485 recordFile: (agent, view, path, text, time, meta, entries, mode) =>
1486 this.#recordFile(agent, view, path, text, time, meta, entries, mode),
1487 };
1488 return this.#movesHost;
1489 }
1491 // Files kept whole, in whole-files.ts behind WholeHost ----------------------------------------------
1493 #wholes?: WholeHost;
1494 get #wholeHost(): WholeHost {
1495 this.#wholes ??= {
1496 initialized: () => this.initialized,
1497 sharedView: () => this.#sharedView(),
1498 whole: this.#whole,
1499 };
1500 return this.#wholes;
1501 }
1503 // Notes list and start notes, in notes.ts behind NoteHost -------------------------------------------
1505 #news?: NewsHost;
1506 get #newsHost(): NewsHost {
1507 this.#news ??= {
1508 graph: this.#graph,
1509 agents: this.#agents,
1510 draft: (agent) => this.#draft(agent),
1511 newerFor: (agent) => this.#newerFor(agent),
1512 spaceOf: (agent) => this.#spaceOf(agent),
1513 setOf: (space) => this.#setOf(space),
1514 viewAt: (space, version) => this.#viewAt(space, version),
1515 origin: (atom, spaceName) => this.#origin(atom, spaceName),
1516 collision: (agent, pair) => this.#collision(agent, pair),
1517 definitionCollisions: (agent, newer) => this.#definitionCollisions(agent, newer),
1518 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
1519 };
1520 return this.#news;
1521 }
1523 #collisions?: CollisionHost;
1524 get #collisionHost(): CollisionHost {
1525 this.#collisions ??= {
1526 graph: this.#graph,
1527 spaces: this.#spaces,
1528 version: () => this.version,
1529 spaceOf: (agent) => this.#spaceOf(agent),
1530 agentSet: (agent) => this.#agentSet(agent),
1531 draft: (agent) => this.#draft(agent),
1532 agentView: (agent) => this.#agentView(agent),
1533 at: (space, version) => this.#at(space, version),
1534 shared: () => this.#shared,
1535 };
1536 return this.#collisions;
1537 }
1539 #markers?: MarkerHost;
1540 get #markerHost(): MarkerHost {
1541 this.#markers ??= {
1542 graph: this.#graph,
1543 agentView: (agent) => this.#agentView(agent),
1544 draft: (agent) => this.#draft(agent),
1545 draftFiles: (agent) => this.#draftFiles(agent),
1546 };
1547 return this.#markers;
1548 }
1550 #noteWrites?: NoteWriteHost;
1551 get #noteWriteHost(): NoteWriteHost {
1552 this.#noteWrites ??= {
1553 notes: this.#notes,
1554 agents: this.#agents,
1555 changes: this.#changes,
1556 graph: this.#graph,
1557 lastNote: () => this.#lastNote,
1558 agentView: (agent) => this.#agentView(agent),
1559 viewAtVersion: (version) => this.viewAt(version),
1560 sharedView: () => this.#sharedView(),
1561 changeOfLines: (lines) => this.#changeOfLines(lines),
1562 apply: (entry) => this.#apply(entry),
1563 flush: (entries) => this.#flush(entries),
1564 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
1565 noteAnswer: (n) => this.#noteAnswer(n),
1566 };
1567 return this.#noteWrites;
1568 }
1570 #noteHost?: NoteHost;
1571 get #notesHost(): NoteHost {
1572 this.#noteHost ??= {
1573 graph: this.#graph,
1574 agents: this.#agents,
1575 spaces: this.#spaces,
1576 notes: this.#notes,
1577 initialized: () => this.initialized,
1578 shared: () => this.#shared,
1579 sharedView: () => this.#sharedView(),
1580 spellingIn: (view, path) => this.spellingIn(view, path),
1581 viewAt: (space, version) => this.#viewAt(space, version),
1582 agentView: (agent) => this.#agentView(agent),
1583 view: (set) => this.#view(set),
1584 at: (space, version) => this.#at(space, version),
1585 liveNote: (agent) => this.#liveNote(agent),
1586 };
1587 return this.#noteHost;
1588 }
1590 #merges?: MergeHost;
1591 get #mergeHost(): MergeHost {
1592 this.#merges ??= {
1593 graph: this.#graph,
1594 openPairs: (agent) => this.#openPairs(agent),
1595 draft: (agent) => this.#unqueuedDraft(agent),
1596 origin: (atom, spaceName) => this.#origin(atom, spaceName),
1597 view: (set) => this.#view(set),
1598 viewAt: (space, version) => this.#viewAt(space, version),
1599 spaceOf: (agent) => this.#spaceOf(agent),
1600 apply: (entry) => this.#apply(entry),
1601 agentView: (agent) => this.#agentView(agent),
1602 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
1603 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
1604 };
1605 return this.#merges;
1606 }
1608 #edits?: EditHost;
1609 get #editHost(): EditHost {
1610 this.#edits ??= {
1611 agents: this.#agents,
1612 whole: this.#whole,
1613 initialized: () => this.initialized,
1614 agentView: (agent) => this.#agentView(agent),
1615 sharedView: () => this.#sharedView(),
1616 isWhole: (path, length, view, rules) => this.#isWhole(path, length, view, rules),
1617 wholeRules: (config) => this.#wholeRules(config),
1618 record: (agentName, files, time, modes, blobs, meta) => this.record(agentName, files, time, modes, blobs, meta),
1619 agent: (name, entries) => this.#agent(name, entries),
1620 draftFiles: (agent) => this.#draftFiles(agent),
1621 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
1622 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
1623 addDraft: (agent, view, input, time, meta, entries) => this.#addDraft(agent, view, input, time, meta, entries),
1624 overlapNews: (agent, before, entries) => this.#overlapNews(agent, before, entries),
1625 markedNews: (agent, files, entries) => this.#markedNews(agent, files, entries),
1626 newsAboutOwnDraft: (agent, entries) => this.#newsAboutOwnDraft(agent, entries),
1627 takeNews: (agent, entries) => this.#takeNews(agent, entries),
1628 flush: (entries) => this.#flush(entries),
1629 };
1630 return this.#edits;
1631 }
1633 #announces?: AnnounceHost;
1634 get #announceHost(): AnnounceHost {
1635 this.#announces ??= {
1636 agents: this.#agents,
1637 announced: () => this.#announced,
1638 setAnnounced: (n) => {
1639 this.#announced = n;
1640 },
1641 agent: (name, entries) => this.#agent(name, entries),
1642 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
1643 apply: (entry) => this.#apply(entry),
1644 flush: (entries) => this.#flush(entries),
1645 needInit: () => this.#needInit(),
1646 };
1647 return this.#announces;
1648 }
1650 #publishers?: PublishHost;
1651 get #publishHost(): PublishHost {
1652 this.#publishers ??= {
1653 agents: this.#agents,
1654 nextAt: () => this.#nextAt,
1655 checkClash: (changes, ahead) => this.#checkClash(changes, ahead),
1656 queueOn: () => this.#queueOn(),
1657 queuedAtoms: (except) => this.#queuedAtoms(except),
1658 agent: (name, entries) => this.#agent(name, entries),
1659 draft: (agent) => this.#draft(agent),
1660 spaceOf: (agent) => this.#spaceOf(agent),
1661 strandedFiles: (draft, set) => this.#strandedFiles(draft, set),
1662 setOf: (space) => this.#setOf(space),
1663 markedFiles: (agent) => this.#markedFiles(agent),
1664 agentView: (agent) => this.#agentView(agent),
1665 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
1666 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
1667 expressMoves: (agent, time, entries) => this.#expressMoves(agent, time, entries),
1668 pairs: (draft, against, settled) => this.#pairs(draft, against, settled),
1669 collision: (agent, pair) => this.#collision(agent, pair),
1670 definitionCollisions: (agent, newer) => this.#definitionCollisions(agent, newer),
1671 duplicates: (agent) => this.#duplicates(agent),
1672 refuse: (agent, space, via, time, collisions, entries) =>
1673 this.#refuse(agent, space, via, time, collisions, entries),
1674 markerCollisions: (agent) => this.#markerCollisions(agent),
1675 enqueue: (agent, message, time, draft, resolves, entries) =>
1676 this.#enqueue(agent, message, time, draft, resolves, entries),
1677 view: (set) => this.#view(set),
1678 requireClosed: (tie, union) => this.#requireClosed(tie, union),
1679 newerFor: (agent) => this.#newerFor(agent),
1680 currentChange: (agent, time) => this.#currentChange(agent, time),
1681 apply: (entry) => this.#apply(entry),
1682 newsForOthers: (publisher, space, version, entries) => this.#newsForOthers(publisher, space, version, entries),
1683 settledNews: (agent, version, settled, entries) => this.#settledNews(agent, version, settled, entries),
1684 addressedNews: (agent, version, entries) => this.#addressedNews(agent, version, entries),
1685 reviewNews: (agent, version, entries) => this.#reviewNews(agent, version, entries),
1686 flush: (entries) => this.#flush(entries),
1687 };
1688 return this.#publishers;
1689 }
1691 #queues?: QueueHost;
1692 get #queueHost(): QueueHost {
1693 this.#queues ??= {
1694 graph: this.#graph,
1695 checkerReady: () => this.checkerReady,
1696 sharedView: () => this.#sharedView(),
1697 queued: () => this.#queue,
1698 queuedId: () => this.#queuedId,
1699 checkingHas: (id) => this.#checking.has(id),
1700 replaceChecking: (ids) => {
1701 this.#checking = new Set(ids);
1702 },
1703 uncheck: (id) => {
1704 this.#checking.delete(id);
1705 },
1706 needInit: () => this.#needInit(),
1707 shared: () => this.#shared,
1708 setOf: (space) => this.#setOf(space),
1709 view: (set) => this.#view(set),
1710 agentSet: (agent) => this.#agentSet(agent),
1711 agentView: (agent) => this.#agentView(agent),
1712 pairs: (draft, against, settled) => this.#pairs(draft, against, settled),
1713 describe: (pair, yoursView, theirsView, spaceName) => this.#describe(pair, yoursView, theirsView, spaceName),
1714 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
1715 refuse: (agent, space, via, time, collisions, entries) =>
1716 this.#refuse(agent, space, via, time, collisions, entries),
1717 currentChange: (agent, time) => this.#currentChange(agent, time),
1718 nextAt: () => this.#nextAt,
1719 apply: (entry) => this.#apply(entry),
1720 agentOf: (name) => this.#agentOf(name),
1721 requireClosed: (tie, union) => this.#requireClosed(tie, union),
1722 newsForOthers: (publisher, space, version, entries) => this.#newsForOthers(publisher, space, version, entries),
1723 settledNews: (agent, version, settled, entries) => this.#settledNews(agent, version, settled, entries),
1724 addressedNews: (agent, version, entries) => this.#addressedNews(agent, version, entries),
1725 reviewNews: (agent, version, entries) => this.#reviewNews(agent, version, entries),
1726 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
1727 flush: (entries) => this.#flush(entries),
1728 };
1729 return this.#queues;
1730 }
1732 #applyEntries?: ApplyEntryHost;
1733 get #applyEntryHost(): ApplyEntryHost {
1734 this.#applyEntries ??= {
1735 graph: this.#graph,
1736 agents: this.#agents,
1737 atomAt: this.#atomAt,
1738 mods: this.#mods,
1739 notes: this.#notes,
1740 changes: this.#changes,
1741 labels: this.#labels,
1742 refusals: this.#refusals,
1743 tells: this.#tells,
1744 uncheck: (id) => {
1745 this.#checking.delete(id);
1746 },
1747 stamp: (t) => {
1748 if (typeof t === "number" && t > this.#lastTime) this.#lastTime = t;
1749 },
1750 applyMembership: (entry, at) => this.#membership.apply(entry, at),
1751 agentOf: (name) => this.#agentOf(name),
1752 active: (agent, time) => this.#active(agent, time),
1753 joinChange: (agent, entry, at, draft, landed) => this.#joinChange(agent, entry, at, draft, landed),
1754 space: (name) => this.#spaces.get(name)!,
1755 queued: () => this.#queue,
1756 setQueued: (items) => {
1757 this.#queue = items;
1758 },
1759 setQueuedId: (id) => {
1760 this.#queuedId = id;
1761 },
1762 queuedId: () => this.#queuedId,
1763 setLastNote: (id) => {
1764 this.#lastNote = id;
1765 },
1766 lastNote: () => this.#lastNote,
1767 setAnnounced: (n) => {
1768 this.#announced = n;
1769 },
1770 announced: () => this.#announced,
1771 at: (space, version) => this.#at(space, version),
1772 spaceOf: (agent) => this.#spaceOf(agent),
1773 draft: (agent) => this.#draft(agent),
1774 currentChange: (agent, time) => this.#currentChange(agent, time),
1775 changeRecord: (id, agent, time) => this.#changeRecord(id, agent, time),
1776 };
1777 return this.#applyEntries;
1778 }
1780 #landers?: LandHost;
1781 get #landHost(): LandHost {
1782 this.#landers ??= {
1783 agents: this.#agents,
1784 graph: this.#graph,
1785 spaces: this.#spaces,
1786 version: () => this.version,
1787 nextAt: () => this.#nextAt,
1788 notQueuedYet: (what) => this.#notQueuedYet(what),
1789 checkClash: (changes) => this.#checkClash(changes),
1790 agent: (name, entries) => this.#agent(name, entries),
1791 namedSpaceOf: (agent) => this.#namedSpaceOf(agent),
1792 shared: () => this.#shared,
1793 setOf: (space) => this.#setOf(space),
1794 at: (space, version) => this.#at(space, version),
1795 view: (set) => this.#view(set),
1796 sharedView: () => this.#sharedView(),
1797 pairs: (draft, against, settled) => this.#pairs(draft, against, settled),
1798 describe: (pair, yoursView, theirsView, spaceName) => this.#describe(pair, yoursView, theirsView, spaceName),
1799 definitionRule: () => this.#definitionRule,
1800 refuse: (agent, space, via, time, collisions, entries) =>
1801 this.#refuse(agent, space, via, time, collisions, entries),
1802 requireClosed: (tie, union) => this.#requireClosed(tie, union),
1803 apply: (entry) => this.#apply(entry),
1804 newsForOthers: (publisher, space, version, entries) => this.#newsForOthers(publisher, space, version, entries),
1805 addressedNews: (agent, version, entries) => this.#addressedNews(agent, version, entries),
1806 reviewNews: (agent, version, entries) => this.#reviewNews(agent, version, entries),
1807 flush: (entries) => this.#flush(entries),
1808 };
1809 return this.#landers;
1810 }
1812 #records?: RecordHost;
1813 get #recordHost(): RecordHost {
1814 this.#records ??= {
1815 agents: this.#agents,
1816 whole: this.#whole,
1817 initialized: () => this.initialized,
1818 agentView: (agent) => this.#agentView(agent),
1819 sharedView: () => this.#sharedView(),
1820 wholeOut: (files, blobs, view, config) => this.#wholeOut(files, blobs, view, config),
1821 checkBlobs: (blobs, files) => this.#checkBlobs(blobs, files),
1822 agent: (name, entries) => this.#agent(name, entries),
1823 draftFiles: (agent) => this.#draftFiles(agent),
1824 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
1825 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
1826 overlapNews: (agent, before, entries) => this.#overlapNews(agent, before, entries),
1827 markedNews: (agent, files, entries) => this.#markedNews(agent, files, entries),
1828 newsAboutOwnDraft: (agent, entries) => this.#newsAboutOwnDraft(agent, entries),
1829 takeNews: (agent, entries) => this.#takeNews(agent, entries),
1830 flush: (entries) => this.#flush(entries),
1831 };
1832 return this.#records;
1833 }
1835 #restores?: RestoreHost;
1836 get #restoreHost(): RestoreHost {
1837 this.#restores ??= {
1838 graph: this.#graph,
1839 agent: (name, entries) => this.#agent(name, entries),
1840 draft: (agent) => this.#unqueuedDraft(agent),
1841 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
1842 apply: (entry) => this.#apply(entry),
1843 view: (set) => this.#view(set),
1844 agentSet: (agent) => this.#agentSet(agent),
1845 agentView: (agent) => this.#agentView(agent),
1846 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
1847 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
1848 flush: (entries) => this.#flush(entries),
1849 };
1850 return this.#restores;
1851 }
1853 #startings?: StartingHost;
1854 get #startingHost(): StartingHost {
1855 this.#startings ??= {
1856 agents: this.#agents,
1857 changes: this.#changes,
1858 agent: (name, entries) => this.#agent(name, entries),
1859 liveNote: (agent) => this.#liveNote(agent),
1860 apply: (entry) => this.#apply(entry),
1861 overlaps: (agent, patterns) => this.#overlaps(agent, patterns),
1862 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
1863 flush: (entries) => this.#flush(entries),
1864 };
1865 return this.#startings;
1866 }
1868 #syncs?: SyncHost;
1869 get #syncHost(): SyncHost {
1870 this.#syncs ??= {
1871 graph: this.#graph,
1872 labels: this.#labels,
1873 agent: (name, entries) => this.#agent(name, entries),
1874 spaceOf: (agent) => this.#spaceOf(agent),
1875 agentView: (agent) => this.#agentView(agent),
1876 at: (space, version) => this.#at(space, version),
1877 draft: (agent) => this.#draft(agent),
1878 strandedFiles: (draft, set) => this.#strandedFiles(draft, set),
1879 apply: (entry) => this.#apply(entry),
1880 flush: (entries) => this.#flush(entries),
1881 mergeIdentical: (agent, before, oldBase, oldVersion, time, entries) =>
1882 this.#mergeIdentical(agent, before, oldBase, oldVersion, time, entries),
1883 changesSince: (agent, before) => this.#changesSince(agent, before),
1884 };
1885 return this.#syncs;
1886 }
1888 #moves?: MoveHost;
1889 get #moveHost(): MoveHost {
1890 this.#moves ??= {
1891 needInit: () => this.#needInit(),
1892 agents: this.#agents,
1893 agentView: (agent) => this.#agentView(agent),
1894 sharedView: () => this.#sharedView(),
1895 agent: (name, entries) => this.#agent(name, entries),
1896 addDraft: (agent, view, input, time, meta, entries) => this.#addDraft(agent, view, input, time, meta, entries),
1897 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
1898 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
1899 newsAboutOwnDraft: (agent, entries) => this.#newsAboutOwnDraft(agent, entries),
1900 takeNews: (agent, entries) => this.#takeNews(agent, entries),
1901 flush: (entries) => this.#flush(entries),
1902 };
1903 return this.#moves;
1904 }
1906 #switches?: SwitchHost;
1907 get #switchHost(): SwitchHost {
1908 this.#switches ??= {
1909 agent: (name, entries) => this.#agent(name, entries),
1910 flush: (entries) => this.#flush(entries),
1911 spaces: this.#spaces,
1912 agentView: (agent) => this.#agentView(agent),
1913 graph: this.#graph,
1914 version: () => this.version,
1915 apply: (entry) => this.#apply(entry),
1916 draft: (agent) => this.#draft(agent),
1917 setOf: (space) => this.#setOf(space),
1918 changesSince: (agent, before) => this.#changesSince(agent, before),
1919 };
1920 return this.#switches;
1921 }
1923 #draftStates?: DraftStateHost;
1924 get #draftStateHost(): DraftStateHost {
1925 this.#draftStates ??= {
1926 needInit: () => this.#needInit(),
1927 spaceNamed: (name) => this.#spaceNamed(name),
1928 shared: () => this.#shared,
1929 graph: this.#graph,
1930 agents: this.#agents,
1931 draft: (agent) => this.#draft(agent),
1932 checkClash: (changes) => this.#checkClash(changes),
1933 landCollisions: (space, changes, pick) => this.#landCollisions(space, changes, pick),
1934 };
1935 return this.#draftStates;
1936 }
1938 #checkClashes?: CheckClashHost;
1939 get #checkClashHost(): CheckClashHost {
1940 this.#checkClashes ??= {
1941 shared: () => this.#shared,
1942 view: (set) => this.#view(set),
1943 sharedView: () => this.#sharedView(),
1944 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
1945 };
1946 return this.#checkClashes;
1947 }
1949 #changesSinces?: ChangesSinceHost;
1950 get #changesSinceHost(): ChangesSinceHost {
1951 this.#changesSinces ??= {
1952 agentView: (agent) => this.#agentView(agent),
1953 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
1954 openPairs: (agent) => this.#openPairs(agent),
1955 collision: (agent, pair) => this.#collision(agent, pair),
1956 duplicates: (agent) => this.#duplicates(agent),
1957 markedCollisions: (agent) => this.#markedCollisions(agent),
1958 };
1959 return this.#changesSinces;
1960 }
1962 #inits?: InitHost;
1963 get #initHost(): InitHost {
1964 this.#inits ??= {
1965 initialized: () => this.initialized,
1966 whole: this.#whole,
1967 wholeOut: (files, blobs, view, config) => this.#wholeOut(files, blobs, view, config),
1968 checkBlobs: (blobs, files) => this.#checkBlobs(blobs, files),
1969 commit: (entries) => this.#commit(entries),
1970 };
1971 return this.#inits;
1972 }
1974 #amends?: AmendHost;
1975 get #amendHost(): AmendHost {
1976 this.#amends ??= {
1977 agent: (name, entries) => this.#agent(name, entries),
1978 spaceOf: (agent) => this.#spaceOf(agent),
1979 apply: (entry) => this.#apply(entry),
1980 flush: (entries) => this.#flush(entries),
1981 };
1982 return this.#amends;
1983 }
1985 #labelHosts?: LabelHost;
1986 get #labelHost(): LabelHost {
1987 this.#labelHosts ??= {
1988 agent: (name, entries) => this.#agent(name, entries),
1989 version: () => this.version,
1990 labels: this.#labels,
1991 apply: (entry) => this.#apply(entry),
1992 flush: (entries) => this.#flush(entries),
1993 };
1994 return this.#labelHosts;
1995 }
1997 #publishOfs?: PublishOfHost;
1998 get #publishOfHost(): PublishOfHost {
1999 this.#publishOfs ??= {
2000 shared: () => this.#shared,
2001 spaces: this.#spaces,
2002 };
2003 return this.#publishOfs;
2004 }
2006 #versionMetas?: VersionMetaHost;
2007 get #versionMetaHost(): VersionMetaHost {
2008 this.#versionMetas ??= {
2009 needInit: () => this.#needInit(),
2010 spaceNamed: (name) => this.#spaceNamed(name),
2011 };
2012 return this.#versionMetas;
2013 }
2015 #refuses?: RefuseHost;
2016 get #refuseHost(): RefuseHost {
2017 this.#refuses ??= {
2018 apply: (entry) => this.#apply(entry),
2019 refusals: this.#refusals,
2020 };
2021 return this.#refuses;
2022 }
2024 #overlapsHost?: OverlapHost;
2025 get #overlapHost(): OverlapHost {
2026 this.#overlapsHost ??= {
2027 graph: this.#graph,
2028 agents: this.#agents,
2029 agentView: (agent) => this.#agentView(agent),
2030 draft: (agent) => this.#draft(agent),
2031 liveNote: (agent) => this.#liveNote(agent),
2032 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
2033 };
2034 return this.#overlapsHost;
2035 }
2037 #recordFiles?: RecordFileHost;
2038 get #recordFileHost(): RecordFileHost {
2039 this.#recordFiles ??= {
2040 addDraft: (agent, view, input, time, meta, entries) => this.#addDraft(agent, view, input, time, meta, entries),
2041 };
2042 return this.#recordFiles;
2043 }
2045 #addDrafts?: AddDraftHost;
2046 get #addDraftHost(): AddDraftHost {
2047 this.#addDrafts ??= {
2048 graph: this.#graph,
2049 openPairs: (agent) => this.#openPairs(agent),
2050 markersSettled: (agent, view, atom) => this.#markersSettled(agent, view, atom),
2051 apply: (entry) => this.#apply(entry),
2052 };
2053 return this.#addDrafts;
2054 }
2056 #ingests?: IngestHost;
2057 get #ingestHost(): IngestHost {
2058 this.#ingests ??= {
2059 agents: this.#agents,
2060 spaces: this.#spaces,
2061 needInit: () => this.#needInit(),
2062 version: () => this.version,
2063 checkBlobs: (blobs, files) => this.#checkBlobs(blobs, files),
2064 apply: (entry) => this.#apply(entry),
2065 flush: (entries) => this.#flush(entries),
2066 wholeOut: (files, blobs, view, config) => this.#wholeOut(files, blobs, view, config),
2067 agentView: (agent) => this.#agentView(agent),
2068 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
2069 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
2070 publish: (agent, message, time, entries, asIs, direct) =>
2071 this.#publish(agent, message, time, entries, asIs, direct),
2072 land: (agent, message, time, entries, pick) => this.#land(agent, message, time, entries, pick),
2073 };
2074 return this.#ingests;
2075 }
2077 #plucks?: PluckHost;
2078 get #pluckHost(): PluckHost {
2079 this.#plucks ??= {
2080 graph: this.#graph,
2081 spaces: this.#spaces,
2082 agent: (name, entries) => this.#agent(name, entries),
2083 shared: () => this.#shared,
2084 notQueuedYet: (what) => this.#notQueuedYet(what),
2085 strandedFiles: (draft, set) => this.#strandedFiles(draft, set),
2086 checkClash: (changes) => this.#checkClash(changes),
2087 land: (agent, message, time, entries, pick) => this.#land(agent, message, time, entries, pick),
2088 flush: (entries) => this.#flush(entries),
2089 };
2090 return this.#plucks;
2091 }
2093 #drops?: DropHost;
2094 get #dropHost(): DropHost {
2095 this.#drops ??= {
2096 graph: this.#graph,
2097 agents: this.#agents,
2098 spaces: this.#spaces,
2099 agent: (name, entries) => this.#agent(name, entries),
2100 shared: () => this.#shared,
2101 flush: (entries) => this.#flush(entries),
2102 apply: (entry) => this.#apply(entry),
2103 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
2104 addressedNews: (agent, version, entries) => this.#addressedNews(agent, version, entries),
2105 };
2106 return this.#drops;
2107 }
2109 // Changes (#44), in change-records.ts behind ChangeHost ---------------------------------------------
2111 #changeRecords?: ChangeHost;
2112 get #changeHost(): ChangeHost {
2113 this.#changeRecords ??= {
2114 changes: this.#changes,
2115 agents: this.#agents,
2116 spaces: this.#spaces,
2117 notes: this.#notes,
2118 versionChange: this.#versionChange,
2119 paths: this.#paths,
2120 graph: this.#graph,
2121 stored: () => this.#stored,
2122 shared: () => this.#shared,
2123 queue: () => this.#queue,
2124 active: (agent, time) => this.#active(agent, time),
2125 currentChange: (agent, time) => this.#currentChange(agent, time),
2126 liveNote: (agent) => this.#liveNote(agent),
2127 noteAnswer: (n) => this.#noteAnswer(n),
2128 reviewersOf: (files, id) => this.#reviewersOf(files, id),
2129 };
2130 return this.#changeRecords;
2131 }
2133 // What the project looks like now, in project-status.ts behind SnapshotHost -------------------------
2135 #snapshotHost?: SnapshotHost;
2136 get #snapshot(): SnapshotHost {
2137 this.#snapshotHost ??= {
2138 agents: this.#agents,
2139 spaces: this.#spaces,
2140 queue: () => this.#queue,
2141 refusals: this.#refusals,
2142 labels: this.#labels,
2143 tells: this.#tells,
2144 needInit: () => this.#needInit(),
2145 shared: () => this.#shared,
2146 draft: (agent) => this.#draft(agent),
2147 draftFiles: (agent) => this.#draftFiles(agent),
2148 liveNote: (agent) => this.#liveNote(agent),
2149 openCollisions: (agent) => this.#openCollisions(agent),
2150 editsOf: (agent) => this.#editsOf(agent),
2151 setOf: (space) => this.#setOf(space),
2152 spaceNamed: (name) => this.#spaceNamed(name),
2153 checkVersion: (space, version) => this.#checkVersion(space, version),
2154 viewAt: (space, version) => this.#viewAt(space, version),
2155 agentView: (agent) => this.#agentView(agent),
2156 version: () => this.version,
2157 projectFile: () => (this.initialized ? projectFileIn(this.#sharedView()) : undefined),
2158 };
2159 return this.#snapshotHost;
2160 }
2162 /** The paths in an agent's view now (project-status.ts). */
2163 agentPaths(...args: Tail<Parameters<typeof snapshotAgentPaths>>): ReturnType<typeof snapshotAgentPaths> {
2164 return snapshotAgentPaths(this.#snapshot, ...args);
2165 }
2167 /** The paths in shared, or a named draft, at a version (project-status.ts). */
2168 pathsAt(...args: Tail<Parameters<typeof snapshotPathsAt>>): ReturnType<typeof snapshotPathsAt> {
2169 return snapshotPathsAt(this.#snapshot, ...args);
2170 }
2172 /** The paths in an agent's view now, for a reader (project-status.ts). */
2173 pathsOf(...args: Tail<Parameters<typeof snapshotPathsOf>>): ReturnType<typeof snapshotPathsOf> {
2174 return snapshotPathsOf(this.#snapshot, ...args);
2175 }
2177 /** Every label, with the versions it marks, newest first (project-status.ts). */
2178 labels(): ReturnType<typeof snapshotLabels> {
2179 return snapshotLabels(this.#snapshot);
2180 }
2182 /** Agents, drafts, refusals and waiting announcements (project-status.ts). */
2183 status(): ReturnType<typeof snapshotStatus> {
2184 return snapshotStatus(this.#snapshot);
2185 }
2187 /** A space's contents at one of its versions. */
2188 #at(space: Space, version: number): ReadonlySet<AtomId> {
2189 return this.#membership.at(space, version);
2190 }
2192 /** A space's contents now. */
2193 #setOf(space: Space): ReadonlySet<AtomId> {
2194 return this.#at(space, last(space));
2195 }
2197 #draft(agent: AgentState): AtomId[] {
2198 const set = this.#setOf(this.#spaceOf(agent));
2199 return agent.mine.filter((id) => !set.has(id));
2200 }
2202 /**
2203 * The draft without the agent's publishes waiting in the queue (#39): what
2204 * moves, restore and sync's merge may drop and make again. A queued item's
2205 * atoms are no longer the draft's to remake; dropping them let the queue
2206 * land a tie that depends on discarded atoms (abso issue 135, item 4).
2207 * Undoing a queued publish is abso unqueue.
2208 */
2209 #unqueuedDraft(agent: AgentState): AtomId[] {
2210 const draft = this.#draft(agent);
2211 const held = this.#queuedAtoms();
2212 return held.size === 0 ? draft : draft.filter((id) => !held.has(id));
2213 }
2215 #agentSet(agent: AgentState): Set<AtomId> {
2216 return new Set([...this.#at(this.#spaceOf(agent), agent.base), ...agent.mine]);
2217 }
2219 #agentView(agent: AgentState): View {
2220 // Keyed by what the set is made of, not by sorting every atom in it (#46): that cost more than the work.
2221 return this.#viewKeyed(`a ${agent.space}@${agent.base}+${agent.mine.join(",")}`, () => this.#agentSet(agent));
2222 }
2224 /** A space at a version: published versions never change, so the key is just their names (#46). */
2225 #viewAt(space: Space, version: number): View {
2226 return this.#viewKeyed(`v ${space.name}@${version}`, () => this.#at(space, version));
2227 }
2229 #sharedView(): View {
2230 return this.#viewAt(this.#shared, last(this.#shared));
2231 }
2233 /** A view of a set, cached by the set's exact contents (views.ts). */
2234 #view(set: ReadonlySet<AtomId>): View {
2235 return this.#views.view(this.#closed(set));
2236 }
2238 /** A view cached under `key` (views.ts). */
2239 #viewKeyed(key: string, set: () => ReadonlySet<AtomId>): View {
2240 return this.#views.keyed(key, () => this.#closed(set()));
2241 }
2243 /**
2244 * A discarded atom that a later publish still depends on stays in the view
2245 * (abso issue 80). A closed set is unchanged.
2246 */
2247 #closed(set: Iterable<AtomId>): Set<AtomId> {
2248 return this.#graph.closureOf(set);
2249 }
2251 /** A new publish or land must not depend on an atom outside the set (abso issue 80). */
2252 #requireClosed(tie: { deps: readonly AtomId[] }, union: ReadonlySet<AtomId>): void {
2253 const missing = tie.deps.filter((id) => !union.has(id));
2254 if (missing.length > 0)
2255 throw new ProjectError(
2256 "conflict",
2257 `this change depends on ${missing.join(", ")}, which is not in the set being published`,
2258 );
2259 }
2261 /** The space's atoms published after the agent's base, by others. */
2262 #newerFor(agent: AgentState): Set<AtomId> {
2263 const space = this.#spaceOf(agent);
2264 const base = this.#at(space, agent.base);
2265 const mine = new Set(agent.mine);
2266 return new Set([...this.#setOf(space)].filter((id) => !base.has(id) && !mine.has(id)));
2267 }
2269 /** The files whose text in the agent's view differs from `before`, and its open collisions. */
2270 #changesSince(...args: Tail<Parameters<typeof hostedChangesSince>>): ReturnType<typeof hostedChangesSince> {
2271 return hostedChangesSince(this.#changesSinceHost, ...args);
2272 }
2274 /** Who published an atom, looking in the given space first and then in shared. */
2275 #origin(atom: AtomId, spaceName: string): Origin {
2276 return originOf(this.#collisionHost, atom, spaceName);
2277 }
2279 // Drafting ----------------------------------------------------------------------
2281 /** Check a {path: sha256} map: hex hashes, no path also given as text, and bytes already uploaded. */
2282 #checkBlobs(blobs: unknown, files: object): Record<string, string> {
2283 if (typeof blobs !== "object" || blobs === null || Array.isArray(blobs))
2284 throw new ProjectError("bad-request", "blobs must be {path: sha256}");
2285 for (const [path, sha] of Object.entries(blobs as Record<string, unknown>)) {
2286 checkPath(path);
2287 if (typeof sha !== "string" || !/^[0-9a-f]{64}$/.test(sha))
2288 throw new ProjectError("bad-request", `${path}: a blob is the SHA-256 of the bytes, in lowercase hex`);
2289 if (Object.hasOwn(files, path)) throw new ProjectError("bad-request", `${path} is given as both text and a blob`);
2290 if (!this.#hasBlob(sha))
2291 throw new ProjectError("bad-request", `${path}: upload blob ${sha} first (PUT /p/:project/blobs/${sha})`);
2292 }
2293 return blobs as Record<string, string>;
2294 }
2296 /**
2297 * Make one file in the agent's view what the folder has, as one draft
2298 * change: `text` (null: the file is gone; "": an empty file; undefined:
2299 * leave its lines alone) and `mode` (only the fields given). Returns
2300 * whether anything changed.
2301 */
2302 #recordFile(...args: Tail<Parameters<typeof hostedRecordFile>>): ReturnType<typeof hostedRecordFile> {
2303 return hostedRecordFile(this.#recordFileHost, ...args);
2304 }
2306 /**
2307 * Moves (#28). Within one agent's unpublished draft, a line that leaves one
2308 * place and the same text that arrives somewhere else is the same line, in
2309 * either order (deleted then written, or written then deleted). Before a
2310 * publish, the draft's changes to the files involved are dropped (a discard
2311 * entry) and made again: one move per matched block, which keeps the
2312 * lines' ids, then a change per file to the draft's final text. The files
2313 * end up exactly as the draft had them. A matched block needs a line with
2314 * real content: blank lines and lone brackets only travel next to one.
2315 */
2316 #expressMoves(agent: AgentState, time: number, entries: Entry[]): void {
2317 hostedExpressMoves(this.#expressMovesHost, agent, time, entries);
2318 }
2320 /**
2321 * Build a draft change against the agent's view. If it touches lines on
2322 * either side of a collision the agent has already seen, it settles that
2323 * collision (the engine's `resolves`).
2324 */
2325 #addDraft(...args: Tail<Parameters<typeof hostedAddDraft>>): ReturnType<typeof hostedAddDraft> {
2326 return hostedAddDraft(this.#addDraftHost, ...args);
2327 }
2329 // Collisions and news -------------------------------------------------------------
2331 #pairs(draft: readonly AtomId[], against: ReadonlySet<AtomId>, settled: ReadonlySet<AtomId>): Pair[] {
2332 return pairsIn(this.#graph, draft, against, settled);
2333 }
2335 /**
2336 * Collisions the agent has synced into and not settled: its draft against
2337 * its space at its base. In a named draft, also the draft's own changes
2338 * against shared work the draft was moved onto.
2339 */
2340 #openPairs(agent: AgentState): Pair[] {
2341 return hostedOpenPairs(this.#collisionHost, agent);
2342 }
2344 /** After the agent's own change: news when its draft now collides with work published after its base. */
2345 #newsAboutOwnDraft(agent: AgentState, entries: Entry[]): void {
2346 hostedNewsAboutOwnDraft(this.#newsHost, agent, entries);
2347 }
2349 /** After a publish or a landing: news for every other agent in that space whose draft collides with what just arrived. */
2350 #newsForOthers(publisher: AgentState, space: Space, version: number, entries: Entry[]): void {
2351 hostedNewsForOthers(this.#newsHost, publisher, space, version, entries);
2352 }
2354 #queueNews(agent: AgentState, items: readonly { key: string; text: string }[], entries: Entry[]): void {
2355 const fresh = items.filter((p) => !agent.told.has(p.key));
2356 if (fresh.length === 0) return;
2357 const text = [...new Set(fresh.map((p) => p.text))];
2358 const entry: Entry = { type: "news", agent: agent.name, pairs: [...new Set(fresh.map((p) => p.key))], text };
2359 entries.push(entry);
2360 this.#apply(entry);
2361 }
2363 #takeNews(agent: AgentState, entries: Entry[]): string[] {
2364 if (agent.news.length === 0) return [];
2365 const news = [...agent.news];
2366 const entry: Entry = { type: "heard", agent: agent.name };
2367 entries.push(entry);
2368 this.#apply(entry);
2369 return news;
2370 }
2372 /** Describe a pair for the agent: its side in its own view, theirs in its space now. */
2373 #collision(agent: AgentState, pair: Pair): Collision {
2374 return this.#describe(
2375 pair,
2376 this.#agentView(agent),
2377 this.#viewAt(this.#spaceOf(agent), last(this.#spaceOf(agent))),
2378 agent.space,
2379 );
2380 }
2382 #describe(pair: Pair, yoursView: View, theirsView: View, spaceName: string): Collision {
2383 return describePair(
2384 this.#graph,
2385 (atom, space) => this.#origin(atom, space),
2386 pair,
2387 yoursView,
2388 theirsView,
2389 spaceName,
2390 );
2391 }
2393 #touchedFiles(ids: Iterable<AtomId>, views: readonly View[]): Set<string> {
2394 return touchedFiles(this.#graph, ids, views);
2395 }
2397 // The changed-definition rule (#11) -------------------------------------------
2399 /** The rule for an agent's draft in its space. */
2400 #definitionCollisions(agent: AgentState, newer: ReadonlySet<AtomId>): DefinitionCollision[] {
2401 const draft = new Set(this.#draft(agent));
2402 if (draft.size === 0 || newer.size === 0) return [];
2403 const space = this.#spaceOf(agent);
2404 const mine = new Set(agent.mine);
2405 const base = this.#view(new Set([...this.#at(space, agent.base)].filter((id) => !mine.has(id))));
2406 return this.#definitionRule.collisions(
2407 draft,
2408 this.#agentView(agent),
2409 base,
2410 this.#viewAt(space, last(space)),
2411 newer,
2412 space.name,
2413 );
2414 }
2415}
2417export { EngineError };