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

Versions 41 to 318

Compare

+899 −78 in 55 places
Lines 15–47 at 318 (were 15–32 at 41)
1515import {
1616 type Atom,
1717 type AtomId,
18− type ConflictKey,
19− conflictKeys,
20− type EditInput,
2118 EngineError,
2219 Graph,
2320 type LineId,
24− type MoveInput,
25− type View,
21+ type ReadView,
22+ View,
2623} from "../../src/engine/index.ts";
24+import {
25+ CachedStateStorage,
26+ differenceSet,
27+ type GraphStateStorage,
28+ isClosedSet,
29+ markClosed,
30+ StableOverlaySet,
31+ StableSet,
32+ StableUnionSet,
33+ StoredMap,
34+ storedArray,
35+ unionOverlay,
36+} from "../../src/engine/state-source.ts";
2737import { type AddDraftHost, addDraft as hostedAddDraft } from "./add-draft.ts";
2838import { type AmendHost, amend as hostedAmend } from "./amend.ts";
29−import { type AnnounceHost, announce as hostedAnnounce, announcePerson as hostedAnnouncePerson } from "./announce.ts";
39+import {
40+ type AnnounceHost,
41+ announce as hostedAnnounce,
42+ announcePerson as hostedAnnouncePerson,
43+ seatNotice as hostedSeatNotice,
44+} from "./announce.ts";
3045import { type ApplyEntryHost, applyEntry as hostedApplyEntry } from "./apply-entry.ts";
3146import {
3247 type ChangeHost,
Lines 63–69 at 318 (were 48–53 at 41)
4863 type Pair,
4964 pairsIn,
5065 strandedFiles,
66+ touchedBeyond,
5167 touchedFiles,
5268} from "./collisions.ts";
5369import { type DefinitionCollision, DefinitionRule } from "./definition-rule.ts";
Lines 81–87 at 318 (were 65–70 at 41)
6581} from "./history.ts";
6682import { ingest as hostedIngest, type IngestHost } from "./ingest.ts";
6783import { init as hostedInit, type InitHost } from "./init.ts";
84+import { KeptParts } from "./kept-parts.ts";
6885import { label as hostedLabel, type LabelHost } from "./label.ts";
6986import {
7087 land as hostedLand,
Lines 105–117 at 318 (were 88–96 at 41)
88105 addressedItem,
89106 newsAboutOwnDraft as hostedNewsAboutOwnDraft,
90107 newsForOthers as hostedNewsForOthers,
108+ newsOwed as hostedNewsOwed,
109+ owedAgents as hostedOwedAgents,
110+ owedNewsNames as hostedOwedNewsNames,
91111 markedItem,
92112 type NewsHost,
93113 type NewsItem,
114+ type OwedDefinitionNews,
94115 reviewItem,
95116 settledItem,
96117} from "./news.ts";
Lines 119–124 at 318 (were 98–104 at 41)
98119 closeNote as hostedCloseNote,
99120 noteAnswer as hostedNoteAnswer,
100121 notes as hostedNotes,
101− noteView as hostedNoteView,
102122 startingNotes as hostedStartingNotes,
103123 writeNote as hostedWriteNote,
104124 type NoteHost,
Lines 160–167 at 318 (were 140–148 at 41)
140160 Entry,
141161 LandAnswer,
142162 MergedLine,
143− Meta,
144− Mode,
145163 Modes,
164+ NewsWritten,
146165 NoteAnswer,
147166 NoteBody,
148167 NoteRecord,
Lines 174–179 at 318 (were 155–161 at 41)
155174 Refusal,
156175 Settled,
157176 Starting,
158− SwitchAnswer,
159177 Tail,
160178 TellRecord,
161179} from "./project-types.ts";
Lines 196–228 at 318 (were 178–192 at 41)
178196import { recordFile as hostedRecordFile, type RecordFileHost } from "./record-file.ts";
179197import { refusals as hostedRefusals, refuse as hostedRefuse, type RefuseHost } from "./refuse.ts";
180198import { restore as hostedRestore, type RestoreHost } from "./restore.ts";
181−import { addVersion, last, Membership, newSpace, type Published, SHARED, type Space, sharedBaseOf } from "./spaces.ts";
199+import {
200+ closureChangedAt,
201+ indexClosure,
202+ last,
203+ Membership,
204+ SHARED,
205+ SharedAdditions,
206+ type Space,
207+ sharedBaseOf,
208+} from "./spaces.ts";
182209import { starting as hostedStarting, type StartingHost } from "./start.ts";
183210import { switchTo as hostedSwitchTo, type SwitchHost } from "./switch-to.ts";
184211import { sync as hostedSync, type SyncHost } from "./sync.ts";
185212import { treeHash } from "./tree.ts";
186213import {
214+ authoredVersion,
215+ authorTotalsAt,
216+ type FileTotals,
217+ versionFiles as keptVersionFiles,
218+ type VersionFilesHost,
219+} from "./version-files.ts";
220+import {
187221 type LogHost,
188222 compare as versionCompare,
223+ compareSummary as versionCompareSummary,
189224 fileAt as versionFileAt,
225+ fileExactAt as versionFileExactAt,
190226 log as versionLog,
191227 ribbon as versionRibbon,
192228 show as versionShow,
Lines 242–249 at 318 (were 206–211 at 41)
206242 wholeRules as hostedWholeRules,
207243 type WholeHost,
208244} from "./whole-files.ts";
245+import { without as hostedWithout, type WithoutHost } from "./without.ts";
246+import { WriterAgents } from "./writer-agents.ts";
209247
210248export { MemoryStore } from "./memory-store.ts";
211249export { checkReadPath, pathProblem } from "./path-rules.ts";
Lines 257–312 at 318 (were 219–230 at 41)
219257
220258/** A start note lasts this long after the agent's last activity (#44). */
221259const NOTE_IDLE = 2 * 60 * 60 * 1000;
260+const WRITER_REOPEN = Symbol("verified writer checkpoint");
261+/**
262+ * The stored writer's read cache (abso Capacity). An agent's diff on typescript-rs touches more rows than the old
263+ * 4,096 held, so it read many of them again: 59,000 reads cold, against 22,000 at this size.
264+ */
265+const WRITER_CACHE_BYTES = 4 * 1_048_576;
266+const WRITER_CACHE_ROWS = 16_384;
267+/** The biggest row the writer cache keeps (abso Capacity): an agent and all the news it was told can be 100 KB. */
268+const WRITER_CACHE_ROW_BYTES = 16_384;
269+/** Old-form agent rows moved to told buckets at each write (abso Capacity): abso's 109 take about 28 writes. */
270+const OLD_TOLD_PER_WRITE = 4;
271+export interface WriterSource {
272+ readonly generation: number;
273+ readonly logLength: number;
274+ readonly sharedVersion: number;
275+}
276+interface WriterAdoption {
277+ source: WriterSource;
278+ next: number;
279+ ready: boolean;
280+}
222281
282+/** A decoded entry is supplied by a host that binds its bytes to canonical authority. */
283+export type WriterAdoptionFrame = { seq: number; json: string } | { seq: number; bytes: number; entry: Entry };
284+function adoptionFrameBytes(frame: WriterAdoptionFrame): number {
285+ return "json" in frame
286+ ? typeof frame.json === "string"
287+ ? new TextEncoder().encode(frame.json).byteLength
288+ : NaN
289+ : frame.bytes;
290+}
291+function adoptionFrameEntry(frame: WriterAdoptionFrame): Entry {
292+ return "json" in frame ? (JSON.parse(frame.json) as Entry) : frame.entry;
293+}
295+/** Where a view and its base place moved lines differently (View.placedDifferently), when both are Views. */
296+function placedBetween(view: ReadView, base: ReadView): ReadonlySet<string> | undefined {
297+ return view instanceof View && base instanceof View ? view.placedDifferently(base) : undefined;
298+}
223300export class Project {
224301 readonly #store: ProjectStore;
302+ readonly #writerStorage?: GraphStateStorage;
225303 readonly #graph: Graph;
226304 /** Views laid out from atom sets, cached under a byte budget (views.ts). */
227305 readonly #views: ViewCache;
306+ /** What draft collisions keep between calls, under its own byte budget (kept-parts.ts). */
307+ #keptParts: KeptParts | undefined;
308+ /** Each agent's draft files, under the key they were worked out for (#draftFiles). */
309+ readonly #draftFilesKept = new Map<string, { key: string; files: Set<string> }>();
228310 /** Each version's files and each path's history (pathindex.ts). */
229311 readonly #paths: PathIndex;
230312 /** For each atom (by seq) that wrote lines, the log position of the entry that recorded it (#46). */
Lines 335–410 at 318 (were 253–284 at 41)
253335 * doesn't depend on it.
254336 */
255337 checkerReady = false;
338+ /**
339+ * Owed news (abso Capacity, 2026-10-15): a publish's definition news for other agents is left for after its write
340+ * (takeOwedDefinitionNews, definitionNewsOwed, deliverOwedNews). The disk route sets it; the replay engine doesn't.
341+ */
342+ owesDefinitionNews = false;
343+ #owed: OwedDefinitionNews[] = [];
256344 readonly #now: (() => number) | undefined;
345+ readonly #newsWritten: ((items: readonly NewsWritten[]) => void) | undefined;
257346 readonly #whole: ProjectOptions["whole"];
258347 readonly #shapes: ProjectOptions["shapes"];
348+ readonly #logLine: ProjectOptions["logLine"];
259349 /** For each log position, the newest time up to it (#41): time to position in one search. */
260350 readonly #timeAt: number[] = [];
261351 /** For each version of shared, the log position of the entry that made it (#41). */
262352 readonly #versionAt: number[] = [];
263353 /** The newest time any applied entry carries: the clock when none was given. */
264− #lastTime = 0;
354+ #lastTimeMemory = 0;
355+ get #lastTime(): number {
356+ return this.#writerStorage
357+ ? ((this.#writerStorage.read("project:meta", "lastTime") as number | undefined) ?? 0)
358+ : this.#lastTimeMemory;
359+ }
360+ set #lastTime(value: number) {
361+ if (this.#writerStorage) this.#writerStorage.write("project:meta", "lastTime", value);
362+ else this.#lastTimeMemory = value;
363+ }
265364 /** Every change (#44), by id. */
266365 readonly #changes = new Map<number, ChangeRecord>();
267366 /** Each version's change, by "<draft or ''> <version>" (#44): what a note on its lines belongs to. */
268367 readonly #versionChange = new Map<string, number>();
269368 /** Every note (#44), by id. */
270369 readonly #notes = new Map<number, NoteRecord>();
271− /** Mod versions (X-Avcs-Client) in the order they first sent an edit (#41): the last is taken as the installed one. */
370+ /** Mod versions (X-Abso-Client) in the order they first sent an edit (#41): the last is taken as the installed one. */
272371 #mods: string[] = [];
273372 /** The merge queue (#39), in order: publishes to shared waiting for their batch's check. */
274373 #queue: QueuedPublish[] = [];
275374 /** The newest note's id (#44). */
276− #lastNote = 0;
277− #queuedId = 0;
375+ #lastNoteMemory = 0;
376+ get #lastNote(): number {
377+ return this.#writerStorage
378+ ? ((this.#writerStorage.read("project:meta", "lastNote") as number | undefined) ?? 0)
379+ : this.#lastNoteMemory;
380+ }
381+ set #lastNote(value: number) {
382+ if (this.#writerStorage) this.#writerStorage.write("project:meta", "lastNote", value);
383+ else this.#lastNoteMemory = value;
384+ }
385+ #queuedIdMemory = 0;
386+ get #queuedId(): number {
387+ return this.#writerStorage
388+ ? ((this.#writerStorage.read("project:meta", "queuedId") as number | undefined) ?? 0)
389+ : this.#queuedIdMemory;
390+ }
391+ set #queuedId(value: number) {
392+ if (this.#writerStorage) this.#writerStorage.write("project:meta", "queuedId", value);
393+ else this.#queuedIdMemory = value;
394+ }
278395 /** Queued ids in the batch being checked now: not in the log, only for refusing an unqueue mid-check. */
279396 #checking = new Set<number>();
280397 /** How many entries the store holds: the log position of the next one (#41, the website's feed and replay). */
281− #stored = 0;
398+ #storedMemory = 0;
399+ get #stored(): number {
400+ return this.#writerStorage
401+ ? ((this.#writerStorage.read("project:meta", "stored") as number | undefined) ?? 0)
402+ : this.#storedMemory;
403+ }
404+ set #stored(value: number) {
405+ if (this.#writerStorage) this.#writerStorage.write("project:meta", "stored", value);
406+ else this.#storedMemory = value;
407+ }
282408 /** Names on the lines a change replaced, by "<atom> <last replaced line>" (atoms never change). */
283409 #rule?: DefinitionRule;
284410 get #definitionRule(): DefinitionRule {
Lines 412–474 at 318 (were 286–302 at 41)
286412 return this.#rule;
287413 }
288414 /** The newest announcement's id (announcements are news entries keyed "announce <id>"). */
289− #announced = 0;
415+ #announcedMemory = 0;
416+ get #announced(): number {
417+ return this.#writerStorage
418+ ? ((this.#writerStorage.read("project:meta", "announced") as number | undefined) ?? 0)
419+ : this.#announcedMemory;
420+ }
421+ set #announced(value: number) {
422+ if (this.#writerStorage) this.#writerStorage.write("project:meta", "announced", value);
423+ else this.#announcedMemory = value;
424+ }
290425 #loading = false;
291426
292427 readonly #hasBlob: (sha256: string) => boolean;
293428
294− constructor(store: ProjectStore, options: ProjectOptions = {}) {
429+ constructor(store: ProjectStore, options: ProjectOptions = {}, checkpoint?: typeof WRITER_REOPEN) {
430+ if (options.indexAcceptedAtom && !options.writerStorage)
431+ throw Error("accepted atom indexing requires writer storage");
295432 this.#store = store;
433+ this.#writerStorage = options.writerStorage
434+ ? new CachedStateStorage(options.writerStorage, WRITER_CACHE_BYTES, WRITER_CACHE_ROWS, WRITER_CACHE_ROW_BYTES)
435+ : undefined;
436+ if (this.#writerStorage) {
437+ const storage = this.#writerStorage;
438+ // A stored Graph cannot be replayed over itself. Check before any
439+ // constructor writes so an accidental reopen preserves the namespace.
440+ if (
441+ checkpoint !== WRITER_REOPEN &&
442+ ((storage.read("atoms:meta", "length") as number | undefined) ||
443+ (storage.read('membership:"":versions:meta', "length") as number | undefined))
444+ )
445+ throw new Error("writer indexes already contain history; Project checkpoint reopen is required");
446+ this.#membership = new Membership(storage);
447+ this.#atomAt = storedArray(storage, "project:atom-at");
448+ this.#timeAt = storedArray(storage, "project:time-at");
449+ this.#versionAt = storedArray(storage, "project:version-at");
450+ this.#notes = new StoredMap(storage, "project:notes");
451+ this.#changes = new StoredMap(storage, "project:changes");
452+ this.#labels = new StoredMap(storage, "project:labels");
453+ this.#versionChange = new StoredMap(storage, "project:version-change");
454+ this.#refusals = storedArray(storage, "project:refusals");
455+ this.#agents = new WriterAgents(storage);
456+ if (checkpoint === WRITER_REOPEN) {
457+ this.#mods = storage.read("project:meta", "mods") as string[];
458+ this.#queue = storage.read("project:meta", "queue") as QueuedPublish[];
459+ const tells = storage.read("project:meta", "tells") as [
460+ number,
461+ Omit<TellRecord, "heard"> & { heard: [string, { at: number | undefined } | null][] },
462+ ][];
463+ this.#tells = new Map(tells.map(([id, tell]) => [id, { ...tell, heard: new Map(tell.heard) }]));
464+ }
465+ }
296466 this.#hasBlob = options.hasBlob ?? (() => false);
297467 this.#now = options.now;
468+ this.#newsWritten = options.newsWritten;
298469 this.#whole = options.whole;
299470 this.#shapes = options.shapes;
471+ this.#logLine = options.logLine;
300472 // For tests (#46): AVCS_TEXT_FROM_LOG=1 runs a project on a MemoryStore with its text read back from the store.
301473 const testing =
302474 (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env?.AVCS_TEXT_FROM_LOG ===
Lines 486–497 at 318 (were 314–323 at 41)
314486 throw new Error(`log entry ${at} holds no atom ${seq}`);
315487 };
316488 // Line text and each atom's deletes and claim keys stay in the log (#46), read back when asked for.
317− this.#graph = entryAt
318− ? new Graph({ texts: (seq) => stored(seq).inserts.map((r) => r.lines), lists: (seq) => stored(seq) })
319− : new Graph();
320− this.#views = new ViewCache(this.#graph);
489+ this.#graph = this.#writerStorage
490+ ? new Graph({ storage: this.#writerStorage, indexAcceptedAtom: options.indexAcceptedAtom })
491+ : entryAt
492+ ? new Graph({ texts: (seq) => stored(seq).inserts.map((r) => r.lines), lists: (seq) => stored(seq) })
493+ : new Graph();
494+ this.#views = new ViewCache(this.#graph, options.readViewProvider);
321495 this.#paths = new PathIndex({
322496 graph: this.#graph,
323497 at: (space, version) => this.#at(space, version),
Lines 517–776 at 318 (were 343–357 at 41)
343517 for (const entry of entries) {
344518 project.#apply(entry);
345519 project.#stored++;
520+ project.#persistMutable();
346521 }
347522 project.#loading = false;
523+ project.#writeCheckpoint();
348524 return project;
349525 }
350526
527+ /** Reopen committed writer indexes. The host supplies the authoritative canonical log length. */
528+ static openWriter(
529+ store: ProjectStore,
530+ storage: GraphStateStorage,
531+ logLength: number,
532+ options: Omit<ProjectOptions, "writerStorage"> = {},
533+ ): Project {
534+ const adoption = storage.read("project:meta", "adoption") as WriterAdoption | undefined;
535+ if (adoption && !adoption.ready) throw new Error("writer adoption is incomplete");
536+ return Project.#openWriter(store, storage, logLength, options);
537+ }
539+ static #openWriter(
540+ store: ProjectStore,
541+ storage: GraphStateStorage,
542+ logLength: number,
543+ options: Omit<ProjectOptions, "writerStorage">,
544+ ): Project {
545+ const checkpoint = storage.read("project:meta", "checkpoint") as
546+ | { format: number; logLength: number; atoms: number; version: number }
547+ | undefined;
548+ const length = (name: string) => (storage.read(`${name}:meta`, "length") as number | undefined) ?? 0;
549+ if (
550+ !Number.isSafeInteger(logLength) ||
551+ logLength < 1 ||
552+ checkpoint?.format !== 1 ||
553+ checkpoint.logLength !== logLength ||
554+ storage.read("project:meta", "stored") !== logLength ||
555+ length("project:time-at") !== logLength ||
556+ length("atoms") !== checkpoint.atoms ||
557+ length("project:atom-at") !== checkpoint.atoms ||
558+ length('membership:"":versions') !== checkpoint.version + 1 ||
559+ length("project:version-at") !== checkpoint.version + 1 ||
560+ !["mods", "queue", "tells"].every((key) => Array.isArray(storage.read("project:meta", key)))
561+ )
562+ throw new Error("writer checkpoint does not match the canonical log and indexes");
563+ return new Project(store, { ...options, writerStorage: storage }, WRITER_REOPEN);
564+ }
566+ /** Open a host-verified historical prefix. Its state must be immutable and
567+ * scoped to canonical authority; adoption readiness describes the live writer,
568+ * not whether this individual prefix has a complete checkpoint. */
569+ static openHistorical(
570+ storage: GraphStateStorage,
571+ logLength: number,
572+ scratch: GraphStateStorage,
573+ assertScope: () => void = () => {
574+ storage.read("project:meta", "checkpoint");
575+ },
576+ readViewProvider?: ProjectOptions["readViewProvider"],
577+ ): Project {
578+ const refuse = (): never => {
579+ throw new Error("historical project is read-only");
580+ };
581+ const selected = (collection: string) => {
582+ // Revalidate the historical scope even when accessing derived scratch.
583+ assertScope();
584+ return collection.startsWith("projection-scratch:") ? scratch : storage;
585+ };
586+ return Project.#openWriter(
587+ { append: refuse },
588+ {
589+ read: (collection, key) => selected(collection).read(collection, key),
590+ entries: (collection) => selected(collection).entries(collection),
591+ write: (collection, key, value) => {
592+ if (selected(collection) !== scratch) refuse();
593+ scratch.write(collection, key, value);
594+ },
595+ remove: (collection, key) => {
596+ if (selected(collection) !== scratch) refuse();
597+ scratch.remove(collection, key);
598+ },
599+ transaction: (body) => storage.transaction(() => scratch.transaction(body)),
600+ },
601+ logLength,
602+ { readViewProvider },
603+ );
604+ }
351606 /**
352− * Apply more stored entries to a copy loaded for reading (#41, replay):
353− * scrubbing forward applies only what's new. Never for the live project.
607+ * Derive one bounded page from the host's canonical frames. The host reads
608+ * those frames from its own log and revalidates the source inside this same
609+ * transaction. Partial adoption cannot be opened for normal operations.
354610 */
611+ static adoptWriterPage(
612+ storage: GraphStateStorage,
613+ input: {
614+ source: WriterSource;
615+ from: number;
616+ frames: Iterable<WriterAdoptionFrame>;
617+ maxEntries: number;
618+ maxBytes: number;
619+ /** The host supplies disk-backed decoded entries and verified byte counts. */
620+ decodedFrames?: boolean;
621+ currentSource(): WriterSource;
622+ /** Select the host's derived historical revision before applying a frame.
623+ * Each selected revision receives a complete Project checkpoint. */
624+ beginRevision?(logLength: number): void;
625+ },
626+ options: Omit<ProjectOptions, "writerStorage"> = {},
627+ ): { next: number; ready: boolean; entries: number; bytes: number } {
628+ const same = (a: WriterSource, b: WriterSource) =>
629+ a.generation === b.generation && a.logLength === b.logLength && a.sharedVersion === b.sharedVersion;
630+ if (
631+ ![input.source.generation, input.source.logLength, input.source.sharedVersion, input.from].every(
632+ (n) => Number.isSafeInteger(n) && n >= 0,
633+ ) ||
634+ input.source.logLength < 1 ||
635+ !Number.isSafeInteger(input.maxEntries) ||
636+ input.maxEntries < 1 ||
637+ input.maxEntries > 256 ||
638+ !Number.isSafeInteger(input.maxBytes) ||
639+ input.maxBytes < 1 ||
640+ (input.maxBytes > 8_000_000 && input.decodedFrames !== true)
641+ )
642+ throw new Error("invalid writer adoption bounds or source");
643+ return storage.transaction(() => {
644+ if (!same(input.currentSource(), input.source))
645+ throw new Error("canonical source changed before writer adoption");
646+ const previous = storage.read("project:meta", "adoption") as WriterAdoption | undefined;
647+ if (
648+ (previous && (!same(previous.source, input.source) || previous.ready || previous.next !== input.from)) ||
649+ (!previous && input.from !== 0)
650+ )
651+ throw new Error("writer adoption source or cursor does not match");
652+ const noAppend: ProjectStore = {
653+ append: () => {
654+ throw new Error("adoption must never append canonical history");
655+ },
656+ };
657+ const project = previous
658+ ? Project.#openWriter(noAppend, storage, input.from, options)
659+ : new Project(noAppend, { ...options, writerStorage: storage });
660+ project.#loading = true;
661+ let count = 0;
662+ let bytes = 0;
663+ for (const frame of input.frames) {
664+ if (input.decodedFrames && "json" in frame) throw new Error("decoded adoption requires decoded frames");
665+ const size = adoptionFrameBytes(frame);
666+ if (
667+ count >= input.maxEntries ||
668+ frame.seq !== input.from + count ||
669+ frame.seq >= input.source.logLength ||
670+ !Number.isSafeInteger(size) ||
671+ size < 1 ||
672+ size > input.maxBytes - bytes
673+ )
674+ throw new Error("writer adoption page exceeds bounds or has a noncontiguous frame");
675+ bytes += size;
676+ if (bytes > input.maxBytes) throw new Error("writer adoption page exceeds byte bound");
677+ input.beginRevision?.(frame.seq + 1);
678+ project.#apply(adoptionFrameEntry(frame));
679+ project.#stored++;
680+ project.#persistMutable();
681+ if (input.beginRevision) project.#writeCheckpoint();
682+ count++;
683+ }
684+ if (count === 0) throw new Error("writer adoption page must advance");
685+ project.#loading = false;
686+ const next = input.from + count;
687+ const ready = next === input.source.logLength;
688+ if (!same(input.currentSource(), input.source))
689+ throw new Error("canonical source changed during writer adoption");
690+ if (ready && project.version !== input.source.sharedVersion)
691+ throw new Error("adopted shared version differs from canonical source");
692+ project.#writeCheckpoint();
693+ storage.write("project:meta", "adoption", { source: input.source, next, ready } satisfies WriterAdoption);
694+ return { next, ready, entries: count, bytes };
695+ });
696+ }
698+ /**
699+ * Extend derived historical indexes from an already checkpointed prefix.
700+ * The host supplies only new canonical frames inside its commit transaction.
701+ */
702+ static extendHistoricalPage(
703+ storage: GraphStateStorage,
704+ input: {
705+ from: number;
706+ frames: Iterable<WriterAdoptionFrame>;
707+ maxEntries: number;
708+ maxBytes: number;
709+ /** The host supplies disk-backed decoded entries and verified byte counts. */
710+ decodedFrames?: boolean;
711+ beginRevision(logLength: number): void;
712+ /** Verify both the saved prefix and the new frames against canonical authority. */
713+ validateAuthority(): void;
714+ },
715+ ): { next: number; entries: number; bytes: number } {
716+ if (
717+ !Number.isSafeInteger(input.from) ||
718+ input.from < 1 ||
719+ !Number.isSafeInteger(input.maxEntries) ||
720+ input.maxEntries < 1 ||
721+ input.maxEntries > 256 ||
722+ !Number.isSafeInteger(input.maxBytes) ||
723+ input.maxBytes < 1 ||
724+ (input.maxBytes > 8_000_000 && input.decodedFrames !== true)
725+ )
726+ throw new Error("invalid historical extension bounds");
727+ const validate = () => {
728+ const result: unknown = input.validateAuthority();
729+ if (result && (typeof result === "object" || typeof result === "function") && "then" in result)
730+ throw new Error("historical authority must be synchronous");
731+ };
732+ return storage.transaction(() => {
733+ validate();
734+ const project = Project.#openWriter(
735+ {
736+ append: () => {
737+ throw new Error("history derivation cannot append canonical entries");
738+ },
739+ },
740+ storage,
741+ input.from,
742+ {},
743+ );
744+ project.#loading = true;
745+ let entries = 0,
746+ bytes = 0;
747+ for (const frame of input.frames) {
748+ if (input.decodedFrames && "json" in frame) throw new Error("decoded adoption requires decoded frames");
749+ const size = adoptionFrameBytes(frame);
750+ if (
751+ entries >= input.maxEntries ||
752+ frame.seq !== input.from + entries ||
753+ !Number.isSafeInteger(size) ||
754+ size < 1 ||
755+ size > input.maxBytes - bytes
756+ )
757+ throw new Error("historical extension exceeds bounds or is not contiguous");
758+ bytes += size;
759+ if (bytes > input.maxBytes) throw new Error("historical extension exceeds byte bound");
760+ input.beginRevision(frame.seq + 1);
761+ project.#apply(adoptionFrameEntry(frame));
762+ project.#stored++;
763+ project.#persistMutable();
764+ project.#writeCheckpoint();
765+ entries++;
766+ }
767+ if (!entries) throw new Error("historical extension must advance");
768+ validate();
769+ return { next: input.from + entries, entries, bytes };
770+ });
771+ }
773+ /** Apply more entries to a replay copy. Never for the live project. */
355774 catchUp(entries: Iterable<Entry>): void {
356775 this.#loading = true;
357776 try {
Lines 813–820 at 318 (were 394–401 at 41)
394813 return modesOf(this.#sharedView());
395814 }
396815
397− /** Shared as a View, for reading lines (blame, why). Don't hold on to it across calls. */
398− sharedView(): View {
816+ /** Shared as a ReadView, for reading lines (blame, why). Don't hold on to it across calls. */
817+ sharedView(): ReadView {
399818 return this.#sharedView();
400819 }
401820
Lines 823–843 at 318 (were 404–413 at 41)
404823 return [...this.#agents.keys()].sort();
405824 }
406825
407− /** An agent's unpublished changes, oldest first, and its view (its space at its base plus its changes). Read only. */
408− draftOf(agentName: string): { atoms: AtomId[]; view: View } | undefined {
826+ /**
827+ * An agent's unpublished changes, oldest first, and its view (its space at its base plus its changes). Read only.
828+ * The view is laid out on first use: where asks every agent, most have no changes, and a big project has more
829+ * agents than the view cache holds, so building every view cost each call about 0.7 s.
830+ */
831+ draftOf(agentName: string): { atoms: AtomId[]; readonly view: ReadView } | undefined {
409832 const agent = this.#agents.get(agentName);
410− return agent && { atoms: this.#draft(agent), view: this.#agentView(agent) };
833+ if (!agent) return undefined;
834+ const view = () => this.#agentView(agent);
835+ return {
836+ atoms: this.#draft(agent),
837+ get view() {
838+ return view();
839+ },
840+ };
411841 }
412842
413843 /** The shared version an atom was published in, or undefined while it's only in a draft. */
Lines 874–885 at 318 (were 444–449 at 41)
444874 return p && { agent: p.agent, message: p.message, time: p.time };
445875 }
446876
877+ /** The atoms a version of shared, or of a named draft, added to its space: what was pushed together (blame's trail). */
878+ versionAtoms(version: number, draft: string | null = null): readonly AtomId[] {
879+ const space = draft === null ? this.#shared : this.#spaces.get(draft);
880+ return space?.versions[version]?.atoms ?? [];
881+ }
447883 /** The graph, for reading (blame, history). Don't add to it. */
448884 get graph(): Graph {
449885 return this.#graph;
Lines 919–925 at 318 (were 483–489 at 41)
483919 }
484920
485921 /**
486− * How the agent's newest edit arrived (#41). The mod sends X-Avcs-Client
922+ * How the agent's newest edit arrived (#41). The mod sends X-Abso-Client
487923 * avcs-mod/<stamp>; the hook sends abso-cli/<version> (avcs-cli/ before #59) with the chat's
488924 * session; abso record and git pushes send no session. Edits stored before
489925 * the client was recorded have only the session: those count as the mod
Lines 970–976 at 318 (were 534–540 at 41)
534970 * last makes it one-way: a file kept whole stays whole while it exists,
535971 * even if it shrinks or the rule changes, so it never flips back and forth.
536972 */
537− #isWhole(path: string, length: number, view: View | undefined, rules: readonly string[]): boolean {
973+ #isWhole(path: string, length: number, view: ReadView | undefined, rules: readonly string[]): boolean {
538974 return hostedIsWhole(this.#wholeHost, path, length, view, rules);
539975 }
540976
Lines 978–984 at 318 (were 542–548 at 41)
542978 #wholeOut(
543979 files: Readonly<Record<string, string | null>>,
544980 blobs: Readonly<Record<string, string>>,
545− view: View | undefined,
981+ view: ReadView | undefined,
546982 config?: string,
547983 ): { files: Record<string, string | null>; blobs: Record<string, string> } {
548984 return hostedWholeOut(this.#wholeHost, files, blobs, view, config);
Lines 1107–1113 at 318 (were 671–676 at 41)
6711107
6721108 /** The project's reviewers per area (#44): avcs.json's `"review": [{"paths": [...], "reviewer": "..."}]` in shared. */
6731109 #reviewRules(): ReviewRule[] {
1110+ if (["abso.json", "avcs.json"].every((path) => this.#graph.startCodeOf(path) === undefined)) return [];
6741111 return reviewRulesIn(projectFileIn(this.#sharedView())?.text);
6751112 }
6761113
Lines 1175–1180 at 318 (were 738–753 at 41)
7381175 return author ? this.#currentChange(author, this.#now?.() ?? this.#lastTime) : undefined;
7391176 }
7401177
741− /**
742− * The view a note's lines live in (#44):
743− * shared once any were published there; else the named draft they were
744− * published into; else their author's draft, where it works now or where it
745− * parked it. Undefined when no space holds them any more (a discarded draft).
746− */
747− #noteView(n: NoteRecord): View | undefined {
748− return hostedNoteView(this.#notesHost, n);
749− }
750−
7511178 #noteAnswer(n: NoteRecord): NoteAnswer {
7521179 return hostedNoteAnswer(this.#notesHost, n);
7531180 }
Lines 1299–1305 at 318 (were 872–878 at 41)
8721299 */
8731300 #mergeIdentical(
8741301 agent: AgentState,
875− before: View,
1302+ before: ReadView,
8761303 oldBase: ReadonlySet<AtomId>,
8771304 oldVersion: number,
8781305 time: number,
Lines 1348–1396 at 318 (were 921–926 at 41)
9211348 return hostedAnnouncePerson(this.#announceHost, ...args);
9221349 }
9231350
1351+ /** The definition news the writes since the last call owe other agents, handed over once (news.ts). */
1352+ takeOwedDefinitionNews(): OwedDefinitionNews[] {
1353+ const owed = this.#owed;
1354+ this.#owed = [];
1355+ return owed;
1356+ }
1358+ /** What a publish owes, worked out against its version (news.ts newsOwed), for `only` these agents if given. Reads only. */
1359+ newsOwed(owed: OwedDefinitionNews, only?: readonly string[]): { agent: string; items: NewsItem[] }[] {
1360+ return hostedNewsOwed(this.#newsHost, owed, only);
1361+ }
1363+ /** newsOwed, under the name owed definition news had before abso 714. */
1364+ definitionNewsOwed(owed: OwedDefinitionNews, only?: readonly string[]): { agent: string; items: NewsItem[] }[] {
1365+ return this.newsOwed(owed, only);
1366+ }
1368+ /** The names a publish's definitions changed (news.ts owedNewsNames), worked out once for its owed news. Reads only. */
1369+ owedNewsNames(owed: OwedDefinitionNews): string[] {
1370+ return hostedOwedNewsNames(this.#newsHost, owed);
1371+ }
1373+ /** The agents a publish's owed news may be for (news.ts owedAgents). Reads only. */
1374+ owedAgents(owed: OwedDefinitionNews): string[] {
1375+ return hostedOwedAgents(this.#newsHost, owed);
1376+ }
1378+ /** Tells each agent its owed items, as queueNews does: what an agent was already told adds nothing. */
1379+ deliverOwedNews(found: readonly { agent: string; items: readonly NewsItem[] }[]): number {
1380+ const entries: Entry[] = [];
1381+ for (const { agent: name, items } of found) {
1382+ const agent = this.#agents.get(name);
1383+ if (agent) this.#queueNews(agent, items, entries);
1384+ }
1385+ this.#flush(entries);
1386+ return entries.length;
1387+ }
1389+ /** A seat's earlier chat hears that another chat just used the seat (announce.ts seatNotice). */
1390+ seatNotice(...args: Tail<Parameters<typeof hostedSeatNotice>>): ReturnType<typeof hostedSeatNotice> {
1391+ return hostedSeatNotice(this.#announceHost, ...args);
1392+ }
9241394 /**
9251395 * Say what the agent is starting on (#37, #13), before any edit lands:
9261396 * `text`, and the files it expects to change if it knows them. Nothing is
Lines 1429–1435 at 318 (were 959–965 at 41)
9591429 }
9601430
9611431 /** The collided changes behind each block whose marker lines `atom` deletes (#11). */
962− #markersSettled(agent: AgentState, view: View, atom: Atom): AtomId[] {
1432+ #markersSettled(agent: AgentState, view: ReadView, atom: Atom): AtomId[] {
9631433 return hostedMarkersSettled(this.#markerHost, agent, view, atom);
9641434 }
9651435
Lines 1462–1481 at 318 (were 992–1000 at 41)
9921462 }
9931463 }
9941464
995− /** The files the agent's unpublished changes touch, in its own view. */
996− #draftFiles(...args: Tail<Parameters<typeof hostedDraftFiles>>): ReturnType<typeof hostedDraftFiles> {
997− return hostedDraftFiles(this.#overlapHost, ...args);
1465+ /**
1466+ * The files the agent's unpublished changes touch, in its own view. Kept per agent under what they're
1467+ * made of: its view's key and its draft. Most agents haven't moved since the last
1468+ * status, and the view cache holds fewer views than a big project has agents, so working them out again
1469+ * on every call cost about 0.5 s on abso. A copy goes out, so no caller can change what's kept.
1470+ */
1471+ #draftFiles(agent: AgentState): Set<string> {
1472+ const key = `${this.#agentViewKey(agent)}|${this.#draft(agent).join(",")}`;
1473+ let kept = this.#draftFilesKept.get(agent.name);
1474+ if (kept?.key !== key) {
1475+ kept = { key, files: hostedDraftFiles(this.#overlapHost, agent) };
1476+ this.#draftFilesKept.set(agent.name, kept);
1477+ }
1478+ return new Set(kept.files);
9981479 }
9991480
10001481 /** Other agents in the agent's space whose unpublished changes or starting note meet `patterns`. */
Lines 1492–1508 at 318 (were 1011–1016 at 41)
10111492 return hostedOverlapNews(this.#overlapHost, ...args);
10121493 }
10131494
1495+ /** The news waiting for an agent, read only: nothing is taken, heard or written. None for an agent it hasn't got. */
1496+ peekNews(agentName: string): { text: string; at: number | null }[] {
1497+ const agent = typeof agentName === "string" ? this.#agents.get(agentName) : undefined;
1498+ return agent ? agent.news.map((text, i) => ({ text, at: agent.newsAt[i] ?? null })) : [];
1499+ }
1501+ /** Whether the project has this agent. Read only. */
1502+ hasAgent(agentName: string): boolean {
1503+ return typeof agentName === "string" && this.#agents.get(agentName) !== undefined;
1504+ }
10141506 /** Hand over the news waiting for an agent (collisions, definitions, moves, announcements), once. */
10151507 news(agentName: string): { news: string[]; items: { text: string; at: number | null }[] } {
10161508 const entries: Entry[] = [];
Lines 1591–1597 at 318 (were 1099–1105 at 41)
10991591 space: Space,
11001592 changes: AtomId[],
11011593 pick: boolean,
1102− ): { collisions: Collision[]; newer: Set<AtomId>; union: Set<AtomId> } {
1594+ ): { collisions: Collision[]; newer: ReadonlySet<AtomId>; union: ReadonlySet<AtomId> } {
11031595 return hostedLandCollisions(this.#landHost, space, changes, pick);
11041596 }
11051597
Lines 1686–1692 at 318 (were 1194–1200 at 41)
11941686 * the one file ever in the view it matches, for a file since taken out.
11951687 * A path that matches two files is answered exactly.
11961688 */
1197− spellingIn(view: View, path: string): string {
1689+ spellingIn(view: ReadView, path: string): string {
11981690 if (view.hasFile(path)) return path;
11991691 const key = pathKey(path);
12001692 const live = view.knownPaths().filter((p) => pathKey(p) === key && view.hasFile(p));
Lines 1713–1739 at 318 (were 1221–1226 at 41)
12211713 const versionsBefore = this.#spaces.get(SHARED)?.versions.length ?? 0;
12221714 try {
12231715 this.#applyEntry(entry, at, keptTime);
1716+ // Shared's closure, kept per version on disk (abso Capacity): after the entry, since its atoms join the graph after
1717+ // its membership.
1718+ if (this.#writerStorage && (this.#spaces.get(SHARED)?.versions.length ?? 0) > versionsBefore) {
1719+ const shared = this.#spaces.get(SHARED)!;
1720+ const storage = this.#writerStorage;
1721+ indexClosure(storage, shared, this.#graph);
1722+ // Each new version's changed files, from what it touched (version-files.ts): kept in the shapes table when
1723+ // the host gives one, so the log, a path's history and the tree never lay versions out to find them.
1724+ const host: VersionFilesHost = {
1725+ storage,
1726+ graph: this.#graph,
1727+ at: (v) => this.#at(shared, v),
1728+ viewAt: (v) => this.#viewAt(shared, v),
1729+ empty: () => new View(this.#graph, []),
1730+ closureChangedAt: (v) => closureChangedAt(storage, v),
1731+ };
1732+ for (let v = versionsBefore; v < shared.versions.length; v++) {
1733+ const { files, exists } = keptVersionFiles(host, shared.versions[v]!);
1734+ this.#paths.keep(shared, v, files, v === 0 ? host.empty() : host.viewAt(v - 1), host.viewAt(v), exists);
1735+ }
1736+ }
12241737 } finally {
12251738 // Positions by version: where each version of shared was made.
12261739 const versionsAfter = this.#spaces.get(SHARED)?.versions.length ?? 0;
Lines 1781–1825 at 318 (were 1268–1278 at 41)
12681781 #flush(_entries: readonly Entry[]): void {
12691782 if (this.#pending.length === 0) return;
12701783 const out = this.#pending;
1271− this.#pending = [];
12721784 this.#store.append(out);
1785+ if (this.#newsWritten) {
1786+ const items: NewsWritten[] = [];
1787+ out.forEach((entry, i) => {
1788+ if (entry.type !== "news") return;
1789+ for (const text of entry.text)
1790+ items.push({ agent: entry.agent, text, at: entry.time ?? null, seq: this.#stored + i });
1791+ });
1792+ if (items.length > 0) this.#newsWritten(items);
1793+ }
1794+ this.#persistMutable();
1795+ // A few more agents' old told lists into their buckets at each write, until every row has moved (writer-agents.ts).
1796+ if (this.#agents instanceof WriterAgents) this.#agents.moveOldTold(OLD_TOLD_PER_WRITE);
1797+ this.#pending = [];
12731798 this.#stored += out.length;
1799+ this.#writeCheckpoint();
12741800 }
12751801
1802+ #writeCheckpoint(): void {
1803+ this.#writerStorage?.write("project:meta", "checkpoint", {
1804+ format: 1,
1805+ logLength: this.#stored,
1806+ atoms: this.#graph.size,
1807+ version: this.version,
1808+ });
1809+ }
1811+ #persistMutable(): void {
1812+ if (!this.#writerStorage) return;
1813+ if (this.#agents instanceof WriterAgents) this.#agents.flush();
1814+ this.#writerStorage.write("project:meta", "mods", this.#mods);
1815+ this.#writerStorage.write("project:meta", "queue", this.#queue);
1816+ this.#writerStorage.write(
1817+ "project:meta",
1818+ "tells",
1819+ [...this.#tells].map(([id, tell]) => [id, { ...tell, heard: [...tell.heard] }]),
1820+ );
1821+ }
12761823 /**
12771824 * The agent an entry names. Before every applied entry was stored, a call
12781825 * that joined an agent and then threw could leave the join out of the log
Lines 1887–1895 at 318 (were 1340–1345 at 41)
13401887 spaceNamed: (name) => this.#spaceNamed(name),
13411888 checkVersion: (space, version) => this.#checkVersion(space, version),
13421889 viewAt: (space, version) => this.#viewAt(space, version),
1890+ keptPaths: (space, version) => this.#keptPaths(space, version),
1891+ authorTotals: (space, version, agent) => this.#authorTotals(space, version, agent as AgentState | undefined),
1892+ agentTouched: (agent) => this.#agentTouched(agent as AgentState),
13431893 agentView: (agent) => this.#agentView(agent as AgentState),
13441894 spellingIn: (view, asked) => this.spellingIn(view, asked),
13451895 pathsOf: (space) => this.#paths.pathsOf(space),
Lines 1900–1956 at 318 (were 1350–1355 at 41)
13501900 return this.#host;
13511901 }
13521902
1903+ /** Shared's file list from kept shapes on a stored writer, where a version's layout reads its files from disk. */
1904+ #keptPaths(space: Space, version: number): string[] | undefined {
1905+ return this.#writerStorage && space.name === SHARED ? this.#paths.keptPaths(space, version) : undefined;
1906+ }
1908+ /**
1909+ * Each file's kept author totals for tree with authors (version-files.ts), on a stored writer and for shared only. An
1910+ * agent's view takes its base's totals for every file its draft doesn't touch, as its layout does (touchedBeyond),
1911+ * and lays out the rest; a draft that moves lines lays out everything.
1912+ */
1913+ #authorTotals(
1914+ space: Space,
1915+ version: number,
1916+ agent?: AgentState,
1917+ ): ((path: string) => FileTotals | undefined) | undefined {
1918+ const storage = this.#writerStorage;
1919+ if (!storage || space.name !== SHARED || authoredVersion(storage) === undefined) return undefined;
1920+ if (!agent) return (path) => authorTotalsAt(storage, path, version);
1921+ const except = this.#agentTouched(agent);
1922+ if (!except) return undefined;
1923+ return (path) => (except.has(path) ? undefined : authorTotalsAt(storage, path, version));
1924+ }
1926+ /**
1927+ * The files an agent's draft, and whatever it depends on beyond its base, can make differ from its base
1928+ * (touchedBeyond); every other file is the same in both. Undefined when the draft moves lines.
1929+ */
1930+ #agentTouched(agent: AgentState): ReadonlySet<string> | undefined {
1931+ if (agent.mine.length === 0) return new Set();
1932+ const base = this.#viewAt(this.#spaceOf(agent), agent.base);
1933+ const view = this.#agentView(agent);
1934+ return touchedBeyond(this.#graph, base.set, agent.mine, [base, view], () => placedBetween(view, base));
1935+ }
1937+ /**
1938+ * Kept author totals for a folder's blame (blame.ts), where blame reads: shared at a version (the newest by default) or
1939+ * an agent's view. A named draft has none. Undefined when none are kept.
1940+ */
1941+ authorTotalsFor(where: {
1942+ version?: number;
1943+ draft?: string;
1944+ agent?: string;
1945+ }): ((path: string) => FileTotals | undefined) | undefined {
1946+ if (where.draft !== undefined) return undefined;
1947+ if (where.agent !== undefined) {
1948+ const agent = this.#agents.get(where.agent);
1949+ return agent ? this.#authorTotals(this.#spaceOf(agent), agent.base, agent) : undefined;
1950+ }
1951+ return this.#authorTotals(this.#shared, where.version ?? last(this.#shared));
1952+ }
13531954 /** One folder at a version (history.ts). */
13541955 tree(...args: Tail<Parameters<typeof historyTree>>): ReturnType<typeof historyTree> {
13551956 return historyTree(this.#history, ...args);
Lines 2009–2045 at 318 (were 1408–1419 at 41)
14082009 return versionFileAt(this.#logHost, ...args);
14092010 }
14102011
2012+ /** fileAt for exactly this spelling, from the file's own lines: no list of the version's files (version-log.ts). */
2013+ fileExactAt(...args: Tail<Parameters<typeof versionFileExactAt>>): ReturnType<typeof versionFileExactAt> {
2014+ return versionFileExactAt(this.#logHost, ...args);
2015+ }
14112017 /** Every file that differs between two versions of shared (or a named draft) (version-log.ts). */
14122018 compare(...args: Tail<Parameters<typeof versionCompare>>): ReturnType<typeof versionCompare> {
14132019 return versionCompare(this.#logHost, ...args);
14142020 }
14152021
1416− /** A version of shared (or of a named draft) as a View (version-log.ts). */
2022+ /** compare as each file's size and SHA-256, not its texts (version-log.ts, abso issue 680). */
2023+ compareSummary(...args: Tail<Parameters<typeof versionCompareSummary>>): ReturnType<typeof versionCompareSummary> {
2024+ return versionCompareSummary(this.#logHost, ...args);
2025+ }
2027+ /** A version of shared without some earlier versions, or the refusal naming what builds on them (without.ts). */
2028+ without(version: number, versions: readonly number[]): ReturnType<typeof hostedWithout> {
2029+ const host: WithoutHost = {
2030+ graph: this.#graph,
2031+ shared: () => this.#shared,
2032+ needInit: () => this.#needInit(),
2033+ checkVersion: (space, v) => this.#checkVersion(space, v),
2034+ viewAt: (space, v) => this.#viewAt(space, v),
2035+ at: (space, v) => this.#at(space, v),
2036+ closed: (set) => this.#closed(set),
2037+ touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
2038+ };
2039+ return hostedWithout(host, version, versions);
2040+ }
2042+ /** A version of shared (or of a named draft) as a ReadView (version-log.ts). */
14172043 viewAt(...args: Tail<Parameters<typeof versionViewAt>>): ReturnType<typeof versionViewAt> {
14182044 return versionViewAt(this.#logHost, ...args);
14192045 }
Lines 2057–2099 at 318 (were 1431–1443 at 41)
14312057 definitionRule: () => this.#definitionRule,
14322058 draft: (agent) => this.#draft(agent as AgentState),
14332059 agentView: (agent) => this.#agentView(agent as AgentState),
1434− view: (set) => this.#view(set),
1435− pairs: (draft, against, settled) => this.#pairs(draft, against, settled),
2060+ draftsView: (agents) => this.#draftsView(agents as readonly AgentState[]),
14362061 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
2062+ // On a stored writer only, as a reader kept between calls is (abso Capacity).
2063+ keptParts: () => (this.#writerStorage ? (this.#keptParts ??= new KeptParts()) : undefined),
2064+ draftKey: (agent) => {
2065+ const a = agent as AgentState;
2066+ return `${last(this.#shared)} ${a.space}@${a.base} ${this.#draft(a).join(",")}`;
2067+ },
14372068 };
14382069 return this.#draftCollisionHost;
14392070 }
14402071
2072+ /**
2073+ * Shared now with some agents' drafts on top, for draft collisions (abso Capacity). Kept under the drafts' atoms and
2074+ * shared's version, so a second ask with nothing changed lays nothing out again, and laid out as shared is for every
2075+ * file the drafts don't touch, as an agent's view is. One agent based on shared's newest version is its own view.
2076+ */
2077+ #draftsView(agents: readonly AgentState[]): ReadView {
2078+ const shared = this.#shared;
2079+ const version = last(shared);
2080+ const only = agents.length === 1 ? agents[0]! : undefined;
2081+ if (only && only.space === SHARED && only.base === version) return this.#agentView(only);
2082+ const drafts = agents.map((agent) => this.#draft(agent));
2083+ const mine = drafts.flat();
2084+ const base = this.#sharedView();
2085+ const view = this.#viewKeyed(`d ${SHARED}@${version}+${drafts.map((d) => d.join(",")).join("+")}`, () =>
2086+ unionOverlay(base.set, mine),
2087+ );
2088+ if (this.#writerStorage && mine.length > 0 && view instanceof View && base instanceof View) {
2089+ view.shareMoves(base);
2090+ view.shareFiles(base, () =>
2091+ touchedBeyond(this.#graph, base.set, mine, [base, view], () => placedBetween(view, base)),
2092+ );
2093+ }
2094+ return view;
2095+ }
14412097 /** Whether agents' unpublished changes would collide, by the publish rule (draft-collisions.ts). */
14422098 collisions(...args: Tail<Parameters<typeof draftCollisions>>): ReturnType<typeof draftCollisions> {
14432099 return draftCollisions(this.#draftCollisions, ...args);
Lines 2108–2117 at 318 (were 1452–1457 at 41)
14522108 needInit: () => this.#needInit(),
14532109 draft: (agent) => this.#draft(agent as AgentState),
14542110 agentView: (agent) => this.#agentView(agent as AgentState),
2111+ agentViewWithout: (agent, excluded) => {
2112+ const state = agent as AgentState;
2113+ return this.#agentView({ ...state, mine: state.mine.filter((id) => !excluded.has(id)) });
2114+ },
14552115 view: (set) => this.#view(set),
14562116 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
14572117 };
Lines 2138–2153 at 318 (were 1478–1483 at 41)
14782138 this.#movesHost ??= {
14792139 graph: this.#graph,
14802140 draft: (agent) => this.#unqueuedDraft(agent),
2141+ beforeDraft: (agent, draft) => {
2142+ const base = this.#at(this.#spaceOf(agent), agent.base);
2143+ if (draft.some((id) => base.has(id)))
2144+ return this.#view(differenceSet(this.#agentView(agent).set, new StableOverlaySet(draft)));
2145+ const removed = new Set(draft),
2146+ kept = agent.mine.filter((id) => !removed.has(id));
2147+ return kept.length === 0
2148+ ? this.#viewAt(this.#spaceOf(agent), agent.base)
2149+ : this.#viewKeyed(`a ${agent.space}@${agent.base}+${kept.join(",")}`, () => unionOverlay(base, kept));
2150+ },
14812151 agentView: (agent) => this.#agentView(agent),
14822152 view: (set) => this.#view(set),
14832153 apply: (entry) => this.#apply(entry),
Lines 2184–2201 at 318 (were 1514–1521 at 41)
15142184 viewAt: (space, version) => this.#viewAt(space, version),
15152185 origin: (atom, spaceName) => this.#origin(atom, spaceName),
15162186 collision: (agent, pair) => this.#collision(agent, pair),
1517− definitionCollisions: (agent, newer) => this.#definitionCollisions(agent, newer),
2187+ definitionCollisions: (agent, newer, names) => this.#definitionCollisions(agent, newer, names),
15182188 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
2189+ logLine: (line) => this.#logLine?.(line),
2190+ owesDefinitionNews: () => this.owesDefinitionNews,
2191+ owe: (owed) => void this.#owed.push(owed),
2192+ spaceNamed: (name) => (name === SHARED ? this.#shared : this.#spaces.get(name)),
2193+ newerAt: (agent, version) => this.#newerFor(agent, version),
2194+ definitionCollisionsAt: (agent, newer, names, version) =>
2195+ this.#definitionCollisions(agent, newer, names, version),
2196+ setAt: (space, version) => this.#at(space, version),
2197+ collisionAt: (agent, pair, version) =>
2198+ this.#describe(pair, this.#agentView(agent), this.#viewAt(this.#spaceOf(agent), version), agent.space),
15192199 };
15202200 return this.#news;
15212201 }
Lines 2207–2213 at 318 (were 1527–1533 at 41)
15272207 spaces: this.#spaces,
15282208 version: () => this.version,
15292209 spaceOf: (agent) => this.#spaceOf(agent),
1530− agentSet: (agent) => this.#agentSet(agent),
2210+ agentSet: (agent) => unionOverlay(this.#at(this.#spaceOf(agent), agent.base), agent.mine),
15312211 draft: (agent) => this.#draft(agent),
15322212 agentView: (agent) => this.#agentView(agent),
15332213 at: (space, version) => this.#at(space, version),
Lines 2349–2365 at 318 (were 1669–1681 at 41)
16692349 collision: (agent, pair) => this.#collision(agent, pair),
16702350 definitionCollisions: (agent, newer) => this.#definitionCollisions(agent, newer),
16712351 duplicates: (agent) => this.#duplicates(agent),
1672− refuse: (agent, space, via, time, collisions, entries) =>
1673− this.#refuse(agent, space, via, time, collisions, entries),
2352+ refuse: (agent, space, via, time, collisions, entries, message) =>
2353+ this.#refuse(agent, space, via, time, collisions, entries, message),
16742354 markerCollisions: (agent) => this.#markerCollisions(agent),
16752355 enqueue: (agent, message, time, draft, resolves, entries) =>
16762356 this.#enqueue(agent, message, time, draft, resolves, entries),
16772357 view: (set) => this.#view(set),
16782358 requireClosed: (tie, union) => this.#requireClosed(tie, union),
2359+ spaceOverlay: (space, atoms) =>
2360+ this.#viewKeyed(`a ${space.name}@${last(space)}+${atoms.join(",")}`, () =>
2361+ unionOverlay(this.#setOf(space), atoms),
2362+ ),
16792363 newerFor: (agent) => this.#newerFor(agent),
16802364 currentChange: (agent, time) => this.#currentChange(agent, time),
16812365 apply: (entry) => this.#apply(entry),
Lines 2378–2395 at 318 (were 1694–1699 at 41)
16942378 graph: this.#graph,
16952379 checkerReady: () => this.checkerReady,
16962380 sharedView: () => this.#sharedView(),
2381+ sharedOverlay: (atoms) =>
2382+ this.#viewKeyed(`a @${last(this.#shared)}+${atoms.join(",")}`, () =>
2383+ unionOverlay(this.#setOf(this.#shared), atoms),
2384+ ),
2385+ sharedAgentOverlay: (agent, atoms) => {
2386+ const current = this.#setOf(this.#shared);
2387+ const added = new Set([...atoms, ...agent.mine]);
2388+ // Retain old-base atoms absent from current shared, without copying shared history.
2389+ if (agent.base !== last(this.#shared))
2390+ for (const id of this.#at(this.#spaceOf(agent), agent.base)) if (!current.has(id)) added.add(id);
2391+ return this.#viewKeyed(`a @${last(this.#shared)}+${[...added].join(",")}`, () => unionOverlay(current, added));
2392+ },
16972393 queued: () => this.#queue,
16982394 queuedId: () => this.#queuedId,
16992395 checkingHas: (id) => this.#checking.has(id),
Lines 2408–2415 at 318 (were 1712–1719 at 41)
17122408 pairs: (draft, against, settled) => this.#pairs(draft, against, settled),
17132409 describe: (pair, yoursView, theirsView, spaceName) => this.#describe(pair, yoursView, theirsView, spaceName),
17142410 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
1715− refuse: (agent, space, via, time, collisions, entries) =>
1716− this.#refuse(agent, space, via, time, collisions, entries),
2411+ refuse: (agent, space, via, time, collisions, entries, message) =>
2412+ this.#refuse(agent, space, via, time, collisions, entries, message),
17172413 currentChange: (agent, time) => this.#currentChange(agent, time),
17182414 nextAt: () => this.#nextAt,
17192415 apply: (entry) => this.#apply(entry),
Lines 2476–2487 at 318 (were 1780–1785 at 41)
17802476 #landers?: LandHost;
17812477 get #landHost(): LandHost {
17822478 this.#landers ??= {
2479+ viewAt: (space, version, changes) =>
2480+ changes?.length
2481+ ? this.#viewKeyed(`a ${space.name}@${version}+${changes.join(",")}`, () =>
2482+ unionOverlay(this.#at(space, version), changes),
2483+ )
2484+ : this.#viewAt(space, version),
17832485 agents: this.#agents,
17842486 graph: this.#graph,
17852487 spaces: this.#spaces,
Lines 2499–2507 at 318 (were 1797–1802 at 41)
17972499 pairs: (draft, against, settled) => this.#pairs(draft, against, settled),
17982500 describe: (pair, yoursView, theirsView, spaceName) => this.#describe(pair, yoursView, theirsView, spaceName),
17992501 definitionRule: () => this.#definitionRule,
2502+ // Only from a stored writer's kept rows, as keptPaths: a project in memory keeps none, and works them out.
2503+ changedSince: (space, from, to) =>
2504+ this.#writerStorage ? this.#paths.keptChangesSince(space, from, to) : undefined,
18002505 refuse: (agent, space, via, time, collisions, entries) =>
18012506 this.#refuse(agent, space, via, time, collisions, entries),
18022507 requireClosed: (tie, union) => this.#requireClosed(tie, union),
Lines 2548–2555 at 318 (were 1843–1848 at 41)
18432548 view: (set) => this.#view(set),
18442549 agentSet: (agent) => this.#agentSet(agent),
18452550 agentView: (agent) => this.#agentView(agent),
2551+ agentViewWithout: (agent, excluded) =>
2552+ this.#agentView({ ...agent, mine: agent.mine.filter((id) => !excluded.has(id)) }),
18462553 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
18472554 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
18482555 flush: (entries) => this.#flush(entries),
Lines 2580–2591 at 318 (were 1873–1878 at 41)
18732580 agent: (name, entries) => this.#agent(name, entries),
18742581 spaceOf: (agent) => this.#spaceOf(agent),
18752582 agentView: (agent) => this.#agentView(agent),
2583+ captureAgentView: (agent) => {
2584+ const key = this.#agentViewKey(agent);
2585+ const original = this.#agentView(agent);
2586+ // Projected readers reopen the immutable key; only the in-memory fallback uses the original set.
2587+ return () => this.#viewKeyed(key, () => original.set);
2588+ },
18762589 at: (space, version) => this.#at(space, version),
18772590 draft: (agent) => this.#draft(agent),
18782591 strandedFiles: (draft, set) => this.#strandedFiles(draft, set),
Lines 2652–2664 at 318 (were 1939–1946 at 41)
19392652 get #checkClashHost(): CheckClashHost {
19402653 this.#checkClashes ??= {
19412654 shared: () => this.#shared,
2655+ setOf: (space) => this.#setOf(space),
19422656 view: (set) => this.#view(set),
19432657 sharedView: () => this.#sharedView(),
2658+ sharedOverlay: (atoms) =>
2659+ this.#viewKeyed(`a @${last(this.#shared)}+${atoms.join(",")}`, () =>
2660+ unionOverlay(this.#setOf(this.#shared), atoms),
2661+ ),
19442662 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
19452663 };
19462664 return this.#checkClashes;
Lines 2746–2752 at 318 (were 2028–2033 at 41)
20282746 agents: this.#agents,
20292747 agentView: (agent) => this.#agentView(agent),
20302748 draft: (agent) => this.#draft(agent),
2749+ draftFiles: (agent) => this.#draftFiles(agent),
20312750 liveNote: (agent) => this.#liveNote(agent),
20322751 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
20332752 };
Lines 2871–2877 at 318 (were 2152–2157 at 41)
21522871 spaceNamed: (name) => this.#spaceNamed(name),
21532872 checkVersion: (space, version) => this.#checkVersion(space, version),
21542873 viewAt: (space, version) => this.#viewAt(space, version),
2874+ keptPaths: (space, version) => this.#keptPaths(space, version),
21552875 agentView: (agent) => this.#agentView(agent),
21562876 version: () => this.version,
21572877 projectFile: () => (this.initialized ? projectFileIn(this.#sharedView()) : undefined),
Lines 2904–2919 at 318 (were 2184–2189 at 41)
21842904 return snapshotStatus(this.#snapshot);
21852905 }
21862906
2907+ /** The operation fence needs one actor's heads, not every agent's file projection. */
2908+ actorHead(name: string): { base: number; draftChanges: number; draft: string | null } | undefined {
2909+ const agent = this.#agents.get(name);
2910+ if (!agent) return undefined;
2911+ const published = this.#setOf(this.#spaceOf(agent));
2912+ let draftChanges = 0;
2913+ for (const id of agent.mine) if (!published.has(id)) draftChanges++;
2914+ return { base: agent.base, draftChanges, draft: agent.space === SHARED ? null : agent.space };
2915+ }
21872917 /** A space's contents at one of its versions. */
21882918 #at(space: Space, version: number): ReadonlySet<AtomId> {
21892919 return this.#membership.at(space, version);
Lines 2946–3015 at 318 (were 2216–2242 at 41)
22162946 return new Set([...this.#at(this.#spaceOf(agent), agent.base), ...agent.mine]);
22172947 }
22182948
2219− #agentView(agent: AgentState): View {
2220− // Keyed by what the set is made of, not by sorting every atom in it (#46): that cost more than the work.
2221− return this.#viewKeyed(`a ${agent.space}@${agent.base}+${agent.mine.join(",")}`, () => this.#agentSet(agent));
2949+ #agentView(agent: AgentState): ReadView {
2950+ const view = this.#viewKeyed(this.#agentViewKey(agent), () => {
2951+ const base = this.#at(this.#spaceOf(agent), agent.base);
2952+ return base instanceof StableSet
2953+ ? new StableUnionSet(base, new StableOverlaySet(agent.mine))
2954+ : new Set([...base, ...agent.mine]);
2955+ });
2956+ // A draft that moves nothing resolves its moves as its base does (abso Capacity): take them from the base's view.
2957+ if (this.#writerStorage && agent.mine.length > 0 && view instanceof View) {
2958+ const base = this.#viewAt(this.#spaceOf(agent), agent.base);
2959+ if (base instanceof View) {
2960+ view.shareMoves(base);
2961+ // And its layout of every file the draft doesn't touch, when the draft moves nothing (abso Capacity). What the
2962+ // view holds beyond its base is the draft and whatever the draft depends on that the base lacks (the view's
2963+ // set is closed): each of those can change a file, so all of them count.
2964+ const mine = agent.mine;
2965+ view.shareFiles(base, () =>
2966+ touchedBeyond(this.#graph, base.set, mine, [base, view], () => placedBetween(view, base)),
2967+ );
2968+ }
2969+ }
2970+ return view;
22222971 }
22232972
2973+ /** 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. */
2974+ #agentViewKey(agent: AgentState): string {
2975+ // An empty draft is exactly its published base. Share its projection
2976+ // with version readers instead of walking the same history twice.
2977+ if (agent.mine.length === 0) return `v ${agent.space}@${agent.base}`;
2978+ return `a ${agent.space}@${agent.base}+${agent.mine.join(",")}`;
2979+ }
22242981 /** A space at a version: published versions never change, so the key is just their names (#46). */
2225− #viewAt(space: Space, version: number): View {
2226− return this.#viewKeyed(`v ${space.name}@${version}`, () => this.#at(space, version));
2982+ #viewAt(space: Space, version: number): ReadView {
2983+ const view = this.#viewKeyed(`v ${space.name}@${version}`, () => this.#at(space, version));
2984+ // Which files it has from the kept path list (abso Capacity, View.knowPaths), as pathsAt answers.
2985+ if (view instanceof View && this.#writerStorage && space.name === SHARED)
2986+ view.knowPaths(() => this.#paths.keptPathSet(space, version));
2987+ return view;
22272988 }
22282989
2229− #sharedView(): View {
2990+ #sharedView(): ReadView {
22302991 return this.#viewAt(this.#shared, last(this.#shared));
22312992 }
22322993
2994+ /**
2995+ * After each read of a reader kept between calls, one that changed nothing (abso Capacity): the cached views back
2996+ * under their budget, since views grow while a call lays files out and the cache weighs them only when they are
2997+ * asked for again (on abso, a tree with authors left 38 MB of views held against the 24 MB budget), and the agents
2998+ * the read decoded let go, read again from storage by the next call (7 MB on abso, every agent's news told).
2999+ */
3000+ afterRead(): void {
3001+ this.#views.trim();
3002+ if (this.#agents instanceof WriterAgents) this.#agents.release();
3003+ }
22333005 /** A view of a set, cached by the set's exact contents (views.ts). */
2234− #view(set: ReadonlySet<AtomId>): View {
3006+ #view(set: ReadonlySet<AtomId>): ReadView {
3007+ this.#views.assertUnkeyedAllowed();
22353008 return this.#views.view(this.#closed(set));
22363009 }
22373010
22383011 /** A view cached under `key` (views.ts). */
2239− #viewKeyed(key: string, set: () => ReadonlySet<AtomId>): View {
3012+ #viewKeyed(key: string, set: () => ReadonlySet<AtomId>): ReadView {
22403013 return this.#views.keyed(key, () => this.#closed(set()));
22413014 }
22423015
Lines 3017–3052 at 318 (were 2244–2250 at 41)
22443017 * A discarded atom that a later publish still depends on stays in the view
22453018 * (abso issue 80). A closed set is unchanged.
22463019 */
2247− #closed(set: Iterable<AtomId>): Set<AtomId> {
3020+ #closed(set: Iterable<AtomId>): ReadonlySet<AtomId> {
3021+ if (isClosedSet(set)) return set as ReadonlySet<AtomId>;
3022+ if (set instanceof StableSet) {
3023+ // Keep indexed membership external. Only dependencies absent from
3024+ // that snapshot belong in the operation's closure overlay. Over a stored closed base (abso Capacity),
3025+ // only the atoms outside it can reach outside it: unions are opened down to their closed parts.
3026+ const walk: Iterable<AtomId>[] = [];
3027+ const open = (part: ReadonlySet<AtomId>): void => {
3028+ if (isClosedSet(part)) return;
3029+ if (part instanceof StableUnionSet) {
3030+ open(part.left);
3031+ open(part.right);
3032+ } else walk.push(part);
3033+ };
3034+ open(set);
3035+ const missing = new Set<AtomId>();
3036+ const visit = (id: AtomId) => {
3037+ const stack = [id];
3038+ while (stack.length) {
3039+ for (const dependency of this.#graph.atom(stack.pop()!).deps) {
3040+ if (!set.has(dependency) && !missing.has(dependency)) {
3041+ missing.add(dependency);
3042+ stack.push(dependency);
3043+ }
3044+ }
3045+ }
3046+ };
3047+ for (const part of walk) for (const id of part) visit(id);
3048+ return markClosed(missing.size ? new StableUnionSet(set, new StableOverlaySet(missing)) : set);
3049+ }
22483050 return this.#graph.closureOf(set);
22493051 }
22503052
Lines 3056–3076 at 318 (were 2254–2269 at 41)
22543056 if (missing.length > 0)
22553057 throw new ProjectError(
22563058 "conflict",
2257− `this change depends on ${missing.join(", ")}, which is not in the set being published`,
3059+ `this change depends on ${missing.join(", ")}, which is not in the set being pushed`,
22583060 );
22593061 }
22603062
22613063 /** The space's atoms published after the agent's base, by others. */
2262− #newerFor(agent: AgentState): Set<AtomId> {
3064+ /** `upTo`: the work published after the agent's base up to that version only (owed news, news.ts). */
3065+ #newerFor(agent: AgentState, upTo?: number): ReadonlySet<AtomId> {
22633066 const space = this.#spaceOf(agent);
22643067 const base = this.#at(space, agent.base);
2265− const mine = new Set(agent.mine);
2266− return new Set([...this.#setOf(space)].filter((id) => !base.has(id) && !mine.has(id)));
3068+ const current = upTo === undefined ? this.#setOf(space) : this.#at(space, upTo);
3069+ const newer =
3070+ space.name === SHARED && space.membershipVersion
3071+ ? new SharedAdditions(space, agent.base, base, current, upTo ?? last(space))
3072+ : differenceSet(current, base);
3073+ return differenceSet(newer, new StableOverlaySet(agent.mine));
22673074 }
22683075
22693076 /** The files whose text in the agent's view differs from `before`, and its open collisions. */
Lines 3186–3192 at 318 (were 2379–2385 at 41)
23793186 );
23803187 }
23813188
2382− #describe(pair: Pair, yoursView: View, theirsView: View, spaceName: string): Collision {
3189+ #describe(pair: Pair, yoursView: ReadView, theirsView: ReadView, spaceName: string): Collision {
23833190 return describePair(
23843191 this.#graph,
23853192 (atom, space) => this.#origin(atom, space),
Lines 3197–3236 at 318 (were 2390–2415 at 41)
23903197 );
23913198 }
23923199
2393− #touchedFiles(ids: Iterable<AtomId>, views: readonly View[]): Set<string> {
3200+ #touchedFiles(ids: Iterable<AtomId>, views: readonly ReadView[]): Set<string> {
23943201 return touchedFiles(this.#graph, ids, views);
23953202 }
23963203
23973204 // The changed-definition rule (#11) -------------------------------------------
23983205
23993206 /** The rule for an agent's draft in its space. */
2400− #definitionCollisions(agent: AgentState, newer: ReadonlySet<AtomId>): DefinitionCollision[] {
3207+ #definitionCollisions(
3208+ agent: AgentState,
3209+ newer: ReadonlySet<AtomId>,
3210+ names?: ReadonlySet<string>,
3211+ /** The space's version to compare against: its newest, or an owed publish's (news.ts). */
3212+ version?: number,
3213+ ): DefinitionCollision[] {
24013214 const draft = new Set(this.#draft(agent));
24023215 if (draft.size === 0 || newer.size === 0) return [];
24033216 const space = this.#spaceOf(agent);
2404− const mine = new Set(agent.mine);
2405− const base = this.#view(new Set([...this.#at(space, agent.base)].filter((id) => !mine.has(id))));
3217+ const at = this.#at(space, agent.base);
3218+ const base = agent.mine.some((id) => at.has(id))
3219+ ? this.#view(differenceSet(at, new StableOverlaySet(agent.mine)))
3220+ : this.#viewAt(space, agent.base);
3221+ const to = version ?? last(space);
24063222 return this.#definitionRule.collisions(
24073223 draft,
24083224 this.#agentView(agent),
24093225 base,
2410− this.#viewAt(space, last(space)),
3226+ this.#viewAt(space, to),
24113227 newer,
24123228 space.name,
3229+ undefined,
3230+ names,
3231+ // Where the space changed since the agent's base, from each version's kept files on a stored writer, as land's
3232+ // (abso 714): walking every newer atom for them was 6.5 s of a publish 770 versions behind on abso.
3233+ () => (this.#writerStorage ? this.#paths.keptChangesSince(space, agent.base, to) : undefined),
24133234 );
24143235 }
24153236}
MCP
compare on this site's /mcp
CLI
abso diff 41 318 worker/project/project.ts --json
JSON
/christopher/abso-core/compare/41..318?file=worker%2Fproject%2Fproject.ts&format=json