Lines 13–26 at 109 (were 13–18 at 108)
1313// unit. Every agent works in one space at a time. 1515import { type Atom, type AtomId, EngineError, Graph, type LineId, type View } from "../../src/engine/index.ts"; 17+ type GraphStateStorage, 23+} from "../../src/engine/state-source.ts"; 1624import { type AddDraftHost, addDraft as hostedAddDraft } from "./add-draft.ts"; 1725import { type AmendHost, amend as hostedAmend } from "./amend.ts"; 1826import { type AnnounceHost, announce as hostedAnnounce, announcePerson as hostedAnnouncePerson } from "./announce.ts"; Lines 199–205 at 109 (were 191–196 at 108)
191199 wholeRules as hostedWholeRules, 193201} from "./whole-files.ts"; 202+import { WriterAgents } from "./writer-agents.ts"; 195204export { MemoryStore } from "./memory-store.ts"; 196205export { checkReadPath, pathProblem } from "./path-rules.ts"; Lines 213–233 at 109 (were 204–212 at 108)
205214/** A start note lasts this long after the agent's last activity (#44). */ 206215const NOTE_IDLE = 2 * 60 * 60 * 1000; 216+const WRITER_REOPEN = Symbol("verified writer checkpoint"); 217+export interface WriterSource { 218+ readonly generation: number; 219+ readonly logLength: number; 220+ readonly sharedVersion: number; 222+interface WriterAdoption { 223+ source: WriterSource; 208228export class Project { 209229 readonly #store: ProjectStore; 230+ readonly #writerStorage?: GraphStateStorage; 210231 readonly #graph: Graph; 211232 /** Views laid out from atom sets, cached under a byte budget (views.ts). */ 212233 readonly #views: ViewCache; Lines 269–284 at 109 (were 248–254 at 108)
248269 /** For each version of shared, the log position of the entry that made it (#41). */ 249270 readonly #versionAt: number[] = []; 250271 /** The newest time any applied entry carries: the clock when none was given. */ 251− #lastTime = 0;
272+ #lastTimeMemory = 0; 273+ get #lastTime(): number { 274+ return this.#writerStorage 275+ ? ((this.#writerStorage.read("project:meta", "lastTime") as number | undefined) ?? 0) 276+ : this.#lastTimeMemory; 278+ set #lastTime(value: number) { 279+ if (this.#writerStorage) this.#writerStorage.write("project:meta", "lastTime", value); 280+ else this.#lastTimeMemory = value; 252282 /** Every change (#44), by id. */ 253283 readonly #changes = new Map<number, ChangeRecord>(); 254284 /** Each version's change, by "<draft or ''> <version>" (#44): what a note on its lines belongs to. */ Lines 290–328 at 109 (were 260–271 at 108)
260290 /** The merge queue (#39), in order: publishes to shared waiting for their batch's check. */ 261291 #queue: QueuedPublish[] = []; 262292 /** The newest note's id (#44). */ 263− #lastNote = 0;
264− #queuedId = 0;
293+ #lastNoteMemory = 0; 294+ get #lastNote(): number { 295+ return this.#writerStorage 296+ ? ((this.#writerStorage.read("project:meta", "lastNote") as number | undefined) ?? 0) 297+ : this.#lastNoteMemory; 299+ set #lastNote(value: number) { 300+ if (this.#writerStorage) this.#writerStorage.write("project:meta", "lastNote", value); 301+ else this.#lastNoteMemory = value; 303+ #queuedIdMemory = 0; 304+ get #queuedId(): number { 305+ return this.#writerStorage 306+ ? ((this.#writerStorage.read("project:meta", "queuedId") as number | undefined) ?? 0) 307+ : this.#queuedIdMemory; 309+ set #queuedId(value: number) { 310+ if (this.#writerStorage) this.#writerStorage.write("project:meta", "queuedId", value); 311+ else this.#queuedIdMemory = value; 265313 /** Queued ids in the batch being checked now: not in the log, only for refusing an unqueue mid-check. */ 266314 #checking = new Set<number>(); 267315 /** How many entries the store holds: the log position of the next one (#41, the website's feed and replay). */ 268− #stored = 0;
317+ get #stored(): number { 318+ return this.#writerStorage 319+ ? ((this.#writerStorage.read("project:meta", "stored") as number | undefined) ?? 0) 320+ : this.#storedMemory; 322+ set #stored(value: number) { 323+ if (this.#writerStorage) this.#writerStorage.write("project:meta", "stored", value); 324+ else this.#storedMemory = value; 269326 /** Names on the lines a change replaced, by "<atom> <last replaced line>" (atoms never change). */ 270327 #rule?: DefinitionRule; 271328 get #definitionRule(): DefinitionRule { Lines 330–382 at 109 (were 273–285 at 108)
273330 return this.#rule; 275332 /** The newest announcement's id (announcements are news entries keyed "announce <id>"). */ 276− #announced = 0;
333+ #announcedMemory = 0; 334+ get #announced(): number { 335+ return this.#writerStorage 336+ ? ((this.#writerStorage.read("project:meta", "announced") as number | undefined) ?? 0) 337+ : this.#announcedMemory; 339+ set #announced(value: number) { 340+ if (this.#writerStorage) this.#writerStorage.write("project:meta", "announced", value); 341+ else this.#announcedMemory = value; 279345 readonly #hasBlob: (sha256: string) => boolean; 281− constructor(store: ProjectStore, options: ProjectOptions = {}) {
347+ constructor(store: ProjectStore, options: ProjectOptions = {}, checkpoint?: typeof WRITER_REOPEN) { 282348 this.#store = store; 349+ this.#writerStorage = options.writerStorage; 350+ if (options.writerStorage) { 351+ const storage = options.writerStorage; 352+ // A stored Graph cannot be replayed over itself. Check before any 353+ // constructor writes so an accidental reopen preserves the namespace. 355+ checkpoint !== WRITER_REOPEN && 356+ ((storage.read("atoms:meta", "length") as number | undefined) || 357+ (storage.read('membership:"":versions:meta', "length") as number | undefined)) 359+ throw new Error("writer indexes already contain history; Project checkpoint reopen is required"); 360+ this.#membership = new Membership(storage); 361+ this.#atomAt = storedArray(storage, "project:atom-at"); 362+ this.#timeAt = storedArray(storage, "project:time-at"); 363+ this.#versionAt = storedArray(storage, "project:version-at"); 364+ this.#notes = new StoredMap(storage, "project:notes"); 365+ this.#changes = new StoredMap(storage, "project:changes"); 366+ this.#labels = new StoredMap(storage, "project:labels"); 367+ this.#versionChange = new StoredMap(storage, "project:version-change"); 368+ this.#refusals = storedArray(storage, "project:refusals"); 369+ this.#agents = new WriterAgents(storage); 370+ if (checkpoint === WRITER_REOPEN) { 371+ this.#mods = storage.read("project:meta", "mods") as string[]; 372+ this.#queue = storage.read("project:meta", "queue") as QueuedPublish[]; 373+ const tells = storage.read("project:meta", "tells") as [ 375+ Omit<TellRecord, "heard"> & { heard: [string, { at: number | undefined } | null][] }, 377+ this.#tells = new Map(tells.map(([id, tell]) => [id, { ...tell, heard: new Map(tell.heard) }])); 283380 this.#hasBlob = options.hasBlob ?? (() => false); 284381 this.#now = options.now; 285382 this.#whole = options.whole; Lines 398–408 at 109 (were 301–309 at 108)
301398 throw new Error(`log entry ${at} holds no atom ${seq}`); 303400 // Line text and each atom's deletes and claim keys stay in the log (#46), read back when asked for. 304− this.#graph = entryAt
305− ? new Graph({ texts: (seq) => stored(seq).inserts.map((r) => r.lines), lists: (seq) => stored(seq) })
306− : new Graph();
401+ this.#graph = options.writerStorage 402+ ? new Graph({ storage: options.writerStorage }) 404+ ? new Graph({ texts: (seq) => stored(seq).inserts.map((r) => r.lines), lists: (seq) => stored(seq) }) 307406 this.#views = new ViewCache(this.#graph); 308407 this.#paths = new PathIndex({ 309408 graph: this.#graph, Lines 429–563 at 109 (were 330–341 at 108)
330429 for (const entry of entries) { 331430 project.#apply(entry); 332431 project.#stored++; 432+ project.#persistMutable(); 334434 project.#loading = false; 435+ project.#writeCheckpoint(); 439+ /** Reopen committed writer indexes. The host supplies the authoritative canonical log length. */ 441+ store: ProjectStore, 442+ storage: GraphStateStorage, 444+ options: Omit<ProjectOptions, "writerStorage"> = {}, 446+ const adoption = storage.read("project:meta", "adoption") as WriterAdoption | undefined; 447+ if (adoption && !adoption.ready) throw new Error("writer adoption is incomplete"); 448+ return Project.#openWriter(store, storage, logLength, options); 452+ store: ProjectStore, 453+ storage: GraphStateStorage, 455+ options: Omit<ProjectOptions, "writerStorage">, 457+ const checkpoint = storage.read("project:meta", "checkpoint") as 458+ | { format: number; logLength: number; atoms: number; version: number } 460+ const length = (name: string) => (storage.read(`${name}:meta`, "length") as number | undefined) ?? 0; 462+ !Number.isSafeInteger(logLength) || 464+ checkpoint?.format !== 1 || 465+ checkpoint.logLength !== logLength || 466+ storage.read("project:meta", "stored") !== logLength || 467+ length("project:time-at") !== logLength || 468+ length("atoms") !== checkpoint.atoms || 469+ length("project:atom-at") !== checkpoint.atoms || 470+ length('membership:"":versions') !== checkpoint.version + 1 || 471+ length("project:version-at") !== checkpoint.version + 1 || 472+ !["mods", "queue", "tells"].every((key) => Array.isArray(storage.read("project:meta", key))) 474+ throw new Error("writer checkpoint does not match the canonical log and indexes"); 475+ return new Project(store, { ...options, writerStorage: storage }, WRITER_REOPEN); 479+ * Derive one bounded page from the host's canonical frames. The host reads 480+ * those frames from its own log and revalidates the source inside this same 481+ * transaction. Partial adoption cannot be opened for normal operations. 483+ static adoptWriterPage( 484+ storage: GraphStateStorage, 486+ source: WriterSource; 488+ frames: Iterable<{ seq: number; json: string }>; 491+ currentSource(): WriterSource; 493+ options: Omit<ProjectOptions, "writerStorage"> = {}, 494+ ): { next: number; ready: boolean; entries: number; bytes: number } { 495+ const same = (a: WriterSource, b: WriterSource) => 496+ a.generation === b.generation && a.logLength === b.logLength && a.sharedVersion === b.sharedVersion; 498+ ![input.source.generation, input.source.logLength, input.source.sharedVersion, input.from].every( 499+ (n) => Number.isSafeInteger(n) && n >= 0, 501+ input.source.logLength < 1 || 502+ !Number.isSafeInteger(input.maxEntries) || 503+ input.maxEntries < 1 || 504+ input.maxEntries > 256 || 505+ !Number.isSafeInteger(input.maxBytes) || 506+ input.maxBytes < 1 || 507+ input.maxBytes > 8_000_000 509+ throw new Error("invalid writer adoption bounds or source"); 510+ return storage.transaction(() => { 511+ if (!same(input.currentSource(), input.source)) 512+ throw new Error("canonical source changed before writer adoption"); 513+ const previous = storage.read("project:meta", "adoption") as WriterAdoption | undefined; 515+ (previous && (!same(previous.source, input.source) || previous.ready || previous.next !== input.from)) || 516+ (!previous && input.from !== 0) 518+ throw new Error("writer adoption source or cursor does not match"); 519+ const noAppend: ProjectStore = { 521+ throw new Error("adoption must never append canonical history"); 524+ const project = previous 525+ ? Project.#openWriter(noAppend, storage, input.from, options) 526+ : new Project(noAppend, { ...options, writerStorage: storage }); 527+ project.#loading = true; 530+ for (const frame of input.frames) { 532+ count >= input.maxEntries || 533+ frame.seq !== input.from + count || 534+ frame.seq >= input.source.logLength || 535+ typeof frame.json !== "string" || 536+ frame.json.length > input.maxBytes - bytes 538+ throw new Error("writer adoption page exceeds bounds or has a noncontiguous frame"); 539+ bytes += new TextEncoder().encode(frame.json).byteLength; 540+ if (bytes > input.maxBytes) throw new Error("writer adoption page exceeds byte bound"); 541+ project.#apply(JSON.parse(frame.json) as Entry); 543+ project.#persistMutable(); 546+ if (count === 0) throw new Error("writer adoption page must advance"); 547+ project.#loading = false; 548+ const next = input.from + count; 549+ const ready = next === input.source.logLength; 550+ if (!same(input.currentSource(), input.source)) 551+ throw new Error("canonical source changed during writer adoption"); 552+ if (ready && project.version !== input.source.sharedVersion) 553+ throw new Error("adopted shared version differs from canonical source"); 554+ project.#writeCheckpoint(); 555+ storage.write("project:meta", "adoption", { source: input.source, next, ready } satisfies WriterAdoption); 556+ return { next, ready, entries: count, bytes }; 339561 * Apply more stored entries to a copy loaded for reading (#41, replay): 340562 * scrubbing forward applies only what's new. Never for the live project. Lines 1489–1522 at 109 (were 1267–1277 at 108)
12671489 #flush(_entries: readonly Entry[]): void { 12681490 if (this.#pending.length === 0) return; 12691491 const out = this.#pending; 1270− this.#pending = [];
12711492 this.#store.append(out); 1493+ this.#persistMutable(); 1494+ this.#pending = []; 12721495 this.#stored += out.length; 1496+ this.#writeCheckpoint(); 1499+ #writeCheckpoint(): void { 1500+ this.#writerStorage?.write("project:meta", "checkpoint", { 1502+ logLength: this.#stored, 1503+ atoms: this.#graph.size, 1504+ version: this.version, 1508+ #persistMutable(): void { 1509+ if (!this.#writerStorage) return; 1510+ if (this.#agents instanceof WriterAgents) this.#agents.flush(); 1511+ this.#writerStorage.write("project:meta", "mods", this.#mods); 1512+ this.#writerStorage.write("project:meta", "queue", this.#queue); 1513+ this.#writerStorage.write( 1516+ [...this.#tells].map(([id, tell]) => [id, { ...tell, heard: [...tell.heard] }]), 12761521 * The agent an entry names. Before every applied entry was stored, a call 12771522 * that joined an agent and then threw could leave the join out of the log Lines 2462–2473 at 109 (were 2217–2223 at 108)
22192464 #agentView(agent: AgentState): View { 2220− return this.#viewKeyed(this.#agentViewKey(agent), () => this.#agentSet(agent));
2465+ return this.#viewKeyed(this.#agentViewKey(agent), () => { 2466+ const base = this.#at(this.#spaceOf(agent), agent.base); 2467+ return base instanceof StableSet 2468+ ? new StableUnionSet(base, new StableOverlaySet(agent.mine)) 2469+ : new Set([...base, ...agent.mine]); 22232473 /** 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. */