- 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=34&format=json
2,418 linesFirst import 100% · pinch 1% · engine 1%Last change pinch in version 31, 3 versions changed it
You're reading version 34. The newest is 318, and 55 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; Git Lessons' review, 2026-10-07):
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, Builder 6 and Writer
1008 * 1): one line per file and agent, once per draft. It tells; it never stops
1009 * the edit.
1010 */
1011 #overlapNews(...args: Tail<Parameters<typeof hostedOverlapNews>>): ReturnType<typeof hostedOverlapNews> {
1012 return hostedOverlapNews(this.#overlapHost, ...args);
1013 }
1015 /** Hand over the news waiting for an agent (collisions, definitions, moves, announcements), once. */
1016 news(agentName: string): { news: string[]; items: { text: string; at: number | null }[] } {
1017 const entries: Entry[] = [];
1018 const agent = this.#agent(agentName, entries);
1019 const items = agent.news.map((text, i) => ({ text, at: agent.newsAt[i] ?? null }));
1020 const news = this.#takeNews(agent, entries);
1021 this.#flush(entries);
1022 return { news, items };
1023 }
1025 /** Refused publishes and lands, newest first (`limit` defaults to 50), with counts over all of them. */
1026 refusals(...args: Tail<Parameters<typeof hostedRefusals>>): ReturnType<typeof hostedRefusals> {
1027 return hostedRefusals(this.#refuseHost, ...args);
1028 }
1030 /**
1031 * Move the agent's base to its space's newest version. Returns every file
1032 * whose text in its view changes (null when it's gone), and the collisions
1033 * it now has to settle. A first sync returns every file (that's how a
1034 * folder joins).
1035 */
1036 sync(...args: Tail<Parameters<typeof hostedSync>>): ReturnType<typeof hostedSync> {
1037 return hostedSync(this.#syncHost, ...args);
1038 }
1040 /**
1041 * Move the agent to a named draft, or back to shared with null. Its
1042 * unpublished changes stay parked on the server in the space it leaves,
1043 * and what it parked in the space it moves to comes back. Nothing is lost
1044 * and nothing has to be published or stashed first. A new named draft
1045 * starts on shared's newest version; with `carry`, the agent's current
1046 * unpublished changes move into it instead of being parked. Answers like a
1047 * sync: the files that change in its folder.
1048 */
1049 switchTo(...args: Tail<Parameters<typeof hostedSwitchTo>>): ReturnType<typeof hostedSwitchTo> {
1050 return hostedSwitchTo(this.#switchHost, ...args);
1051 }
1053 /**
1054 * Move the agent's named draft onto shared's newest version. The draft's
1055 * agents see it when they next sync; anything it collides with is theirs
1056 * to settle before the draft lands.
1057 */
1058 syncDraft(agentName: string, time: number): DraftSyncAnswer {
1059 const entries: Entry[] = [];
1060 const agent = this.#agent(agentName, entries);
1061 const space = this.#namedSpaceOf(agent);
1062 const ownOnly = [...space.own].filter((id) => !this.#shared.own.has(id) && !this.#shared.droppedIn.has(id));
1063 const stranded = this.#strandedFiles(ownOnly, this.#shared.own);
1064 if (stranded.length > 0) {
1065 throw new ProjectError(
1066 "conflict",
1067 `draft ${space.name} has changes to ${stranded.join(", ")} that build on lines a drop took out of shared`,
1068 );
1069 }
1070 if (sharedBaseOf(space) !== this.version) {
1071 entries.push({
1072 type: "space-sync",
1073 space: space.name,
1074 agent: agent.name,
1075 time,
1076 version: last(space) + 1,
1077 sharedBase: this.version,
1078 });
1079 this.#apply(entries[entries.length - 1]!);
1080 }
1081 this.#flush(entries);
1082 return { draft: space.name, version: last(space), sharedBase: sharedBaseOf(space) };
1083 }
1085 /**
1086 * Land the agent's named draft in shared as one unit: every change
1087 * published into it that shared doesn't have yet. Refused, like a publish,
1088 * when those changes collide with work that landed in shared after the
1089 * draft's base; sync the draft, settle, and land again.
1090 */
1091 land(...args: Tail<Parameters<typeof hostedLand>>): ReturnType<typeof hostedLand> {
1092 return hostedLand(this.#landHost, ...args);
1093 }
1095 /**
1096 * What landing `changes` of a named draft would collide with in shared now (#41, the Drafts page reads it
1097 * too): the same pairs and definitions land refuses on.
1098 */
1099 #landCollisions(
1100 space: Space,
1101 changes: AtomId[],
1102 pick: boolean,
1103 ): { collisions: Collision[]; newer: Set<AtomId>; union: Set<AtomId> } {
1104 return hostedLandCollisions(this.#landHost, space, changes, pick);
1105 }
1107 /**
1108 * A named draft's state in one read (#41, the Drafts page, D3 and D16): the shared version it builds on and
1109 * how far behind shared that is, its versions, when its first edit was, who works in it, and what landing it
1110 * now would collide with (the same check land makes, so nothing is written).
1111 */
1112 draftState(...args: Tail<Parameters<typeof hostedDraftState>>): ReturnType<typeof hostedDraftState> {
1113 return hostedDraftState(this.#draftStateHost, ...args);
1114 }
1116 #land(
1117 agent: AgentState,
1118 message: string,
1119 time: number,
1120 entries: Entry[],
1121 pick?: { space: Space; changes: AtomId[] },
1122 ): LandAnswer {
1123 return hostedLandDraft(this.#landHost, agent, message, time, entries, pick);
1124 }
1126 /**
1127 * Take part of a named draft into shared (#27): the changes of some of its
1128 * versions, as one new version of shared, checked for collisions like a
1129 * land. When they build on other versions of the draft, those are listed
1130 * and it is refused, unless `withDependencies` takes them too. The draft
1131 * stays as it is; landing it later brings in only what's left.
1132 */
1133 pluck(
1134 agentName: string,
1135 draftName: string,
1136 versions: readonly number[],
1137 message: string,
1138 time: number,
1139 options: { withDependencies?: boolean } = {},
1140 ): PluckAnswer {
1141 return hostedPluck(this.#pluckHost, agentName, draftName, versions, message, time, options);
1142 }
1144 /**
1145 * Take in commits a person pushed with plain git (demo moment 5, #5, #8).
1146 * `base` is the shared version their first commit builds on (the
1147 * `avcs-version` of the commit they cloned). Each commit gives its whole
1148 * tree as text; a file of the view missing from it is deleted. The commits
1149 * go into a named draft `git-<sha>` on that version, one publish each, and
1150 * the draft lands in shared at once if nothing collides. The push already
1151 * happened, so a collision isn't refused: the draft waits, with its
1152 * collisions listed, for someone to switch to it, settle and land it.
1153 */
1154 ingest(...args: Tail<Parameters<typeof hostedIngest>>): ReturnType<typeof hostedIngest> {
1155 return hostedIngest(this.#ingestHost, ...args);
1156 }
1158 // Reading history, and discarding -------------------------------------------
1160 #checkVersion(space: Space, version: number): void {
1161 hostedCheckVersion(space, version);
1162 }
1164 /**
1165 * Discard the agent's unpublished changes to some files (all of them with
1166 * `files` null), like git restore. Changes that touch only those files and
1167 * that no kept change builds on leave the draft; anything left over is
1168 * undone by a new change that puts the files back. Answers with each
1169 * file's text now, for the folder.
1170 */
1171 restore(...args: Tail<Parameters<typeof hostedRestore>>): ReturnType<typeof hostedRestore> {
1172 return hostedRestore(this.#restoreHost, ...args);
1173 }
1175 /** The space options name: an agent's current space with `agent`, else the named draft, else shared. */
1176 #spaceFor(options: { draft?: string | null; agent?: string }): Space {
1177 if (options.agent !== undefined) {
1178 const agent = this.#agents.get(options.agent);
1179 if (!agent) throw new ProjectError("bad-request", `there is no agent ${JSON.stringify(options.agent)}`);
1180 return this.#spaceOf(agent);
1181 }
1182 return this.#spaceNamed(options.draft ?? null);
1183 }
1185 #spaceNamed(name: string | null): Space {
1186 const key = name === null ? SHARED : checkDraftName(name);
1187 const space = this.#spaces.get(key);
1188 if (!space) throw new ProjectError("bad-request", `there is no draft ${String(name)}`);
1189 return space;
1190 }
1192 /**
1193 * The stored spelling a read means (#41, F7, the rule #49 set for writes):
1194 * the path itself, else the one file it matches by pathKey; failing that,
1195 * the one file ever in the view it matches, for a file since taken out.
1196 * A path that matches two files is answered exactly.
1197 */
1198 spellingIn(view: View, path: string): string {
1199 if (view.hasFile(path)) return path;
1200 const key = pathKey(path);
1201 const live = view.knownPaths().filter((p) => pathKey(p) === key && view.hasFile(p));
1202 if (live.length > 0) return live.length === 1 ? live[0]! : path;
1203 const known = view.knownPaths();
1204 if (known.includes(path)) return path;
1205 const gone = known.filter((p) => pathKey(p) === key);
1206 return gone.length === 1 ? gone[0]! : path;
1207 }
1209 // Applying entries ------------------------------------------------------------
1211 #apply(entry: Entry): void {
1212 // Entries written before #41 have no time on these kinds; new ones do, so replay can place them (website, Product Lead).
1213 const kept =
1214 this.#loading || !UNTIMED.has(entry.type) || "time" in entry ? entry : ({ ...entry, time: Date.now() } as Entry);
1215 if (!this.#loading) this.#pending.push(kept);
1216 const at = this.#loading ? this.#stored : this.#stored + this.#pending.length - 1;
1217 // Positions by time (#41, the website): the newest time up to each position, as the log holds it.
1218 const keptTime =
1219 kept.type === "draft" ? kept.atom.time : "time" in kept && typeof kept.time === "number" ? kept.time : undefined;
1220 const prior = at > 0 ? this.#timeAt[at - 1]! : 0;
1221 this.#timeAt[at] = keptTime !== undefined && keptTime > prior ? keptTime : prior;
1222 const versionsBefore = this.#spaces.get(SHARED)?.versions.length ?? 0;
1223 try {
1224 this.#applyEntry(entry, at, keptTime);
1225 } finally {
1226 // Positions by version: where each version of shared was made.
1227 const versionsAfter = this.#spaces.get(SHARED)?.versions.length ?? 0;
1228 for (let v = versionsBefore; v < versionsAfter; v++) this.#versionAt[v] = at;
1229 }
1230 }
1232 /**
1233 * The log position for a time or a version of shared (#41, the website):
1234 * for `time`, the position just after the last entry no later than it
1235 * (entries with no time take their predecessor's); for `version`, the
1236 * position just after the entry that made it. `end` is the log's length.
1237 */
1238 position(q: { time?: number; version?: number }): { position: number; end: number } {
1239 const end = this.#timeAt.length;
1240 if (q.version !== undefined) {
1241 if (!Number.isInteger(q.version) || q.version < 0 || q.version >= this.#versionAt.length)
1242 throw new ProjectError("not-found", `there is no version ${String(q.version)}`);
1243 return { position: this.#versionAt[q.version]! + 1, end };
1244 }
1245 if (typeof q.time !== "number" || !Number.isFinite(q.time))
1246 throw new ProjectError("bad-request", "position needs ?time= or ?version=");
1247 // The newest time up to each position never goes down, so halve.
1248 let lo = 0;
1249 let hi = end;
1250 while (lo < hi) {
1251 const mid = (lo + hi) >> 1;
1252 if (this.#timeAt[mid]! <= q.time) lo = mid + 1;
1253 else hi = mid;
1254 }
1255 return { position: lo, end };
1256 }
1258 #applyEntry(entry: Entry, at: number, time: number | undefined): void {
1259 hostedApplyEntry(this.#applyEntryHost, entry, at, time);
1260 }
1262 /** Apply entries and store them. */
1263 #commit(entries: Entry[]): void {
1264 for (const e of entries) this.#apply(e);
1265 this.#flush(entries);
1266 }
1268 /** Store entries that are already applied. */
1269 #flush(_entries: readonly Entry[]): void {
1270 if (this.#pending.length === 0) return;
1271 const out = this.#pending;
1272 this.#pending = [];
1273 this.#store.append(out);
1274 this.#stored += out.length;
1275 }
1277 /**
1278 * The agent an entry names. Before every applied entry was stored, a call
1279 * that joined an agent and then threw could leave the join out of the log
1280 * while later entries named the agent. The lost join had the version the
1281 * project was at then, which is the version now, during replay.
1282 */
1283 #agentOf(name: string): AgentState {
1284 let agent = this.#agents.get(name);
1285 if (!agent) {
1286 this.#apply({ type: "join", agent: name, version: this.#shared.versions.length - 1 });
1287 agent = this.#agents.get(name)!;
1288 }
1289 return agent;
1290 }
1292 // Agents, spaces and views ----------------------------------------------------
1294 get #shared(): Space {
1295 return this.#spaces.get(SHARED)!;
1296 }
1298 #needInit(): void {
1299 if (!this.initialized) throw new ProjectError("not-initialized", "the project has no files yet; init it first");
1300 }
1302 #agent(name: string, entries: Entry[]): AgentState {
1303 this.#needInit();
1304 if (typeof name !== "string" || !NAME.test(name) || name === "init") {
1305 throw new ProjectError(
1306 "bad-agent",
1307 `bad agent name ${JSON.stringify(name)}: letters, digits, '.', '_' and '-', up to 64`,
1308 );
1309 }
1310 let agent = this.#agents.get(name);
1311 if (!agent) {
1312 const join: Entry = { type: "join", agent: name, version: this.version };
1313 entries.push(join);
1314 this.#apply(join);
1315 agent = this.#agents.get(name)!;
1316 }
1317 return agent;
1318 }
1320 #spaceOf(agent: AgentState): Space {
1321 return this.#spaces.get(agent.space)!;
1322 }
1324 #namedSpaceOf(agent: AgentState): Space {
1325 if (agent.space === SHARED) {
1326 throw new ProjectError("bad-request", `${agent.name} works in shared, not a named draft; switch to one first`);
1327 }
1328 return this.#spaceOf(agent);
1329 }
1331 // History reads (#41), in history.ts behind HistoryHost (#46, disk-first 1) ------------------------
1333 #host?: HistoryHost;
1334 /** The project as the history reads see it: the seam the derived tables plug into (abso issues 48, 79). */
1335 get #history(): HistoryHost {
1336 this.#host ??= {
1337 graph: this.#graph,
1338 agents: this.#agents,
1339 spaces: this.#spaces,
1340 needInit: () => this.#needInit(),
1341 spaceNamed: (name) => this.#spaceNamed(name),
1342 checkVersion: (space, version) => this.#checkVersion(space, version),
1343 viewAt: (space, version) => this.#viewAt(space, version),
1344 agentView: (agent) => this.#agentView(agent as AgentState),
1345 spellingIn: (view, asked) => this.spellingIn(view, asked),
1346 pathsOf: (space) => this.#paths.pathsOf(space),
1347 lastChange: (space, version) => this.#paths.lastChange(space, version),
1348 atOrBefore: (list, version) => PathIndex.atOrBefore(list, version),
1349 removedIn: (space, from, to, line) => this.#paths.removedIn(space, from, to, line),
1350 };
1351 return this.#host;
1352 }
1354 /** One folder at a version (history.ts). */
1355 tree(...args: Tail<Parameters<typeof historyTree>>): ReturnType<typeof historyTree> {
1356 return historyTree(this.#history, ...args);
1357 }
1359 /** A path's life at a version (history.ts). */
1360 pathLife(...args: Tail<Parameters<typeof historyPathLife>>): ReturnType<typeof historyPathLife> {
1361 return historyPathLife(this.#history, ...args);
1362 }
1364 /** Where lines went after a version (history.ts). */
1365 follow(...args: Tail<Parameters<typeof historyFollow>>): ReturnType<typeof historyFollow> {
1366 return historyFollow(this.#history, ...args);
1367 }
1369 // The version list (log, ribbon, show), in version-log.ts behind LogHost ----------------------------
1371 #logs?: LogHost;
1372 get #logHost(): LogHost {
1373 this.#logs ??= {
1374 graph: this.#graph,
1375 paths: this.#paths,
1376 labels: this.#labels,
1377 shared: () => this.#shared,
1378 needInit: () => this.#needInit(),
1379 spaceFor: (options) => this.#spaceFor(options),
1380 checkVersion: (space, version) => this.#checkVersion(space, version),
1381 viewAt: (space, version) => this.#viewAt(space, version),
1382 view: (set) => this.#view(set),
1383 at: (space, version) => this.#at(space, version),
1384 spellingIn: (view, path) => this.spellingIn(view, path),
1385 versionChange: (space, version) =>
1386 this.#versionChange.get(`${space.name === SHARED ? "" : space.name} ${version}`),
1387 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
1388 };
1389 return this.#logs;
1390 }
1392 /** The versions of shared (or of a named draft), newest first (version-log.ts). */
1393 log(...args: Tail<Parameters<typeof versionLog>>): ReturnType<typeof versionLog> {
1394 return versionLog(this.#logHost, ...args);
1395 }
1397 /** Shared's versions in one small answer, for the website's version ribbon (version-log.ts). */
1398 ribbon(): ReturnType<typeof versionRibbon> {
1399 return versionRibbon(this.#logHost);
1400 }
1402 /** One version of shared (or of a named draft) and the files it changed (version-log.ts). */
1403 show(...args: Tail<Parameters<typeof versionShow>>): ReturnType<typeof versionShow> {
1404 return versionShow(this.#logHost, ...args);
1405 }
1407 /** A file as it was at a version of shared (or a named draft) (version-log.ts). */
1408 fileAt(...args: Tail<Parameters<typeof versionFileAt>>): ReturnType<typeof versionFileAt> {
1409 return versionFileAt(this.#logHost, ...args);
1410 }
1412 /** Every file that differs between two versions of shared (or a named draft) (version-log.ts). */
1413 compare(...args: Tail<Parameters<typeof versionCompare>>): ReturnType<typeof versionCompare> {
1414 return versionCompare(this.#logHost, ...args);
1415 }
1417 /** A version of shared (or of a named draft) as a View (version-log.ts). */
1418 viewAt(...args: Tail<Parameters<typeof versionViewAt>>): ReturnType<typeof versionViewAt> {
1419 return versionViewAt(this.#logHost, ...args);
1420 }
1422 // Whether agents' drafts would collide, in draft-collisions.ts behind DraftCollisionHost -------------
1424 #draftCollisionHost?: DraftCollisionHost;
1425 get #draftCollisions(): DraftCollisionHost {
1426 this.#draftCollisionHost ??= {
1427 graph: this.#graph,
1428 agents: this.#agents,
1429 needInit: () => this.#needInit(),
1430 shared: () => this.#shared,
1431 sharedView: () => this.#sharedView(),
1432 definitionRule: () => this.#definitionRule,
1433 draft: (agent) => this.#draft(agent as AgentState),
1434 agentView: (agent) => this.#agentView(agent as AgentState),
1435 view: (set) => this.#view(set),
1436 pairs: (draft, against, settled) => this.#pairs(draft, against, settled),
1437 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
1438 };
1439 return this.#draftCollisionHost;
1440 }
1442 /** Whether agents' unpublished changes would collide, by the publish rule (draft-collisions.ts). */
1443 collisions(...args: Tail<Parameters<typeof draftCollisions>>): ReturnType<typeof draftCollisions> {
1444 return draftCollisions(this.#draftCollisions, ...args);
1445 }
1447 // An agent's unpublished changes, in draft-diff.ts behind DraftDiffHost -----------------------------
1449 #draftDiffHost?: DraftDiffHost;
1450 get #draftDiff(): DraftDiffHost {
1451 this.#draftDiffHost ??= {
1452 agents: this.#agents,
1453 needInit: () => this.#needInit(),
1454 draft: (agent) => this.#draft(agent as AgentState),
1455 agentView: (agent) => this.#agentView(agent as AgentState),
1456 view: (set) => this.#view(set),
1457 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
1458 };
1459 return this.#draftDiffHost;
1460 }
1462 /** What the agent's unpublished changes do, file by file (draft-diff.ts). Creates the agent if needed. */
1463 diff(agentName: string): DiffAnswer {
1464 const entries: Entry[] = [];
1465 const answer = diffOfAgent(this.#draftDiff, this.#agent(agentName, entries));
1466 this.#flush(entries);
1467 return answer;
1468 }
1470 /** An agent's draft diff for a reader: never creates the agent, never writes (draft-diff.ts). */
1471 diffOf(...args: Tail<Parameters<typeof draftDiffOf>>): ReturnType<typeof draftDiffOf> {
1472 return draftDiffOf(this.#draftDiff, ...args);
1473 }
1475 // Unpublished deletes-and-writes of the same text become a move (express-moves.ts) -----------------
1477 #movesHost?: ExpressMovesHost;
1478 get #expressMovesHost(): ExpressMovesHost {
1479 this.#movesHost ??= {
1480 graph: this.#graph,
1481 draft: (agent) => this.#unqueuedDraft(agent),
1482 agentView: (agent) => this.#agentView(agent),
1483 view: (set) => this.#view(set),
1484 apply: (entry) => this.#apply(entry),
1485 addDraft: (agent, view, input, time, meta, entries) => this.#addDraft(agent, view, input, time, meta, entries),
1486 recordFile: (agent, view, path, text, time, meta, entries, mode) =>
1487 this.#recordFile(agent, view, path, text, time, meta, entries, mode),
1488 };
1489 return this.#movesHost;
1490 }
1492 // Files kept whole, in whole-files.ts behind WholeHost ----------------------------------------------
1494 #wholes?: WholeHost;
1495 get #wholeHost(): WholeHost {
1496 this.#wholes ??= {
1497 initialized: () => this.initialized,
1498 sharedView: () => this.#sharedView(),
1499 whole: this.#whole,
1500 };
1501 return this.#wholes;
1502 }
1504 // Notes list and start notes, in notes.ts behind NoteHost -------------------------------------------
1506 #news?: NewsHost;
1507 get #newsHost(): NewsHost {
1508 this.#news ??= {
1509 graph: this.#graph,
1510 agents: this.#agents,
1511 draft: (agent) => this.#draft(agent),
1512 newerFor: (agent) => this.#newerFor(agent),
1513 spaceOf: (agent) => this.#spaceOf(agent),
1514 setOf: (space) => this.#setOf(space),
1515 viewAt: (space, version) => this.#viewAt(space, version),
1516 origin: (atom, spaceName) => this.#origin(atom, spaceName),
1517 collision: (agent, pair) => this.#collision(agent, pair),
1518 definitionCollisions: (agent, newer) => this.#definitionCollisions(agent, newer),
1519 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
1520 };
1521 return this.#news;
1522 }
1524 #collisions?: CollisionHost;
1525 get #collisionHost(): CollisionHost {
1526 this.#collisions ??= {
1527 graph: this.#graph,
1528 spaces: this.#spaces,
1529 version: () => this.version,
1530 spaceOf: (agent) => this.#spaceOf(agent),
1531 agentSet: (agent) => this.#agentSet(agent),
1532 draft: (agent) => this.#draft(agent),
1533 agentView: (agent) => this.#agentView(agent),
1534 at: (space, version) => this.#at(space, version),
1535 shared: () => this.#shared,
1536 };
1537 return this.#collisions;
1538 }
1540 #markers?: MarkerHost;
1541 get #markerHost(): MarkerHost {
1542 this.#markers ??= {
1543 graph: this.#graph,
1544 agentView: (agent) => this.#agentView(agent),
1545 draft: (agent) => this.#draft(agent),
1546 draftFiles: (agent) => this.#draftFiles(agent),
1547 };
1548 return this.#markers;
1549 }
1551 #noteWrites?: NoteWriteHost;
1552 get #noteWriteHost(): NoteWriteHost {
1553 this.#noteWrites ??= {
1554 notes: this.#notes,
1555 agents: this.#agents,
1556 changes: this.#changes,
1557 graph: this.#graph,
1558 lastNote: () => this.#lastNote,
1559 agentView: (agent) => this.#agentView(agent),
1560 viewAtVersion: (version) => this.viewAt(version),
1561 sharedView: () => this.#sharedView(),
1562 changeOfLines: (lines) => this.#changeOfLines(lines),
1563 apply: (entry) => this.#apply(entry),
1564 flush: (entries) => this.#flush(entries),
1565 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
1566 noteAnswer: (n) => this.#noteAnswer(n),
1567 };
1568 return this.#noteWrites;
1569 }
1571 #noteHost?: NoteHost;
1572 get #notesHost(): NoteHost {
1573 this.#noteHost ??= {
1574 graph: this.#graph,
1575 agents: this.#agents,
1576 spaces: this.#spaces,
1577 notes: this.#notes,
1578 initialized: () => this.initialized,
1579 shared: () => this.#shared,
1580 sharedView: () => this.#sharedView(),
1581 spellingIn: (view, path) => this.spellingIn(view, path),
1582 viewAt: (space, version) => this.#viewAt(space, version),
1583 agentView: (agent) => this.#agentView(agent),
1584 view: (set) => this.#view(set),
1585 at: (space, version) => this.#at(space, version),
1586 liveNote: (agent) => this.#liveNote(agent),
1587 };
1588 return this.#noteHost;
1589 }
1591 #merges?: MergeHost;
1592 get #mergeHost(): MergeHost {
1593 this.#merges ??= {
1594 graph: this.#graph,
1595 openPairs: (agent) => this.#openPairs(agent),
1596 draft: (agent) => this.#unqueuedDraft(agent),
1597 origin: (atom, spaceName) => this.#origin(atom, spaceName),
1598 view: (set) => this.#view(set),
1599 viewAt: (space, version) => this.#viewAt(space, version),
1600 spaceOf: (agent) => this.#spaceOf(agent),
1601 apply: (entry) => this.#apply(entry),
1602 agentView: (agent) => this.#agentView(agent),
1603 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
1604 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
1605 };
1606 return this.#merges;
1607 }
1609 #edits?: EditHost;
1610 get #editHost(): EditHost {
1611 this.#edits ??= {
1612 agents: this.#agents,
1613 whole: this.#whole,
1614 initialized: () => this.initialized,
1615 agentView: (agent) => this.#agentView(agent),
1616 sharedView: () => this.#sharedView(),
1617 isWhole: (path, length, view, rules) => this.#isWhole(path, length, view, rules),
1618 wholeRules: (config) => this.#wholeRules(config),
1619 record: (agentName, files, time, modes, blobs, meta) => this.record(agentName, files, time, modes, blobs, meta),
1620 agent: (name, entries) => this.#agent(name, entries),
1621 draftFiles: (agent) => this.#draftFiles(agent),
1622 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
1623 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
1624 addDraft: (agent, view, input, time, meta, entries) => this.#addDraft(agent, view, input, time, meta, entries),
1625 overlapNews: (agent, before, entries) => this.#overlapNews(agent, before, entries),
1626 markedNews: (agent, files, entries) => this.#markedNews(agent, files, entries),
1627 newsAboutOwnDraft: (agent, entries) => this.#newsAboutOwnDraft(agent, entries),
1628 takeNews: (agent, entries) => this.#takeNews(agent, entries),
1629 flush: (entries) => this.#flush(entries),
1630 };
1631 return this.#edits;
1632 }
1634 #announces?: AnnounceHost;
1635 get #announceHost(): AnnounceHost {
1636 this.#announces ??= {
1637 agents: this.#agents,
1638 announced: () => this.#announced,
1639 setAnnounced: (n) => {
1640 this.#announced = n;
1641 },
1642 agent: (name, entries) => this.#agent(name, entries),
1643 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
1644 apply: (entry) => this.#apply(entry),
1645 flush: (entries) => this.#flush(entries),
1646 needInit: () => this.#needInit(),
1647 };
1648 return this.#announces;
1649 }
1651 #publishers?: PublishHost;
1652 get #publishHost(): PublishHost {
1653 this.#publishers ??= {
1654 agents: this.#agents,
1655 nextAt: () => this.#nextAt,
1656 checkClash: (changes, ahead) => this.#checkClash(changes, ahead),
1657 queueOn: () => this.#queueOn(),
1658 queuedAtoms: (except) => this.#queuedAtoms(except),
1659 agent: (name, entries) => this.#agent(name, entries),
1660 draft: (agent) => this.#draft(agent),
1661 spaceOf: (agent) => this.#spaceOf(agent),
1662 strandedFiles: (draft, set) => this.#strandedFiles(draft, set),
1663 setOf: (space) => this.#setOf(space),
1664 markedFiles: (agent) => this.#markedFiles(agent),
1665 agentView: (agent) => this.#agentView(agent),
1666 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
1667 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
1668 expressMoves: (agent, time, entries) => this.#expressMoves(agent, time, entries),
1669 pairs: (draft, against, settled) => this.#pairs(draft, against, settled),
1670 collision: (agent, pair) => this.#collision(agent, pair),
1671 definitionCollisions: (agent, newer) => this.#definitionCollisions(agent, newer),
1672 duplicates: (agent) => this.#duplicates(agent),
1673 refuse: (agent, space, via, time, collisions, entries) =>
1674 this.#refuse(agent, space, via, time, collisions, entries),
1675 markerCollisions: (agent) => this.#markerCollisions(agent),
1676 enqueue: (agent, message, time, draft, resolves, entries) =>
1677 this.#enqueue(agent, message, time, draft, resolves, entries),
1678 view: (set) => this.#view(set),
1679 requireClosed: (tie, union) => this.#requireClosed(tie, union),
1680 newerFor: (agent) => this.#newerFor(agent),
1681 currentChange: (agent, time) => this.#currentChange(agent, time),
1682 apply: (entry) => this.#apply(entry),
1683 newsForOthers: (publisher, space, version, entries) => this.#newsForOthers(publisher, space, version, entries),
1684 settledNews: (agent, version, settled, entries) => this.#settledNews(agent, version, settled, entries),
1685 addressedNews: (agent, version, entries) => this.#addressedNews(agent, version, entries),
1686 reviewNews: (agent, version, entries) => this.#reviewNews(agent, version, entries),
1687 flush: (entries) => this.#flush(entries),
1688 };
1689 return this.#publishers;
1690 }
1692 #queues?: QueueHost;
1693 get #queueHost(): QueueHost {
1694 this.#queues ??= {
1695 graph: this.#graph,
1696 checkerReady: () => this.checkerReady,
1697 sharedView: () => this.#sharedView(),
1698 queued: () => this.#queue,
1699 queuedId: () => this.#queuedId,
1700 checkingHas: (id) => this.#checking.has(id),
1701 replaceChecking: (ids) => {
1702 this.#checking = new Set(ids);
1703 },
1704 uncheck: (id) => {
1705 this.#checking.delete(id);
1706 },
1707 needInit: () => this.#needInit(),
1708 shared: () => this.#shared,
1709 setOf: (space) => this.#setOf(space),
1710 view: (set) => this.#view(set),
1711 agentSet: (agent) => this.#agentSet(agent),
1712 agentView: (agent) => this.#agentView(agent),
1713 pairs: (draft, against, settled) => this.#pairs(draft, against, settled),
1714 describe: (pair, yoursView, theirsView, spaceName) => this.#describe(pair, yoursView, theirsView, spaceName),
1715 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
1716 refuse: (agent, space, via, time, collisions, entries) =>
1717 this.#refuse(agent, space, via, time, collisions, entries),
1718 currentChange: (agent, time) => this.#currentChange(agent, time),
1719 nextAt: () => this.#nextAt,
1720 apply: (entry) => this.#apply(entry),
1721 agentOf: (name) => this.#agentOf(name),
1722 requireClosed: (tie, union) => this.#requireClosed(tie, union),
1723 newsForOthers: (publisher, space, version, entries) => this.#newsForOthers(publisher, space, version, entries),
1724 settledNews: (agent, version, settled, entries) => this.#settledNews(agent, version, settled, entries),
1725 addressedNews: (agent, version, entries) => this.#addressedNews(agent, version, entries),
1726 reviewNews: (agent, version, entries) => this.#reviewNews(agent, version, entries),
1727 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
1728 flush: (entries) => this.#flush(entries),
1729 };
1730 return this.#queues;
1731 }
1733 #applyEntries?: ApplyEntryHost;
1734 get #applyEntryHost(): ApplyEntryHost {
1735 this.#applyEntries ??= {
1736 graph: this.#graph,
1737 agents: this.#agents,
1738 atomAt: this.#atomAt,
1739 mods: this.#mods,
1740 notes: this.#notes,
1741 changes: this.#changes,
1742 labels: this.#labels,
1743 refusals: this.#refusals,
1744 tells: this.#tells,
1745 uncheck: (id) => {
1746 this.#checking.delete(id);
1747 },
1748 stamp: (t) => {
1749 if (typeof t === "number" && t > this.#lastTime) this.#lastTime = t;
1750 },
1751 applyMembership: (entry, at) => this.#membership.apply(entry, at),
1752 agentOf: (name) => this.#agentOf(name),
1753 active: (agent, time) => this.#active(agent, time),
1754 joinChange: (agent, entry, at, draft, landed) => this.#joinChange(agent, entry, at, draft, landed),
1755 space: (name) => this.#spaces.get(name)!,
1756 queued: () => this.#queue,
1757 setQueued: (items) => {
1758 this.#queue = items;
1759 },
1760 setQueuedId: (id) => {
1761 this.#queuedId = id;
1762 },
1763 queuedId: () => this.#queuedId,
1764 setLastNote: (id) => {
1765 this.#lastNote = id;
1766 },
1767 lastNote: () => this.#lastNote,
1768 setAnnounced: (n) => {
1769 this.#announced = n;
1770 },
1771 announced: () => this.#announced,
1772 at: (space, version) => this.#at(space, version),
1773 spaceOf: (agent) => this.#spaceOf(agent),
1774 draft: (agent) => this.#draft(agent),
1775 currentChange: (agent, time) => this.#currentChange(agent, time),
1776 changeRecord: (id, agent, time) => this.#changeRecord(id, agent, time),
1777 };
1778 return this.#applyEntries;
1779 }
1781 #landers?: LandHost;
1782 get #landHost(): LandHost {
1783 this.#landers ??= {
1784 agents: this.#agents,
1785 graph: this.#graph,
1786 spaces: this.#spaces,
1787 version: () => this.version,
1788 nextAt: () => this.#nextAt,
1789 notQueuedYet: (what) => this.#notQueuedYet(what),
1790 checkClash: (changes) => this.#checkClash(changes),
1791 agent: (name, entries) => this.#agent(name, entries),
1792 namedSpaceOf: (agent) => this.#namedSpaceOf(agent),
1793 shared: () => this.#shared,
1794 setOf: (space) => this.#setOf(space),
1795 at: (space, version) => this.#at(space, version),
1796 view: (set) => this.#view(set),
1797 sharedView: () => this.#sharedView(),
1798 pairs: (draft, against, settled) => this.#pairs(draft, against, settled),
1799 describe: (pair, yoursView, theirsView, spaceName) => this.#describe(pair, yoursView, theirsView, spaceName),
1800 definitionRule: () => this.#definitionRule,
1801 refuse: (agent, space, via, time, collisions, entries) =>
1802 this.#refuse(agent, space, via, time, collisions, entries),
1803 requireClosed: (tie, union) => this.#requireClosed(tie, union),
1804 apply: (entry) => this.#apply(entry),
1805 newsForOthers: (publisher, space, version, entries) => this.#newsForOthers(publisher, space, version, entries),
1806 addressedNews: (agent, version, entries) => this.#addressedNews(agent, version, entries),
1807 reviewNews: (agent, version, entries) => this.#reviewNews(agent, version, entries),
1808 flush: (entries) => this.#flush(entries),
1809 };
1810 return this.#landers;
1811 }
1813 #records?: RecordHost;
1814 get #recordHost(): RecordHost {
1815 this.#records ??= {
1816 agents: this.#agents,
1817 whole: this.#whole,
1818 initialized: () => this.initialized,
1819 agentView: (agent) => this.#agentView(agent),
1820 sharedView: () => this.#sharedView(),
1821 wholeOut: (files, blobs, view, config) => this.#wholeOut(files, blobs, view, config),
1822 checkBlobs: (blobs, files) => this.#checkBlobs(blobs, files),
1823 agent: (name, entries) => this.#agent(name, entries),
1824 draftFiles: (agent) => this.#draftFiles(agent),
1825 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
1826 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
1827 overlapNews: (agent, before, entries) => this.#overlapNews(agent, before, entries),
1828 markedNews: (agent, files, entries) => this.#markedNews(agent, files, entries),
1829 newsAboutOwnDraft: (agent, entries) => this.#newsAboutOwnDraft(agent, entries),
1830 takeNews: (agent, entries) => this.#takeNews(agent, entries),
1831 flush: (entries) => this.#flush(entries),
1832 };
1833 return this.#records;
1834 }
1836 #restores?: RestoreHost;
1837 get #restoreHost(): RestoreHost {
1838 this.#restores ??= {
1839 graph: this.#graph,
1840 agent: (name, entries) => this.#agent(name, entries),
1841 draft: (agent) => this.#unqueuedDraft(agent),
1842 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
1843 apply: (entry) => this.#apply(entry),
1844 view: (set) => this.#view(set),
1845 agentSet: (agent) => this.#agentSet(agent),
1846 agentView: (agent) => this.#agentView(agent),
1847 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
1848 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
1849 flush: (entries) => this.#flush(entries),
1850 };
1851 return this.#restores;
1852 }
1854 #startings?: StartingHost;
1855 get #startingHost(): StartingHost {
1856 this.#startings ??= {
1857 agents: this.#agents,
1858 changes: this.#changes,
1859 agent: (name, entries) => this.#agent(name, entries),
1860 liveNote: (agent) => this.#liveNote(agent),
1861 apply: (entry) => this.#apply(entry),
1862 overlaps: (agent, patterns) => this.#overlaps(agent, patterns),
1863 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
1864 flush: (entries) => this.#flush(entries),
1865 };
1866 return this.#startings;
1867 }
1869 #syncs?: SyncHost;
1870 get #syncHost(): SyncHost {
1871 this.#syncs ??= {
1872 graph: this.#graph,
1873 labels: this.#labels,
1874 agent: (name, entries) => this.#agent(name, entries),
1875 spaceOf: (agent) => this.#spaceOf(agent),
1876 agentView: (agent) => this.#agentView(agent),
1877 at: (space, version) => this.#at(space, version),
1878 draft: (agent) => this.#draft(agent),
1879 strandedFiles: (draft, set) => this.#strandedFiles(draft, set),
1880 apply: (entry) => this.#apply(entry),
1881 flush: (entries) => this.#flush(entries),
1882 mergeIdentical: (agent, before, oldBase, oldVersion, time, entries) =>
1883 this.#mergeIdentical(agent, before, oldBase, oldVersion, time, entries),
1884 changesSince: (agent, before) => this.#changesSince(agent, before),
1885 };
1886 return this.#syncs;
1887 }
1889 #moves?: MoveHost;
1890 get #moveHost(): MoveHost {
1891 this.#moves ??= {
1892 needInit: () => this.#needInit(),
1893 agents: this.#agents,
1894 agentView: (agent) => this.#agentView(agent),
1895 sharedView: () => this.#sharedView(),
1896 agent: (name, entries) => this.#agent(name, entries),
1897 addDraft: (agent, view, input, time, meta, entries) => this.#addDraft(agent, view, input, time, meta, entries),
1898 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
1899 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
1900 newsAboutOwnDraft: (agent, entries) => this.#newsAboutOwnDraft(agent, entries),
1901 takeNews: (agent, entries) => this.#takeNews(agent, entries),
1902 flush: (entries) => this.#flush(entries),
1903 };
1904 return this.#moves;
1905 }
1907 #switches?: SwitchHost;
1908 get #switchHost(): SwitchHost {
1909 this.#switches ??= {
1910 agent: (name, entries) => this.#agent(name, entries),
1911 flush: (entries) => this.#flush(entries),
1912 spaces: this.#spaces,
1913 agentView: (agent) => this.#agentView(agent),
1914 graph: this.#graph,
1915 version: () => this.version,
1916 apply: (entry) => this.#apply(entry),
1917 draft: (agent) => this.#draft(agent),
1918 setOf: (space) => this.#setOf(space),
1919 changesSince: (agent, before) => this.#changesSince(agent, before),
1920 };
1921 return this.#switches;
1922 }
1924 #draftStates?: DraftStateHost;
1925 get #draftStateHost(): DraftStateHost {
1926 this.#draftStates ??= {
1927 needInit: () => this.#needInit(),
1928 spaceNamed: (name) => this.#spaceNamed(name),
1929 shared: () => this.#shared,
1930 graph: this.#graph,
1931 agents: this.#agents,
1932 draft: (agent) => this.#draft(agent),
1933 checkClash: (changes) => this.#checkClash(changes),
1934 landCollisions: (space, changes, pick) => this.#landCollisions(space, changes, pick),
1935 };
1936 return this.#draftStates;
1937 }
1939 #checkClashes?: CheckClashHost;
1940 get #checkClashHost(): CheckClashHost {
1941 this.#checkClashes ??= {
1942 shared: () => this.#shared,
1943 view: (set) => this.#view(set),
1944 sharedView: () => this.#sharedView(),
1945 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
1946 };
1947 return this.#checkClashes;
1948 }
1950 #changesSinces?: ChangesSinceHost;
1951 get #changesSinceHost(): ChangesSinceHost {
1952 this.#changesSinces ??= {
1953 agentView: (agent) => this.#agentView(agent),
1954 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
1955 openPairs: (agent) => this.#openPairs(agent),
1956 collision: (agent, pair) => this.#collision(agent, pair),
1957 duplicates: (agent) => this.#duplicates(agent),
1958 markedCollisions: (agent) => this.#markedCollisions(agent),
1959 };
1960 return this.#changesSinces;
1961 }
1963 #inits?: InitHost;
1964 get #initHost(): InitHost {
1965 this.#inits ??= {
1966 initialized: () => this.initialized,
1967 whole: this.#whole,
1968 wholeOut: (files, blobs, view, config) => this.#wholeOut(files, blobs, view, config),
1969 checkBlobs: (blobs, files) => this.#checkBlobs(blobs, files),
1970 commit: (entries) => this.#commit(entries),
1971 };
1972 return this.#inits;
1973 }
1975 #amends?: AmendHost;
1976 get #amendHost(): AmendHost {
1977 this.#amends ??= {
1978 agent: (name, entries) => this.#agent(name, entries),
1979 spaceOf: (agent) => this.#spaceOf(agent),
1980 apply: (entry) => this.#apply(entry),
1981 flush: (entries) => this.#flush(entries),
1982 };
1983 return this.#amends;
1984 }
1986 #labelHosts?: LabelHost;
1987 get #labelHost(): LabelHost {
1988 this.#labelHosts ??= {
1989 agent: (name, entries) => this.#agent(name, entries),
1990 version: () => this.version,
1991 labels: this.#labels,
1992 apply: (entry) => this.#apply(entry),
1993 flush: (entries) => this.#flush(entries),
1994 };
1995 return this.#labelHosts;
1996 }
1998 #publishOfs?: PublishOfHost;
1999 get #publishOfHost(): PublishOfHost {
2000 this.#publishOfs ??= {
2001 shared: () => this.#shared,
2002 spaces: this.#spaces,
2003 };
2004 return this.#publishOfs;
2005 }
2007 #versionMetas?: VersionMetaHost;
2008 get #versionMetaHost(): VersionMetaHost {
2009 this.#versionMetas ??= {
2010 needInit: () => this.#needInit(),
2011 spaceNamed: (name) => this.#spaceNamed(name),
2012 };
2013 return this.#versionMetas;
2014 }
2016 #refuses?: RefuseHost;
2017 get #refuseHost(): RefuseHost {
2018 this.#refuses ??= {
2019 apply: (entry) => this.#apply(entry),
2020 refusals: this.#refusals,
2021 };
2022 return this.#refuses;
2023 }
2025 #overlapsHost?: OverlapHost;
2026 get #overlapHost(): OverlapHost {
2027 this.#overlapsHost ??= {
2028 graph: this.#graph,
2029 agents: this.#agents,
2030 agentView: (agent) => this.#agentView(agent),
2031 draft: (agent) => this.#draft(agent),
2032 liveNote: (agent) => this.#liveNote(agent),
2033 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
2034 };
2035 return this.#overlapsHost;
2036 }
2038 #recordFiles?: RecordFileHost;
2039 get #recordFileHost(): RecordFileHost {
2040 this.#recordFiles ??= {
2041 addDraft: (agent, view, input, time, meta, entries) => this.#addDraft(agent, view, input, time, meta, entries),
2042 };
2043 return this.#recordFiles;
2044 }
2046 #addDrafts?: AddDraftHost;
2047 get #addDraftHost(): AddDraftHost {
2048 this.#addDrafts ??= {
2049 graph: this.#graph,
2050 openPairs: (agent) => this.#openPairs(agent),
2051 markersSettled: (agent, view, atom) => this.#markersSettled(agent, view, atom),
2052 apply: (entry) => this.#apply(entry),
2053 };
2054 return this.#addDrafts;
2055 }
2057 #ingests?: IngestHost;
2058 get #ingestHost(): IngestHost {
2059 this.#ingests ??= {
2060 agents: this.#agents,
2061 spaces: this.#spaces,
2062 needInit: () => this.#needInit(),
2063 version: () => this.version,
2064 checkBlobs: (blobs, files) => this.#checkBlobs(blobs, files),
2065 apply: (entry) => this.#apply(entry),
2066 flush: (entries) => this.#flush(entries),
2067 wholeOut: (files, blobs, view, config) => this.#wholeOut(files, blobs, view, config),
2068 agentView: (agent) => this.#agentView(agent),
2069 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
2070 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
2071 publish: (agent, message, time, entries, asIs, direct) =>
2072 this.#publish(agent, message, time, entries, asIs, direct),
2073 land: (agent, message, time, entries, pick) => this.#land(agent, message, time, entries, pick),
2074 };
2075 return this.#ingests;
2076 }
2078 #plucks?: PluckHost;
2079 get #pluckHost(): PluckHost {
2080 this.#plucks ??= {
2081 graph: this.#graph,
2082 spaces: this.#spaces,
2083 agent: (name, entries) => this.#agent(name, entries),
2084 shared: () => this.#shared,
2085 notQueuedYet: (what) => this.#notQueuedYet(what),
2086 strandedFiles: (draft, set) => this.#strandedFiles(draft, set),
2087 checkClash: (changes) => this.#checkClash(changes),
2088 land: (agent, message, time, entries, pick) => this.#land(agent, message, time, entries, pick),
2089 flush: (entries) => this.#flush(entries),
2090 };
2091 return this.#plucks;
2092 }
2094 #drops?: DropHost;
2095 get #dropHost(): DropHost {
2096 this.#drops ??= {
2097 graph: this.#graph,
2098 agents: this.#agents,
2099 spaces: this.#spaces,
2100 agent: (name, entries) => this.#agent(name, entries),
2101 shared: () => this.#shared,
2102 flush: (entries) => this.#flush(entries),
2103 apply: (entry) => this.#apply(entry),
2104 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
2105 addressedNews: (agent, version, entries) => this.#addressedNews(agent, version, entries),
2106 };
2107 return this.#drops;
2108 }
2110 // Changes (#44), in change-records.ts behind ChangeHost ---------------------------------------------
2112 #changeRecords?: ChangeHost;
2113 get #changeHost(): ChangeHost {
2114 this.#changeRecords ??= {
2115 changes: this.#changes,
2116 agents: this.#agents,
2117 spaces: this.#spaces,
2118 notes: this.#notes,
2119 versionChange: this.#versionChange,
2120 paths: this.#paths,
2121 graph: this.#graph,
2122 stored: () => this.#stored,
2123 shared: () => this.#shared,
2124 queue: () => this.#queue,
2125 active: (agent, time) => this.#active(agent, time),
2126 currentChange: (agent, time) => this.#currentChange(agent, time),
2127 liveNote: (agent) => this.#liveNote(agent),
2128 noteAnswer: (n) => this.#noteAnswer(n),
2129 reviewersOf: (files, id) => this.#reviewersOf(files, id),
2130 };
2131 return this.#changeRecords;
2132 }
2134 // What the project looks like now, in project-status.ts behind SnapshotHost -------------------------
2136 #snapshotHost?: SnapshotHost;
2137 get #snapshot(): SnapshotHost {
2138 this.#snapshotHost ??= {
2139 agents: this.#agents,
2140 spaces: this.#spaces,
2141 queue: () => this.#queue,
2142 refusals: this.#refusals,
2143 labels: this.#labels,
2144 tells: this.#tells,
2145 needInit: () => this.#needInit(),
2146 shared: () => this.#shared,
2147 draft: (agent) => this.#draft(agent),
2148 draftFiles: (agent) => this.#draftFiles(agent),
2149 liveNote: (agent) => this.#liveNote(agent),
2150 openCollisions: (agent) => this.#openCollisions(agent),
2151 editsOf: (agent) => this.#editsOf(agent),
2152 setOf: (space) => this.#setOf(space),
2153 spaceNamed: (name) => this.#spaceNamed(name),
2154 checkVersion: (space, version) => this.#checkVersion(space, version),
2155 viewAt: (space, version) => this.#viewAt(space, version),
2156 agentView: (agent) => this.#agentView(agent),
2157 version: () => this.version,
2158 projectFile: () => (this.initialized ? projectFileIn(this.#sharedView()) : undefined),
2159 };
2160 return this.#snapshotHost;
2161 }
2163 /** The paths in an agent's view now (project-status.ts). */
2164 agentPaths(...args: Tail<Parameters<typeof snapshotAgentPaths>>): ReturnType<typeof snapshotAgentPaths> {
2165 return snapshotAgentPaths(this.#snapshot, ...args);
2166 }
2168 /** The paths in shared, or a named draft, at a version (project-status.ts). */
2169 pathsAt(...args: Tail<Parameters<typeof snapshotPathsAt>>): ReturnType<typeof snapshotPathsAt> {
2170 return snapshotPathsAt(this.#snapshot, ...args);
2171 }
2173 /** The paths in an agent's view now, for a reader (project-status.ts). */
2174 pathsOf(...args: Tail<Parameters<typeof snapshotPathsOf>>): ReturnType<typeof snapshotPathsOf> {
2175 return snapshotPathsOf(this.#snapshot, ...args);
2176 }
2178 /** Every label, with the versions it marks, newest first (project-status.ts). */
2179 labels(): ReturnType<typeof snapshotLabels> {
2180 return snapshotLabels(this.#snapshot);
2181 }
2183 /** Agents, drafts, refusals and waiting announcements (project-status.ts). */
2184 status(): ReturnType<typeof snapshotStatus> {
2185 return snapshotStatus(this.#snapshot);
2186 }
2188 /** A space's contents at one of its versions. */
2189 #at(space: Space, version: number): ReadonlySet<AtomId> {
2190 return this.#membership.at(space, version);
2191 }
2193 /** A space's contents now. */
2194 #setOf(space: Space): ReadonlySet<AtomId> {
2195 return this.#at(space, last(space));
2196 }
2198 #draft(agent: AgentState): AtomId[] {
2199 const set = this.#setOf(this.#spaceOf(agent));
2200 return agent.mine.filter((id) => !set.has(id));
2201 }
2203 /**
2204 * The draft without the agent's publishes waiting in the queue (#39): what
2205 * moves, restore and sync's merge may drop and make again. A queued item's
2206 * atoms are no longer the draft's to remake; dropping them let the queue
2207 * land a tie that depends on discarded atoms (abso issue 135, item 4).
2208 * Undoing a queued publish is abso unqueue.
2209 */
2210 #unqueuedDraft(agent: AgentState): AtomId[] {
2211 const draft = this.#draft(agent);
2212 const held = this.#queuedAtoms();
2213 return held.size === 0 ? draft : draft.filter((id) => !held.has(id));
2214 }
2216 #agentSet(agent: AgentState): Set<AtomId> {
2217 return new Set([...this.#at(this.#spaceOf(agent), agent.base), ...agent.mine]);
2218 }
2220 #agentView(agent: AgentState): View {
2221 // Keyed by what the set is made of, not by sorting every atom in it (#46): that cost more than the work.
2222 return this.#viewKeyed(`a ${agent.space}@${agent.base}+${agent.mine.join(",")}`, () => this.#agentSet(agent));
2223 }
2225 /** A space at a version: published versions never change, so the key is just their names (#46). */
2226 #viewAt(space: Space, version: number): View {
2227 return this.#viewKeyed(`v ${space.name}@${version}`, () => this.#at(space, version));
2228 }
2230 #sharedView(): View {
2231 return this.#viewAt(this.#shared, last(this.#shared));
2232 }
2234 /** A view of a set, cached by the set's exact contents (views.ts). */
2235 #view(set: ReadonlySet<AtomId>): View {
2236 return this.#views.view(this.#closed(set));
2237 }
2239 /** A view cached under `key` (views.ts). */
2240 #viewKeyed(key: string, set: () => ReadonlySet<AtomId>): View {
2241 return this.#views.keyed(key, () => this.#closed(set()));
2242 }
2244 /**
2245 * A discarded atom that a later publish still depends on stays in the view
2246 * (abso issue 80). A closed set is unchanged.
2247 */
2248 #closed(set: Iterable<AtomId>): Set<AtomId> {
2249 return this.#graph.closureOf(set);
2250 }
2252 /** A new publish or land must not depend on an atom outside the set (abso issue 80). */
2253 #requireClosed(tie: { deps: readonly AtomId[] }, union: ReadonlySet<AtomId>): void {
2254 const missing = tie.deps.filter((id) => !union.has(id));
2255 if (missing.length > 0)
2256 throw new ProjectError(
2257 "conflict",
2258 `this change depends on ${missing.join(", ")}, which is not in the set being published`,
2259 );
2260 }
2262 /** The space's atoms published after the agent's base, by others. */
2263 #newerFor(agent: AgentState): Set<AtomId> {
2264 const space = this.#spaceOf(agent);
2265 const base = this.#at(space, agent.base);
2266 const mine = new Set(agent.mine);
2267 return new Set([...this.#setOf(space)].filter((id) => !base.has(id) && !mine.has(id)));
2268 }
2270 /** The files whose text in the agent's view differs from `before`, and its open collisions. */
2271 #changesSince(...args: Tail<Parameters<typeof hostedChangesSince>>): ReturnType<typeof hostedChangesSince> {
2272 return hostedChangesSince(this.#changesSinceHost, ...args);
2273 }
2275 /** Who published an atom, looking in the given space first and then in shared. */
2276 #origin(atom: AtomId, spaceName: string): Origin {
2277 return originOf(this.#collisionHost, atom, spaceName);
2278 }
2280 // Drafting ----------------------------------------------------------------------
2282 /** Check a {path: sha256} map: hex hashes, no path also given as text, and bytes already uploaded. */
2283 #checkBlobs(blobs: unknown, files: object): Record<string, string> {
2284 if (typeof blobs !== "object" || blobs === null || Array.isArray(blobs))
2285 throw new ProjectError("bad-request", "blobs must be {path: sha256}");
2286 for (const [path, sha] of Object.entries(blobs as Record<string, unknown>)) {
2287 checkPath(path);
2288 if (typeof sha !== "string" || !/^[0-9a-f]{64}$/.test(sha))
2289 throw new ProjectError("bad-request", `${path}: a blob is the SHA-256 of the bytes, in lowercase hex`);
2290 if (Object.hasOwn(files, path)) throw new ProjectError("bad-request", `${path} is given as both text and a blob`);
2291 if (!this.#hasBlob(sha))
2292 throw new ProjectError("bad-request", `${path}: upload blob ${sha} first (PUT /p/:project/blobs/${sha})`);
2293 }
2294 return blobs as Record<string, string>;
2295 }
2297 /**
2298 * Make one file in the agent's view what the folder has, as one draft
2299 * change: `text` (null: the file is gone; "": an empty file; undefined:
2300 * leave its lines alone) and `mode` (only the fields given). Returns
2301 * whether anything changed.
2302 */
2303 #recordFile(...args: Tail<Parameters<typeof hostedRecordFile>>): ReturnType<typeof hostedRecordFile> {
2304 return hostedRecordFile(this.#recordFileHost, ...args);
2305 }
2307 /**
2308 * Moves (#28). Within one agent's unpublished draft, a line that leaves one
2309 * place and the same text that arrives somewhere else is the same line, in
2310 * either order (deleted then written, or written then deleted). Before a
2311 * publish, the draft's changes to the files involved are dropped (a discard
2312 * entry) and made again: one move per matched block, which keeps the
2313 * lines' ids, then a change per file to the draft's final text. The files
2314 * end up exactly as the draft had them. A matched block needs a line with
2315 * real content: blank lines and lone brackets only travel next to one.
2316 */
2317 #expressMoves(agent: AgentState, time: number, entries: Entry[]): void {
2318 hostedExpressMoves(this.#expressMovesHost, agent, time, entries);
2319 }
2321 /**
2322 * Build a draft change against the agent's view. If it touches lines on
2323 * either side of a collision the agent has already seen, it settles that
2324 * collision (the engine's `resolves`).
2325 */
2326 #addDraft(...args: Tail<Parameters<typeof hostedAddDraft>>): ReturnType<typeof hostedAddDraft> {
2327 return hostedAddDraft(this.#addDraftHost, ...args);
2328 }
2330 // Collisions and news -------------------------------------------------------------
2332 #pairs(draft: readonly AtomId[], against: ReadonlySet<AtomId>, settled: ReadonlySet<AtomId>): Pair[] {
2333 return pairsIn(this.#graph, draft, against, settled);
2334 }
2336 /**
2337 * Collisions the agent has synced into and not settled: its draft against
2338 * its space at its base. In a named draft, also the draft's own changes
2339 * against shared work the draft was moved onto.
2340 */
2341 #openPairs(agent: AgentState): Pair[] {
2342 return hostedOpenPairs(this.#collisionHost, agent);
2343 }
2345 /** After the agent's own change: news when its draft now collides with work published after its base. */
2346 #newsAboutOwnDraft(agent: AgentState, entries: Entry[]): void {
2347 hostedNewsAboutOwnDraft(this.#newsHost, agent, entries);
2348 }
2350 /** After a publish or a landing: news for every other agent in that space whose draft collides with what just arrived. */
2351 #newsForOthers(publisher: AgentState, space: Space, version: number, entries: Entry[]): void {
2352 hostedNewsForOthers(this.#newsHost, publisher, space, version, entries);
2353 }
2355 #queueNews(agent: AgentState, items: readonly { key: string; text: string }[], entries: Entry[]): void {
2356 const fresh = items.filter((p) => !agent.told.has(p.key));
2357 if (fresh.length === 0) return;
2358 const text = [...new Set(fresh.map((p) => p.text))];
2359 const entry: Entry = { type: "news", agent: agent.name, pairs: [...new Set(fresh.map((p) => p.key))], text };
2360 entries.push(entry);
2361 this.#apply(entry);
2362 }
2364 #takeNews(agent: AgentState, entries: Entry[]): string[] {
2365 if (agent.news.length === 0) return [];
2366 const news = [...agent.news];
2367 const entry: Entry = { type: "heard", agent: agent.name };
2368 entries.push(entry);
2369 this.#apply(entry);
2370 return news;
2371 }
2373 /** Describe a pair for the agent: its side in its own view, theirs in its space now. */
2374 #collision(agent: AgentState, pair: Pair): Collision {
2375 return this.#describe(
2376 pair,
2377 this.#agentView(agent),
2378 this.#viewAt(this.#spaceOf(agent), last(this.#spaceOf(agent))),
2379 agent.space,
2380 );
2381 }
2383 #describe(pair: Pair, yoursView: View, theirsView: View, spaceName: string): Collision {
2384 return describePair(
2385 this.#graph,
2386 (atom, space) => this.#origin(atom, space),
2387 pair,
2388 yoursView,
2389 theirsView,
2390 spaceName,
2391 );
2392 }
2394 #touchedFiles(ids: Iterable<AtomId>, views: readonly View[]): Set<string> {
2395 return touchedFiles(this.#graph, ids, views);
2396 }
2398 // The changed-definition rule (#11) -------------------------------------------
2400 /** The rule for an agent's draft in its space. */
2401 #definitionCollisions(agent: AgentState, newer: ReadonlySet<AtomId>): DefinitionCollision[] {
2402 const draft = new Set(this.#draft(agent));
2403 if (draft.size === 0 || newer.size === 0) return [];
2404 const space = this.#spaceOf(agent);
2405 const mine = new Set(agent.mine);
2406 const base = this.#view(new Set([...this.#at(space, agent.base)].filter((id) => !mine.has(id))));
2407 return this.#definitionRule.collisions(
2408 draft,
2409 this.#agentView(agent),
2410 base,
2411 this.#viewAt(space, last(space)),
2412 newer,
2413 space.name,
2414 );
2415 }
2416}
2418export { EngineError };