- 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=95&format=json
2,421 linesFirst import 98% · engine 1% · speed 1% · pinch 1% · infra-split 1%Last change speed in version 83, 9 versions changed it
You're reading version 95. The newest is 318, and 49 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 { type Atom, type AtomId, EngineError, Graph, type LineId, type View } from "../../src/engine/index.ts";
16import { type AddDraftHost, addDraft as hostedAddDraft } from "./add-draft.ts";
17import { type AmendHost, amend as hostedAmend } from "./amend.ts";
18import { type AnnounceHost, announce as hostedAnnounce, announcePerson as hostedAnnouncePerson } from "./announce.ts";
19import { type ApplyEntryHost, applyEntry as hostedApplyEntry } from "./apply-entry.ts";
20import {
21 type ChangeHost,
22 change as hostedChange,
23 changeRecord as hostedChangeRecord,
24 changes as hostedChanges,
25 joinChange as hostedJoinChange,
26 namedFiles as hostedNamedFiles,
27} from "./change-records.ts";
28import { type ChangesSinceHost, changesSince as hostedChangesSince } from "./changes-since.ts";
29import { type CheckClashHost, checkClash as hostedCheckClash } from "./check-clash.ts";
30import {
31 type CollisionHost,
32 describePair,
33 duplicateCollisions,
34 openPairs as hostedOpenPairs,
35 type Origin,
36 originOf,
37 type Pair,
38 pairsIn,
39 strandedFiles,
40 touchedFiles,
41} from "./collisions.ts";
42import { type DefinitionCollision, DefinitionRule } from "./definition-rule.ts";
43import { type DraftCollisionHost, draftCollisions } from "./draft-collisions.ts";
44import { type DraftDiffHost, diffOfAgent, diffOf as draftDiffOf } from "./draft-diff.ts";
45import { type DraftStateHost, draftState as hostedDraftState } from "./draft-state.ts";
46import { type DropHost, drop as hostedDrop } from "./drop.ts";
47import { type EditHost, edit as hostedEdit } from "./edit.ts";
48import { type ExpressMovesHost, expressMoves as hostedExpressMoves } from "./express-moves.ts";
49import {
50 type HistoryHost,
51 follow as historyFollow,
52 pathLife as historyPathLife,
53 tree as historyTree,
54} from "./history.ts";
55import { ingest as hostedIngest, type IngestHost } from "./ingest.ts";
56import { init as hostedInit, type InitHost } from "./init.ts";
57import { label as hostedLabel, type LabelHost } from "./label.ts";
58import {
59 land as hostedLand,
60 landCollisions as hostedLandCollisions,
61 landDraft as hostedLandDraft,
62 type LandHost,
63} from "./land.ts";
64import {
65 blocksIn,
66 markedCollisions as hostedMarkedCollisions,
67 markedFiles as hostedMarkedFiles,
68 markerCollisions as hostedMarkerCollisions,
69 markersSettled as hostedMarkersSettled,
70 openCollisions as hostedOpenCollisions,
71 type MarkerHost,
72} from "./markers.ts";
73import { MemoryStore } from "./memory-store.ts";
74import { mergeIdentical as hostedMergeIdentical, type MergeHost } from "./merge-identical.ts";
75import { move as hostedMove, type MoveHost } from "./move.ts";
76import {
77 addressedItem,
78 newsAboutOwnDraft as hostedNewsAboutOwnDraft,
79 newsForOthers as hostedNewsForOthers,
80 markedItem,
81 type NewsHost,
82 type NewsItem,
83 reviewItem,
84 settledItem,
85} from "./news.ts";
86import {
87 closeNote as hostedCloseNote,
88 noteAnswer as hostedNoteAnswer,
89 notes as hostedNotes,
90 startingNotes as hostedStartingNotes,
91 writeNote as hostedWriteNote,
92 type NoteHost,
93 type NoteWriteHost,
94 type ReviewRule,
95 reviewersOf,
96 reviewRulesIn,
97} from "./notes.ts";
98import {
99 draftFiles as hostedDraftFiles,
100 overlapNews as hostedOverlapNews,
101 overlaps as hostedOverlaps,
102 type OverlapHost,
103} from "./overlaps.ts";
104import { checkPath } from "./path-rules.ts";
105import { PathIndex } from "./pathindex.ts";
106import { pathKey } from "./pathkey.ts";
107import { pluck as hostedPluck, type PluckHost } from "./pluck.ts";
108import { ProjectError } from "./project-error.ts";
109import { checkDraftName, checkPerson, NAME, projectFileIn } from "./project-helpers.ts";
110import {
111 type SnapshotHost,
112 agentPaths as snapshotAgentPaths,
113 labels as snapshotLabels,
114 pathsAt as snapshotPathsAt,
115 pathsOf as snapshotPathsOf,
116 status as snapshotStatus,
117} from "./project-status.ts";
118import type {
119 AgentState,
120 AgentStatus,
121 ChangeAnswer,
122 ChangeRecord,
123 Collision,
124 DiffAnswer,
125 DraftSyncAnswer,
126 DropAnswer,
127 EditsVia,
128 Entry,
129 LandAnswer,
130 MergedLine,
131 Modes,
132 NoteAnswer,
133 NoteBody,
134 NoteRecord,
135 PersonSender,
136 PluckAnswer,
137 ProjectOptions,
138 ProjectStore,
139 PublishAnswer,
140 QueuedPublish,
141 Refusal,
142 Settled,
143 Starting,
144 Tail,
145 TellRecord,
146} from "./project-types.ts";
147import { publish as hostedPublish, publishDraft as hostedPublishDraft, type PublishHost } from "./publish.ts";
148import { publishOf as hostedPublishOf, type PublishOfHost } from "./publish-of.ts";
149import {
150 enqueue as hostedEnqueue,
151 notQueuedYet as hostedNotQueuedYet,
152 queue as hostedQueue,
153 queueCandidate as hostedQueueCandidate,
154 queueChecking as hostedQueueChecking,
155 queuedAtoms as hostedQueuedAtoms,
156 queueLand as hostedQueueLand,
157 queueOn as hostedQueueOn,
158 queuePull as hostedQueuePull,
159 unqueue as hostedUnqueue,
160 type QueueHost,
161} from "./queue.ts";
162import { record as hostedRecord, type RecordHost } from "./record.ts";
163import { recordFile as hostedRecordFile, type RecordFileHost } from "./record-file.ts";
164import { refusals as hostedRefusals, refuse as hostedRefuse, type RefuseHost } from "./refuse.ts";
165import { restore as hostedRestore, type RestoreHost } from "./restore.ts";
166import { last, Membership, SHARED, type Space, sharedBaseOf } from "./spaces.ts";
167import { starting as hostedStarting, type StartingHost } from "./start.ts";
168import { switchTo as hostedSwitchTo, type SwitchHost } from "./switch-to.ts";
169import { sync as hostedSync, type SyncHost } from "./sync.ts";
170import { treeHash } from "./tree.ts";
171import {
172 type LogHost,
173 compare as versionCompare,
174 fileAt as versionFileAt,
175 log as versionLog,
176 ribbon as versionRibbon,
177 show as versionShow,
178 viewAt as versionViewAt,
179} from "./version-log.ts";
180import {
181 checkVersion as hostedCheckVersion,
182 lastVersion as hostedLastVersion,
183 versionMeta as hostedVersionMeta,
184 type VersionMetaHost,
185} from "./version-meta.ts";
186import { modesOf } from "./view-changes.ts";
187import { ViewCache } from "./views.ts";
188import {
189 isWhole as hostedIsWhole,
190 wholeOut as hostedWholeOut,
191 wholeRules as hostedWholeRules,
192 type WholeHost,
193} from "./whole-files.ts";
195export { MemoryStore } from "./memory-store.ts";
196export { checkReadPath, pathProblem } from "./path-rules.ts";
197export { ProjectError } from "./project-error.ts";
198export { shapeStamp, utf8Bytes } from "./project-helpers.ts";
199export type * from "./project-types.ts";
200export { differs } from "./view-changes.ts";
202/** Entry kinds that had no time before #41; new ones get one. */
203const UNTIMED = new Set<Entry["type"]>(["join", "sync", "news", "heard", "discard", "switch"]);
205/** A start note lasts this long after the agent's last activity (#44). */
206const NOTE_IDLE = 2 * 60 * 60 * 1000;
208export class Project {
209 readonly #store: ProjectStore;
210 readonly #graph: Graph;
211 /** Views laid out from atom sets, cached under a byte budget (views.ts). */
212 readonly #views: ViewCache;
213 /** Each agent's draft files, under the key they were worked out for (#draftFiles). */
214 readonly #draftFilesKept = new Map<string, { key: string; files: Set<string> }>();
215 /** Each version's files and each path's history (pathindex.ts). */
216 readonly #paths: PathIndex;
217 /** For each atom (by seq) that wrote lines, the log position of the entry that recorded it (#46). */
218 readonly #atomAt: number[] = [];
219 /** Which atoms are in which space at which version (#46, disk-first 1): the rules live in spaces.ts. */
220 readonly #membership = new Membership();
221 get #spaces(): Map<string, Space> {
222 return this.#membership.spaces;
223 }
224 readonly #agents = new Map<string, AgentState>();
225 readonly #refusals: Refusal[] = [];
226 /** Labels on shared's versions: name -> versions, ascending. */
227 readonly #labels = new Map<string, number[]>();
228 /** The newest tells and who has heard each (apply-entry.ts). */
229 readonly #tells = new Map<number, TellRecord>();
230 /**
231 * Entries applied but not stored yet, in order. Every applied entry is
232 * stored at the next flush, even when the call that applied it threw
233 * afterwards; otherwise the log could miss a join that later entries rely on.
234 */
235 #pending: Entry[] = [];
236 /**
237 * Whether something runs the merge queue's check (#39). Until the Worker has
238 * a checker it stays false, and `"queue": true` in avcs.json does nothing:
239 * publishes would otherwise wait for a check that never comes. Replay
240 * doesn't depend on it.
241 */
242 checkerReady = false;
243 readonly #now: (() => number) | undefined;
244 readonly #whole: ProjectOptions["whole"];
245 readonly #shapes: ProjectOptions["shapes"];
246 /** For each log position, the newest time up to it (#41): time to position in one search. */
247 readonly #timeAt: number[] = [];
248 /** For each version of shared, the log position of the entry that made it (#41). */
249 readonly #versionAt: number[] = [];
250 /** The newest time any applied entry carries: the clock when none was given. */
251 #lastTime = 0;
252 /** Every change (#44), by id. */
253 readonly #changes = new Map<number, ChangeRecord>();
254 /** Each version's change, by "<draft or ''> <version>" (#44): what a note on its lines belongs to. */
255 readonly #versionChange = new Map<string, number>();
256 /** Every note (#44), by id. */
257 readonly #notes = new Map<number, NoteRecord>();
258 /** Mod versions (X-Abso-Client) in the order they first sent an edit (#41): the last is taken as the installed one. */
259 #mods: string[] = [];
260 /** The merge queue (#39), in order: publishes to shared waiting for their batch's check. */
261 #queue: QueuedPublish[] = [];
262 /** The newest note's id (#44). */
263 #lastNote = 0;
264 #queuedId = 0;
265 /** Queued ids in the batch being checked now: not in the log, only for refusing an unqueue mid-check. */
266 #checking = new Set<number>();
267 /** How many entries the store holds: the log position of the next one (#41, the website's feed and replay). */
268 #stored = 0;
269 /** Names on the lines a change replaced, by "<atom> <last replaced line>" (atoms never change). */
270 #rule?: DefinitionRule;
271 get #definitionRule(): DefinitionRule {
272 this.#rule ??= new DefinitionRule(this.#graph, (atom, space) => this.#origin(atom, space));
273 return this.#rule;
274 }
275 /** The newest announcement's id (announcements are news entries keyed "announce <id>"). */
276 #announced = 0;
277 #loading = false;
279 readonly #hasBlob: (sha256: string) => boolean;
281 constructor(store: ProjectStore, options: ProjectOptions = {}) {
282 this.#store = store;
283 this.#hasBlob = options.hasBlob ?? (() => false);
284 this.#now = options.now;
285 this.#whole = options.whole;
286 this.#shapes = options.shapes;
287 // For tests (#46): AVCS_TEXT_FROM_LOG=1 runs a project on a MemoryStore with its text read back from the store.
288 const testing =
289 (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env?.AVCS_TEXT_FROM_LOG ===
290 "1";
291 const entryAt =
292 options.entryAt ??
293 (testing && store instanceof MemoryStore ? (at: number) => (store as MemoryStore).entries[at]! : undefined);
294 // An atom as its log entry stores it. Not stored yet: still in this call's pending entries; while loading, every entry is stored.
295 const stored = (seq: number): Atom => {
296 const at = this.#atomAt[seq]!;
297 const entry = !this.#loading && at >= this.#stored ? this.#pending[at - this.#stored]! : entryAt!(at);
298 if (entry?.type === "init" || entry?.type === "draft") return entry.atom;
299 // A publish's or land's tie atom (#46: its lists are read back too).
300 if (entry?.type === "publish" || entry?.type === "land") return entry.tie;
301 throw new Error(`log entry ${at} holds no atom ${seq}`);
302 };
303 // Line text and each atom's deletes and claim keys stay in the log (#46), read back when asked for.
304 this.#graph = entryAt
305 ? new Graph({ texts: (seq) => stored(seq).inserts.map((r) => r.lines), lists: (seq) => stored(seq) })
306 : new Graph();
307 this.#views = new ViewCache(this.#graph);
308 this.#paths = new PathIndex({
309 graph: this.#graph,
310 at: (space, version) => this.#at(space, version),
311 viewAt: (space, version) => this.#viewAt(space, version),
312 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
313 shapes: this.#shapes,
314 });
315 }
317 /** Rebuild a project from its stored entries. New entries go to `store`. */
318 static load(entries: Iterable<Entry>, store: ProjectStore, options: ProjectOptions = {}): Project {
319 const testing =
320 (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env?.AVCS_TEXT_FROM_LOG ===
321 "1";
322 if (testing && !options.entryAt && Array.isArray(entries)) {
323 // Loaded from someone else's entries: its text is read back from them (and from the new store after them).
324 const from = entries as Entry[];
325 const after = store instanceof MemoryStore ? store : undefined;
326 options = { ...options, entryAt: (at) => (at < from.length ? from[at]! : after!.entries[at - from.length]!) };
327 }
328 const project = new Project(store, options);
329 project.#loading = true;
330 for (const entry of entries) {
331 project.#apply(entry);
332 project.#stored++;
333 }
334 project.#loading = false;
335 return project;
336 }
338 /**
339 * Apply more stored entries to a copy loaded for reading (#41, replay):
340 * scrubbing forward applies only what's new. Never for the live project.
341 */
342 catchUp(entries: Iterable<Entry>): void {
343 this.#loading = true;
344 try {
345 for (const entry of entries) {
346 this.#apply(entry);
347 this.#stored++;
348 }
349 } finally {
350 this.#loading = false;
351 }
352 }
354 /** The log position of the next entry: how many entries the log holds (#41). */
355 get logLength(): number {
356 return this.#stored;
357 }
359 get initialized(): boolean {
360 return this.#shared.versions.length > 0;
361 }
363 /** The current shared version. */
364 get version(): number {
365 this.#needInit();
366 return this.#shared.versions.length - 1;
367 }
369 /** Shared's files, for the push out to Artifacts. */
370 files(): Record<string, string> {
371 return this.#sharedView().files();
372 }
374 /** Shared's binary files, for the push out to Artifacts: path -> the SHA-256 of its bytes. Not in `files()`. */
375 blobs(): Record<string, string> {
376 return this.#sharedView().blobs();
377 }
379 /** Shared's executable files and links, for the push out to Artifacts: path -> mode. Other files are plain. */
380 modes(): Modes {
381 return modesOf(this.#sharedView());
382 }
384 /** Shared as a View, for reading lines (blame, why). Don't hold on to it across calls. */
385 sharedView(): View {
386 return this.#sharedView();
387 }
389 /** The agents the project knows, by name. */
390 agents(): string[] {
391 return [...this.#agents.keys()].sort();
392 }
394 /**
395 * An agent's unpublished changes, oldest first, and its view (its space at its base plus its changes). Read only.
396 * The view is laid out on first use: where asks every agent, most have no changes, and a big project has more
397 * agents than the view cache holds, so building every view cost each call about 0.7 s.
398 */
399 draftOf(agentName: string): { atoms: AtomId[]; readonly view: View } | undefined {
400 const agent = this.#agents.get(agentName);
401 if (!agent) return undefined;
402 const view = () => this.#agentView(agent);
403 return {
404 atoms: this.#draft(agent),
405 get view() {
406 return view();
407 },
408 };
409 }
411 /** The shared version an atom was published in, or undefined while it's only in a draft. */
412 versionOf(atom: AtomId): number | undefined {
413 return this.#shared.publishedIn.get(atom);
414 }
416 /**
417 * Where an atom was published: shared if it's there, else the named draft
418 * that has it (by name), else undefined (it's only in a draft so far).
419 */
420 publishOf(...args: Tail<Parameters<typeof hostedPublishOf>>): ReturnType<typeof hostedPublishOf> {
421 return hostedPublishOf(this.#publishOfHost, ...args);
422 }
424 /** The newest version of shared, or of a named draft. */
425 lastVersion(...args: Tail<Parameters<typeof hostedLastVersion>>): ReturnType<typeof hostedLastVersion> {
426 return hostedLastVersion(this.#versionMetaHost, ...args);
427 }
429 /** Shared (null), then each named draft by name: every space with versions (abso issue 80). */
430 spaceNames(): (string | null)[] {
431 return [null, ...[...this.#spaces.keys()].filter((n) => n !== SHARED).sort()];
432 }
434 /** Who made a version of shared or a named draft, why and when, and a draft's shared base (abso issue 80). */
435 versionMeta(...args: Tail<Parameters<typeof hostedVersionMeta>>): ReturnType<typeof hostedVersionMeta> {
436 return hostedVersionMeta(this.#versionMetaHost, ...args);
437 }
439 /** Who published a version of shared, and why. */
440 published(version: number): { agent: string; message: string; time: number } | undefined {
441 const p = this.#shared.versions[version];
442 return p && { agent: p.agent, message: p.message, time: p.time };
443 }
445 /** The graph, for reading (blame, history). Don't add to it. */
446 get graph(): Graph {
447 return this.#graph;
448 }
450 // Calls -------------------------------------------------------------------
452 /** Create the project from a folder's text files. Empty files are skipped (the engine can't hold them). */
453 init(...args: Tail<Parameters<typeof hostedInit>>): ReturnType<typeof hostedInit> {
454 return hostedInit(this.#initHost, ...args);
455 }
457 /** An Edit, Write or MultiEdit from the hook, against the agent's view. */
458 edit(...args: Tail<Parameters<typeof hostedEdit>>): ReturnType<typeof hostedEdit> {
459 return hostedEdit(this.#editHost, ...args);
460 }
462 /** Whole files as the agent's folder has them; each is diffed against its view. */
463 record(...args: Tail<Parameters<typeof hostedRecord>>): ReturnType<typeof hostedRecord> {
464 return hostedRecord(this.#recordHost, ...args);
465 }
467 /** Add the agent's draft to its space (publish.ts). */
468 publish(...args: Tail<Parameters<typeof hostedPublish>>): ReturnType<typeof hostedPublish> {
469 return hostedPublish(this.#publishHost, ...args);
470 }
472 #publish(
473 agent: AgentState,
474 message: string,
475 time: number,
476 entries: Entry[],
477 asIs = false,
478 direct = false,
479 ): PublishAnswer {
480 return hostedPublishDraft(this.#publishHost, agent, message, time, entries, asIs, direct);
481 }
483 /**
484 * How the agent's newest edit arrived (#41). The mod sends X-Abso-Client
485 * avcs-mod/<stamp>; the hook sends abso-cli/<version> (avcs-cli/ before #59) with the chat's
486 * session; abso record and git pushes send no session. Edits stored before
487 * the client was recorded have only the session: those count as the mod
488 * (the hook stands down where the mod is installed), with modCurrent null.
489 */
490 #editsOf(agent: AgentState): {
491 edits: EditsVia;
492 modCurrent: boolean | null;
493 lastEdit: number | null;
494 joined: number | null;
495 } {
496 const last = agent.lastEdit;
497 const joined = agent.joined ?? null;
498 if (!last) return { edits: "none", modCurrent: null, lastEdit: null, joined };
499 const { client, session } = last;
500 if (client?.startsWith("avcs-mod/"))
501 return { edits: "mod", modCurrent: client === this.#mods[this.#mods.length - 1], lastEdit: last.time, joined };
502 if (client === undefined && session) return { edits: "mod", modCurrent: null, lastEdit: last.time, joined };
503 return { edits: session ? "hook" : "commands", modCurrent: null, lastEdit: last.time, joined };
504 }
506 // Spellings and moves (#49) --------------------------------------------------------
508 /** Refuse work whose paths would clash in shared (#49), before anything of it is written. */
509 #checkClash(...args: Tail<Parameters<typeof hostedCheckClash>>): ReturnType<typeof hostedCheckClash> {
510 return hostedCheckClash(this.#checkClashHost, ...args);
511 }
513 /**
514 * Move a file in the agent's draft (#49): its lines keep their ids, as with
515 * git mv, so blame and why follow it. The only way to change a file's case.
516 * Refused when `to` is another existing file, ignoring case.
517 */
518 move(...args: Tail<Parameters<typeof hostedMove>>): ReturnType<typeof hostedMove> {
519 return hostedMove(this.#moveHost, ...args);
520 }
522 // Files kept whole (#46) ----------------------------------------------------------
524 /** avcs.json's `"whole": [globs]`: paths kept whole. From `config` when given (init), else shared's. */
525 #wholeRules(config?: string): string[] {
526 return hostedWholeRules(this.#wholeHost, config);
527 }
529 /**
530 * Whether a file is kept whole: its path matches avcs.json's "whole", its
531 * text passes WHOLE_LIMIT, or it is already a blob where it's going. The
532 * last makes it one-way: a file kept whole stays whole while it exists,
533 * even if it shrinks or the rule changes, so it never flips back and forth.
534 */
535 #isWhole(path: string, length: number, view: View | undefined, rules: readonly string[]): boolean {
536 return hostedIsWhole(this.#wholeHost, path, length, view, rules);
537 }
539 /** Files and blobs with every whole file's text moved into the blob store. */
540 #wholeOut(
541 files: Readonly<Record<string, string | null>>,
542 blobs: Readonly<Record<string, string>>,
543 view: View | undefined,
544 config?: string,
545 ): { files: Record<string, string | null>; blobs: Record<string, string> } {
546 return hostedWholeOut(this.#wholeHost, files, blobs, view, config);
547 }
549 // Changes (#44) -------------------------------------------------------------------
551 /** The agent did something at `time`: its start note ends first if it had been idle over 2 hours. */
552 #active(agent: AgentState, time: number): void {
553 if (agent.starting && agent.lastActive !== undefined && time - agent.lastActive > NOTE_IDLE) {
554 delete agent.starting;
555 delete agent.noteAt;
556 }
557 if (agent.lastActive === undefined || time > agent.lastActive) agent.lastActive = time;
558 }
560 /** The agent's start note, unless it has been idle over 2 hours. */
561 #liveNote(agent: AgentState): Starting | undefined {
562 if (!agent.starting) return undefined;
563 const now = this.#now?.() ?? this.#lastTime;
564 return agent.lastActive !== undefined && now - agent.lastActive > NOTE_IDLE ? undefined : agent.starting;
565 }
567 /** The change the agent is working on at `time`: its named draft's, or its start note's; none for a lone publish. */
568 #currentChange(agent: AgentState, time: number): number | undefined {
569 if (agent.space !== SHARED) return this.#spaces.get(agent.space)?.startedAt;
570 if (!agent.starting || agent.noteAt === undefined) return undefined;
571 return agent.lastActive !== undefined && time - agent.lastActive > NOTE_IDLE ? undefined : agent.noteAt;
572 }
574 /** The position the next entry written will have. */
575 get #nextAt(): number {
576 return this.#stored + this.#pending.length;
577 }
579 #changeRecord(id: number, agent: AgentState, time: number, queuedNote?: Starting): ChangeRecord {
580 return hostedChangeRecord(this.#changeHost, id, agent, time, queuedNote);
581 }
583 /** A publish or land joins its change. Entries from before changes: the start note named it, and the publish ended the note. */
584 #joinChange(
585 agent: AgentState,
586 entry: Extract<Entry, { type: "publish" | "land" }>,
587 at: number,
588 draft: string | null,
589 landed?: string,
590 ): void {
591 hostedJoinChange(this.#changeHost, agent, entry, at, draft, landed);
592 }
594 /**
595 * One change (#44): the start note, named draft or publish that began it,
596 * each of its versions and the files they changed, what it settled, and its
597 * refusals. `id` is the log position of the entry that began it.
598 */
599 change(id: number): ChangeAnswer {
600 return hostedChange(this.#changeHost, id);
601 }
603 /** The files a version's changes name: cheap, for lists (the change page works out the net changes). */
604 #namedFiles(space: Space, version: number): string[] {
605 return hostedNamedFiles(this.#graph, space, version);
606 }
608 /**
609 * "Since you last looked" (#44): the changes with anything new at or after
610 * log position `since`, newest first, at most `limit`. Their files are the
611 * ones their changes name; the change page has the net changes.
612 */
613 changes(
614 since = 0,
615 limit = 50,
616 before?: number,
617 issue?: number,
618 ): { since: number; next: number; changes: ChangeAnswer[]; older?: number } {
619 return hostedChanges(this.#changeHost, since, limit, before, issue);
620 }
622 // Notes on lines (#44) --------------------------------------------------------------
624 /**
625 * Leave a note on lines of a file (#44): lines `from` to `to` (1-based) as
626 * shared shows them now, as `of`'s draft shows them (to note work before
627 * it's published), or at `version`. Or answer a note with `reply`. The
628 * lines' authors, the change's agent and the thread hear it as news.
629 */
630 note(
631 agentName: string,
632 body: NoteBody,
633 time: number,
634 ): { id: number; change: number | null; lines: [number, number] } {
635 this.#needInit();
636 const entries: Entry[] = [];
637 return this.#note(entries, () => ({ name: this.#agent(agentName, entries).name }), body, time);
638 }
640 /**
641 * A signed-in person's note from the website (#41). The Worker has checked
642 * who it is. The writer is recorded as "person:<id>" with `person`, never
643 * as an agent, and the news quotes the text.
644 */
645 notePerson(
646 person: { id: unknown; name: unknown },
647 body: NoteBody,
648 time: number,
649 ): { id: number; change: number | null; lines: [number, number] } {
650 this.#needInit();
651 const from = checkPerson(person);
652 return this.#note([], () => ({ name: `person:${from.person.id}`, person: from }), body, time);
653 }
655 /** Close a person's own note (#41): only the person who wrote it can. */
656 closeNotePerson(person: { id: unknown; name: unknown }, id: number, how: unknown, time: number): NoteAnswer {
657 const from = checkPerson(person);
658 return this.#closeNote(`person:${from.person.id}`, id, how, time, from);
659 }
661 #note(
662 entries: Entry[],
663 writerOf: () => { name: string; person?: PersonSender },
664 body: NoteBody,
665 time: number,
666 ): { id: number; change: number | null; lines: [number, number] } {
667 return hostedWriteNote(this.#noteWriteHost, entries, writerOf, body, time);
668 }
670 /** The project's reviewers per area (#44): avcs.json's `"review": [{"paths": [...], "reviewer": "..."}]` in shared. */
671 #reviewRules(): ReviewRule[] {
672 return reviewRulesIn(projectFileIn(this.#sharedView())?.text);
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 #noteAnswer(n: NoteRecord): NoteAnswer {
740 return hostedNoteAnswer(this.#notesHost, n);
741 }
743 // The merge queue (#39) ------------------------------------------------------------
745 /** Whether shared's avcs.json turns the merge queue on (`"queue": true`). */
746 #queueOn(): boolean {
747 return hostedQueueOn(this.#queueHost);
748 }
750 /** With the queue on, nothing lands in shared unchecked; land and pluck don't go through the queue yet. */
751 #notQueuedYet(what: string): void {
752 hostedNotQueuedYet(this.#queueHost, what);
753 }
755 /** Atoms of every queued publish, or only other agents' with `except`. */
756 #queuedAtoms(except?: string): Set<AtomId> {
757 return hostedQueuedAtoms(this.#queueHost, except);
758 }
760 /** Queue the agent's publish (#39). */
761 #enqueue(
762 agent: AgentState,
763 message: string,
764 time: number,
765 draft: readonly AtomId[],
766 resolves: readonly AtomId[],
767 entries: Entry[],
768 ): PublishAnswer {
769 return hostedEnqueue(this.#queueHost, agent, message, time, draft, resolves, entries);
770 }
772 /** The merge queue now (#39): waiting publishes in order, and which are in the batch being checked. */
773 queue(...args: Tail<Parameters<typeof hostedQueue>>): ReturnType<typeof hostedQueue> {
774 return hostedQueue(this.#queueHost, ...args);
775 }
777 /** Mark the first `n` queued publishes as the batch being checked (0 ends it). Not logged. */
778 queueChecking(...args: Tail<Parameters<typeof hostedQueueChecking>>): ReturnType<typeof hostedQueueChecking> {
779 return hostedQueueChecking(this.#queueHost, ...args);
780 }
782 /** Shared with the first `n` queued publishes on top (#39): the files a batch's check runs on, and their tree hash. */
783 queueCandidate(...args: Tail<Parameters<typeof hostedQueueCandidate>>): ReturnType<typeof hostedQueueCandidate> {
784 return hostedQueueCandidate(this.#queueHost, ...args);
785 }
787 /** The tree hash of a version of shared (#39): it equals a candidate's when that's what landed. */
788 treeAt(version: number): string {
789 const view = this.viewAt(version);
790 return treeHash({ files: view.files(), modes: modesOf(view), blobs: view.blobs() });
791 }
793 /**
794 * Land the first `n` queued publishes (#39), in order, each as its own
795 * version, after their batch passed. Each tells others what arrived, its
796 * author that it landed, and the authors of what it settled what it kept.
797 */
798 queueLand(...args: Tail<Parameters<typeof hostedQueueLand>>): ReturnType<typeof hostedQueueLand> {
799 return hostedQueueLand(this.#queueHost, ...args);
800 }
802 /**
803 * Take a queued publish out (#39): its check failed, or its author withdrew
804 * it. Its changes are simply still in its author's draft. Later queued
805 * publishes that build on its changes come out with it.
806 */
807 queuePull(...args: Tail<Parameters<typeof hostedQueuePull>>): ReturnType<typeof hostedQueuePull> {
808 return hostedQueuePull(this.#queueHost, ...args);
809 }
811 /** The agent withdraws its queued publishes (#39): refused while one is in the batch being checked. */
812 unqueue(...args: Tail<Parameters<typeof hostedUnqueue>>): ReturnType<typeof hostedUnqueue> {
813 return hostedUnqueue(this.#queueHost, ...args);
814 }
816 /**
817 * Correct the message of the agent's newest publish in its space (#27).
818 * Only the message changes: shared only grows, so a version's changes are
819 * fixed by publishing again (or dropping it). The log keeps the original.
820 */
821 amend(...args: Tail<Parameters<typeof hostedAmend>>): ReturnType<typeof hostedAmend> {
822 return hostedAmend(this.#amendHost, ...args);
823 }
825 /**
826 * Put a label on a version of shared (the newest by default), or take it
827 * off with `remove`. A label can mark many versions ("passed-ci"); a folder
828 * follows the newest with `sync {label}`.
829 */
830 label(...args: Tail<Parameters<typeof hostedLabel>>): ReturnType<typeof hostedLabel> {
831 return hostedLabel(this.#labelHost, ...args);
832 }
834 /**
835 * Drop published versions of shared (#10): a new shared version whose set
836 * leaves out their changes. Later work that doesn't depend on them stays;
837 * history keeps them. When later published work built on them, they are
838 * refused with that work listed, unless `withDependents`, which drops it
839 * too. Unpublished work that builds on them (an agent's draft, a named
840 * draft not yet landed) always refuses it: drop never touches it.
841 */
842 drop(
843 agentName: string,
844 versions: readonly number[],
845 message: string,
846 time: number,
847 options: { withDependents?: boolean } = {},
848 ): DropAnswer {
849 return hostedDrop(this.#dropHost, agentName, versions, message, time, options);
850 }
852 /**
853 * After a sync, merge files where the agent's draft and the newer work
854 * collide, the way git merges a file (#25, Fuzzer): from the agent's old
855 * base, its draft's text and the newer text. Changes both made identically
856 * are kept once; changes on one side are kept. Only when every file
857 * involved merges with no conflict are the draft's changes to them dropped
858 * (a discard entry) and made again as the merged text. Otherwise nothing
859 * changes, and the collision stands with both sides' lines in the file.
860 */
861 #mergeIdentical(
862 agent: AgentState,
863 before: View,
864 oldBase: ReadonlySet<AtomId>,
865 oldVersion: number,
866 time: number,
867 entries: Entry[],
868 ): MergedLine[] {
869 return hostedMergeIdentical(this.#mergeHost, agent, before, oldBase, oldVersion, time, entries);
870 }
872 /**
873 * Names the agent's draft defines at the top level of a file where other
874 * work defines them too, so they are defined twice there (#25, Fuzzer).
875 */
876 #duplicates(agent: AgentState): Collision[] {
877 return duplicateCollisions(this.#collisionHost, agent);
878 }
880 /**
881 * Draft changes that build on atoms a set doesn't have (a drop took them
882 * out): the files they touch. Those changes can't move onto that set.
883 */
884 #strandedFiles(draft: readonly AtomId[], set: ReadonlySet<AtomId>): string[] {
885 return strandedFiles(this.#graph, draft, set);
886 }
888 /** Answer a refusal, and log it (an entry that changes nothing but the counts). */
889 #refuse(...args: Tail<Parameters<typeof hostedRefuse>>): ReturnType<typeof hostedRefuse> {
890 return hostedRefuse(this.#refuseHost, ...args);
891 }
893 /**
894 * Tell other agents something, as news: "Announcement from <agent>:
895 * <text>". It reaches each one with its next edit, record or news call.
896 * `to` names agents; without it, every other agent the project has now.
897 */
898 announce(...args: Tail<Parameters<typeof hostedAnnounce>>): ReturnType<typeof hostedAnnounce> {
899 return hostedAnnounce(this.#announceHost, ...args);
900 }
902 /**
903 * A signed-in person's announcement from the website (#41). The Worker has
904 * checked who sent it; the engine records it on each recipient's news with
905 * `from`, and never makes the person an agent. The text is JSON-quoted, so
906 * a line break in it can't pass for another item.
907 */
908 announcePerson(...args: Tail<Parameters<typeof hostedAnnouncePerson>>): ReturnType<typeof hostedAnnouncePerson> {
909 return hostedAnnouncePerson(this.#announceHost, ...args);
910 }
912 /**
913 * Say what the agent is starting on (#37, #13), before any edit lands:
914 * `text`, and the files it expects to change if it knows them. Nothing is
915 * locked or refused. where and status show it until the agent publishes,
916 * lands, or sends null. The answer names who already has unpublished
917 * changes in, or a starting note on, those files; they hear of it too.
918 */
919 starting(...args: Tail<Parameters<typeof hostedStarting>>): ReturnType<typeof hostedStarting> {
920 return hostedStarting(this.#startingHost, ...args);
921 }
923 /** Every agent's starting note, by agent name. */
924 startingNotes(): ReturnType<typeof hostedStartingNotes> {
925 return hostedStartingNotes(this.#notesHost);
926 }
928 #openCollisions(agent: AgentState): { collisions?: AgentStatus["collisions"] } {
929 return hostedOpenCollisions(this.#markerHost, agent);
930 }
932 /**
933 * News when an edit leaves a file holding blocks of collision markers
934 * (#11): how many, and how to settle them. Again whenever the count changes.
935 */
936 #markedNews(agent: AgentState, files: readonly string[], entries: Entry[]): void {
937 const marked = new Set(this.#markedFiles(agent));
938 const view = this.#agentView(agent);
939 const items: NewsItem[] = [];
940 for (const file of [...new Set(files)].sort()) {
941 if (!marked.has(file) || !view.hasFile(file)) continue;
942 const n = blocksIn(view.lines(file).map((l) => l.text)).length;
943 if (n === 0) continue;
944 items.push(markedItem(this.#draft(agent)[0] ?? "", file, n));
945 }
946 this.#queueNews(agent, items, entries);
947 }
949 /** The collided changes behind each block whose marker lines `atom` deletes (#11). */
950 #markersSettled(agent: AgentState, view: View, atom: Atom): AtomId[] {
951 return hostedMarkersSettled(this.#markerHost, agent, view, atom);
952 }
954 /** Files where a sync wrote the agent collision markers in its current space (#11). */
955 #markedFiles(agent: AgentState): string[] {
956 return hostedMarkedFiles(agent);
957 }
959 /** The blocks of markers still in the agent's files, as collisions (#11): listed by sync and status. */
960 #markedCollisions(agent: AgentState): Collision[] {
961 return hostedMarkedCollisions(this.#markerHost, agent);
962 }
964 /**
965 * Marker lines the agent's draft adds (#11), as collisions: each
966 * well-formed block, and any marker line left outside one. Only the labeled
967 * lines the engine writes count, so a document that shows markers can be
968 * published.
969 */
970 #markerCollisions(agent: AgentState): Collision[] {
971 return hostedMarkerCollisions(this.#markerHost, agent);
972 }
974 /** One line of news for each other author whose marked collision a publish settled (#11): what was kept, and any lines lost. */
975 #settledNews(agent: AgentState, version: number, settled: readonly Settled[], entries: Entry[]): void {
976 for (const s of settled) {
977 const other = this.#agents.get(s.theirs.agent);
978 if (!other || other === agent) continue;
979 this.#queueNews(other, [settledItem(agent.name, version, s)], entries);
980 }
981 }
983 /**
984 * The files the agent's unpublished changes touch, in its own view. Kept per agent under what they're
985 * made of: its view's key and its draft. Most agents haven't moved since the last
986 * status, and the view cache holds fewer views than a big project has agents, so working them out again
987 * on every call cost about 0.5 s on abso. A copy goes out, so no caller can change what's kept.
988 */
989 #draftFiles(agent: AgentState): Set<string> {
990 const key = `${this.#agentViewKey(agent)}|${this.#draft(agent).join(",")}`;
991 let kept = this.#draftFilesKept.get(agent.name);
992 if (kept?.key !== key) {
993 kept = { key, files: hostedDraftFiles(this.#overlapHost, agent) };
994 this.#draftFilesKept.set(agent.name, kept);
995 }
996 return new Set(kept.files);
997 }
999 /** Other agents in the agent's space whose unpublished changes or starting note meet `patterns`. */
1000 #overlaps(...args: Tail<Parameters<typeof hostedOverlaps>>): ReturnType<typeof hostedOverlaps> {
1001 return hostedOverlaps(this.#overlapHost, ...args);
1002 }
1004 /**
1005 * News the first time a draft touches a file someone else in its space has
1006 * unpublished changes in, or a starting note on (#37): 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.
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 tells: this.#tells,
1743 uncheck: (id) => {
1744 this.#checking.delete(id);
1745 },
1746 stamp: (t) => {
1747 if (typeof t === "number" && t > this.#lastTime) this.#lastTime = t;
1748 },
1749 applyMembership: (entry, at) => this.#membership.apply(entry, at),
1750 agentOf: (name) => this.#agentOf(name),
1751 active: (agent, time) => this.#active(agent, time),
1752 joinChange: (agent, entry, at, draft, landed) => this.#joinChange(agent, entry, at, draft, landed),
1753 space: (name) => this.#spaces.get(name)!,
1754 queued: () => this.#queue,
1755 setQueued: (items) => {
1756 this.#queue = items;
1757 },
1758 setQueuedId: (id) => {
1759 this.#queuedId = id;
1760 },
1761 queuedId: () => this.#queuedId,
1762 setLastNote: (id) => {
1763 this.#lastNote = id;
1764 },
1765 lastNote: () => this.#lastNote,
1766 setAnnounced: (n) => {
1767 this.#announced = n;
1768 },
1769 announced: () => this.#announced,
1770 at: (space, version) => this.#at(space, version),
1771 spaceOf: (agent) => this.#spaceOf(agent),
1772 draft: (agent) => this.#draft(agent),
1773 currentChange: (agent, time) => this.#currentChange(agent, time),
1774 changeRecord: (id, agent, time) => this.#changeRecord(id, agent, time),
1775 };
1776 return this.#applyEntries;
1777 }
1779 #landers?: LandHost;
1780 get #landHost(): LandHost {
1781 this.#landers ??= {
1782 agents: this.#agents,
1783 graph: this.#graph,
1784 spaces: this.#spaces,
1785 version: () => this.version,
1786 nextAt: () => this.#nextAt,
1787 notQueuedYet: (what) => this.#notQueuedYet(what),
1788 checkClash: (changes) => this.#checkClash(changes),
1789 agent: (name, entries) => this.#agent(name, entries),
1790 namedSpaceOf: (agent) => this.#namedSpaceOf(agent),
1791 shared: () => this.#shared,
1792 setOf: (space) => this.#setOf(space),
1793 at: (space, version) => this.#at(space, version),
1794 view: (set) => this.#view(set),
1795 sharedView: () => this.#sharedView(),
1796 pairs: (draft, against, settled) => this.#pairs(draft, against, settled),
1797 describe: (pair, yoursView, theirsView, spaceName) => this.#describe(pair, yoursView, theirsView, spaceName),
1798 definitionRule: () => this.#definitionRule,
1799 refuse: (agent, space, via, time, collisions, entries) =>
1800 this.#refuse(agent, space, via, time, collisions, entries),
1801 requireClosed: (tie, union) => this.#requireClosed(tie, union),
1802 apply: (entry) => this.#apply(entry),
1803 newsForOthers: (publisher, space, version, entries) => this.#newsForOthers(publisher, space, version, entries),
1804 addressedNews: (agent, version, entries) => this.#addressedNews(agent, version, entries),
1805 reviewNews: (agent, version, entries) => this.#reviewNews(agent, version, entries),
1806 flush: (entries) => this.#flush(entries),
1807 };
1808 return this.#landers;
1809 }
1811 #records?: RecordHost;
1812 get #recordHost(): RecordHost {
1813 this.#records ??= {
1814 agents: this.#agents,
1815 whole: this.#whole,
1816 initialized: () => this.initialized,
1817 agentView: (agent) => this.#agentView(agent),
1818 sharedView: () => this.#sharedView(),
1819 wholeOut: (files, blobs, view, config) => this.#wholeOut(files, blobs, view, config),
1820 checkBlobs: (blobs, files) => this.#checkBlobs(blobs, files),
1821 agent: (name, entries) => this.#agent(name, entries),
1822 draftFiles: (agent) => this.#draftFiles(agent),
1823 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
1824 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
1825 overlapNews: (agent, before, entries) => this.#overlapNews(agent, before, entries),
1826 markedNews: (agent, files, entries) => this.#markedNews(agent, files, entries),
1827 newsAboutOwnDraft: (agent, entries) => this.#newsAboutOwnDraft(agent, entries),
1828 takeNews: (agent, entries) => this.#takeNews(agent, entries),
1829 flush: (entries) => this.#flush(entries),
1830 };
1831 return this.#records;
1832 }
1834 #restores?: RestoreHost;
1835 get #restoreHost(): RestoreHost {
1836 this.#restores ??= {
1837 graph: this.#graph,
1838 agent: (name, entries) => this.#agent(name, entries),
1839 draft: (agent) => this.#unqueuedDraft(agent),
1840 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
1841 apply: (entry) => this.#apply(entry),
1842 view: (set) => this.#view(set),
1843 agentSet: (agent) => this.#agentSet(agent),
1844 agentView: (agent) => this.#agentView(agent),
1845 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
1846 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
1847 flush: (entries) => this.#flush(entries),
1848 };
1849 return this.#restores;
1850 }
1852 #startings?: StartingHost;
1853 get #startingHost(): StartingHost {
1854 this.#startings ??= {
1855 agents: this.#agents,
1856 changes: this.#changes,
1857 agent: (name, entries) => this.#agent(name, entries),
1858 liveNote: (agent) => this.#liveNote(agent),
1859 apply: (entry) => this.#apply(entry),
1860 overlaps: (agent, patterns) => this.#overlaps(agent, patterns),
1861 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
1862 flush: (entries) => this.#flush(entries),
1863 };
1864 return this.#startings;
1865 }
1867 #syncs?: SyncHost;
1868 get #syncHost(): SyncHost {
1869 this.#syncs ??= {
1870 graph: this.#graph,
1871 labels: this.#labels,
1872 agent: (name, entries) => this.#agent(name, entries),
1873 spaceOf: (agent) => this.#spaceOf(agent),
1874 agentView: (agent) => this.#agentView(agent),
1875 at: (space, version) => this.#at(space, version),
1876 draft: (agent) => this.#draft(agent),
1877 strandedFiles: (draft, set) => this.#strandedFiles(draft, set),
1878 apply: (entry) => this.#apply(entry),
1879 flush: (entries) => this.#flush(entries),
1880 mergeIdentical: (agent, before, oldBase, oldVersion, time, entries) =>
1881 this.#mergeIdentical(agent, before, oldBase, oldVersion, time, entries),
1882 changesSince: (agent, before) => this.#changesSince(agent, before),
1883 };
1884 return this.#syncs;
1885 }
1887 #moves?: MoveHost;
1888 get #moveHost(): MoveHost {
1889 this.#moves ??= {
1890 needInit: () => this.#needInit(),
1891 agents: this.#agents,
1892 agentView: (agent) => this.#agentView(agent),
1893 sharedView: () => this.#sharedView(),
1894 agent: (name, entries) => this.#agent(name, entries),
1895 addDraft: (agent, view, input, time, meta, entries) => this.#addDraft(agent, view, input, time, meta, entries),
1896 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
1897 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
1898 newsAboutOwnDraft: (agent, entries) => this.#newsAboutOwnDraft(agent, entries),
1899 takeNews: (agent, entries) => this.#takeNews(agent, entries),
1900 flush: (entries) => this.#flush(entries),
1901 };
1902 return this.#moves;
1903 }
1905 #switches?: SwitchHost;
1906 get #switchHost(): SwitchHost {
1907 this.#switches ??= {
1908 agent: (name, entries) => this.#agent(name, entries),
1909 flush: (entries) => this.#flush(entries),
1910 spaces: this.#spaces,
1911 agentView: (agent) => this.#agentView(agent),
1912 graph: this.#graph,
1913 version: () => this.version,
1914 apply: (entry) => this.#apply(entry),
1915 draft: (agent) => this.#draft(agent),
1916 setOf: (space) => this.#setOf(space),
1917 changesSince: (agent, before) => this.#changesSince(agent, before),
1918 };
1919 return this.#switches;
1920 }
1922 #draftStates?: DraftStateHost;
1923 get #draftStateHost(): DraftStateHost {
1924 this.#draftStates ??= {
1925 needInit: () => this.#needInit(),
1926 spaceNamed: (name) => this.#spaceNamed(name),
1927 shared: () => this.#shared,
1928 graph: this.#graph,
1929 agents: this.#agents,
1930 draft: (agent) => this.#draft(agent),
1931 checkClash: (changes) => this.#checkClash(changes),
1932 landCollisions: (space, changes, pick) => this.#landCollisions(space, changes, pick),
1933 };
1934 return this.#draftStates;
1935 }
1937 #checkClashes?: CheckClashHost;
1938 get #checkClashHost(): CheckClashHost {
1939 this.#checkClashes ??= {
1940 shared: () => this.#shared,
1941 view: (set) => this.#view(set),
1942 sharedView: () => this.#sharedView(),
1943 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
1944 };
1945 return this.#checkClashes;
1946 }
1948 #changesSinces?: ChangesSinceHost;
1949 get #changesSinceHost(): ChangesSinceHost {
1950 this.#changesSinces ??= {
1951 agentView: (agent) => this.#agentView(agent),
1952 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
1953 openPairs: (agent) => this.#openPairs(agent),
1954 collision: (agent, pair) => this.#collision(agent, pair),
1955 duplicates: (agent) => this.#duplicates(agent),
1956 markedCollisions: (agent) => this.#markedCollisions(agent),
1957 };
1958 return this.#changesSinces;
1959 }
1961 #inits?: InitHost;
1962 get #initHost(): InitHost {
1963 this.#inits ??= {
1964 initialized: () => this.initialized,
1965 whole: this.#whole,
1966 wholeOut: (files, blobs, view, config) => this.#wholeOut(files, blobs, view, config),
1967 checkBlobs: (blobs, files) => this.#checkBlobs(blobs, files),
1968 commit: (entries) => this.#commit(entries),
1969 };
1970 return this.#inits;
1971 }
1973 #amends?: AmendHost;
1974 get #amendHost(): AmendHost {
1975 this.#amends ??= {
1976 agent: (name, entries) => this.#agent(name, entries),
1977 spaceOf: (agent) => this.#spaceOf(agent),
1978 apply: (entry) => this.#apply(entry),
1979 flush: (entries) => this.#flush(entries),
1980 };
1981 return this.#amends;
1982 }
1984 #labelHosts?: LabelHost;
1985 get #labelHost(): LabelHost {
1986 this.#labelHosts ??= {
1987 agent: (name, entries) => this.#agent(name, entries),
1988 version: () => this.version,
1989 labels: this.#labels,
1990 apply: (entry) => this.#apply(entry),
1991 flush: (entries) => this.#flush(entries),
1992 };
1993 return this.#labelHosts;
1994 }
1996 #publishOfs?: PublishOfHost;
1997 get #publishOfHost(): PublishOfHost {
1998 this.#publishOfs ??= {
1999 shared: () => this.#shared,
2000 spaces: this.#spaces,
2001 };
2002 return this.#publishOfs;
2003 }
2005 #versionMetas?: VersionMetaHost;
2006 get #versionMetaHost(): VersionMetaHost {
2007 this.#versionMetas ??= {
2008 needInit: () => this.#needInit(),
2009 spaceNamed: (name) => this.#spaceNamed(name),
2010 };
2011 return this.#versionMetas;
2012 }
2014 #refuses?: RefuseHost;
2015 get #refuseHost(): RefuseHost {
2016 this.#refuses ??= {
2017 apply: (entry) => this.#apply(entry),
2018 refusals: this.#refusals,
2019 };
2020 return this.#refuses;
2021 }
2023 #overlapsHost?: OverlapHost;
2024 get #overlapHost(): OverlapHost {
2025 this.#overlapsHost ??= {
2026 graph: this.#graph,
2027 agents: this.#agents,
2028 agentView: (agent) => this.#agentView(agent),
2029 draft: (agent) => this.#draft(agent),
2030 draftFiles: (agent) => this.#draftFiles(agent),
2031 liveNote: (agent) => this.#liveNote(agent),
2032 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
2033 };
2034 return this.#overlapsHost;
2035 }
2037 #recordFiles?: RecordFileHost;
2038 get #recordFileHost(): RecordFileHost {
2039 this.#recordFiles ??= {
2040 addDraft: (agent, view, input, time, meta, entries) => this.#addDraft(agent, view, input, time, meta, entries),
2041 };
2042 return this.#recordFiles;
2043 }
2045 #addDrafts?: AddDraftHost;
2046 get #addDraftHost(): AddDraftHost {
2047 this.#addDrafts ??= {
2048 graph: this.#graph,
2049 openPairs: (agent) => this.#openPairs(agent),
2050 markersSettled: (agent, view, atom) => this.#markersSettled(agent, view, atom),
2051 apply: (entry) => this.#apply(entry),
2052 };
2053 return this.#addDrafts;
2054 }
2056 #ingests?: IngestHost;
2057 get #ingestHost(): IngestHost {
2058 this.#ingests ??= {
2059 agents: this.#agents,
2060 spaces: this.#spaces,
2061 needInit: () => this.#needInit(),
2062 version: () => this.version,
2063 checkBlobs: (blobs, files) => this.#checkBlobs(blobs, files),
2064 apply: (entry) => this.#apply(entry),
2065 flush: (entries) => this.#flush(entries),
2066 wholeOut: (files, blobs, view, config) => this.#wholeOut(files, blobs, view, config),
2067 agentView: (agent) => this.#agentView(agent),
2068 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
2069 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
2070 publish: (agent, message, time, entries, asIs, direct) =>
2071 this.#publish(agent, message, time, entries, asIs, direct),
2072 land: (agent, message, time, entries, pick) => this.#land(agent, message, time, entries, pick),
2073 };
2074 return this.#ingests;
2075 }
2077 #plucks?: PluckHost;
2078 get #pluckHost(): PluckHost {
2079 this.#plucks ??= {
2080 graph: this.#graph,
2081 spaces: this.#spaces,
2082 agent: (name, entries) => this.#agent(name, entries),
2083 shared: () => this.#shared,
2084 notQueuedYet: (what) => this.#notQueuedYet(what),
2085 strandedFiles: (draft, set) => this.#strandedFiles(draft, set),
2086 checkClash: (changes) => this.#checkClash(changes),
2087 land: (agent, message, time, entries, pick) => this.#land(agent, message, time, entries, pick),
2088 flush: (entries) => this.#flush(entries),
2089 };
2090 return this.#plucks;
2091 }
2093 #drops?: DropHost;
2094 get #dropHost(): DropHost {
2095 this.#drops ??= {
2096 graph: this.#graph,
2097 agents: this.#agents,
2098 spaces: this.#spaces,
2099 agent: (name, entries) => this.#agent(name, entries),
2100 shared: () => this.#shared,
2101 flush: (entries) => this.#flush(entries),
2102 apply: (entry) => this.#apply(entry),
2103 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
2104 addressedNews: (agent, version, entries) => this.#addressedNews(agent, version, entries),
2105 };
2106 return this.#drops;
2107 }
2109 // Changes (#44), in change-records.ts behind ChangeHost ---------------------------------------------
2111 #changeRecords?: ChangeHost;
2112 get #changeHost(): ChangeHost {
2113 this.#changeRecords ??= {
2114 changes: this.#changes,
2115 agents: this.#agents,
2116 spaces: this.#spaces,
2117 notes: this.#notes,
2118 versionChange: this.#versionChange,
2119 paths: this.#paths,
2120 graph: this.#graph,
2121 stored: () => this.#stored,
2122 shared: () => this.#shared,
2123 queue: () => this.#queue,
2124 active: (agent, time) => this.#active(agent, time),
2125 currentChange: (agent, time) => this.#currentChange(agent, time),
2126 liveNote: (agent) => this.#liveNote(agent),
2127 noteAnswer: (n) => this.#noteAnswer(n),
2128 reviewersOf: (files, id) => this.#reviewersOf(files, id),
2129 };
2130 return this.#changeRecords;
2131 }
2133 // What the project looks like now, in project-status.ts behind SnapshotHost -------------------------
2135 #snapshotHost?: SnapshotHost;
2136 get #snapshot(): SnapshotHost {
2137 this.#snapshotHost ??= {
2138 agents: this.#agents,
2139 spaces: this.#spaces,
2140 queue: () => this.#queue,
2141 refusals: this.#refusals,
2142 labels: this.#labels,
2143 tells: this.#tells,
2144 needInit: () => this.#needInit(),
2145 shared: () => this.#shared,
2146 draft: (agent) => this.#draft(agent),
2147 draftFiles: (agent) => this.#draftFiles(agent),
2148 liveNote: (agent) => this.#liveNote(agent),
2149 openCollisions: (agent) => this.#openCollisions(agent),
2150 editsOf: (agent) => this.#editsOf(agent),
2151 setOf: (space) => this.#setOf(space),
2152 spaceNamed: (name) => this.#spaceNamed(name),
2153 checkVersion: (space, version) => this.#checkVersion(space, version),
2154 viewAt: (space, version) => this.#viewAt(space, version),
2155 agentView: (agent) => this.#agentView(agent),
2156 version: () => this.version,
2157 projectFile: () => (this.initialized ? projectFileIn(this.#sharedView()) : undefined),
2158 };
2159 return this.#snapshotHost;
2160 }
2162 /** The paths in an agent's view now (project-status.ts). */
2163 agentPaths(...args: Tail<Parameters<typeof snapshotAgentPaths>>): ReturnType<typeof snapshotAgentPaths> {
2164 return snapshotAgentPaths(this.#snapshot, ...args);
2165 }
2167 /** The paths in shared, or a named draft, at a version (project-status.ts). */
2168 pathsAt(...args: Tail<Parameters<typeof snapshotPathsAt>>): ReturnType<typeof snapshotPathsAt> {
2169 return snapshotPathsAt(this.#snapshot, ...args);
2170 }
2172 /** The paths in an agent's view now, for a reader (project-status.ts). */
2173 pathsOf(...args: Tail<Parameters<typeof snapshotPathsOf>>): ReturnType<typeof snapshotPathsOf> {
2174 return snapshotPathsOf(this.#snapshot, ...args);
2175 }
2177 /** Every label, with the versions it marks, newest first (project-status.ts). */
2178 labels(): ReturnType<typeof snapshotLabels> {
2179 return snapshotLabels(this.#snapshot);
2180 }
2182 /** Agents, drafts, refusals and waiting announcements (project-status.ts). */
2183 status(): ReturnType<typeof snapshotStatus> {
2184 return snapshotStatus(this.#snapshot);
2185 }
2187 /** A space's contents at one of its versions. */
2188 #at(space: Space, version: number): ReadonlySet<AtomId> {
2189 return this.#membership.at(space, version);
2190 }
2192 /** A space's contents now. */
2193 #setOf(space: Space): ReadonlySet<AtomId> {
2194 return this.#at(space, last(space));
2195 }
2197 #draft(agent: AgentState): AtomId[] {
2198 const set = this.#setOf(this.#spaceOf(agent));
2199 return agent.mine.filter((id) => !set.has(id));
2200 }
2202 /**
2203 * The draft without the agent's publishes waiting in the queue (#39): what
2204 * moves, restore and sync's merge may drop and make again. A queued item's
2205 * atoms are no longer the draft's to remake; dropping them let the queue
2206 * land a tie that depends on discarded atoms (abso issue 135, item 4).
2207 * Undoing a queued publish is abso unqueue.
2208 */
2209 #unqueuedDraft(agent: AgentState): AtomId[] {
2210 const draft = this.#draft(agent);
2211 const held = this.#queuedAtoms();
2212 return held.size === 0 ? draft : draft.filter((id) => !held.has(id));
2213 }
2215 #agentSet(agent: AgentState): Set<AtomId> {
2216 return new Set([...this.#at(this.#spaceOf(agent), agent.base), ...agent.mine]);
2217 }
2219 #agentView(agent: AgentState): View {
2220 return this.#viewKeyed(this.#agentViewKey(agent), () => this.#agentSet(agent));
2221 }
2223 /** An agent's view, keyed by what the set is made of, not by sorting every atom in it (#46): that cost more than the work. */
2224 #agentViewKey(agent: AgentState): string {
2225 return `a ${agent.space}@${agent.base}+${agent.mine.join(",")}`;
2226 }
2228 /** A space at a version: published versions never change, so the key is just their names (#46). */
2229 #viewAt(space: Space, version: number): View {
2230 return this.#viewKeyed(`v ${space.name}@${version}`, () => this.#at(space, version));
2231 }
2233 #sharedView(): View {
2234 return this.#viewAt(this.#shared, last(this.#shared));
2235 }
2237 /** A view of a set, cached by the set's exact contents (views.ts). */
2238 #view(set: ReadonlySet<AtomId>): View {
2239 return this.#views.view(this.#closed(set));
2240 }
2242 /** A view cached under `key` (views.ts). */
2243 #viewKeyed(key: string, set: () => ReadonlySet<AtomId>): View {
2244 return this.#views.keyed(key, () => this.#closed(set()));
2245 }
2247 /**
2248 * A discarded atom that a later publish still depends on stays in the view
2249 * (abso issue 80). A closed set is unchanged.
2250 */
2251 #closed(set: Iterable<AtomId>): Set<AtomId> {
2252 return this.#graph.closureOf(set);
2253 }
2255 /** A new publish or land must not depend on an atom outside the set (abso issue 80). */
2256 #requireClosed(tie: { deps: readonly AtomId[] }, union: ReadonlySet<AtomId>): void {
2257 const missing = tie.deps.filter((id) => !union.has(id));
2258 if (missing.length > 0)
2259 throw new ProjectError(
2260 "conflict",
2261 `this change depends on ${missing.join(", ")}, which is not in the set being published`,
2262 );
2263 }
2265 /** The space's atoms published after the agent's base, by others. */
2266 #newerFor(agent: AgentState): Set<AtomId> {
2267 const space = this.#spaceOf(agent);
2268 const base = this.#at(space, agent.base);
2269 const mine = new Set(agent.mine);
2270 return new Set([...this.#setOf(space)].filter((id) => !base.has(id) && !mine.has(id)));
2271 }
2273 /** The files whose text in the agent's view differs from `before`, and its open collisions. */
2274 #changesSince(...args: Tail<Parameters<typeof hostedChangesSince>>): ReturnType<typeof hostedChangesSince> {
2275 return hostedChangesSince(this.#changesSinceHost, ...args);
2276 }
2278 /** Who published an atom, looking in the given space first and then in shared. */
2279 #origin(atom: AtomId, spaceName: string): Origin {
2280 return originOf(this.#collisionHost, atom, spaceName);
2281 }
2283 // Drafting ----------------------------------------------------------------------
2285 /** Check a {path: sha256} map: hex hashes, no path also given as text, and bytes already uploaded. */
2286 #checkBlobs(blobs: unknown, files: object): Record<string, string> {
2287 if (typeof blobs !== "object" || blobs === null || Array.isArray(blobs))
2288 throw new ProjectError("bad-request", "blobs must be {path: sha256}");
2289 for (const [path, sha] of Object.entries(blobs as Record<string, unknown>)) {
2290 checkPath(path);
2291 if (typeof sha !== "string" || !/^[0-9a-f]{64}$/.test(sha))
2292 throw new ProjectError("bad-request", `${path}: a blob is the SHA-256 of the bytes, in lowercase hex`);
2293 if (Object.hasOwn(files, path)) throw new ProjectError("bad-request", `${path} is given as both text and a blob`);
2294 if (!this.#hasBlob(sha))
2295 throw new ProjectError("bad-request", `${path}: upload blob ${sha} first (PUT /p/:project/blobs/${sha})`);
2296 }
2297 return blobs as Record<string, string>;
2298 }
2300 /**
2301 * Make one file in the agent's view what the folder has, as one draft
2302 * change: `text` (null: the file is gone; "": an empty file; undefined:
2303 * leave its lines alone) and `mode` (only the fields given). Returns
2304 * whether anything changed.
2305 */
2306 #recordFile(...args: Tail<Parameters<typeof hostedRecordFile>>): ReturnType<typeof hostedRecordFile> {
2307 return hostedRecordFile(this.#recordFileHost, ...args);
2308 }
2310 /**
2311 * Moves (#28). Within one agent's unpublished draft, a line that leaves one
2312 * place and the same text that arrives somewhere else is the same line, in
2313 * either order (deleted then written, or written then deleted). Before a
2314 * publish, the draft's changes to the files involved are dropped (a discard
2315 * entry) and made again: one move per matched block, which keeps the
2316 * lines' ids, then a change per file to the draft's final text. The files
2317 * end up exactly as the draft had them. A matched block needs a line with
2318 * real content: blank lines and lone brackets only travel next to one.
2319 */
2320 #expressMoves(agent: AgentState, time: number, entries: Entry[]): void {
2321 hostedExpressMoves(this.#expressMovesHost, agent, time, entries);
2322 }
2324 /**
2325 * Build a draft change against the agent's view. If it touches lines on
2326 * either side of a collision the agent has already seen, it settles that
2327 * collision (the engine's `resolves`).
2328 */
2329 #addDraft(...args: Tail<Parameters<typeof hostedAddDraft>>): ReturnType<typeof hostedAddDraft> {
2330 return hostedAddDraft(this.#addDraftHost, ...args);
2331 }
2333 // Collisions and news -------------------------------------------------------------
2335 #pairs(draft: readonly AtomId[], against: ReadonlySet<AtomId>, settled: ReadonlySet<AtomId>): Pair[] {
2336 return pairsIn(this.#graph, draft, against, settled);
2337 }
2339 /**
2340 * Collisions the agent has synced into and not settled: its draft against
2341 * its space at its base. In a named draft, also the draft's own changes
2342 * against shared work the draft was moved onto.
2343 */
2344 #openPairs(agent: AgentState): Pair[] {
2345 return hostedOpenPairs(this.#collisionHost, agent);
2346 }
2348 /** After the agent's own change: news when its draft now collides with work published after its base. */
2349 #newsAboutOwnDraft(agent: AgentState, entries: Entry[]): void {
2350 hostedNewsAboutOwnDraft(this.#newsHost, agent, entries);
2351 }
2353 /** After a publish or a landing: news for every other agent in that space whose draft collides with what just arrived. */
2354 #newsForOthers(publisher: AgentState, space: Space, version: number, entries: Entry[]): void {
2355 hostedNewsForOthers(this.#newsHost, publisher, space, version, entries);
2356 }
2358 #queueNews(agent: AgentState, items: readonly { key: string; text: string }[], entries: Entry[]): void {
2359 const fresh = items.filter((p) => !agent.told.has(p.key));
2360 if (fresh.length === 0) return;
2361 const text = [...new Set(fresh.map((p) => p.text))];
2362 const entry: Entry = { type: "news", agent: agent.name, pairs: [...new Set(fresh.map((p) => p.key))], text };
2363 entries.push(entry);
2364 this.#apply(entry);
2365 }
2367 #takeNews(agent: AgentState, entries: Entry[]): string[] {
2368 if (agent.news.length === 0) return [];
2369 const news = [...agent.news];
2370 const entry: Entry = { type: "heard", agent: agent.name };
2371 entries.push(entry);
2372 this.#apply(entry);
2373 return news;
2374 }
2376 /** Describe a pair for the agent: its side in its own view, theirs in its space now. */
2377 #collision(agent: AgentState, pair: Pair): Collision {
2378 return this.#describe(
2379 pair,
2380 this.#agentView(agent),
2381 this.#viewAt(this.#spaceOf(agent), last(this.#spaceOf(agent))),
2382 agent.space,
2383 );
2384 }
2386 #describe(pair: Pair, yoursView: View, theirsView: View, spaceName: string): Collision {
2387 return describePair(
2388 this.#graph,
2389 (atom, space) => this.#origin(atom, space),
2390 pair,
2391 yoursView,
2392 theirsView,
2393 spaceName,
2394 );
2395 }
2397 #touchedFiles(ids: Iterable<AtomId>, views: readonly View[]): Set<string> {
2398 return touchedFiles(this.#graph, ids, views);
2399 }
2401 // The changed-definition rule (#11) -------------------------------------------
2403 /** The rule for an agent's draft in its space. */
2404 #definitionCollisions(agent: AgentState, newer: ReadonlySet<AtomId>): DefinitionCollision[] {
2405 const draft = new Set(this.#draft(agent));
2406 if (draft.size === 0 || newer.size === 0) return [];
2407 const space = this.#spaceOf(agent);
2408 const mine = new Set(agent.mine);
2409 const base = this.#view(new Set([...this.#at(space, agent.base)].filter((id) => !mine.has(id))));
2410 return this.#definitionRule.collisions(
2411 draft,
2412 this.#agentView(agent),
2413 base,
2414 this.#viewAt(space, last(space)),
2415 newer,
2416 space.name,
2417 );
2418 }
2419}
2421export { EngineError };