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