Skip to content

abso-core

Public

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

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